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

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\DocumentAttachmentMeta;
  16. use ApplicationBundle\Entity\BankList;
  17. use ApplicationBundle\Entity\Brs;
  18. use ApplicationBundle\Entity\CheckFormat;
  19. use ApplicationBundle\Entity\ExpenseInvoice;
  20. use ApplicationBundle\Entity\FiscalClosing;
  21. use ApplicationBundle\Entity\FundRequisition;
  22. use ApplicationBundle\Entity\ReceiptCheck;
  23. use ApplicationBundle\Entity\TaxConfig;
  24. use ApplicationBundle\Helper\CountryTemplateResolver;
  25. use ApplicationBundle\Helper\TaxMarkerLookup;
  26. use ApplicationBundle\Helper\Generic;
  27. use ApplicationBundle\Modules\Accounts\Support\VoucherBalanceGuard;
  28. use ApplicationBundle\Modules\Accounts\Support\VoucherAllocationInput;
  29. use ApplicationBundle\Interfaces\SessionCheckInterface;
  30. use ApplicationBundle\Modules\Accounts\Accounts;
  31. use ApplicationBundle\Modules\Accounts\Service\AccountHeadPermissionService;
  32. use ApplicationBundle\Modules\Accounts\Service\AccountHeadExternalMappingService;
  33. use ApplicationBundle\Modules\Authentication\Constants\UserConstants; use ApplicationBundle\Modules\Api\Constants\ApiConstants;
  34. use ApplicationBundle\Modules\FixedAsset\FixedAsset;
  35. use ApplicationBundle\Modules\Inventory\Inventory;
  36. use ApplicationBundle\Modules\Project\ProjectM;
  37. use ApplicationBundle\Modules\Document\DocumentRegistry;
  38. use ApplicationBundle\Modules\Purchase\Purchase;
  39. use ApplicationBundle\Modules\Sales\Client;
  40. use ApplicationBundle\Modules\Sales\SalesOrderM;
  41. use ApplicationBundle\Modules\System\ApprovalFunction;
  42. use ApplicationBundle\Modules\System\DeleteDocument;
  43. use ApplicationBundle\Modules\System\DocValidation;
  44. use ApplicationBundle\Modules\System\MiscActions;
  45. use ApplicationBundle\Modules\System\System;
  46. use ApplicationBundle\Modules\User\Company;
  47. use ApplicationBundle\Modules\User\Users;
  48. use CompanyGroupBundle\Entity\EntityFile;
  49. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  50. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  51. use Ps\PdfBundle\Annotation\Pdf;
  52. use Symfony\Component\HttpFoundation\JsonResponse;
  53. use Symfony\Component\HttpFoundation\RedirectResponse;
  54. use Symfony\Component\HttpFoundation\Request;
  55. use Symfony\Component\HttpFoundation\Response;
  56. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  57. use Symfony\Component\HttpFoundation\StreamedResponse;
  58. use Symfony\Component\Process\Process;
  59. use Symfony\Component\Routing\Generator\UrlGenerator;
  60. use Symfony\Component\Validator\Constraints\Json;
  61. //use Symfony\Bundle\FrameworkBundle\Console\Application;
  62. //use Symfony\Component\Console\Input\ArrayInput;
  63. //use Symfony\Component\Console\Output\NullOutput;
  64. class AccountsController extends GenericController implements SessionCheckInterface
  65. {
  66.     private function getAllocationReportFilters(Request $request)
  67.     {
  68.         return array(
  69.             'tag_type' => trim((string) $request->query->get('tag_type''')),
  70.             'tag_value' => trim((string) $request->query->get('tag_value''')),
  71.             'projectId' => (int) $request->query->get('projectId'0),
  72.             'branchId' => (int) $request->query->get('branchId'0),
  73.             'costCenterId' => (int) $request->query->get('costCenterId'0),
  74.         );
  75.     }
  76.     private function getAllocationReportSupportData($emRequest $request)
  77.     {
  78.         $companyId $this->getLoggedUserCompanyId($request);
  79.         $filters $this->getAllocationReportFilters($request);
  80.         $summaryRows $em->getRepository('ApplicationBundle\\Entity\\TransactionDetailAllocation')
  81.             ->getAllocationSummary();
  82.         $tagTypes = [];
  83.         $tagValuesByType = [];
  84.         foreach ($summaryRows as $row) {
  85.             $type strtolower(trim((string) ($row['tag_type'] ?? '')));
  86.             $value trim((string) ($row['tag_value'] ?? ''));
  87.             if ($type === '' || $value === '') {
  88.                 continue;
  89.             }
  90.             if (!isset($tagTypes[$type])) {
  91.                 $tagTypes[$type] = array(
  92.                     'id' => $type,
  93.                     'text' => ucwords(str_replace(array('_''-'), ' '$type)),
  94.                 );
  95.             }
  96.             if (!isset($tagValuesByType[$type])) {
  97.                 $tagValuesByType[$type] = array();
  98.             }
  99.             $tagValuesByType[$type][$value] = array(
  100.                 'id' => $value,
  101.                 'text' => $value,
  102.             );
  103.         }
  104.         foreach ($tagValuesByType as $type => $values) {
  105.             $tagValuesByType[$type] = array_values($values);
  106.         }
  107.         return array(
  108.             'allocation_filters' => $filters,
  109.             'allocation_tag_types' => array_values($tagTypes),
  110.             'allocation_tag_values_by_type' => $tagValuesByType,
  111.             'project_list' => ProjectM::GetProjectList($em),
  112.             'branch_list' => Client::BranchList($em$companyId),
  113.             'cost_centers' => Accounts::CostCenterList($em),
  114.         );
  115.     }
  116.     public function exportDatabase(Request $request)
  117.     {
  118.         $session $request->getSession();
  119.         $gocDbName $session->get(UserConstants::USER_DB_NAME);
  120.         $gocDbUser $session->get(UserConstants::USER_DB_USER);
  121.         $gocDbPass $session->get(UserConstants::USER_DB_PASS);
  122.         $gocDbHost $session->get(UserConstants::USER_DB_HOST);
  123.         ////                        $connector = $this->container->get('application_connector');
  124.         //        $connector = $this->applicationConnector;
  125.         //        $connector->resetConnection(
  126.         //            'default',
  127.         //            $gocDbName,
  128.         //            $gocDbUser,
  129.         //            $gocDbPass,
  130.         //            $gocDbHost,
  131.         //            $reset = false);
  132.         $process = new Process([
  133.             'mysqldump',
  134.             '-u',
  135.             $gocDbUser// Replace with your DB username
  136.             '-p' $gocDbPass// Replace with your DB password
  137.             $gocDbName // Replace with your database name
  138.         ]);
  139.         $process->setTimeout(3600); // Increase timeout if needed
  140.         $process->run();
  141.         if (!$process->isSuccessful()) {
  142.             return new Response('Database export failed: ' $process->getErrorOutput(), Response::HTTP_INTERNAL_SERVER_ERROR);
  143.         }
  144.         // Get output of the process (SQL dump)
  145.         $sqlDump $process->getOutput();
  146.         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/dbase_backup';
  147.         if (!file_exists($upl_dir)) {
  148.             mkdir($upl_dir0777true);
  149.         }
  150.         // Save to a file
  151.         $filePath $upl_dir 'database_dump.sql'// Update this path
  152.         file_put_contents($filePath$sqlDump);
  153.         return new Response('Database exported successfully to ' $filePath);
  154.     }
  155.     public function importDatabase(Request $request)
  156.     {
  157.         $uploadedFile $request->files->get('file');
  158.         if ($uploadedFile && $uploadedFile->isValid()) {
  159.             // Save uploaded file to a temporary location
  160.             $filePath '/path/to/temp/import_file.sql'// Update this path
  161.             $uploadedFile->move(dirname($filePath), basename($filePath));
  162.             $process = new Process([
  163.                 'mysql',
  164.                 '-u',
  165.                 'your_db_user'// Replace with your DB username
  166.                 '-p' 'your_db_password'// Replace with your DB password
  167.                 'your_db_name'// Replace with your database name
  168.                 '<',
  169.                 $filePath
  170.             ]);
  171.             $process->run();
  172.             if (!$process->isSuccessful()) {
  173.                 return new Response('Database import failed: ' $process->getErrorOutput(), Response::HTTP_INTERNAL_SERVER_ERROR);
  174.             }
  175.             return new Response('Database imported successfully!');
  176.         }
  177.         return new Response('Invalid file or file not uploaded'Response::HTTP_BAD_REQUEST);
  178.     }
  179.     public function prePopulateDatabaseAction(Request $request)
  180.     {
  181.         $em $this->getDoctrine()->getManager();
  182.         System::prePopulateDatabase($em);
  183.         return new JsonResponse(array(
  184.             'success' => true,
  185.         ));
  186.     }
  187.     public function selectDataAjaxAccHeadAction(Request $request$queryStr '',
  188.                                                  $version 'latest',
  189.                                                  $identifier '_default_',
  190.                                                  $apiKey '_ignore_'
  191.     )
  192.     {
  193.         $em $this->getDoctrine()->getManager();
  194.         $em_goc $this->getDoctrine()->getManager('company_group');
  195.         $companyId 0;
  196.         $skipCurrentUserIdRestriction $request->get('skipCurrentUserIdRestriction'0);
  197.         $dataOnly $request->get('dataOnly'0);
  198.         $skipCurrentEmployeeIdRestriction $request->get('skipCurrentEmployeeIdRestriction'0);
  199.         $skipCurrentUserLoginIdRestriction $request->get('skipCurrentUserLoginIdRestriction'0);
  200.         $currentUserId $request->getSession()->get(UserConstants::USER_ID0);
  201.         $currentEmployeeId $request->getSession()->get(UserConstants::USER_EMPLOYEE_ID0);
  202.         $currentUserLoginIds = [];
  203.         if ($request->request->get('entity_group'0)) {
  204.             $companyId 0;
  205.             $em $this->getDoctrine()->getManager('company_group');
  206.         } else {
  207.             if ($request->request->get('appId'0) != 0) {
  208.                 $gocEnabled 0;
  209.                 if ($this->container->hasParameter('entity_group_enabled'))
  210.                     $gocEnabled $this->container->getParameter('entity_group_enabled');
  211.                 else
  212.                     $gocEnabled 1;
  213.                 if ($gocEnabled == 1) {
  214.                     $dataToConnect System::changeDoctrineManagerByAppId(
  215.                         $this->getDoctrine()->getManager('company_group'),
  216.                         $gocEnabled,
  217.                         $request->request->get('appId'0)
  218.                     );
  219.                     if (!empty($dataToConnect)) {
  220.                         $connector $this->container->get('application_connector');
  221.                         $connector->resetConnection(
  222.                             'default',
  223.                             $dataToConnect['dbName'],
  224.                             $dataToConnect['dbUser'],
  225.                             $dataToConnect['dbPass'],
  226.                             $dataToConnect['dbHost'],
  227.                             $reset true
  228.                         );
  229.                         $em $this->getDoctrine()->getManager();
  230.                     }
  231.                 }
  232.             } else if ($request->getSession()->get(UserConstants::USER_APP_ID) != && $request->getSession()->get(UserConstants::USER_APP_ID) != null) {
  233.                 $gocEnabled 0;
  234.                 if ($this->container->hasParameter('entity_group_enabled'))
  235.                     $gocEnabled $this->container->getParameter('entity_group_enabled');
  236.                 else
  237.                     $gocEnabled 1;
  238.                 if ($gocEnabled == 1) {
  239.                     $dataToConnect System::changeDoctrineManagerByAppId(
  240.                         $this->getDoctrine()->getManager('company_group'),
  241.                         $gocEnabled,
  242.                         $request->getSession()->get(UserConstants::USER_APP_ID)
  243.                     );
  244.                     if (!empty($dataToConnect)) {
  245.                         $connector $this->container->get('application_connector');
  246.                         $connector->resetConnection(
  247.                             'default',
  248.                             $dataToConnect['dbName'],
  249.                             $dataToConnect['dbUser'],
  250.                             $dataToConnect['dbPass'],
  251.                             $dataToConnect['dbHost'],
  252.                             $reset true
  253.                         );
  254.                         $em $this->getDoctrine()->getManager();
  255.                     }
  256.                 }
  257.             }
  258.             $companyId $this->getLoggedUserCompanyId($request);
  259.         }
  260.         $configData = [];
  261.         $isSingleDataset 1;
  262.         $dataSet $request->request->has('dataset') ? $request->request->get('dataset') : [];
  263.         if (is_string($dataSet)) $dataSet json_decode($dataSettrue);
  264.         $valuePairs $request->get('valuePairs', []);
  265.         if (is_string($valuePairs)) $valuePairs json_decode($valuePairstrue);
  266.         $allResult = [];
  267.         $datasetFromConfig = [];
  268.         if ($identifier != '_default_') {
  269.             $config_file $this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' $identifier 'Config.json';
  270.             if (!file_exists($config_file)) {
  271.             } else {
  272.                 $fileText file_get_contents($config_file);
  273.                 //now replace any value pairs
  274.                 foreach ($valuePairs as $kkeeyy => $vvaalluuee) {
  275.                     if (is_array($vvaalluuee)) {
  276.                         if (isset($vvaalluuee['value']) && isset($vvaalluuee['type'])) {
  277.                             if ($vvaalluuee['type'] == 'array'$fileText str_ireplace('_' $kkeeyy '_'json_encode($vvaalluuee['value']), $fileText);
  278.                             if ($vvaalluuee['type'] == 'value'$fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee['value'], $fileText);
  279.                             if ($vvaalluuee['type'] == 'text'$fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee['value'], $fileText);
  280.                         } else {
  281.                             $fileText str_ireplace('_' $kkeeyy '_'json_encode($vvaalluuee), $fileText);
  282.                         }
  283.                     }
  284.                     $fileText str_ireplace('_' $kkeeyy '_'$vvaalluuee$fileText);
  285.                 }
  286.                 $fileText str_ireplace('_query_'$request->get('query'$queryStr), $fileText);
  287.                 $fileText str_ireplace('_itemLimit_'$request->get('itemLimit''_all_'), $fileText);
  288.                 $fileText str_ireplace('_offset_'$request->get('offset', ($request->get('itemLimit'10))*($request->get('page'1)-1)), $fileText);
  289.                 if (!(strpos($fileText'_CURRENT_USER_LOGIN_IDS_') === false) && $skipCurrentUserLoginIdRestriction == 0) {
  290.                     $userInfo = [];
  291.                     if ($request->getSession()->get(UserConstants::USER_TYPE0) == UserConstants::USER_TYPE_APPLICANT) {
  292.                         $userInfo $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityLoginLog')->findBy(
  293.                             array('userId' => $currentUserId)
  294.                         );
  295.                     } else {
  296.                         $userInfo $em->getRepository('ApplicationBundle\\Entity\\SysLoginLog')->findBy(
  297.                             array('userId' => $currentUserId)
  298.                         );
  299.                     }
  300.                     foreach ($userInfo as $uLogininfo) {
  301.                         $currentUserLoginIds[] = $uLogininfo->getLoginId();
  302.                     }
  303.                     $fileText str_ireplace('_CURRENT_USER_LOGIN_IDS_'json_encode($currentUserLoginIds), $fileText);
  304.                 } else {
  305.                     $fileText str_ireplace('_CURRENT_USER_LOGIN_IDS_''_EMPTY_'$fileText);
  306.                 }
  307.                 if (!(strpos($fileText'_CURRENT_USER_ID_') === false) && $skipCurrentUserIdRestriction == 0) {
  308.                     $fileText str_ireplace('_CURRENT_USER_ID_'$currentUserId$fileText);
  309.                 } else {
  310.                     $fileText str_ireplace('_CURRENT_USER_ID_''_EMPTY_'$fileText);
  311.                 }
  312.                 if (!(strpos($fileText'_CURRENT_USER_EMPLOYEE_ID_') === false) && $skipCurrentEmployeeIdRestriction == 0) {
  313.                     if ((strpos($fileText'skipCurrentEmployeeIdRestriction') === false)) {
  314.                         $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_'$currentEmployeeId$fileText);
  315.                     } else {
  316.                         $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_''_EMPTY_'$fileText);
  317.                     }
  318.                 } else {
  319.                     $fileText str_ireplace('_CURRENT_USER_EMPLOYEE_ID_''_EMPTY_'$fileText);
  320.                 }
  321.                 if ($fileText)
  322.                     $datasetFromConfig json_decode($fileTexttrue);
  323.                 $skipCurrentUserIdRestriction = isset($datasetFromConfig['skipCurrentUserIdRestriction']) ? $datasetFromConfig['skipCurrentUserIdRestriction'] : $skipCurrentUserIdRestriction;
  324.                 $skipCurrentEmployeeIdRestriction = isset($datasetFromConfig['skipCurrentEmployeeIdRestriction']) ? $datasetFromConfig['skipCurrentEmployeeIdRestriction'] : $skipCurrentEmployeeIdRestriction;
  325.                 $skipCurrentUserLoginIdRestriction = isset($datasetFromConfig['skipCurrentUserLoginIdRestriction']) ? $datasetFromConfig['skipCurrentUserLoginIdRestriction'] : $skipCurrentUserLoginIdRestriction;
  326.             }
  327.         }
  328.         if ($dataSet == null$dataSet = [];
  329. //        return new JsonResponse(array(
  330. //            'queryStr'=>$queryStr
  331. //        ));
  332.         if (!empty($datasetFromConfig)) {
  333.             if (isset($datasetFromConfig['tableName'])) {
  334.                 $isSingleDataset 1;
  335.                 $dataSet[] = $datasetFromConfig;
  336.             } else {
  337.                 if (count($datasetFromConfig) == 1)
  338.                     $isSingleDataset 1;
  339.                 $dataSet $datasetFromConfig;
  340.             }
  341.         }
  342.         if (empty($dataSet)) {
  343.             $isSingleDataset 1;
  344.             $singleDataSet = array(
  345.                 "valueField" => $request->request->has('valueField') ? $request->request->get('valueField') : 'id',
  346.                 "query" => $request->get('query'$queryStr),
  347.                 "headMarkers" => $request->get('headMarkers'''),
  348.                 "headMarkersStrictMatch" => $request->get('headMarkersStrictMatch'0),
  349.                 "itemLimit" => $request->request->has('itemLimit') ? $request->request->get('itemLimit') : 25,
  350.                 "selectorId" => $request->request->has('selectorId') ? $request->request->get('selectorId') : '_NONE_',
  351.                 "textField" => $request->request->has('textField') ? $request->request->get('textField') : 'name',
  352.                 "tableName" => $request->request->has('tableName') ? $request->request->get('tableName') : '',
  353.                 "isMultiple" => $request->request->has('isMultiple') ? $request->request->get('isMultiple') : 0,
  354.                 "orConditions" => $request->request->has('orConditions') ? $request->request->get('orConditions') : [],
  355.                 "andConditions" => $request->request->has('andConditions') ? $request->request->get('andConditions') : [],
  356.                 "andOrConditions" => $request->request->has('andOrConditions') ? $request->request->get('andOrConditions') : [],
  357.                 "mustConditions" => $request->request->has('mustConditions') ? $request->request->get('mustConditions') : [],
  358.                 "joinTableData" => $request->request->has('joinTableData') ? $request->request->get('joinTableData') : [],
  359.                 "renderTextFormat" => $request->request->has('renderTextFormat') ? $request->request->get('renderTextFormat') : '',
  360.                 "setDataForSingle" => $request->request->has('setDataForSingle') ? $request->request->get('setDataForSingle') : 0,
  361.                 "dataId" => $request->request->has('dataId') ? $request->request->get('dataId') : 0,
  362.                 "lastChildrenOnly" => $request->request->has('lastChildrenOnly') ? $request->request->get('lastChildrenOnly') : 0,
  363.                 "parentOnly" => $request->request->has('parentOnly') ? $request->request->get('parentOnly') : 0,
  364.                 "parentIdField" => $request->request->has('parentIdField') ? $request->request->get('parentIdField') : 'parent_id',
  365.                 "skipDefaultCompanyId" => $request->request->has('skipDefaultCompanyId') ? $request->request->get('skipDefaultCompanyId') : 1,
  366.                 "offset" => $request->request->has('offset') ? $request->request->get('offset') : 0,
  367.                 "returnTotalMatchedEntriesFlag" => $request->request->has('returnTotalMatched') ? $request->request->get('returnTotalMatched') : 0,
  368.                 "nextOffset" => 0,
  369.                 "totalMatchedEntries" => 0,
  370.                 "convertToObject" => $request->request->has('convertToObject') ? $request->request->get('convertToObject') : [],
  371.                 "convertDateToStringFieldList" => $request->request->has('convertDateToStringFieldList') ? $request->request->get('convertDateToStringFieldList') : [],
  372.                 "orderByConditions" => $request->request->has('orderByConditions') ? $request->request->get('orderByConditions') : [],
  373.                 "convertToUrl" => $request->request->has('convertToUrl') ? $request->request->get('convertToUrl') : [],
  374.                 "fullPathList" => $request->request->has('fullPathList') ? $request->request->get('fullPathList') : [],
  375.                 "ret_data" => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  376.             );
  377.             $dataSet[] = $singleDataSet;
  378.         }
  379. //        $lastResult = [
  380. //            'identifier' => $identifier,
  381. //            'dataSet' => $dataSet,
  382. //        ];
  383. //        return new JsonResponse($lastResult);
  384.         $userId $request->getSession()->get(UserConstants::USER_ID);
  385. //        public static function selectDataSystem($em, $queryStr = '_EMPTY_', $data = [],$userId=0)
  386.         foreach ($dataSet as $dsIndex => $dataConfig) {
  387.             $companyId 0;
  388.             $queryStringIndividual $queryStr;
  389.             $data = [];
  390.             $data_by_id = [];
  391.             $setValueArray = [];
  392.             $silentChangeSelectize 0;
  393.             $setValue 0;
  394.             $setValueType 0;// 0 for id , 1 for query
  395.             $selectAll 0;
  396.             if ($queryStringIndividual == '_EMPTY_')
  397.                 $queryStringIndividual '';
  398.             if (isset($dataConfig['query']))
  399.                 $queryStringIndividual $dataConfig['query'];
  400.             if ($queryStringIndividual == '_EMPTY_')
  401.                 $queryStringIndividual '';
  402.             $queryStringIndividual str_replace('_FSLASH_''/'$queryStringIndividual);
  403.             if ($queryStringIndividual === '#setValue:') {
  404.                 $queryStringIndividual '';
  405.             }
  406.             if (!(strpos($queryStringIndividual'_silent_change_') === false)) {
  407.                 $silentChangeSelectize 1;
  408.                 $queryStringIndividual str_ireplace('_silent_change_'''$queryStringIndividual);
  409.             }
  410.             if (!(strpos($queryStringIndividual'#setValue:') === false)) {
  411.                 $setValueArrayBeforeFilter explode(','str_replace('#setValue:'''$queryStringIndividual));
  412.                 foreach ($setValueArrayBeforeFilter as $svf) {
  413.                     if ($svf == '_ALL_') {
  414.                         $selectAll 1;
  415.                         $setValueArray = [];
  416.                         continue;
  417.                     }
  418.                     if (is_numeric($svf)) {
  419.                         $setValueArray[] = ($svf 1);
  420.                         $setValue $svf 1;
  421.                     }
  422.                 }
  423.                 $queryStringIndividual '';
  424.             }
  425.             $valueField = isset($dataConfig['valueField']) ? $dataConfig['valueField'] : 'id';
  426.             $headMarkers = isset($dataConfig['headMarkers']) ? $dataConfig['headMarkers'] : ''//Special Field
  427.             $headMarkersStrictMatch = isset($dataConfig['headMarkersStrictMatch']) ? $dataConfig['headMarkersStrictMatch'] : 0//Special Field
  428.             $itemLimit = isset($dataConfig['itemLimit']) ? $dataConfig['itemLimit'] : 25;
  429.             $selectorId = isset($dataConfig['selectorId']) ? $dataConfig['selectorId'] : '_NONE_';
  430.             $textField = isset($dataConfig['textField']) ? $dataConfig['textField'] : 'name';
  431.             $table = isset($dataConfig['tableName']) ? $dataConfig['tableName'] : '';
  432.             $isMultiple = isset($dataConfig['isMultiple']) ? $dataConfig['isMultiple'] : 0;
  433.             $orConditions = isset($dataConfig['orConditions']) ? $dataConfig['orConditions'] : [];
  434.             $andConditions = isset($dataConfig['andConditions']) ? $dataConfig['andConditions'] : [];
  435.             $andOrConditions = isset($dataConfig['andOrConditions']) ? $dataConfig['andOrConditions'] : [];
  436.             $mustConditions = isset($dataConfig['mustConditions']) ? $dataConfig['mustConditions'] : [];
  437.             $joinTableData = isset($dataConfig['joinTableData']) ? $dataConfig['joinTableData'] : [];
  438.             $renderTextFormat = isset($dataConfig['renderTextFormat']) ? $dataConfig['renderTextFormat'] : '';
  439.             $setDataForSingle = isset($dataConfig['setDataForSingle']) ? $dataConfig['setDataForSingle'] : 0;
  440.             $dataId = isset($dataConfig['dataId']) ? $dataConfig['dataId'] : 0;
  441.             $lastChildrenOnly = isset($dataConfig['lastChildrenOnly']) ? $dataConfig['lastChildrenOnly'] : 0;
  442.             $parentOnly = isset($dataConfig['parentOnly']) ? $dataConfig['parentOnly'] : 0;
  443.             $parentIdField = isset($dataConfig['parentIdField']) ? $dataConfig['parentIdField'] : 'parent_id';
  444.             $skipDefaultCompanyId = isset($dataConfig['skipDefaultCompanyId']) ? $dataConfig['skipDefaultCompanyId'] : 1;
  445.             $offset = isset($dataConfig['offset']) ? $dataConfig['offset'] : 0;
  446.             $returnTotalMatchedEntriesFlag = isset($dataConfig['returnTotalMatched']) ? $dataConfig['returnTotalMatched'] : 0;
  447.             $nextOffset 0;
  448.             $totalMatchedEntries 0;
  449.             $convertToObjectFieldList = isset($dataConfig['convertToObject']) ? $dataConfig['convertToObject'] : [];
  450.             $convertDateToStringFieldList = isset($dataConfig['convertDateToStringFieldList']) ? $dataConfig['convertDateToStringFieldList'] : [];
  451.             $orderByConditions = isset($dataConfig['orderByConditions']) ? $dataConfig['orderByConditions'] : [];
  452.             $convertToUrl = isset($dataConfig['convertToUrl']) ? $dataConfig['convertToUrl'] : [];
  453.             $fullPathList = isset($dataConfig['fullPathList']) ? $dataConfig['fullPathList'] : [];
  454.             if (is_string($andConditions)) $andConditions json_decode($andConditionstrue);
  455.             if (is_string($orConditions)) $orConditions json_decode($orConditionstrue);
  456.             if (is_string($andOrConditions)) $andOrConditions json_decode($andOrConditionstrue);
  457.             if (is_string($mustConditions)) $mustConditions json_decode($mustConditionstrue);
  458.             if (is_string($joinTableData)) $joinTableData json_decode($joinTableDatatrue);
  459.             if (is_string($convertToObjectFieldList)) $convertToObjectFieldList json_decode($convertToObjectFieldListtrue);
  460.             if (is_string($orderByConditions)) $orderByConditions json_decode($orderByConditionstrue);
  461.             if (is_string($convertToUrl)) $convertToUrl json_decode($convertToUrltrue);
  462.             if (is_string($fullPathList)) $fullPathList json_decode($fullPathListtrue);
  463. //            return new JsonResponse(array(
  464. //                'dataSet'=>$dataSet,
  465. //                'dataConfig'=>$dataConfig,
  466. //                'hi'=>$this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json',
  467. //                'hiD'=>file_get_contents($this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json')
  468. //            ));
  469.             if ($table == '') {
  470.                 $lastResult = array(
  471.                     'success' => false,
  472.                     'currentTs' => (new \Datetime())->format('U'),
  473.                     'isMultiple' => $isMultiple,
  474.                     'setValueArray' => $setValueArray,
  475.                     'setValue' => $setValue,
  476.                     'data' => $data,
  477.                     'dataId' => $dataId,
  478.                     'selectorId' => $selectorId,
  479.                     'dataById' => $data_by_id,
  480.                     'selectedId' => 0,
  481.                     'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  482.                 );
  483.             } else {
  484.                 $restrictionData = array(
  485. //            'table'=>'relevantField in restriction'
  486.                     'warehouse_action' => 'warehouseActionIds',
  487.                     'branch' => 'branchIds',
  488.                     'warehouse' => 'warehouseIds',
  489.                     'production_process_settings' => 'productionProcessIds',
  490.                 );
  491.                 $restrictionIdList = [];
  492.                 $filterQryForCriteria "select ";
  493.                 $selectQry "";
  494. //        $selectQry=" `$table`.* ";
  495.                 $selectFieldList = isset($dataConfig['selectFieldList']) ? $dataConfig['selectFieldList'] : ['*'];
  496.                 $selectPrefix = isset($dataConfig['selectPrefix']) ? $dataConfig['selectPrefix'] : '';
  497.                 if (is_string($selectFieldList)) $selectFieldList json_decode($selectFieldListtrue);
  498.                 foreach ($selectFieldList as $selField) {
  499.                     if ($selectQry != '')
  500.                         $selectQry .= ", ";
  501.                     if ($selField == '*')
  502.                         $selectQry .= " `$table`.$selField ";
  503.                     else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  504.                         if ($selectPrefix == '')
  505.                             $selectQry .= " count(*)  ";
  506.                         else
  507.                             $selectQry .= (" count(*  )  $selectPrefix"_RESULT_COUNT_ ");
  508.                     } else {
  509.                         if ($selectPrefix == '')
  510.                             $selectQry .= " `$table`.`$selField` ";
  511.                         else
  512.                             $selectQry .= (" `$table`.`$selField`  $selectPrefix"$selField ");
  513.                     }
  514.                 }
  515.                 $joinQry " from $table ";
  516. //        $filterQryForCriteria = "select * from $table ";
  517.                 $joinMustString '';
  518.                 $joinOrString '';
  519.                 $joinAndString '';
  520.                 $joinAndOrString '';
  521.                 foreach ($joinTableData as $joinIndex => $joinTableDatum) {
  522. //            $conditionStr.=' 1=1 ';
  523.                     $joinTableName = isset($joinTableDatum['tableName']) ? $joinTableDatum['tableName'] : '=';
  524.                     $joinTableAlias $joinTableName '_' $joinIndex;
  525.                     $joinTablePrimaryField = isset($joinTableDatum['joinFieldPrimary']) ? $joinTableDatum['joinFieldPrimary'] : ''//field of main table
  526.                     $joinTableOnField = isset($joinTableDatum['joinOn']) ? $joinTableDatum['joinOn'] : ''//field of joining table
  527.                     $fieldJoinType = isset($joinTableDatum['fieldJoinType']) ? $joinTableDatum['fieldJoinType'] : '=';
  528.                     $tableJoinType = isset($joinTableDatum['tableJoinType']) ? $joinTableDatum['tableJoinType'] : 'join';//or inner join
  529.                     $selectFieldList = isset($joinTableDatum['selectFieldList']) ? $joinTableDatum['selectFieldList'] : ['*'];
  530.                     $selectPrefix = isset($joinTableDatum['selectPrefix']) ? $joinTableDatum['selectPrefix'] : '';
  531.                     $joinMustConditions = isset($joinTableDatum['joinMustConditions']) ? $joinTableDatum['joinMustConditions'] : [];
  532.                     $joinAndConditions = isset($joinTableDatum['joinAndConditions']) ? $joinTableDatum['joinAndConditions'] : [];
  533.                     $joinAndOrConditions = isset($joinTableDatum['joinAndOrConditions']) ? $joinTableDatum['joinAndOrConditions'] : [];
  534.                     $joinOrConditions = isset($joinTableDatum['joinOrConditions']) ? $joinTableDatum['joinOrConditions'] : [];
  535.                     if (is_string($joinAndConditions)) $joinAndConditions json_decode($joinAndConditionstrue);
  536.                     if (is_string($joinMustConditions)) $joinMustConditions json_decode($joinMustConditionstrue);
  537.                     if (is_string($joinAndOrConditions)) $joinAndOrConditions json_decode($joinAndOrConditionstrue);
  538.                     if (is_string($joinOrConditions)) $joinOrConditions json_decode($joinOrConditionstrue);
  539.                     foreach ($selectFieldList as $selField) {
  540.                         if ($selField == '*')
  541.                             $selectQry .= ", `$joinTableAlias`.$selField ";
  542.                         else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  543.                             if ($selectPrefix == '')
  544.                                 $selectQry .= ", count(`$joinTableAlias`." $joinTableOnField ")  ";
  545.                             else
  546.                                 $selectQry .= (", count(`$joinTableAlias`." $joinTableOnField ")  $selectPrefix"_RESULT_COUNT_ ");
  547.                         } else {
  548.                             if ($selectPrefix == '')
  549.                                 $selectQry .= ", `$joinTableAlias`.`$selField`  ";
  550.                             else
  551.                                 $selectQry .= (", `$joinTableAlias`.`$selField`  $selectPrefix"$selField ");
  552.                         }
  553.                     }
  554.                     $joinQry .= $tableJoinType $joinTableName $joinTableAlias on  ";
  555. //            if($joinTablePrimaryField!='')
  556. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  557. //            $joinAndString = '';
  558.                     $joinMustString '';
  559.                     if ($joinTablePrimaryField != '')
  560.                         $joinQry .= "  `$joinTableAlias`.`$joinTableOnField$fieldJoinType `$table`.`$joinTablePrimaryField` ";
  561.                     foreach ($joinMustConditions as $mustCondition) {
  562. //            $conditionStr.=' 1=1 ';
  563.                         $ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
  564.                         $cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
  565.                         $aliasInCondition $table;
  566.                         if (!(strpos($cfield'.') === false)) {
  567.                             $fullCfieldArray explode('.'$cfield);
  568.                             $aliasInCondition $fullCfieldArray[0];
  569.                             $cfield $fullCfieldArray[1];
  570.                         }
  571.                         $cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStringIndividual;
  572.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  573.                             if ($joinMustString != '')
  574.                                 $joinMustString .= " and ";
  575.                             if ($ctype == 'like') {
  576.                                 $joinMustString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  577.                                 $wordsBySpaces explode(' '$cvalue);
  578.                                 foreach ($wordsBySpaces as $word) {
  579.                                     if ($joinMustString != '')
  580.                                         $joinMustString .= " and ";
  581.                                     $joinMustString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  582.                                 }
  583.                             } else if ($ctype == 'not like') {
  584.                                 $joinMustString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  585.                                 $wordsBySpaces explode(' '$cvalue);
  586.                                 foreach ($wordsBySpaces as $word) {
  587.                                     if ($joinMustString != '')
  588.                                         $joinMustString .= " and ";
  589.                                     $joinMustString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  590.                                 }
  591.                             } else if ($ctype == 'not_in') {
  592.                                 $joinMustString .= " ( ";
  593.                                 if (in_array('null'$cvalue)) {
  594.                                     $joinMustString .= " `$joinTableAlias`.$cfield is not null";
  595.                                     $cvalue array_diff($cvalue, ['null']);
  596.                                     if (!empty($cvalue))
  597.                                         $joinMustString .= " and ";
  598.                                 }
  599.                                 if (in_array(''$cvalue)) {
  600.                                     $joinMustString .= "`$joinTableAlias`.$cfield != '' ";
  601.                                     $cvalue array_diff($cvalue, ['']);
  602.                                     if (!empty($cvalue))
  603.                                         $joinMustString .= " and ";
  604.                                 }
  605.                                 $joinMustString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  606.                             } else if ($ctype == 'in') {
  607.                                 if (in_array('null'$cvalue)) {
  608.                                     $joinMustString .= "`$joinTableAlias`.$cfield is null";
  609.                                     $cvalue array_diff($cvalue, ['null']);
  610.                                     if (!empty($cvalue))
  611.                                         $joinMustString .= " and ";
  612.                                 }
  613.                                 if (in_array(''$cvalue)) {
  614.                                     $joinMustString .= "`$joinTableAlias`.$cfield = '' ";
  615.                                     $cvalue array_diff($cvalue, ['']);
  616.                                     if (!empty($cvalue))
  617.                                         $joinMustString .= " and ";
  618.                                 }
  619.                                 $joinMustString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  620.                             } else if ($ctype == '=') {
  621. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  622. //                            $fullCfieldArray = explode('.', $cfield);
  623. //                            $aliasInCondition = $fullCfieldArray[0];
  624. //                            $cfield = $fullCfieldArray[1];
  625. //                        }
  626.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  627.                                     $joinMustString .= "`$joinTableAlias`.$cfield is null ";
  628.                                 else
  629.                                     $joinMustString .= "`$joinTableAlias`.$cfield = $cvalue ";
  630.                             } else if ($ctype == '!=') {
  631.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  632.                                     $joinMustString .= "`$joinTableAlias`.$cfield is not null ";
  633.                                 else
  634.                                     $joinMustString .= "`$joinTableAlias`.$cfield != $cvalue ";
  635.                             } else {
  636.                                 if (is_string($cvalue))
  637.                                     $joinMustString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  638.                                 else
  639.                                     $joinMustString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  640.                             }
  641.                         }
  642.                     }
  643. //            if ($joinMustString != '') {
  644. //                if ($conditionStr != '')
  645. //                    $conditionStr .= (" and (" . $joinMustString . ") ");
  646. //                else
  647. //                    $conditionStr .= ("  (" . $joinMustString . ") ");
  648. //            }
  649. //                    if ($joinMustString != '') {
  650. //                        $joinQry .= (' and ' . $joinMustString);
  651. ////                        $joinQry.=' and (';
  652. //                    }
  653.                     $mustBracketDone 0;
  654. //                    if ($joinTablePrimaryField != '')
  655. //                        $joinAndString .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  656.                     foreach ($joinAndConditions as $andCondition) {
  657. //            $conditionStr.=' 1=1 ';
  658.                         $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  659.                         $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  660.                         $aliasInCondition $table;
  661.                         if (!(strpos($cfield'.') === false)) {
  662.                             $fullCfieldArray explode('.'$cfield);
  663.                             $aliasInCondition $fullCfieldArray[0];
  664.                             $cfield $fullCfieldArray[1];
  665.                         }
  666.                         $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStringIndividual;
  667.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  668.                             if ($joinAndString != '')
  669.                                 $joinAndString .= " and ";
  670.                             if ($ctype == 'like') {
  671.                                 $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  672.                                 $wordsBySpaces explode(' '$cvalue);
  673.                                 foreach ($wordsBySpaces as $word) {
  674.                                     if ($joinAndString != '')
  675.                                         $joinAndString .= " and ";
  676.                                     $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  677.                                 }
  678.                             } else if ($ctype == 'not like') {
  679.                                 $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  680.                                 $wordsBySpaces explode(' '$cvalue);
  681.                                 foreach ($wordsBySpaces as $word) {
  682.                                     if ($joinAndString != '')
  683.                                         $joinAndString .= " and ";
  684.                                     $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  685.                                 }
  686.                             } else if ($ctype == 'not_in') {
  687.                                 $joinAndString .= " ( ";
  688.                                 if (in_array('null'$cvalue)) {
  689.                                     $joinAndString .= " `$joinTableAlias`.$cfield is not null";
  690.                                     $cvalue array_diff($cvalue, ['null']);
  691.                                     if (!empty($cvalue))
  692.                                         $joinAndString .= " and ";
  693.                                 }
  694.                                 if (in_array(''$cvalue)) {
  695.                                     $joinAndString .= "`$joinTableAlias`.$cfield != '' ";
  696.                                     $cvalue array_diff($cvalue, ['']);
  697.                                     if (!empty($cvalue))
  698.                                         $joinAndString .= " and ";
  699.                                 }
  700.                                 $joinAndString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  701.                             } else if ($ctype == 'in') {
  702.                                 if (in_array('null'$cvalue)) {
  703.                                     $joinAndString .= "`$joinTableAlias`.$cfield is null";
  704.                                     $cvalue array_diff($cvalue, ['null']);
  705.                                     if (!empty($cvalue))
  706.                                         $joinAndString .= " and ";
  707.                                 }
  708.                                 if (in_array(''$cvalue)) {
  709.                                     $joinAndString .= "`$joinTableAlias`.$cfield = '' ";
  710.                                     $cvalue array_diff($cvalue, ['']);
  711.                                     if (!empty($cvalue))
  712.                                         $joinAndString .= " and ";
  713.                                 }
  714.                                 $joinAndString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  715.                             } else if ($ctype == '=') {
  716. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  717. //                            $fullCfieldArray = explode('.', $cfield);
  718. //                            $aliasInCondition = $fullCfieldArray[0];
  719. //                            $cfield = $fullCfieldArray[1];
  720. //                        }
  721.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  722.                                     $joinAndString .= "`$joinTableAlias`.$cfield is null ";
  723.                                 else
  724.                                     $joinAndString .= "`$joinTableAlias`.$cfield = $cvalue ";
  725.                             } else if ($ctype == '!=') {
  726.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  727.                                     $joinAndString .= "`$joinTableAlias`.$cfield is not null ";
  728.                                 else
  729.                                     $joinAndString .= "`$joinTableAlias`.$cfield != $cvalue ";
  730.                             } else {
  731.                                 if (is_string($cvalue))
  732.                                     $joinAndString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  733.                                 else
  734.                                     $joinAndString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  735.                             }
  736.                         }
  737.                     }
  738. //            if ($joinAndString != '') {
  739. //                if ($conditionStr != '')
  740. //                    $conditionStr .= (" and (" . $joinAndString . ") ");
  741. //                else
  742. //                    $conditionStr .= ("  (" . $joinAndString . ") ");
  743. //            }
  744. //                    if ($joinAndString != '') {
  745. //                        if ($joinMustString != '' && $mustBracketDone == 0) {
  746. //                            $joinQry .= ' and (';
  747. //                            $mustBracketDone = 1;
  748. //                        }
  749. //
  750. //
  751. //                        if ($joinQry != '')
  752. //                            $joinQry .= (" and (" . $joinAndString . ") ");
  753. //                        else
  754. //                            $joinQry .= ("  (" . $joinAndString . ") ");
  755. //
  756. //                    }
  757.                     foreach ($joinAndOrConditions as $andOrCondition) {
  758. //            $conditionStr.=' 1=1 ';
  759.                         $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  760.                         $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  761.                         $aliasInCondition $table;
  762.                         if (!(strpos($cfield'.') === false)) {
  763.                             $fullCfieldArray explode('.'$cfield);
  764.                             $aliasInCondition $fullCfieldArray[0];
  765.                             $cfield $fullCfieldArray[1];
  766.                         }
  767.                         $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStringIndividual;
  768.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  769.                             if ($joinAndOrString != '')
  770.                                 $joinAndOrString .= " or ";
  771.                             if ($ctype == 'like') {
  772.                                 $joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  773.                                 $wordsBySpaces explode(' '$cvalue);
  774.                                 foreach ($wordsBySpaces as $word) {
  775.                                     if ($joinAndOrString != '')
  776.                                         $joinAndOrString .= " or ";
  777.                                     $joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  778.                                 }
  779.                             } else if ($ctype == 'not like') {
  780.                                 $joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  781.                                 $wordsBySpaces explode(' '$cvalue);
  782.                                 foreach ($wordsBySpaces as $word) {
  783.                                     if ($joinAndOrString != '')
  784.                                         $joinAndOrString .= " or ";
  785.                                     $joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  786.                                 }
  787.                             } else if ($ctype == 'not_in') {
  788.                                 $joinAndOrString .= " ( ";
  789.                                 if (in_array('null'$cvalue)) {
  790.                                     $joinAndOrString .= " `$joinTableAlias`.$cfield is not null";
  791.                                     $cvalue array_diff($cvalue, ['null']);
  792.                                     if (!empty($cvalue))
  793.                                         $joinAndOrString .= " or ";
  794.                                 }
  795.                                 if (in_array(''$cvalue)) {
  796.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield != '' ";
  797.                                     $cvalue array_diff($cvalue, ['']);
  798.                                     if (!empty($cvalue))
  799.                                         $joinAndOrString .= " or ";
  800.                                 }
  801.                                 $joinAndOrString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  802.                             } else if ($ctype == 'in') {
  803.                                 if (in_array('null'$cvalue)) {
  804.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is null";
  805.                                     $cvalue array_diff($cvalue, ['null']);
  806.                                     if (!empty($cvalue))
  807.                                         $joinAndOrString .= " or ";
  808.                                 }
  809.                                 if (in_array(''$cvalue)) {
  810.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield = '' ";
  811.                                     $cvalue array_diff($cvalue, ['']);
  812.                                     if (!empty($cvalue))
  813.                                         $joinAndOrString .= " or ";
  814.                                 }
  815.                                 $joinAndOrString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  816.                             } else if ($ctype == '=') {
  817. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  818. //                            $fullCfieldArray = explode('.', $cfield);
  819. //                            $aliasInCondition = $fullCfieldArray[0];
  820. //                            $cfield = $fullCfieldArray[1];
  821. //                        }
  822.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  823.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is null ";
  824.                                 else
  825.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
  826.                             } else if ($ctype == '!=') {
  827.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  828.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield is not null ";
  829.                                 else
  830.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
  831.                             } else {
  832.                                 if (is_string($cvalue))
  833.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  834.                                 else
  835.                                     $joinAndOrString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  836.                             }
  837.                         }
  838.                     }
  839. //            if ($joinAndOrString != '')
  840. //                $joinQry .= $joinAndOrString;
  841. //                    if ($joinAndOrString != '') {
  842. //                        if ($joinMustString != '' && $mustBracketDone == 0) {
  843. //                            $joinQry .= ' and (';
  844. //                            $mustBracketDone = 1;
  845. //                        }
  846. //
  847. //
  848. //                        if ($joinQry != '')
  849. //                            $joinQry .= (" and (" . $joinAndOrString . ") ");
  850. //                        else
  851. //                            $joinQry .= ("  (" . $joinAndOrString . ") ");
  852. //                    }
  853.                     //pika
  854. //                    $joinOrString = "";
  855.                     foreach ($joinOrConditions as $orCondition) {
  856. //            $conditionStr.=' 1=1 ';
  857.                         $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  858.                         $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  859.                         $aliasInCondition $table;
  860.                         if (!(strpos($cfield'.') === false)) {
  861.                             $fullCfieldArray explode('.'$cfield);
  862.                             $aliasInCondition $fullCfieldArray[0];
  863.                             $cfield $fullCfieldArray[1];
  864.                         }
  865.                         $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStringIndividual;
  866.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  867.                             if ($joinOrString != '' || $joinAndString != '' || $joinMustString != '')
  868.                                 $joinOrString .= " or ";
  869.                             if ($ctype == 'like') {
  870.                                 $joinOrString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  871.                                 $wordsBySpaces explode(' '$cvalue);
  872.                                 foreach ($wordsBySpaces as $word) {
  873.                                     if ($joinOrString != '')
  874.                                         $joinOrString .= " or ";
  875.                                     $joinOrString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  876.                                 }
  877.                             } else if ($ctype == 'not like') {
  878.                                 $joinOrString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  879.                                 $wordsBySpaces explode(' '$cvalue);
  880.                                 foreach ($wordsBySpaces as $word) {
  881.                                     if ($joinOrString != '')
  882.                                         $joinOrString .= " or ";
  883.                                     $joinOrString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  884.                                 }
  885.                             } else if ($ctype == 'not_in') {
  886.                                 $joinOrString .= " ( ";
  887.                                 if (in_array('null'$cvalue)) {
  888.                                     $joinOrString .= " `$joinTableAlias`.$cfield is not null";
  889.                                     $cvalue array_diff($cvalue, ['null']);
  890.                                     if (!empty($cvalue))
  891.                                         $joinOrString .= " or ";
  892.                                 }
  893.                                 if (in_array(''$cvalue)) {
  894.                                     $joinOrString .= "`$joinTableAlias`.$cfield != '' ";
  895.                                     $cvalue array_diff($cvalue, ['']);
  896.                                     if (!empty($cvalue))
  897.                                         $joinOrString .= " or ";
  898.                                 }
  899.                                 $joinOrString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  900.                             } else if ($ctype == 'in') {
  901.                                 if (in_array('null'$cvalue)) {
  902.                                     $joinOrString .= "`$joinTableAlias`.$cfield is null";
  903.                                     $cvalue array_diff($cvalue, ['null']);
  904.                                     if (!empty($cvalue))
  905.                                         $joinOrString .= " or ";
  906.                                 }
  907.                                 if (in_array(''$cvalue)) {
  908.                                     $joinOrString .= "`$joinTableAlias`.$cfield = '' ";
  909.                                     $cvalue array_diff($cvalue, ['']);
  910.                                     if (!empty($cvalue))
  911.                                         $joinOrString .= " or ";
  912.                                 }
  913.                                 $joinOrString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  914.                             } else if ($ctype == '=') {
  915. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  916. //                            $fullCfieldArray = explode('.', $cfield);
  917. //                            $aliasInCondition = $fullCfieldArray[0];
  918. //                            $cfield = $fullCfieldArray[1];
  919. //                        }
  920.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  921.                                     $joinOrString .= "`$joinTableAlias`.$cfield is null ";
  922.                                 else
  923.                                     $joinOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
  924.                             } else if ($ctype == '!=') {
  925.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  926.                                     $joinOrString .= "`$joinTableAlias`.$cfield is not null ";
  927.                                 else
  928.                                     $joinOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
  929.                             } else {
  930.                                 if (is_string($cvalue))
  931.                                     $joinOrString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  932.                                 else
  933.                                     $joinOrString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  934.                             }
  935.                         }
  936.                     }
  937. //            if ($joinOrString != '')
  938. //                $joinQry .= $joinOrString;
  939. //                    if ($joinOrString != '') {
  940. //                        if ($joinMustString != '' && $mustBracketDone == 0) {
  941. //                            $joinQry .= ' and (';
  942. //                            $mustBracketDone = 1;
  943. //                        }
  944. //                        if ($joinQry != '')
  945. //                            $joinQry .= (" or (" . $joinOrString . ") ");
  946. //                        else
  947. //                            $joinQry .= ("  (" . $joinOrString . ") ");
  948. //                    }
  949. //
  950. //                    if ($joinMustString != '' && $mustBracketDone == 1) {
  951. //                        $joinQry .= ' ) ';
  952. //
  953. //                    }
  954. //
  955. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  956.                 }
  957.                 $filterQryForCriteria .= $selectQry;
  958.                 $filterQryForCriteria .= $joinQry;
  959.                 if ($skipDefaultCompanyId == && $companyId != && !isset($dataConfig['entity_group']))
  960.                     $filterQryForCriteria .= " where `$table`.`company_id`=" $companyId " ";
  961.                 else
  962.                     $filterQryForCriteria .= " where 1=1 ";
  963.                 $conditionStr "";
  964.                 $aliasInCondition $table;
  965.                 if ($headMarkers != '' && $table == 'acc_accounts_head') {
  966.                     $markerList explode(','$headMarkers);
  967.                     $spMarkerQry "SELECT distinct accounts_head_id FROM acc_accounts_head where 1=1 ";
  968.                     $markerPassedHeads = [];
  969.                     foreach ($markerList as $mrkr) {
  970.                         $spMarkerQry .= " and marker_hash like '%" $mrkr "%'";
  971.                     }
  972.                     $spStmt $em->getConnection()->fetchAllAssociative($spMarkerQry);
  973.                     
  974.                     $spStmtResults $spStmt;
  975.                     foreach ($spStmtResults as $ggres) {
  976.                         $markerPassedHeads[] = $ggres['accounts_head_id'];
  977.                     }
  978.                     if (!empty($markerPassedHeads)) {
  979.                         if ($conditionStr != '')
  980.                             $conditionStr .= " and (";
  981.                         else
  982.                             $conditionStr .= " (";
  983.                         if ($headMarkersStrictMatch != 1) {
  984.                             foreach ($markerPassedHeads as $mh) {
  985.                                 $conditionStr .= " `$aliasInCondition`.`path_tree` like'%/" $mh "/%' or ";
  986.                             }
  987.                         }
  988.                         $conditionStr .= "  `$aliasInCondition`.`accounts_head_id` in (" implode(','$markerPassedHeads) . ") ";
  989.                         $conditionStr .= " )";
  990.                     }
  991.                 }
  992.                 if (isset($restrictionData[$table])) {
  993.                     $userRestrictionData Users::getUserApplicationAccessSettings($em$userId)['options'];
  994.                     if (isset($userRestrictionData[$restrictionData[$table]])) {
  995.                         $restrictionIdList $userRestrictionData[$restrictionData[$table]];
  996.                         if ($restrictionIdList == null)
  997.                             $restrictionIdList = [];
  998.                     }
  999.                     if (!empty($restrictionIdList)) {
  1000.                         if ($conditionStr != '')
  1001.                             $conditionStr .= " and ";
  1002.                         $conditionStr .= " `$table`.$valueField in (" implode(','$restrictionIdList) . ") ";
  1003.                     }
  1004.                 }
  1005. //        $aliasInCondition = $table;
  1006.                 if (!empty($setValueArray) || $selectAll == 1) {
  1007.                     if (!empty($setValueArray)) {
  1008.                         if ($conditionStr != '')
  1009.                             $conditionStr .= " and ";
  1010.                         $conditionStr .= " `$aliasInCondition`.$valueField in (" implode(','$setValueArray) . ") ";
  1011.                     }
  1012.                 } else {
  1013. //                    $andString = '';
  1014.                     $andString $joinAndString;   /////New testing
  1015.                     foreach ($andConditions as $andCondition) {
  1016. //            $conditionStr.=' 1=1 ';
  1017.                         $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  1018.                         $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  1019.                         $aliasInCondition $table;
  1020.                         if (!(strpos($cfield'.') === false)) {
  1021.                             $fullCfieldArray explode('.'$cfield);
  1022.                             $aliasInCondition $fullCfieldArray[0];
  1023.                             $cfield $fullCfieldArray[1];
  1024.                         }
  1025.                         $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStringIndividual;
  1026.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  1027.                             if ($andString != '')
  1028.                                 $andString .= " and ";
  1029.                             if ($ctype == 'like') {
  1030.                                 $andString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  1031.                                 $wordsBySpaces explode(' '$cvalue);
  1032.                                 foreach ($wordsBySpaces as $word) {
  1033.                                     if ($andString != '')
  1034.                                         $andString .= " and ";
  1035.                                     $andString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  1036.                                 }
  1037.                             } else if ($ctype == 'not like') {
  1038.                                 $andString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  1039.                                 $wordsBySpaces explode(' '$cvalue);
  1040.                                 foreach ($wordsBySpaces as $word) {
  1041.                                     if ($andString != '')
  1042.                                         $andString .= " and ";
  1043.                                     $andString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  1044.                                 }
  1045.                             } else if ($ctype == 'not_in') {
  1046.                                 $andString .= " ( ";
  1047.                                 if (in_array('null'$cvalue)) {
  1048.                                     $andString .= " `$aliasInCondition`.$cfield is not null";
  1049.                                     $cvalue array_diff($cvalue, ['null']);
  1050.                                     if (!empty($cvalue))
  1051.                                         $andString .= " and ";
  1052.                                 }
  1053.                                 if (in_array(''$cvalue)) {
  1054.                                     $andString .= "`$aliasInCondition`.$cfield != '' ";
  1055.                                     $cvalue array_diff($cvalue, ['']);
  1056.                                     if (!empty($cvalue))
  1057.                                         $andString .= " and ";
  1058.                                 }
  1059.                                 $andString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  1060.                             } else if ($ctype == 'in') {
  1061.                                 if (in_array('null'$cvalue)) {
  1062.                                     $andString .= "`$aliasInCondition`.$cfield is null";
  1063.                                     $cvalue array_diff($cvalue, ['null']);
  1064.                                     if (!empty($cvalue))
  1065.                                         $andString .= " and ";
  1066.                                 }
  1067.                                 if (in_array(''$cvalue)) {
  1068.                                     $andString .= "`$aliasInCondition`.$cfield = '' ";
  1069.                                     $cvalue array_diff($cvalue, ['']);
  1070.                                     if (!empty($cvalue))
  1071.                                         $andString .= " and ";
  1072.                                 }
  1073.                                 $andString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ";
  1074.                             } else if ($ctype == '=') {
  1075.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  1076.                                     $andString .= "`$aliasInCondition`.$cfield is null ";
  1077.                                 else
  1078.                                     $andString .= "`$aliasInCondition`.$cfield = $cvalue ";
  1079.                             } else if ($ctype == '!=') {
  1080.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  1081.                                     $andString .= "`$aliasInCondition`.$cfield is not null ";
  1082.                                 else
  1083.                                     $andString .= "`$aliasInCondition`.$cfield != $cvalue ";
  1084.                             } else {
  1085.                                 if (is_string($cvalue))
  1086.                                     $andString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  1087.                                 else
  1088.                                     $andString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  1089.                             }
  1090.                         }
  1091.                     }
  1092.                     if ($andString != '') {
  1093.                         if ($conditionStr != '')
  1094.                             $conditionStr .= (" and (" $andString ") ");
  1095.                         else
  1096.                             $conditionStr .= ("  (" $andString ") ");
  1097.                     }
  1098. //                    $orString = '';
  1099.                     $orString $joinOrString;   /////New testing
  1100.                     foreach ($orConditions as $orCondition) {
  1101.                         $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  1102.                         $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  1103.                         $aliasInCondition $table;
  1104.                         if (!(strpos($cfield'.') === false)) {
  1105.                             $fullCfieldArray explode('.'$cfield);
  1106.                             $aliasInCondition $fullCfieldArray[0];
  1107.                             $cfield $fullCfieldArray[1];
  1108.                         }
  1109.                         $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStringIndividual;
  1110.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  1111.                             if ($orString != '')
  1112.                                 $orString .= " or ";
  1113.                             if ($ctype == 'like') {
  1114.                                 $orString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  1115.                                 $wordsBySpaces explode(' '$cvalue);
  1116.                                 foreach ($wordsBySpaces as $word) {
  1117.                                     if ($orString != '')
  1118.                                         $orString .= " or ";
  1119.                                     $orString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  1120.                                 }
  1121.                             } else if ($ctype == 'not like') {
  1122.                                 $orString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  1123.                                 $wordsBySpaces explode(' '$cvalue);
  1124.                                 foreach ($wordsBySpaces as $word) {
  1125.                                     if ($orString != '')
  1126.                                         $orString .= " or ";
  1127.                                     $orString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  1128.                                 }
  1129.                             } else if ($ctype == 'not_in') {
  1130.                                 $orString .= " ( ";
  1131.                                 if (in_array('null'$cvalue)) {
  1132.                                     $orString .= " `$aliasInCondition`.$cfield is not null";
  1133.                                     $cvalue array_diff($cvalue, ['null']);
  1134.                                     if (!empty($cvalue))
  1135.                                         $orString .= " or ";
  1136.                                 }
  1137.                                 if (in_array(''$cvalue)) {
  1138.                                     $orString .= "`$aliasInCondition`.$cfield != '' ";
  1139.                                     $cvalue array_diff($cvalue, ['']);
  1140.                                     if (!empty($cvalue))
  1141.                                         $orString .= " or ";
  1142.                                 }
  1143.                                 $orString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  1144.                             } else if ($ctype == 'in') {
  1145.                                 $orString .= " ( ";
  1146.                                 if (in_array('null'$cvalue)) {
  1147.                                     $orString .= " `$aliasInCondition`.$cfield is null";
  1148.                                     $cvalue array_diff($cvalue, ['null']);
  1149.                                     if (!empty($cvalue))
  1150.                                         $orString .= " or ";
  1151.                                 }
  1152.                                 if (in_array(''$cvalue)) {
  1153.                                     $orString .= "`$aliasInCondition`.$cfield = '' ";
  1154.                                     $cvalue array_diff($cvalue, ['']);
  1155.                                     if (!empty($cvalue))
  1156.                                         $orString .= " or ";
  1157.                                 }
  1158.                                 $orString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  1159.                             } else if ($ctype == '=') {
  1160.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  1161.                                     $orString .= "`$aliasInCondition`.$cfield is null ";
  1162.                                 else
  1163.                                     $orString .= "`$aliasInCondition`.$cfield = $cvalue ";
  1164.                             } else if ($ctype == '!=') {
  1165.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  1166.                                     $orString .= "`$aliasInCondition`.$cfield is not null ";
  1167.                                 else
  1168.                                     $orString .= "`$aliasInCondition`.$cfield != $cvalue ";
  1169.                             } else {
  1170.                                 if (is_string($cvalue))
  1171.                                     $orString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  1172.                                 else
  1173.                                     $orString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  1174.                             }
  1175.                         }
  1176.                     }
  1177.                     if ($orString != '') {
  1178.                         if ($conditionStr != '')
  1179.                             $conditionStr .= (" or (" $orString ") ");
  1180.                         else
  1181.                             $conditionStr .= ("  (" $orString ") ");
  1182.                     }
  1183. //                    $andOrString = '';
  1184.                     $andOrString $joinAndOrString;   /////New testing
  1185.                     foreach ($andOrConditions as $andOrCondition) {
  1186.                         $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  1187.                         $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  1188.                         $aliasInCondition $table;
  1189.                         if (!(strpos($cfield'.') === false)) {
  1190.                             $fullCfieldArray explode('.'$cfield);
  1191.                             $aliasInCondition $fullCfieldArray[0];
  1192.                             $cfield $fullCfieldArray[1];
  1193.                         }
  1194.                         $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStringIndividual;
  1195.                         if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  1196.                             if ($andOrString != '')
  1197.                                 $andOrString .= " or ";
  1198.                             if ($ctype == 'like') {
  1199.                                 $andOrString .= (" `$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  1200.                                 $wordsBySpaces explode(' '$cvalue);
  1201.                                 foreach ($wordsBySpaces as $word) {
  1202.                                     if ($andOrString != '')
  1203.                                         $andOrString .= " or ";
  1204.                                     $andOrString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  1205.                                 }
  1206.                             } else if ($ctype == 'not like') {
  1207.                                 $andOrString .= (" `$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  1208.                                 $wordsBySpaces explode(' '$cvalue);
  1209.                                 foreach ($wordsBySpaces as $word) {
  1210.                                     if ($andOrString != '')
  1211.                                         $andOrString .= " or ";
  1212.                                     $andOrString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  1213.                                 }
  1214.                             } else if ($ctype == 'in') {
  1215.                                 $andOrString .= " ( ";
  1216.                                 if (in_array('null'$cvalue)) {
  1217.                                     $andOrString .= " `$aliasInCondition`.$cfield is null";
  1218.                                     $cvalue array_diff($cvalue, ['null']);
  1219.                                     if (!empty($cvalue))
  1220.                                         $andOrString .= " or ";
  1221.                                 }
  1222.                                 if (in_array(''$cvalue)) {
  1223.                                     $andOrString .= "`$aliasInCondition`.$cfield = '' ";
  1224.                                     $cvalue array_diff($cvalue, ['']);
  1225.                                     if (!empty($cvalue))
  1226.                                         $andOrString .= " or ";
  1227.                                 }
  1228.                                 if (!empty($cvalue))
  1229.                                     $andOrString .= " `$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  1230.                                 else
  1231.                                     $andOrString .= "  ) ";
  1232.                             } else if ($ctype == 'not_in') {
  1233.                                 $andOrString .= " ( ";
  1234.                                 if (in_array('null'$cvalue)) {
  1235.                                     $andOrString .= " `$aliasInCondition`.$cfield is not null";
  1236.                                     $cvalue array_diff($cvalue, ['null']);
  1237.                                     if (!empty($cvalue))
  1238.                                         $andOrString .= " or ";
  1239.                                 }
  1240.                                 if (in_array(''$cvalue)) {
  1241.                                     $andOrString .= "`$aliasInCondition`.$cfield != '' ";
  1242.                                     $cvalue array_diff($cvalue, ['']);
  1243.                                     if (!empty($cvalue))
  1244.                                         $andOrString .= " or ";
  1245.                                 }
  1246.                                 if (!empty($cvalue))
  1247.                                     $andOrString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  1248.                                 else
  1249.                                     $andOrString .= "  ) ";
  1250.                             } else if ($ctype == '=') {
  1251.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  1252.                                     $andOrString .= "`$aliasInCondition`.$cfield is null ";
  1253.                                 else
  1254.                                     $andOrString .= "`$aliasInCondition`.$cfield = $cvalue ";
  1255.                             } else if ($ctype == '!=') {
  1256.                                 if ($cvalue == 'null' || $cvalue == 'Null')
  1257.                                     $andOrString .= "`$aliasInCondition`.$cfield is not null ";
  1258.                                 else
  1259.                                     $andOrString .= "`$aliasInCondition`.$cfield != $cvalue ";
  1260.                             } else {
  1261.                                 if (is_string($cvalue))
  1262.                                     $andOrString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  1263.                                 else
  1264.                                     $andOrString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  1265.                             }
  1266.                         }
  1267.                     }
  1268.                     if ($andOrString != '') {
  1269.                         if ($conditionStr != '')
  1270.                             $conditionStr .= (" and (" $andOrString ") ");
  1271.                         else
  1272.                             $conditionStr .= ("  (" $andOrString ") ");
  1273.                     }
  1274.                 }
  1275.                 $mustStr $joinMustString;   /////New testing
  1276. //                $mustStr = '';
  1277. ///now must conditions
  1278.                 foreach ($mustConditions as $mustCondition) {
  1279. //            $conditionStr.=' 1=1 ';
  1280.                     $ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
  1281.                     $cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
  1282.                     $aliasInCondition $table;
  1283.                     if (!(strpos($cfield'.') === false)) {
  1284.                         $fullCfieldArray explode('.'$cfield);
  1285.                         $aliasInCondition $fullCfieldArray[0];
  1286.                         $cfield $fullCfieldArray[1];
  1287.                     }
  1288.                     $cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStringIndividual;
  1289.                     if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  1290.                         if ($mustStr != '')
  1291.                             $mustStr .= " and ";
  1292.                         if ($ctype == 'like') {
  1293.                             $mustStr .= ("(`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  1294.                             $wordsBySpaces explode(' '$cvalue);
  1295.                             foreach ($wordsBySpaces as $word) {
  1296.                                 if ($mustStr != '')
  1297.                                     $mustStr .= " or ";
  1298.                                 $mustStr .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  1299.                             }
  1300.                             $mustStr .= " )";
  1301.                         } else if ($ctype == 'not like') {
  1302.                             $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  1303.                             $wordsBySpaces explode(' '$cvalue);
  1304.                             foreach ($wordsBySpaces as $word) {
  1305.                                 if ($mustStr != '')
  1306.                                     $mustStr .= " and ";
  1307.                                 $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  1308.                             }
  1309.                         } else if ($ctype == 'in') {
  1310.                             $mustStr .= " ( ";
  1311.                             if (in_array('null'$cvalue)) {
  1312.                                 $mustStr .= " `$aliasInCondition`.$cfield is null";
  1313.                                 $cvalue array_diff($cvalue, ['null']);
  1314.                                 if (!empty($cvalue))
  1315.                                     $mustStr .= " or ";
  1316.                             }
  1317.                             if (in_array(''$cvalue)) {
  1318.                                 $mustStr .= "`$aliasInCondition`.$cfield = '' ";
  1319.                                 $cvalue array_diff($cvalue, ['']);
  1320.                                 if (!empty($cvalue))
  1321.                                     $mustStr .= " or ";
  1322.                             }
  1323.                             $mustStr .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  1324.                         } else if ($ctype == 'not_in') {
  1325.                             $mustStr .= " ( ";
  1326.                             if (in_array('null'$cvalue)) {
  1327.                                 $mustStr .= " `$aliasInCondition`.$cfield is not null";
  1328.                                 $cvalue array_diff($cvalue, ['null']);
  1329.                                 if (!empty($cvalue))
  1330.                                     $mustStr .= " and ";
  1331.                             }
  1332.                             if (in_array(''$cvalue)) {
  1333.                                 $mustStr .= "`$aliasInCondition`.$cfield != '' ";
  1334.                                 $cvalue array_diff($cvalue, ['']);
  1335.                                 if (!empty($cvalue))
  1336.                                     $mustStr .= " and ";
  1337.                             }
  1338.                             $mustStr .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  1339.                         } else if ($ctype == '=') {
  1340.                             if ($cvalue == 'null' || $cvalue == 'Null')
  1341.                                 $mustStr .= "`$aliasInCondition`.$cfield is null ";
  1342.                             else
  1343.                                 $mustStr .= "`$aliasInCondition`.$cfield = $cvalue ";
  1344.                         } else if ($ctype == '!=') {
  1345.                             if ($cvalue == 'null' || $cvalue == 'Null')
  1346.                                 $mustStr .= "`$aliasInCondition`.$cfield is not null ";
  1347.                             else
  1348.                                 $mustStr .= "`$aliasInCondition`.$cfield != $cvalue ";
  1349.                         } else {
  1350.                             if (is_string($cvalue))
  1351.                                 $mustStr .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  1352.                             else
  1353.                                 $mustStr .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  1354.                         }
  1355.                     }
  1356.                 }
  1357.                 if ($mustStr != '') {
  1358.                     if ($conditionStr != '')
  1359.                         $conditionStr .= (" and (" $mustStr ") ");
  1360.                     else
  1361.                         $conditionStr .= ("  (" $mustStr ") ");
  1362.                 }
  1363.                 if ($conditionStr != '')
  1364.                     $filterQryForCriteria .= (" and (" $conditionStr ") ");
  1365.                 if ($lastChildrenOnly == 1) {
  1366.                     if ($filterQryForCriteria != '')
  1367.                         $filterQryForCriteria .= ' and ';
  1368.                     $filterQryForCriteria .= " `$table`.`$valueField` not in ( select distinct $parentIdField from  $table)";
  1369.                 } else if ($parentOnly == 1) {
  1370.                     if ($filterQryForCriteria != '')
  1371.                         $filterQryForCriteria .= ' and ';
  1372.                     $filterQryForCriteria .= " `$table`.`$valueField`  in ( select distinct $parentIdField from  $table)";
  1373.                 }
  1374.                 if (!empty($orderByConditions)) {
  1375.                     $filterQryForCriteria .= "  order by ";
  1376.                     $fone 1;
  1377.                     foreach ($orderByConditions as $orderByCondition) {
  1378.                         if ($fone != 1) {
  1379.                             $filterQryForCriteria .= " , ";
  1380.                         }
  1381.                         if (isset($orderByCondition['valueList'])) {
  1382.                             if (is_string($orderByCondition['valueList'])) $orderByCondition['valueList'] = json_decode($orderByCondition['valueList'], true);
  1383.                             if ($orderByCondition['valueList'] == null)
  1384.                                 $orderByCondition['valueList'] = [];
  1385.                             $filterQryForCriteria .= "   field(" $orderByCondition['field'] . "," implode(','$orderByCondition['valueList']) . "," $orderByCondition['field'] . ") " $orderByCondition['sortType'] . " ";
  1386.                         } else
  1387.                             $filterQryForCriteria .= " " $orderByCondition['field'] . " " $orderByCondition['sortType'] . " ";
  1388.                         $fone 0;
  1389.                     }
  1390.                 }
  1391.                 if ($returnTotalMatchedEntriesFlag == 1) {
  1392. //            $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  1393. //            
  1394. //            $get_kids = $stmt;
  1395.                 }
  1396.                 if ($filterQryForCriteria != '')
  1397.                     if (!empty($setValueArray) || $selectAll == 1) {
  1398.                     } else {
  1399.                         if ($itemLimit != '_ALL_')
  1400.                             $filterQryForCriteria .= "  limit $offset$itemLimit ";
  1401.                         else
  1402.                             $filterQryForCriteria .= "  limit $offset, 18446744073709551615 ";
  1403.                     }
  1404.                 $get_kids_sql $filterQryForCriteria;
  1405.                 $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  1406.                 
  1407.                 $get_kids $stmt;
  1408.                 $selectedId 0;
  1409.                 if ($table == 'warehouse_action') {
  1410.                     if (empty($get_kids)) {
  1411.                         $get_kids_sql_2 "select * from warehouse_action";
  1412.                         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql_2);
  1413.                         
  1414.                         $get_kids2 $stmt;
  1415.                         if (empty($get_kids2))
  1416.                             $get_kids GeneralConstant::$warehouse_action_list;
  1417.                     }
  1418.                 }
  1419.                 if (!empty($get_kids)) {
  1420.                     $nextOffset $offset count($get_kids);
  1421.                     $nextOffset++;
  1422.                     foreach ($get_kids as $pa) {
  1423.                         if (!empty($setValueArray) && $selectAll == 0) {
  1424.                             if (!in_array($pa[$valueField], $setValueArray))
  1425.                                 continue;
  1426.                         }
  1427.                         if (!empty($restrictionIdList)) {
  1428.                             if (!in_array($pa[$valueField], $restrictionIdList))
  1429.                                 continue;
  1430.                         }
  1431.                         if ($selectAll == 1) {
  1432.                             $setValueArray[] = $pa[$valueField];
  1433.                             $setValue $pa[$valueField];
  1434.                         } else if (count($get_kids) == && $setDataForSingle == 1) {
  1435.                             $setValueArray[] = $pa[$valueField];
  1436.                             $setValue $pa[$valueField];
  1437.                         }
  1438.                         if ($valueField != '')
  1439.                             $pa['value'] = $pa[$valueField];
  1440.                         $renderedText $renderTextFormat;
  1441.                         $compare_array = [];
  1442.                         if ($renderTextFormat != '') {
  1443.                             $renderedText $renderTextFormat;
  1444.                             $compare_arrayFull = [];
  1445.                             $compare_array = [];
  1446.                             $toBeReplacedData = array(//                        'curr'=>'tobereplaced'
  1447.                             );
  1448.                             preg_match_all("/__\w+__/"$renderedText$compare_arrayFull);
  1449.                             if (isset($compare_arrayFull[0]))
  1450.                                 $compare_array $compare_arrayFull[0];
  1451. //                   $compare_array= preg_split("/__\w+__/",$renderedText);
  1452.                             foreach ($compare_array as $cmpdt) {
  1453.                                 $tbr str_replace("__"""$cmpdt);
  1454.                                 if ($tbr != '') {
  1455.                                     if (isset($pa[$tbr])) {
  1456.                                         if ($pa[$tbr] == null)
  1457.                                             $renderedText str_replace($cmpdt''$renderedText);
  1458.                                         else
  1459.                                             $renderedText str_replace($cmpdt$pa[$tbr], $renderedText);
  1460.                                     } else {
  1461.                                         $renderedText str_replace($cmpdt''$renderedText);
  1462.                                     }
  1463.                                 }
  1464.                             }
  1465.                         }
  1466.                         $pa['rendered_text'] = $renderedText;
  1467.                         $pa['text'] = ($textField != '' $pa[$textField] : '');
  1468. //                $pa['compare_array'] = $compare_array;
  1469.                         foreach ($convertToObjectFieldList as $convField) {
  1470.                             if (isset($pa[$convField])) {
  1471.                                 $taA json_decode($pa[$convField], true);
  1472.                                 if ($taA == null$taA = [];
  1473.                                 $pa[$convField] = $taA;
  1474.                             } else {
  1475.                                 $pa[$convField] = [];
  1476.                             }
  1477.                         }
  1478.                         foreach ($convertDateToStringFieldList as $convField) {
  1479.                             if (is_array($convField)) {
  1480.                                 $fld $convField['field'];
  1481.                                 $frmt = isset($convField['format']) ? $convField['format'] : 'Y-m-d H:i:s';
  1482.                             } else {
  1483.                                 $fld $convField;
  1484.                                 $frmt 'Y-m-d H:i:s';
  1485.                             }
  1486.                             if (isset($pa[$fld])) {
  1487.                                 $taA = new \DateTime($pa[$fld]);
  1488.                                 $pa[$fld] = $taA->format($frmt);
  1489.                             }
  1490.                         }
  1491.                         foreach ($convertToUrl as $convField) {
  1492. //
  1493. //                            $fld = $convField;
  1494. //
  1495. //
  1496. //                            if (isset($pa[$fld])) {
  1497. //
  1498. //
  1499. //                                $pa[$fld] =
  1500. //                                    $this->generateUrl(
  1501. //                                        'dashboard', [
  1502. //
  1503. //                                    ], UrlGenerator::ABSOLUTE_URL
  1504. //                                    ).'/'.$pa[$fld];
  1505. //
  1506. //                            }
  1507.                         }
  1508.                         foreach ($fullPathList as $pathField) {
  1509.                             $fld $pathField;
  1510.                             if (isset($pa[$fld])) {
  1511.                                 if ($pa[$fld] !='' && $pa[$fld] !=null) {
  1512.                                     $pa[$fld]=($this->generateUrl(
  1513.                                             'dashboard', [
  1514.                                         ], UrlGenerator::ABSOLUTE_URL
  1515.                                         ).$pa[$fld]);
  1516.                                 }
  1517.                             }
  1518.                         }
  1519.                         $pa['currentTs'] = (new \Datetime())->format('U');
  1520.                         $data[] = $pa;
  1521.                         if ($valueField != '') {
  1522.                             $data_by_id[$pa[$valueField]] = $pa;
  1523.                             $selectedId $pa[$valueField];
  1524.                         }
  1525.                     }
  1526.                 }
  1527.                 if ($dataOnly == 1)
  1528.                     $lastResult = array(
  1529.                         'success' => true,
  1530.                         'data' => $data,
  1531.                         'currentTs' => (new \Datetime())->format('U'),
  1532.                         'restrictionIdList' => $restrictionIdList,
  1533.                         'nextOffset' => $nextOffset,
  1534.                         'totalMatchedEntries' => $totalMatchedEntries,
  1535.                         'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  1536.                     );
  1537.                 else
  1538.                     $lastResult = array(
  1539.                         'success' => true,
  1540.                         'data' => $data,
  1541.                         'tableName' => $table,
  1542.                         'setValue' => $setValue,
  1543.                         'currentTs' => (new \Datetime())->format('U'),
  1544.                         'restrictionIdList' => $restrictionIdList,
  1545.                         'andConditions' => $andConditions,
  1546.                         'queryStr' => $queryStringIndividual,
  1547.                         'isMultiple' => $isMultiple,
  1548.                         'nextOffset' => $nextOffset,
  1549.                         'totalMatchedEntries' => $totalMatchedEntries,
  1550.                         'selectorId' => $selectorId,
  1551.                         'setValueArray' => $setValueArray,
  1552.                         'silentChangeSelectize' => $silentChangeSelectize,
  1553.                         'convertToObjectFieldList' => $convertToObjectFieldList,
  1554.                         'conditionStr' => $conditionStr,
  1555. //                    'andStr' => $andString,
  1556. //                    'andOrStr' => $andOrString,
  1557.                         'dataById' => $data_by_id,
  1558.                         'selectedId' => $selectedId,
  1559.                         'dataId' => $dataId,
  1560.                         'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
  1561.                     );
  1562.             }
  1563.             $allResult[] = $lastResult;
  1564.         }
  1565.         if ($isSingleDataset == 1)
  1566.             return new JsonResponse($lastResult);
  1567.         else
  1568.             return new JsonResponse($allResult);
  1569.     }
  1570.     public function GenericDataTableAjax(Request $request)
  1571.     {
  1572.         $em $this->getDoctrine()->getManager();
  1573.         $companyId $this->getLoggedUserCompanyId($request);
  1574.         // Sales-person + region visibility (owner-ruled 2026-07-22): scope the
  1575.         // sales lists (proposal / opportunity / order / client) to what this user
  1576.         // may see, SERVER-SIDE, so a tampered client config can't widen it. Any
  1577.         // non-sales list's config is returned untouched. Never fatal.
  1578.         $svConfig $request->request->get('config');
  1579.         if (is_array($svConfig)) {
  1580.             $request->request->set('config',
  1581.                 \ApplicationBundle\Modules\Sales\Service\SalesVisibilityService::applyConfigScope(
  1582.                     $em->getConnection(), $request->getSession(), $svConfig));
  1583.         }
  1584.         $listData MiscActions::GetDtDataAjax($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId$this->container->getParameter('kernel.root_dir'));
  1585.         if (isset($listData['data']['encryptedData'])) {
  1586.             foreach ($listData['data']['encryptedData'] as $k => $d) {
  1587.                 foreach ($d as $l => $f) {
  1588.                     $d[$l] = $this->get('url_encryptor')->encrypt($f);
  1589.                 }
  1590.                 $listData['data']['encryptedData'][$k] = $d;
  1591.             }
  1592.         }
  1593.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  1594.             if ($request->query->has('dataTableQry')) {
  1595.                 return new JsonResponse(
  1596.                     $listData
  1597.                 );
  1598.             }
  1599.         }
  1600.         $data = [];
  1601.         return new JsonResponse(
  1602.             $listData
  1603.         );
  1604.         //        return $this->render('@Inventory/pages/views/delivery_receipts.html.twig',
  1605.         //            array(
  1606.         //                'page_title' => 'Delivery Receipts',
  1607.         //                'data' => $data,
  1608.         //
  1609.         //            )
  1610.         //        );
  1611.     }
  1612.     public function RefreshApprovalStatusIfPending(Request $request)
  1613.     {
  1614.         $em $this->getDoctrine()->getManager();
  1615.         $Entity_list GeneralConstant::$Entity_list;
  1616.         $skipEntities $request->request->has('skipEntities') ? $request->request->get('skipEntities') : [427142627282931];
  1617.         $skipEntitiesById $request->request->has('skipEntitiesById') ? $request->request->get('skipEntitiesById') : [];
  1618.         $debugData = array(
  1619.             'skipEntities' => $skipEntities,
  1620.             'skipEntitiesById' => $skipEntitiesById,
  1621.             'allDone' => 1,
  1622.             'actedOnDoc' => ''
  1623.         );
  1624.         $didAct 0;
  1625.         $foundAtleastOne 0;
  1626.         $lastEntity 0;
  1627.         foreach ($Entity_list as $entity => $entityName) {
  1628.             if (in_array($entity$skipEntities))
  1629.                 continue;
  1630.             $lastEntity $entity;
  1631.             $debugData['allDone'] = 0;
  1632.             $doc null;
  1633.             //            if (class_exists('ApplicationBundle\\Entity\\' . $entityName))
  1634.             {
  1635.                 $docs $em->getRepository('ApplicationBundle\\Entity\\' $entityName)
  1636.                     ->findBy(
  1637.                         array(
  1638.                             'approved' => GeneralConstant::APPROVAL_STATUS_PENDING
  1639.                         )
  1640.                     );
  1641.             }
  1642.             $entityFieldGetFunction GeneralConstant::$Entity_id_get_method_list[$entity];
  1643.             if (!isset($skipEntitiesById[$entity]))
  1644.                 $skipEntitiesById[$entity] = [];
  1645.             foreach ($docs as $doc) {
  1646.                 if (in_array($doc->$entityFieldGetFunction(), $skipEntitiesById[$entity]))
  1647.                     continue;
  1648.                 $foundAtleastOne 1;
  1649.                 if ($doc) {
  1650.                     $fully_approved System::fullyApproved($em$entity$doc->$entityFieldGetFunction(), 0$this->get('mail_module'));
  1651.                     if ($fully_approved == 1)
  1652.                         $debugData['actedOnDoc'] = $doc->getDocumentHash();
  1653.                     $didAct 1;
  1654.                     $skipEntitiesById[$entity][] = $doc->$entityFieldGetFunction();
  1655.                 } else {
  1656.                 }
  1657.                 if ($didAct == 1)
  1658.                     break;
  1659.             }
  1660.             if ($didAct == 1)
  1661.                 break;
  1662.         }
  1663.         if ($foundAtleastOne == 0)
  1664.             $debugData['skipEntities'][] = $lastEntity;
  1665.         $debugData['skipEntitiesById'] = $skipEntitiesById;
  1666.         return new JsonResponse(
  1667.             $debugData
  1668.         );
  1669.     }
  1670.     // CreateDummyRows REMOVED 2026-07-04 (route test_insert_lot_of_rows deleted). A 2022
  1671.     // load-test relic that inserted 50,000 rows into employee_attendance_log per GET and
  1672.     // self-chained via redirect to startFrom=1,000,000 — a DoS vector. See the sibling
  1673.     // CreateDummyRowsEgAction removal in PublicPagesController.
  1674.     public function CreateSalesInvoice(Request $request)
  1675.     {
  1676.         //function start
  1677.         ///function end
  1678.         $em $this->getDoctrine()->getManager();
  1679.         return new JsonResponse(Accounts::GetBalanceOnDateByMarkerHash($em'2021-01-21', [], [], 1));
  1680.         $childEm $this->getDoctrine()->getManager('company_group');
  1681.         ob_start();
  1682.         phpinfo();
  1683.         $phpinfo ob_get_contents();
  1684.         ob_end_clean();
  1685.         $em $this->getDoctrine()->getManager();
  1686.         return $this->render(
  1687.             '@Accounts/pages/input_forms/sales_invoice.html.twig',
  1688.             array(
  1689.                 'page_title' => 'Create Sales Invoice',
  1690.                 'phpinfo' => $phpinfo,
  1691.                 'debug_data' => $this->getDoctrine()->getManager('company_group'),
  1692.                 'debug_data_2' => Company::getMonthlyDataForDashboard($this->getDoctrine()->getManager(), 1)
  1693.             )
  1694.         );
  1695.         //refreshing/ assigning invoice/order/challan/grn/stock requisition etc id to voucher as entity id
  1696.         $tocheckEntityList = array(
  1697.             => 'Grn',
  1698.             => 'PurchaseInvoice',
  1699.             10 => 'ExpenseInvoice',
  1700.             16 => 'DeliveryReceipt',
  1701.             18 => 'SalesInvoice',
  1702.             20 => 'StockTransfer',
  1703.             21 => 'StockReceivedNote',
  1704.             30 => 'ServiceChallan',
  1705.             41 => 'ItemReceivedAndReplacement',
  1706.             44 => 'StockConsumptionNote',
  1707.             47 => 'FixedAssetConversionNote',
  1708.             48 => 'FixedAssetDisposalNote',
  1709.             53 => 'Production',
  1710.         );
  1711.         foreach ($tocheckEntityList as $entity => $entityName) {
  1712.             $entityList $em->getRepository('ApplicationBundle\\Entity\\' $entityName)->findBy(
  1713.                 array()
  1714.             );
  1715.             foreach ($entityList as $entry) {
  1716.                 $voucherIds method_exists($entry'getVoucherIds') ? json_decode($entry->getVoucherIds(), true) : [];
  1717.                 $getMethod GeneralConstant::$Entity_id_get_method_list[$entity];
  1718.                 if ($voucherIds == null)
  1719.                     $voucherIds = [];
  1720.                 if (!empty($voucherIds)) {
  1721.                     $transactions $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findBy(
  1722.                         array(
  1723.                             'transactionId' => $voucherIds
  1724.                         )
  1725.                     );
  1726.                     foreach ($transactions as $transaction) {
  1727.                         $transaction->setEntityId($entry->$getMethod());
  1728.                         $transaction->setEntity($entity);
  1729.                         $transaction->setEntityDocHash($entry->getDocumentHash());
  1730.                         $em->flush();
  1731.                     }
  1732.                 }
  1733.             }
  1734.         }
  1735.         //        return $this->render('phpinfo.html.twig', array(
  1736.         //            'phpinfo'=>$phpinfo,
  1737.         //        ));
  1738.         //If we want to change the childEm to a different database:
  1739.         /**
  1740.          * IMPORTANT: The $reset parameter is used to clear all Units of Work fro
  1741.          * the EntityManager, this means anything that was not previously flushed
  1742.          * will be lost if you do $reset = true.
  1743.          *
  1744.          * Separately, $reset is necessary if you want to apply changes across
  1745.          * multiple EntityManagers in one Controller. Make sure you flush, then
  1746.          * $reset, and you will be good to go.
  1747.          */
  1748.         /**
  1749.          * get your new database parameters here..
  1750.          */
  1751.         //        $connector = $this->container->get('application_connector');
  1752.         //        $connector->resetConnection('company_group', 'bengal_v2', "root", "", "localhost", $reset = true);
  1753.         $soList $em->getRepository('ApplicationBundle\\Entity\\SalesOrder')->findBy(
  1754.             array()
  1755.         );
  1756.         foreach ($soList as $so) {
  1757.             //            SalesOrderM::checkIfSalesOrderComplete($em, $so->getSalesOrderId());
  1758.         }
  1759.         //childEM is now connected to the new database.
  1760.         //        $childEm = $this->getDoctrine()->getManager('company_group')
  1761.         //            ->getRepository("ApplicationBundle\\Entity\\AccSuppliers")
  1762.         //        ->findAll();
  1763.         return $this->render(
  1764.             '@Accounts/pages/input_forms/sales_invoice.html.twig',
  1765.             array(
  1766.                 'page_title' => 'Create Sales Invoice',
  1767.                 'phpinfo' => $phpinfo,
  1768.                 'debug_data' => $this->getDoctrine()->getManager('company_group'),
  1769.                 'debug_data_2' => Company::getMonthlyDataForDashboard($this->getDoctrine()->getManager(), 1)
  1770.             )
  1771.         );
  1772.     }
  1773.     public function GetFilteredCostCentres(Request $request$headId 0)
  1774.     {
  1775.         $em $this->getDoctrine()->getManager();
  1776.         $companyId $this->getLoggedUserCompanyId($request);
  1777.         $asArray $request->query->has('asArray') ? $request->query->get('asArray') : 0;
  1778.         return new JsonResponse(array(
  1779.             'costCentreList' => Accounts::CostCenterListFilteredByHeadId($em$companyId$headId$asArray)
  1780.         ));
  1781.     }
  1782.     public function GetAllocationRules(Request $request)
  1783.     {
  1784.         $em $this->getDoctrine()->getManager();
  1785.         $accountId = (int) $request->query->get('account_id'0);
  1786.         if ($accountId <= 0) {
  1787.             return new JsonResponse([
  1788.                 'success' => true,
  1789.                 'data' => [],
  1790.             ]);
  1791.         }
  1792.         $rules $em->getRepository('ApplicationBundle\\Entity\\AllocationRule')->findByAccountId($accountId);
  1793.         $data = [];
  1794.         foreach ($rules as $rule) {
  1795.             $data[] = [
  1796.                 'id' => $rule->getId(),
  1797.                 'account_id' => $rule->getAccountId(),
  1798.                 'tag_type' => $rule->getTagType(),
  1799.                 'tag_value' => $rule->getTagValue(),
  1800.                 'percentage' => (float) $rule->getPercentage(),
  1801.             ];
  1802.         }
  1803.         return new JsonResponse([
  1804.             'success' => true,
  1805.             'data' => $data,
  1806.         ]);
  1807.     }
  1808.     public function RefreshFunction(Request $request)
  1809.     {
  1810.         $em $this->getDoctrine()->getManager();
  1811.         //
  1812.         //        UPDATE `acc_accounts_head` SET `head_nature`='dr' WHERE path_tree like '%/1/%' or path_tree like '%/5/%';
  1813.         //UPDATE `acc_accounts_head` SET `head_nature`='cr' WHERE path_tree like '%/3/%' or path_tree like '%/4/%';
  1814.         $dataList2 $em->getRepository('ApplicationBundle\\Entity\\StoreRequisitionItem')->findBy(
  1815.             array()
  1816.         );
  1817.         foreach ($dataList2 as $dt2) {
  1818.             if ($dt2->getNote() == "" || $dt2->getNote() == null) {
  1819.                 //find tagged data
  1820.                 $tagData = [];
  1821.                 $note "";
  1822.                 $tagData json_decode($dt2->getTagData(), true);
  1823.                 if ($tagData) {
  1824.                     foreach ($tagData as $tg) {
  1825.                         $data1 $em->getRepository('ApplicationBundle\\Entity\\StockRequisitionItem')->findOneBy(
  1826.                             array(
  1827.                                 'id' => $tg['detailsId']
  1828.                             )
  1829.                         );
  1830.                         if ($data1) {
  1831.                             if ($data1->getNote() == "" || $data1->getNote() == null) {
  1832.                                 $note .= ", ";
  1833.                                 $note .= $data1->getNote();
  1834.                             }
  1835.                         }
  1836.                     }
  1837.                 }
  1838.                 $dt2->setNote($note);
  1839.             }
  1840.         }
  1841.         $em->flush();
  1842.         $dataList2 $em->getRepository('ApplicationBundle\\Entity\\PurchaseRequisitionItem')->findBy(
  1843.             array()
  1844.         );
  1845.         foreach ($dataList2 as $dt2) {
  1846.             if ($dt2->getNote() == "" || $dt2->getNote() == null) {
  1847.                 //find tagged data
  1848.                 $tagData = [];
  1849.                 $note "";
  1850.                 $tagData json_decode($dt2->getTagData(), true);
  1851.                 if ($tagData) {
  1852.                     foreach ($tagData as $tg) {
  1853.                         $data1 $em->getRepository('ApplicationBundle\\Entity\\StoreRequisitionItem')->findOneBy(
  1854.                             array(
  1855.                                 'id' => $tg['detailsId']
  1856.                             )
  1857.                         );
  1858.                         if ($data1) {
  1859.                             if ($data1->getNote() == "" || $data1->getNote() == null) {
  1860.                                 $note .= ", ";
  1861.                                 $note .= $data1->getNote();
  1862.                             }
  1863.                         }
  1864.                     }
  1865.                 }
  1866.                 $dt2->setNote($note);
  1867.             }
  1868.         }
  1869.         $em->flush();
  1870.         return new Response(1);
  1871.         //        $query_here=$em->getRepository('ApplicationBundle\\Entity\\EncryptedSignature')
  1872.         //            ->findOneBy(
  1873.         //                array(
  1874.         //                    'userId'=>4
  1875.         //                )
  1876.         //            );
  1877.         //             if($query_here)
  1878.         //        {
  1879.         //            $dt=$query_here->getData();
  1880.         //        }
  1881.         //        else
  1882.         //        {
  1883.         //            return false;
  1884.         //        }
  1885.         //
  1886.         //
  1887.         //
  1888.         //        $iv = '1234567812345678';
  1889.         //        $data=openssl_encrypt('ki koro miavai', "AES-128-CBC", 'monada', OPENSSL_RAW_DATA, $iv);
  1890.         ////        $decrypted = openssl_decrypt(base64_decode(base64_encode($data)), "AES-128-CBC", 'monada', OPENSSL_RAW_DATA, $iv);
  1891.         //        $decrypted = openssl_decrypt(base64_decode($dt), "AES-128-CBC", 'monada', OPENSSL_RAW_DATA, $iv);
  1892.         //
  1893.         //        return new JsonResponse(array("success"=>false,'decoded_data'=>$decrypted,'data'=>base64_encode($data)));
  1894.         //1st remove any category that is not assigned to remove redundancy
  1895.         //now
  1896.     }
  1897.     public function RefreshHeadCode(Request $request)
  1898.     {
  1899.         $head_list = [];
  1900.         $digits = [];
  1901.         //first get max level
  1902.         $em $this->getDoctrine()->getManager();
  1903.         $max_level 0;
  1904.         $query "SELECT max(head_level) max_level from  acc_accounts_head   where company_id=" $this->getLoggedUserCompanyId($request);
  1905.         $stmt $em->getConnection()->fetchAllAssociative($query);
  1906.         
  1907.         $results $stmt;
  1908.         if ($results) {
  1909.             $max_level $results[0]['max_level'];
  1910.         }
  1911.         //now create multipliers
  1912.         for ($i 1$i <= $max_level$i++) {
  1913.             $query "SELECT count(accounts_head_id) count_of_level from  acc_accounts_head   where head_level=$i and company_id=" $this->getLoggedUserCompanyId($request);
  1914.             $stmt $em->getConnection()->fetchAllAssociative($query);
  1915.             
  1916.             $res $stmt;
  1917.             if ($res) {
  1918.                 $c $res[0]['count_of_level'];
  1919.                 $m 1;
  1920.                 $t 1;
  1921.                 for ($m 1$t <= $c$m++) {
  1922.                     $t $t 10;
  1923.                 }
  1924.                 //                while($c/10>0)
  1925.                 //                {
  1926.                 //                    $m+=1;
  1927.                 //                    $c = $c % 10;
  1928.                 //                }
  1929.                 $digits[$i] = $m;
  1930.             } else
  1931.                 $digits[$i] = 0;
  1932.         }
  1933.         //now get all acc heads and serialize them based on parent id
  1934.         $query "SELECT * from  acc_accounts_head  where company_id=" $this->getLoggedUserCompanyId($request) . " ORDER BY parent_id ASC";
  1935.         //        $query="SELECT accounts_head_id, type_hash, prefix_hash, assoc_hash, number_hash from  acc_transactions  where status=".GeneralConstant::ACTIVE;
  1936.         $stmt $em->getConnection()->fetchAllAssociative($query);
  1937.         
  1938.         $results $stmt;
  1939.         $update_qry "";
  1940.         foreach ($results as $entry) {
  1941.             $new_code '';
  1942.             $path explode('/'$entry['path_tree']);
  1943.             $path_string '';
  1944.             $new_ser 1;
  1945.             foreach ($path as $head_id) {
  1946.                 if ($head_id != '' && $head_id != 0) {
  1947.                     if ($head_id == $entry['parent_id']) {
  1948.                         $new_ser $head_list[$head_id]['last_serial'] + 1;
  1949.                         $head_list[$head_id]['last_serial'] + $new_ser;
  1950.                     }
  1951.                     $new_code $new_code $head_list[$head_id]['code'] * 1;
  1952.                 }
  1953.             }
  1954.             //now this oneonly
  1955.             for ($k 0$k $digits[$entry['head_level']]; $k++)
  1956.                 $new_code 10 $new_code;
  1957.             //now last zeroes
  1958.             for ($j $entry['head_level']; $j <= $max_level$j++) {
  1959.                 for ($k 0$k $digits[$j]; $k++)
  1960.                     $new_code 10 $new_code;
  1961.             }
  1962.             $head_list[$entry['accounts_head_id']] = array(
  1963.                 'code' => $new_code,
  1964.                 'last_serial' => 0
  1965.             );
  1966.             $update_qry .= "UPDATE acc_accounts_head set ledger_head_code=$new_code
  1967.                       where accounts_head_id=" $entry['accounts_head_id'] . "; ";
  1968.         }
  1969.         $stmt $em->getConnection()->fetchAllAssociative($update_qry);
  1970.         
  1971.         return $this->redirectToRoute('dashboard');
  1972.     }
  1973.     public function RefreshHeadLevel(Request $request)
  1974.     {
  1975.         $em $this->getDoctrine()->getManager();
  1976.         $assign_list = array();
  1977.         //        $new_cc = $em
  1978.         //            ->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
  1979.         //            ->findOneBy(
  1980.         //                array(
  1981.         //                    'name' => 'accounting_year_start',
  1982.         //                )
  1983.         //            );
  1984.         $heads = [];
  1985.         $query "SELECT * from  acc_accounts_head  where company_id=" $this->getLoggedUserCompanyId($request) . " ORDER BY parent_id ASC";
  1986.         //        $query="SELECT accounts_head_id, type_hash, prefix_hash, assoc_hash, number_hash from  acc_transactions  where status=".GeneralConstant::ACTIVE;
  1987.         $stmt $em->getConnection()->fetchAllAssociative($query);
  1988.         
  1989.         $results $stmt;
  1990.         $update_qry "";
  1991.         $head_list_by_id = [];
  1992.         $child_list_by_parent_id = [];
  1993.         $zero_parent_head_ids = [];
  1994.         foreach ($results as $entry) {
  1995.             $head_list_by_id[$entry['accounts_head_id']] = $entry;
  1996.             $parent_id $entry['parent_id'];
  1997.             if ($parent_id == null || $parent_id == '' || $parent_id == 0) {
  1998.                 $zero_parent_head_ids[] = $entry['accounts_head_id'];
  1999.                 $parent_id 0;
  2000.             }
  2001.             if (!isset($child_list_by_parent_id[$parent_id]))
  2002.                 $child_list_by_parent_id[$parent_id] = array();
  2003.             $child_list_by_parent_id[$parent_id][] = $entry['accounts_head_id'];
  2004.         }
  2005.         foreach ($zero_parent_head_ids as $parId) {
  2006.             $heads[$parId] = array(
  2007.                 'level' => 1
  2008.             );
  2009.             $next_ids $child_list_by_parent_id[$parId];
  2010.             $cur_level 1;
  2011.             $infLoopBreaker 0;
  2012.             while (!empty($next_ids) && $infLoopBreaker 100) {
  2013.                 $cur_level $cur_level 1;
  2014.                 $new_next_ids = [];
  2015.                 foreach ($next_ids as $childId) {
  2016.                     $entry $head_list_by_id[$childId];
  2017.                     if ($cur_level == $entry['head_level']) {
  2018.                     } else {
  2019.                         $update_qry .= "UPDATE acc_accounts_head set head_level=$cur_level
  2020.                                 where accounts_head_id=" $entry['accounts_head_id'] . "; ";
  2021.                     }
  2022.                     if (isset($child_list_by_parent_id[$childId]))
  2023.                         array_merge($new_next_idsarray_diff($new_next_ids$child_list_by_parent_id[$childId]));
  2024.                     $heads[$entry['accounts_head_id']] = array(
  2025.                         'level' => $cur_level
  2026.                     );
  2027.                 }
  2028.                 $next_ids $new_next_ids;
  2029.                 $infLoopBreaker++;
  2030.             }
  2031.         }
  2032.         //        System::log_it($this->container->getParameter('kernel.root_dir'), json_encode($zero_parent_head_ids), 'head_level_test');
  2033.         //
  2034.         //        foreach ($results as $entry) {
  2035.         //            if ($entry['parent_id'] == 0 || $entry['parent_id'] == '') {
  2036.         //                //top parent
  2037.         //                $heads[$entry['accounts_head_id']] = array(
  2038.         //                    'level' => 1
  2039.         //                );
  2040.         //            } else {
  2041.         //                $cur_level = 1 + $heads[$entry['parent_id']]['level'];
  2042.         //                if ($cur_level == $entry['head_level']) {
  2043.         //                } else {
  2044.         //                    $update_qry .= "UPDATE acc_accounts_head set head_level=$cur_level
  2045.         //                     where accounts_head_id=" . $entry['accounts_head_id'] . "; ";
  2046.         //                }
  2047.         //
  2048.         //
  2049.         //                $heads[$entry['accounts_head_id']] = array(
  2050.         //                    'level' => $cur_level
  2051.         //                );
  2052.         //            }
  2053.         //        }
  2054.         if ($update_qry != '') {
  2055.             $stmt $em->getConnection()->fetchAllAssociative($update_qry);
  2056.             
  2057.         }
  2058.         //        $Transactions=$stmt;
  2059.         return $this->redirectToRoute('opening_head_balance_assign');
  2060.     }
  2061.     public function PrintCheckRegister(Request $request)
  2062.     {
  2063.         $em $this->getDoctrine()->getManager();
  2064.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  2065.         $head_list Accounts::HeadList($em);
  2066.         $voucher_list Accounts::VoucherListForCheckRegister($em);
  2067.         $find_array = array(
  2068.             'type' => 1
  2069.         );
  2070.         if ($request->query->has('viewOption')) {
  2071.             if ($request->query->get('viewOption') == 1)
  2072.                 $find_array = ['active' => GeneralConstant::ACTIVE];
  2073.             if ($request->query->get('viewOption') == 2)
  2074.                 $find_array = ['active' => GeneralConstant::INACTIVE];
  2075.         }
  2076.         $assignedflag $request->query->has('assign_flag') ? $request->query->get('assign_flag') : 0;
  2077.         if ($assignedflag == 1)
  2078.             $find_array['assigned'] = 1;
  2079.         $check_query $this->getDoctrine()
  2080.             ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  2081.             ->findBy(
  2082.                 $find_array,
  2083.                 array(
  2084.                     'checkNumber' => 'ASC',
  2085.                 )
  2086.             );
  2087.         $check_data = [];
  2088.         $check_data_by_bank = [];
  2089.         // Treat a blank date param as "no filter", NOT as today. `has()` is true for a
  2090.         // present-but-empty query value (?start_date=&end_date=), and `new \DateTime('')`
  2091.         // resolves to NOW — so an empty end_date silently clamped the report to the current
  2092.         // date. Guard on a non-empty trimmed value instead.
  2093.         $rawStartDate trim((string) $request->query->get('start_date'''));
  2094.         $rawEndDate trim((string) $request->query->get('end_date'''));
  2095.         $start_date = ($rawStartDate !== '') ? (new \DateTime($rawStartDate)) : '';
  2096.         $end_date = ($rawEndDate !== '') ? (new \DateTime($rawEndDate ' ' ' 23:59:59.999')) : '';
  2097.         //            if($end_date!='')
  2098.         //                $end_date->modify('+1 day');
  2099.         $book_list_by_bank = [];
  2100.         foreach ($check_query as $entry) {
  2101.             $checkTransDate $entry->getTransactionDate();
  2102.             if ($checkTransDate == null)
  2103.                 continue;
  2104.             if ($start_date != '' && ($checkTransDate instanceof \DateTime) && ($start_date $checkTransDate))
  2105.                 continue;
  2106.             if ($end_date != '' && ($checkTransDate instanceof \DateTime) && ($end_date $checkTransDate))
  2107.                 continue;
  2108.             $v_date = isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['date'] : '';
  2109.             //                if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
  2110.             if ($start_date != '' && ($v_date instanceof \DateTime) && ($start_date $v_date))
  2111.                 continue;
  2112.             //                if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
  2113.             if ($end_date != '' && ($v_date instanceof \DateTime) && ($end_date $v_date))
  2114.                 continue;
  2115.             //                if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
  2116.             //                    continue;
  2117.             //                if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
  2118.             //                    continue;
  2119.             $checkDate = ($entry->getCheckDate() instanceof \DateTime) ? $entry->getCheckDate()->format('m/d/Y') : '';
  2120.             $assignedDate = ($entry->getAssignedDate() instanceof \DateTime) ? $entry->getAssignedDate()->format('m/d/Y') : '';
  2121.             if (!isset($book_list_by_bank[$entry->getAccountsHeadId()])) $book_list_by_bank[$entry->getAccountsHeadId()] = [];
  2122.             if (!in_array($entry->getBookNumber(), $book_list_by_bank[$entry->getAccountsHeadId()])) {
  2123.                 $book_list_by_bank[$entry->getAccountsHeadId()][] = $entry->getBookNumber();
  2124.             }
  2125.             $check_data_by_bank[$entry->getAccountsHeadId()][] = array(
  2126.                 'checkId' => $entry->getCheckId(),
  2127.                 'checkNumber' => sprintf("%07d"$entry->getCheckNumber()),
  2128.                 'checkNarration' => $entry->getCheckNarration(),
  2129.                 'voucherNarration' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['desc'] : '',
  2130.                 'voucherDate' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['date']->format('m/d/Y') : '',
  2131.                 'accountNumber' => $entry->getAccountNumber(),
  2132.                 'checkDate' => $checkDate,
  2133.                 'head' => $head_list[$entry->getAccountsHeadId()]['name'],
  2134.                 'head_id' => $entry->getAccountsHeadId(),
  2135.                 'received_head' => isset($head_list[$entry->getRecAccountsHeadId()]) ? $head_list[$entry->getRecAccountsHeadId()]['name'] : '',
  2136.                 'received_head_id' => $entry->getRecAccountsHeadId(),
  2137.                 'received_head_id_list' => $entry->getRecAccountsHeadIdList(),
  2138.                 'assignedDate' => $assignedDate,
  2139.                 'checkAmount' => $entry->getCheckAmount(),
  2140.                 'voucher_number' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['doc_hash'] : '',
  2141.                 'voucher_id' => $entry->getVoucherId(),
  2142.             );
  2143.         }
  2144.         $count_details_by_bank = [];
  2145.         if ($request->query->has('countDetails')) {
  2146.             $check_query $this->getDoctrine()
  2147.                 ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  2148.                 ->findAll();
  2149.             $count_details_by_bank = [];
  2150.             $assigned_books = [];
  2151.             foreach ($check_query as $entry) {
  2152.                 if (isset($count_details_by_bank[$entry->getAccountsHeadId()])) {
  2153.                     $count_details_by_bank[$entry->getAccountsHeadId()]['total_chk'] += 1;
  2154.                     if ($entry->getAssigned() == 1)
  2155.                         $count_details_by_bank[$entry->getAccountsHeadId()]['total_ass'] += 1;
  2156.                     else
  2157.                         $count_details_by_bank[$entry->getAccountsHeadId()]['total_avail'] += 1;
  2158.                     if (!in_array($entry->getBookNumber(), $assigned_books)) {
  2159.                         $count_details_by_bank[$entry->getAccountsHeadId()]['books'] .= (', ' $entry->getBookNumber());
  2160.                         array_push($assigned_books$entry->getBookNumber());
  2161.                     }
  2162.                 } else {
  2163.                     $count_details_by_bank[$entry->getAccountsHeadId()]['total_chk'] = 1;
  2164.                     $count_details_by_bank[$entry->getAccountsHeadId()]['total_ass'] = 0;
  2165.                     $count_details_by_bank[$entry->getAccountsHeadId()]['total_avail'] = 0;
  2166.                     if ($entry->getAssigned() == 1)
  2167.                         $count_details_by_bank[$entry->getAccountsHeadId()]['total_ass'] = 1;
  2168.                     else
  2169.                         $count_details_by_bank[$entry->getAccountsHeadId()]['total_avail'] = 1;
  2170.                     array_push($assigned_books$entry->getBookNumber());
  2171.                     $count_details_by_bank[$entry->getAccountsHeadId()]['books'] = (' ' $entry->getBookNumber());
  2172.                 }
  2173.             }
  2174.         }
  2175.         foreach ($voucher_list as $key => $entry) {
  2176.             $v_date $entry['date'];
  2177.             //                if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
  2178.             if ($start_date != '' && ($v_date instanceof \DateTime) && ($start_date $v_date))
  2179.                 continue;
  2180.             //                if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
  2181.             if ($end_date != '' && ($v_date instanceof \DateTime) && ($end_date $v_date))
  2182.                 continue;
  2183.             if (!in_array($entry['prMethod'], [34]))
  2184.                 continue;
  2185.             //                if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
  2186.             //                    continue;
  2187.             //                if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
  2188.             //                    continue;
  2189.             $trans_details $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(
  2190.                 array(
  2191.                     'transactionId' => $key,
  2192.                     'position' => 'cr'
  2193.                 )
  2194.             );
  2195.             foreach ($trans_details as $value) {
  2196.                 $checkDate $entry['date']->format('m/d/Y');
  2197.                 $assignedDate $entry['date']->format('m/d/Y');
  2198.                 $dr_details $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(
  2199.                     array(
  2200.                         'transactionId' => $key,
  2201.                         'position' => 'dr'
  2202.                     )
  2203.                 );
  2204.                 $rec_id_list = [];
  2205.                 $rec_narr "";
  2206.                 foreach ($dr_details as $dt) {
  2207.                     $rec_id_list[] = $dt->getAccountsHeadId();
  2208.                     $rec_narr .= $head_list[$dt->getAccountsHeadId()]['name'];
  2209.                     $rec_narr .= ", ";
  2210.                 }
  2211.                 $check_data_by_bank[$value->getAccountsHeadId()][] = array(
  2212.                     'checkId' => 0,
  2213.                     'checkNumber' => $entry['prReference'],
  2214.                     'checkNarration' => $rec_narr,
  2215.                     'voucherNarration' => $entry['desc'],
  2216.                     'voucherDate' => $entry['date']->format('m/d/Y'),
  2217.                     'accountNumber' => '',
  2218.                     'checkDate' => $checkDate,
  2219.                     'head' => $head_list[$value->getAccountsHeadId()]['name'],
  2220.                     'head_id' => $value->getAccountsHeadId(),
  2221.                     'received_head' => $rec_narr,
  2222.                     'received_head_id' => 0,
  2223.                     'received_head_id_list' => json_encode($rec_id_list),
  2224.                     'assignedDate' => $assignedDate,
  2225.                     'checkAmount' => $value->getAmount(),
  2226.                     'voucher_number' => $entry['doc_hash'],
  2227.                     'voucher_id' => $key,
  2228.                 );
  2229.             }
  2230.         }
  2231.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  2232.             $html $this->renderView(
  2233.                 '@Accounts/pages/print/check_register_print.html.twig',
  2234.                 array(
  2235.                     //full array here
  2236.                     'pdf' => true,
  2237.                     'page_title' => 'Cheque Register ',
  2238.                     //                'ledger_data'=>$ledger_det,
  2239.                     'export' => "pdf,print",
  2240.                     'check_data' => $check_data_by_bank,
  2241.                     'count_details_by_bank' => $count_details_by_bank,
  2242.                     'page_header' => 'Cheque Register',
  2243.                     'document_type' => 'Cheque Register',
  2244.                     //                'document_mark_image'=>$document_mark['original'],
  2245.                     'page_header_sub' => 'Add',
  2246.                     'start_date' => $start_date,
  2247.                     'end_date' => $end_date,
  2248.                     'head_list' => Accounts::HeadList($em),
  2249.                     //                'provisional'=>$provisional_option,
  2250.                     //                'type_list'=>$type_list,
  2251.                     //            'child_list'=>$child_list,
  2252.                     //                'trans_data_by_closing'=>$trans_data_by_closing,
  2253.                     'item_data' => [],
  2254.                     'received' => 2,
  2255.                     'return' => 1,
  2256.                     'total_w_vat' => 1,
  2257.                     'total_vat' => 1,
  2258.                     'total_wo_vat' => 1,
  2259.                     'invoice_id' => 'abcd1234',
  2260.                     'book_list_by_bank' => $book_list_by_bank,
  2261.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  2262.                     'created_by' => 'created by',
  2263.                     'created_at' => '',
  2264.                     'red' => 0,
  2265.                     //                'desc_head_list'=>$desc_tree_list,
  2266.                     'company_name' => $company_data->getName(),
  2267.                     'company_data' => $company_data,
  2268.                     'company_address' => $company_data->getAddress(),
  2269.                     'company_image' => $company_data->getImage(),
  2270.                     //
  2271.                 )
  2272.             );
  2273.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  2274.                 //                'orientation' => 'landscape',
  2275.                 //                'enable-javascript' => true,
  2276.                 //                'javascript-delay' => 1000,
  2277.                 'no-stop-slow-scripts' => false,
  2278.                 'no-background' => false,
  2279.                 'lowquality' => false,
  2280.                 'encoding' => 'utf-8',
  2281.                 //            'images' => true,
  2282.                 //            'cookie' => array(),
  2283.                 'dpi' => 300,
  2284.                 'image-dpi' => 300,
  2285.                 //                'enable-external-links' => true,
  2286.                 //                'enable-internal-links' => true
  2287.             ));
  2288.             return new Response(
  2289.                 $pdf_response,
  2290.                 200,
  2291.                 array(
  2292.                     'Content-Type' => 'application/pdf',
  2293.                     'Content-Disposition' => 'attachment; filename="Cheque_Register.pdf"'
  2294.                 )
  2295.             );
  2296.         }
  2297.         return $this->render(
  2298.             '@Accounts/pages/print/check_register_print.html.twig',
  2299.             array(
  2300.                 'page_title' => 'Cheque Register ',
  2301.                 //                'ledger_data'=>$ledger_det,
  2302.                 'export' => "pdf,print",
  2303.                 'check_data' => $check_data_by_bank,
  2304.                 'count_details_by_bank' => $count_details_by_bank,
  2305.                 'page_header' => 'Cheque Register',
  2306.                 'document_type' => 'Cheque Register',
  2307.                 //                'document_mark_image'=>$document_mark['original'],
  2308.                 'page_header_sub' => 'Add',
  2309.                 'start_date' => $start_date,
  2310.                 'end_date' => $end_date,
  2311.                 'head_list' => Accounts::HeadList($em),
  2312.                 //                'provisional'=>$provisional_option,
  2313.                 //                'type_list'=>$type_list,
  2314.                 //            'child_list'=>$child_list,
  2315.                 //                'trans_data_by_closing'=>$trans_data_by_closing,
  2316.                 'item_data' => [],
  2317.                 'received' => 2,
  2318.                 'return' => 1,
  2319.                 'total_w_vat' => 1,
  2320.                 'total_vat' => 1,
  2321.                 'total_wo_vat' => 1,
  2322.                 'invoice_id' => 'abcd1234',
  2323.                 'book_list_by_bank' => $book_list_by_bank,
  2324.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  2325.                 'created_by' => 'created by',
  2326.                 'created_at' => '',
  2327.                 'red' => 0,
  2328.                 //                'desc_head_list'=>$desc_tree_list,
  2329.                 'company_name' => $company_data->getName(),
  2330.                 'company_data' => $company_data,
  2331.                 'company_address' => $company_data->getAddress(),
  2332.                 'company_image' => $company_data->getImage(),
  2333.                 //                'p'=>$p
  2334.             )
  2335.         );
  2336.     }
  2337.     public function CheckRegister(Request $request)
  2338.     {
  2339.         $em $this->getDoctrine()->getManager();
  2340.         if ($request->isMethod('POST')) {
  2341.             $startCheckRaw trim((string)$request->request->get('checkNumberStart'));
  2342.             $endCheckRaw trim((string)$request->request->get('checkNumberEnd'));
  2343.             $accountNumber trim((string)$request->request->get('accountNumber'));
  2344.             $bookNumber trim((string)$request->request->get('bookNumber'));
  2345.             $accountsHeadId = (int)$request->request->get('accountsHeadId');
  2346.             $formatId = (int)$request->request->get('formatId');
  2347.             $errors = [];
  2348.             if ($accountsHeadId <= 0) {
  2349.                 $errors[] = 'Please select account.';
  2350.             }
  2351.             if ($accountNumber === '') {
  2352.                 $errors[] = 'Please enter account number.';
  2353.             }
  2354.             if ($bookNumber === '') {
  2355.                 $errors[] = 'Please enter cheque book number.';
  2356.             }
  2357.             if ($startCheckRaw === '' || !ctype_digit($startCheckRaw)) {
  2358.                 $errors[] = 'Please enter a valid starting cheque number.';
  2359.             }
  2360.             if ($endCheckRaw !== '' && !ctype_digit($endCheckRaw)) {
  2361.                 $errors[] = 'Please enter a valid ending cheque number.';
  2362.             }
  2363.             if ($formatId <= 0) {
  2364.                 $errors[] = 'Please select cheque layout format.';
  2365.             }
  2366.             if (empty($errors)) {
  2367.                 $startCheck = (int)$startCheckRaw;
  2368.                 $endCheck $endCheckRaw === '' $startCheck : (int)$endCheckRaw;
  2369.                 if ($startCheck <= 0) {
  2370.                     $errors[] = 'Please enter a valid starting cheque number.';
  2371.                 } elseif ($endCheck $startCheck) {
  2372.                     $errors[] = 'Ending cheque number cannot be smaller than starting cheque number.';
  2373.                 } else {
  2374.                     for ($p $startCheck$p <= $endCheck$p++) {
  2375.                         $duplicate $em->getRepository('ApplicationBundle\\Entity\\AccCheck')
  2376.                             ->createQueryBuilder('c')
  2377.                             ->where('c.accountsHeadId = :headId')
  2378.                             ->andWhere('c.checkNumber = :checkNumber')
  2379.                             ->setParameter('headId'$accountsHeadId)
  2380.                             ->setParameter('checkNumber'$p)
  2381.                             ->getQuery()
  2382.                             ->getOneOrNullResult();
  2383.                         if ($duplicate) {
  2384.                             $errors[] = 'Cheque number ' $p ' already exists for this account head.';
  2385.                             break;
  2386.                         }
  2387.                     }
  2388.                 }
  2389.             }
  2390.             if (!empty($errors)) {
  2391.                 $this->addFlash('error'implode(' '$errors));
  2392.             } else {
  2393.                 for ($p $startCheck$p <= $endCheck$p++) {
  2394.                     $new = new AccCheck();
  2395.                     $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  2396.                     $new->setCheckNumber($p);
  2397.                     $new->setAccountsHeadId($accountsHeadId);
  2398.                     $new->setAccountNumber($accountNumber);
  2399.                     $new->setBookNumber($bookNumber);
  2400.                     $new->setActive(GeneralConstant::ACTIVE);
  2401.                     $new->setAssigned(0);
  2402.                     $new->setStatus(3); // pending. will stay like that till its bounced or confirmed transation physically
  2403.                     $new->setFormatId($formatId);
  2404.                     $new->setType(1);
  2405.                     $new->setDetails(1);
  2406.                     $em->persist($new);
  2407.                 }
  2408.                 $em->flush();
  2409.                 $this->addFlash('success''Cheque range added.');
  2410.             }
  2411.         }
  2412.         return $this->render(
  2413.             '@Accounts/pages/views/check_register.html.twig',
  2414.             array(
  2415.                 'page_title' => 'Cheque Register',
  2416.                 'head_list' => Accounts::HeadList($em),
  2417.                 'format_list' => Accounts::CheckFormatList($em),
  2418.             )
  2419.         );
  2420.     }
  2421.     public function BankGuaranteeList(Request $request)
  2422.     {
  2423.         $em $this->getDoctrine()->getManager();
  2424.         return $this->render(
  2425.             '@Application/pages/accounts/settings/bank_guarantee_list.html.twig',
  2426.             array(
  2427.                 'page_title' => 'Bank Guarantees',
  2428.                 'bgTypes' => AccountsConstant::$BankGuarnteeTypes,
  2429.             )
  2430.         );
  2431.     }
  2432.     public function BankGuaranteeView(Request $request$id 0)
  2433.     {
  2434.         $em $this->getDoctrine()->getManager();
  2435.         $check_here $this->getDoctrine()
  2436.             ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  2437.             ->findOneBy(
  2438.                 array(
  2439.                     'CheckId' => $request->request->get('checkId'$id),
  2440.                     //                    'approved' =>  GeneralConstant::APPROVED,
  2441.                 )
  2442.             );
  2443.         $existingBidData null;
  2444.         if ($check_here->getOpportunityId()) {
  2445.             $lead $this->getDoctrine()
  2446.                 ->getRepository('ApplicationBundle\\Entity\\Opportunity')
  2447.                 ->findOneBy(
  2448.                     array(
  2449.                         'opportunityId' => $check_here->getOpportunityId(),
  2450.                         //                    'approved' =>  GeneralConstant::APPROVED,
  2451.                     )
  2452.                 );
  2453.             if ($lead)
  2454.                 $existingBidData json_decode($lead->getBidInformation(), true);
  2455.         }
  2456.         if ($existingBidData == null)
  2457.             $existingBidData = [];
  2458. //        return new JsonResponse($check_here);
  2459.         return $this->render(
  2460.             '@Application/pages/accounts/settings/view_bank_guarantee.html.twig',
  2461.             array(
  2462.                 'page_title' => 'Bank Guarantee',
  2463.                 'data' => $check_here,
  2464.                 'bgTypes' => AccountsConstant::$BankGuarnteeTypes,
  2465.                 'bidDataList' => SalesConstant::$bidDataList,
  2466.                 'existingBidData' => $existingBidData,
  2467.                 'head_list' => Accounts::getParentLedgerHeads($em),
  2468.             )
  2469.         );
  2470.     }
  2471.     public function ApproveBankGuarantee(Request $request$id 0)
  2472.     {
  2473.         $em $this->getDoctrine()->getManager();
  2474.         $success ProjectM::PaymentReceivedInstrumentApproveAction($em$id);
  2475.         return new JsonResponse(array('success' => $success));
  2476.     }
  2477.     public function CheckManagement(Request $request)
  2478.     {
  2479.         $em $this->getDoctrine()->getManager();
  2480.         if ($request->isMethod('POST')) {
  2481.             if ($request->request->has('carryForwardCheck')) {
  2482.                 $rows $request->request->get('checkNumber');
  2483.                 $accountsHeadIds $request->request->get('accountsHeadId', []);
  2484.                 $accountNumbers $request->request->get('accountNumber', []);
  2485.                 $bookNumbers $request->request->get('bookNumber', []);
  2486.                 $checkTypes $request->request->get('checkType', []);
  2487.                 $checkAmounts $request->request->get('checkAmount', []);
  2488.                 $checkDates $request->request->get('checkDate', []);
  2489.                 $checkNarrations $request->request->get('checkNarration', []);
  2490.                 $receivedHeads $request->request->get('receivedHead', []);
  2491.                 $errors = [];
  2492.                 $submittedKeys = [];
  2493.                 $parsedRows = [];
  2494.                 if (!is_array($rows) || count($rows) < 1) {
  2495.                     $errors[] = 'Please add at least one cheque row.';
  2496.                 } else {
  2497.                     foreach ($rows as $key => $value) {
  2498.                         $rowNo $key 1;
  2499.                         $checkNumber trim((string)$value);
  2500.                         $accountsHeadId = isset($accountsHeadIds[$key]) ? (int)$accountsHeadIds[$key] : 0;
  2501.                         $accountNumber = isset($accountNumbers[$key]) ? trim((string)$accountNumbers[$key]) : '';
  2502.                         $bookNumber = isset($bookNumbers[$key]) ? trim((string)$bookNumbers[$key]) : '';
  2503.                         $checkType = isset($checkTypes[$key]) ? trim((string)$checkTypes[$key]) : '';
  2504.                         $checkAmount = isset($checkAmounts[$key]) ? trim((string)$checkAmounts[$key]) : '';
  2505.                         $checkDateRaw = isset($checkDates[$key]) ? trim((string)$checkDates[$key]) : '';
  2506.                         $checkNarration = isset($checkNarrations[$key]) ? trim((string)$checkNarrations[$key]) : '';
  2507.                         $receivedHead = isset($receivedHeads[$key]) ? (int)$receivedHeads[$key] : 0;
  2508.                         if ($accountsHeadId <= 0) {
  2509.                             $errors[] = 'Please select bank account in row ' $rowNo '.';
  2510.                         }
  2511.                         if ($accountNumber === '') {
  2512.                             $errors[] = 'Please enter account number in row ' $rowNo '.';
  2513.                         }
  2514.                         if ($bookNumber === '') {
  2515.                             $errors[] = 'Please enter book number in row ' $rowNo '.';
  2516.                         }
  2517.                         if ($checkNumber === '' || !ctype_digit($checkNumber)) {
  2518.                             $errors[] = 'Please enter a valid cheque number in row ' $rowNo '.';
  2519.                         }
  2520.                         if ($checkType === '' || !in_array((int)$checkType, array(12), true)) {
  2521.                             $errors[] = 'Please select cheque type in row ' $rowNo '.';
  2522.                         }
  2523.                         if ($checkAmount === '' || !is_numeric($checkAmount) || (float)$checkAmount <= 0) {
  2524.                             $errors[] = 'Please enter a valid amount in row ' $rowNo '.';
  2525.                         }
  2526.                         if ($checkDateRaw === '') {
  2527.                             $errors[] = 'Please enter cheque date in row ' $rowNo '.';
  2528.                         }
  2529.                         if ($receivedHead <= 0) {
  2530.                             $errors[] = 'Please select assigned account in row ' $rowNo '.';
  2531.                         }
  2532.                         $duplicateKey $accountsHeadId '|' $checkNumber;
  2533.                         if ($checkNumber !== '' && isset($submittedKeys[$duplicateKey])) {
  2534.                             $errors[] = 'Cheque number ' $checkNumber ' is duplicated in the submitted rows.';
  2535.                         }
  2536.                         $submittedKeys[$duplicateKey] = 1;
  2537.                         if ($accountsHeadId && $checkNumber !== '' && ctype_digit($checkNumber)) {
  2538.                             $duplicate $em->getRepository('ApplicationBundle\\Entity\\AccCheck')
  2539.                                 ->createQueryBuilder('c')
  2540.                                 ->where('c.accountsHeadId = :headId')
  2541.                                 ->andWhere('c.checkNumber = :checkNumber')
  2542.                                 ->setParameter('headId'$accountsHeadId)
  2543.                                 ->setParameter('checkNumber', (int)$checkNumber)
  2544.                                 ->getQuery()
  2545.                                 ->getOneOrNullResult();
  2546.                             if ($duplicate) {
  2547.                                 $errors[] = 'Cheque number ' $checkNumber ' already exists for this account head.';
  2548.                             }
  2549.                         }
  2550.                         try {
  2551.                             $checkDate = new \DateTime($checkDateRaw);
  2552.                         } catch (\Exception $e) {
  2553.                             $errors[] = 'Please enter a valid cheque date in row ' $rowNo '.';
  2554.                             $checkDate null;
  2555.                         }
  2556.                         $parsedRows[] = array(
  2557.                             'accountsHeadId' => $accountsHeadId,
  2558.                             'accountNumber' => $accountNumber,
  2559.                             'bookNumber' => $bookNumber,
  2560.                             'checkNumber' => $checkNumber,
  2561.                             'checkType' => $checkType,
  2562.                             'checkAmount' => $checkAmount,
  2563.                             'checkDate' => $checkDate,
  2564.                             'checkNarration' => $checkNarration,
  2565.                             'receivedHead' => $receivedHead,
  2566.                         );
  2567.                     }
  2568.                 }
  2569.                 if (empty($errors)) {
  2570.                     foreach ($parsedRows as $row) {
  2571.                         $new = new AccCheck();
  2572.                         $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  2573.                         $new->setCheckNumber($row['checkNumber']);
  2574.                         $new->setAccountsHeadId($row['accountsHeadId']);
  2575.                         $new->setAccountNumber($row['accountNumber']);
  2576.                         $new->setBookNumber($row['bookNumber']);
  2577.                         $new->setActive(GeneralConstant::ACTIVE);
  2578.                         $new->setAssigned(1);
  2579.                         $new_id_list = [$row['receivedHead']];
  2580.                         $new->setRecAccountsHeadId($row['receivedHead']);
  2581.                         $new->setRecAccountsHeadIdList(json_encode($new_id_list));
  2582.                         $new->setCheckNarration($row['checkNarration']);
  2583.                         $new->setCheckAmount($row['checkAmount']);
  2584.                         $checkDate $row['checkDate'];
  2585.                         $new->setCheckDate($checkDate);
  2586.                         $new->setTransactionDate($checkDate);
  2587.                         $new->setLedgerHitDate($checkDate);
  2588.                         $new->setVoucherId(0);
  2589.                         $new->setStatus(3);
  2590.                         $new->setFormatId(0);
  2591.                         $new->setType($row['checkType']);
  2592.                         $new->setDetails(1);
  2593.                         $em->persist($new);
  2594.                     }
  2595.                     $em->flush();
  2596.                     $this->addFlash('success''Carry forward cheques added.');
  2597.                 } else {
  2598.                     $this->addFlash('error'implode(' 'array_unique($errors)));
  2599.                 }
  2600.             } else {
  2601.                 $startCheckRaw trim((string)$request->request->get('checkNumberStart'));
  2602.                 $endCheckRaw trim((string)$request->request->get('checkNumberEnd'));
  2603.                 $accountNumber trim((string)$request->request->get('accountNumber'));
  2604.                 $bookNumber trim((string)$request->request->get('bookNumber'));
  2605.                 $accountsHeadId = (int)$request->request->get('accountsHeadId');
  2606.                 $formatId = (int)$request->request->get('formatId');
  2607.                 $errors = [];
  2608.                 if ($accountsHeadId <= 0) {
  2609.                     $errors[] = 'Please select account.';
  2610.                 }
  2611.                 if ($accountNumber === '') {
  2612.                     $errors[] = 'Please enter account number.';
  2613.                 }
  2614.                 if ($bookNumber === '') {
  2615.                     $errors[] = 'Please enter cheque book number.';
  2616.                 }
  2617.                 if ($startCheckRaw === '' || !ctype_digit($startCheckRaw)) {
  2618.                     $errors[] = 'Please enter a valid starting cheque number.';
  2619.                 }
  2620.                 if ($endCheckRaw !== '' && !ctype_digit($endCheckRaw)) {
  2621.                     $errors[] = 'Please enter a valid ending cheque number.';
  2622.                 }
  2623.                 if ($formatId <= 0) {
  2624.                     $errors[] = 'Please select cheque layout format.';
  2625.                 }
  2626.                 if (empty($errors)) {
  2627.                     $startCheck = (int)$startCheckRaw;
  2628.                     $endCheck $endCheckRaw === '' $startCheck : (int)$endCheckRaw;
  2629.                     if ($startCheck <= 0) {
  2630.                         $errors[] = 'Please enter a valid starting cheque number.';
  2631.                     } elseif ($endCheck $startCheck) {
  2632.                         $errors[] = 'Ending cheque number cannot be smaller than starting cheque number.';
  2633.                     } else {
  2634.                         for ($p $startCheck$p <= $endCheck$p++) {
  2635.                             $duplicate $em->getRepository('ApplicationBundle\\Entity\\AccCheck')->findOneBy(array(
  2636.                                 'accountsHeadId' => $accountsHeadId,
  2637.                                 'accountNumber' => $accountNumber,
  2638.                                 'bookNumber' => $bookNumber,
  2639.                                 'checkNumber' => $p,
  2640.                                 'destroyed' => [0null],
  2641.                             ));
  2642.                             if ($duplicate) {
  2643.                                 $errors[] = 'Cheque number ' $p ' already exists for this account and book.';
  2644.                                 break;
  2645.                             }
  2646.                         }
  2647.                     }
  2648.                 }
  2649.                 if (empty($errors)) {
  2650.                     for ($p $startCheck$p <= $endCheck$p++) {
  2651.                         $new = new AccCheck();
  2652.                         $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  2653.                         $new->setCheckNumber($p);
  2654.                         $new->setAccountsHeadId($accountsHeadId);
  2655.                         $new->setAccountNumber($accountNumber);
  2656.                         $new->setBookNumber($bookNumber);
  2657.                         $new->setActive(GeneralConstant::ACTIVE);
  2658.                         $new->setAssigned(0);
  2659.                         $new->setStatus(3);
  2660.                         $new->setFormatId($formatId);
  2661.                         $new->setType(1);
  2662.                         $new->setDetails(1);
  2663.                         $em->persist($new);
  2664.                     }
  2665.                     $em->flush();
  2666.                     $this->addFlash('success''Cheque range added.');
  2667.                 } else {
  2668.                     $this->addFlash('error'implode(' 'array_unique($errors)));
  2669.                 }
  2670.             }
  2671.         }
  2672.         return $this->render(
  2673.             '@Application/pages/accounts/settings/check_management.html.twig',
  2674.             array(
  2675.                 'page_title' => 'Cheque Management',
  2676.                 'head_list' => Accounts::getParentLedgerHeads($em),
  2677.                 'format_list' => Accounts::CheckFormatList($em),
  2678.             )
  2679.         );
  2680.     }
  2681.     public function CheckManagementEntryForApp(Request $request)
  2682.     {
  2683.         $em $this->getDoctrine()->getManager();
  2684.         if ($request->isMethod('POST')) {
  2685.             $check_number_list = [];
  2686.             if ($request->request->has('carryForwardCheck')) {
  2687.                 foreach ($request->request->get('checkNumber') as $key => $value) {
  2688.                     $new = new AccCheck();
  2689.                     $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  2690.                     $new->setCheckNumber($value);
  2691.                     $new->setAccountsHeadId($request->request->get('accountsHeadId')[$key]);
  2692.                     $new->setAccountNumber($request->request->get('accountNumber')[$key]);
  2693.                     $new->setBookNumber($request->request->get('bookNumber')[$key]);
  2694.                     $new->setActive(GeneralConstant::ACTIVE);
  2695.                     $new->setAssigned(1);
  2696.                     $new_id_list = [$request->request->get('receivedHead')[$key]];
  2697.                     $new->setRecAccountsHeadId($request->request->get('receivedHead')[$key]);
  2698.                     $new->setRecAccountsHeadIdList(json_encode($new_id_list));
  2699.                     $new->setCheckNarration($request->request->get('checkNarration')[$key]);
  2700.                     $new->setCheckAmount($request->request->get('checkAmount')[$key]);
  2701.                     $new->setCheckDate(new \DateTime($request->request->get('checkDate')[$key]));
  2702.                     $new->setTransactionDate(new \DateTime($request->request->get('checkDate')[$key]));
  2703.                     $new->setLedgerHitDate(new \DateTime($request->request->get('checkDate')[$key]));
  2704.                     $new->setVoucherId(0);
  2705.                     $new->setStatus(3); // pending. will stay like that till its bounced or confirmed transation physically
  2706.                     $new->setFormatId(0);
  2707.                     $new->setType($request->request->get('checkType')[$key]);
  2708.                     $new->setDetails(1);
  2709.                     $em->persist($new);
  2710.                     $em->flush();
  2711.                 }
  2712.             } else if ($request->request->get('checkNumberEnd') != '')
  2713.                 for ($p $request->request->get('checkNumberStart'); $p <= $request->request->get('checkNumberEnd'); $p++) {
  2714.                     $new = new AccCheck();
  2715.                     $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  2716.                     $new->setCheckNumber($p);
  2717.                     $new->setAccountsHeadId($request->request->get('accountsHeadId'));
  2718.                     $new->setAccountNumber($request->request->get('accountNumber'));
  2719.                     $new->setBookNumber($request->request->get('bookNumber'));
  2720.                     $new->setActive(GeneralConstant::ACTIVE);
  2721.                     $new->setAssigned(0);
  2722.                     $new->setStatus(3); // pending. will stay like that till its bounced or confirmed transation physically
  2723.                     $new->setFormatId($request->request->get('formatId'));
  2724.                     $new->setType(1);
  2725.                     $new->setDetails(1);
  2726.                     $em->persist($new);
  2727.                     $em->flush();
  2728.                 }
  2729.         }
  2730. //        return $this->render(
  2731. //            'ApplicationBundle:pages/accounts/settings:check_management.html.twig',
  2732. //            array(
  2733. //                'page_title' => 'Cheque Management',
  2734. //                'head_list' => Accounts::getParentLedgerHeads($em),
  2735. //                'format_list' => Accounts::CheckFormatList($em),
  2736. //            )
  2737. //        );
  2738.         return new JsonResponse([
  2739.             'success' => true,
  2740.         ]);
  2741.     }
  2742.     public function SecurityCheckManagement(Request $request)
  2743.     {
  2744.         $em $this->getDoctrine()->getManager();
  2745.         if ($request->isMethod('POST')) {
  2746.             $check_here $this->getDoctrine()
  2747.                 ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  2748.                 ->findOneBy(
  2749.                     array(
  2750.                         'CheckId' => $request->request->get('checkId'),
  2751.                         //                    'approved' =>  GeneralConstant::APPROVED,
  2752.                     )
  2753.                 );
  2754.             if ($check_here) {
  2755.                 $ind_head_id_list $request->request->get('recAccountsHeadId');
  2756.                 $new_id_list = [];
  2757.                 foreach ($ind_head_id_list as $ind_head_id) {
  2758.                     $new_id_list[] = $ind_head_id;
  2759.                 }
  2760.                 $check_here->setRecAccountsHeadId(null);
  2761.                 $check_here->setRecAccountsHeadIdList(json_encode($new_id_list));
  2762.                 $check_here->setCheckNarration($request->request->get('check_narration'));
  2763.                 $check_here->setCheckAmount($request->request->get('check_assigned_amount'));
  2764.                 //                $check_here->setCheckDate(new \DateTime($request->request->get('checkDate')[$k]));
  2765.                 //                        $check_here->setCheckDate(new \DateTime($request->request->get('date')));
  2766.                 $check_here->setAssigned(1);
  2767.                 $check_here->setStatus(1); // pending. will stay like that till its bounced or confirmed transation physically
  2768.                 $check_here->setFormatId($request->request->get('formatId'));
  2769.                 $check_here->setType(1);
  2770.                 $check_here->setSecurityCheck(1);
  2771.                 $check_here->setDetails(1);
  2772.                 //                    $em->persist($new);
  2773.                 $em->flush();
  2774.             }
  2775.         }
  2776.         $sec_check $this->getDoctrine()
  2777.             ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  2778.             ->findBy(
  2779.                 array(
  2780.                     'active' => GeneralConstant::ACTIVE,
  2781.                     'assigned' => [0null],
  2782.                     'destroyed' => [0null],
  2783.                     'securityCheck' => [0null],
  2784.                     'type' => 1,
  2785.                     //                    'approved' =>  GeneralConstant::APPROVED,
  2786.                 )
  2787.             );
  2788.         $assignable_check_list = [];
  2789.         foreach ($sec_check as $s) {
  2790.             $assignable_check_list[] = array(
  2791.                 'checkId' => $s->getCheckId(),
  2792.                 'id' => $s->getCheckId(),
  2793.                 'value' => $s->getCheckId(),
  2794.                 'accountsHeadId' => $s->getAccountsHeadId(),
  2795.                 'text' => $s->getAccountNumber() . "-" sprintf("%07d"$s->getCheckNumber()),
  2796.                 'name' => $s->getAccountNumber() . "-" sprintf("%07d"$s->getCheckNumber())
  2797.             );
  2798.         }
  2799.         return $this->render(
  2800.             '@Application/pages/accounts/settings/security_check.html.twig',
  2801.             array(
  2802.                 'page_title' => 'Security Cheque Management',
  2803.                 'assignableCheckList' => $assignable_check_list,
  2804.                 'heads' => Accounts::getLedgerHeadsWithParents($em),
  2805.                 'format_list' => Accounts::CheckFormatList($em),
  2806.             )
  2807.         );
  2808.     }
  2809.     public function ChequeListAjax(Request $request)
  2810.     {
  2811.         $em $this->getDoctrine()->getManager();
  2812.         $allowed_ids = [];
  2813.         $companyId $this->getLoggedUserCompanyId($request);
  2814.         $viewOption 1;
  2815.         if ($request->query->has('viewOption'))
  2816.             $viewOption $request->query->get('viewOption');
  2817.         $listData Accounts::GetChequetListForChequeListAjax($em$viewOption$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  2818.         //        if ($request->isMethod('POST'))
  2819.         {
  2820.             if ($request->query->has('dataTableQry')) {
  2821.                 return new JsonResponse(
  2822.                     $listData
  2823.                 );
  2824.             }
  2825.         }
  2826.         return $this->render(
  2827.             '@Sales/pages/list_tables/client_list.html.twig',
  2828.             //         return $this->render('ApplicationBundle:pages/dashboard:test_pix_invent.html.twig',
  2829.             array(
  2830.                 'page_title' => 'Cheque List',
  2831.             )
  2832.         );
  2833.     }
  2834.     public function GetCheckList(Request $request)
  2835.     {
  2836.         $em $this->getDoctrine()->getManager();
  2837.         if ($request->isMethod('POST')) {
  2838.             $head_list Accounts::HeadList($em);
  2839.             $voucher_list Accounts::VoucherListForCheckRegister($em);
  2840.             $find_array = array(
  2841.                 'type' => 1
  2842.             );
  2843.             if ($request->request->has('viewOption')) {
  2844.                 if ($request->request->get('viewOption') == 1)
  2845.                     $find_array = ['active' => GeneralConstant::ACTIVE];
  2846.                 if ($request->request->get('viewOption') == 2)
  2847.                     $find_array = ['active' => GeneralConstant::INACTIVE];
  2848.             }
  2849.             $assignedflag $request->request->has('assign_flag') ? $request->request->get('assign_flag') : 0;
  2850.             $unassignedflag $request->request->has('unassign_flag') ? $request->request->get('unassign_flag') : 0;
  2851.             $securityCheckFlag $request->request->has('security_check_flag') ? $request->request->get('security_check_flag') : 0;
  2852.             if ($assignedflag == 1)
  2853.                 $find_array['assigned'] = 1;
  2854.             if ($unassignedflag == 1)
  2855.                 $find_array['assigned'] = [0null];
  2856.             if ($securityCheckFlag == 1)
  2857.                 $find_array['securityCheck'] = 1;
  2858.             $check_query $this->getDoctrine()
  2859.                 ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  2860.                 ->findBy(
  2861.                     $find_array,
  2862.                     array(
  2863.                         //                        'checkNumber'=>'ASC'
  2864.                         'CheckId' => 'ASC'
  2865.                     )
  2866.                 );
  2867.             $check_data = [];
  2868.             $start_date $request->request->has('start_date') ? (new \DateTime($request->request->get('start_date'))) : '';
  2869.             $end_date $request->request->has('end_date') ? (new \DateTime($request->request->get('end_date') . ' ' ' 23:59:59.999')) : '';
  2870.             //            if($end_date!='')
  2871.             //                $end_date->modify('+1 day');
  2872.             $book_list_by_bank = [];
  2873.             foreach ($check_query as $entry) {
  2874.                 if ($assignedflag == 1) {
  2875.                     if ($securityCheckFlag == 0) {
  2876.                         $checkTransDate $entry->getTransactionDate();
  2877.                         if ($checkTransDate == null)
  2878.                             continue;
  2879.                         if ($start_date != '' && ($checkTransDate instanceof \DateTime) && ($start_date $checkTransDate))
  2880.                             continue;
  2881.                         if ($end_date != '' && ($checkTransDate instanceof \DateTime) && ($end_date $checkTransDate))
  2882.                             continue;
  2883.                     }
  2884.                 }
  2885.                 $v_date = isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['date'] : '';
  2886.                 //                if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
  2887.                 if ($start_date != '' && ($v_date instanceof \DateTime) && ($start_date $v_date))
  2888.                     continue;
  2889.                 //                if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
  2890.                 if ($end_date != '' && ($v_date instanceof \DateTime) && ($end_date $v_date))
  2891.                     continue;
  2892.                 $checkDate = ($entry->getCheckDate() instanceof \DateTime) ? $entry->getCheckDate()->format('m/d/Y') : '';
  2893.                 $assignedDate = ($entry->getAssignedDate() instanceof \DateTime) ? $entry->getAssignedDate()->format('m/d/Y') : '';
  2894.                 if (!isset($book_list_by_bank[$entry->getAccountsHeadId()])) $book_list_by_bank[$entry->getAccountsHeadId()] = [];
  2895.                 if (!in_array($entry->getBookNumber(), $book_list_by_bank[$entry->getAccountsHeadId()])) {
  2896.                     $book_list_by_bank[$entry->getAccountsHeadId()][] = $entry->getBookNumber();
  2897.                 }
  2898.                 $check_data[] = array(
  2899.                     'checkId' => $entry->getCheckId(),
  2900.                     //                    'checkNumber'=>$entry->getCheckNumber(),
  2901.                     'checkNumber' => sprintf("%07d"$entry->getCheckNumber()),
  2902.                     'checkNarration' => $entry->getCheckNarration(),
  2903.                     'voucherNarration' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['desc'] : '',
  2904.                     'voucherDate' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['date']->format('m/d/Y') : '',
  2905.                     'accountNumber' => $entry->getAccountNumber(),
  2906.                     'checkDate' => $checkDate,
  2907.                     'active' => $entry->getActive(),
  2908.                     'head' => isset($head_list[$entry->getAccountsHeadId()]) ? $head_list[$entry->getAccountsHeadId()]['name'] : '',
  2909.                     'head_id' => $entry->getAccountsHeadId(),
  2910.                     'received_head' => isset($head_list[$entry->getRecAccountsHeadId()]) ? $head_list[$entry->getRecAccountsHeadId()]['name'] : '',
  2911.                     'received_head_id' => $entry->getRecAccountsHeadId(),
  2912.                     'received_head_id_list' => $entry->getRecAccountsHeadIdList(),
  2913.                     'assignedDate' => $assignedDate,
  2914.                     'checkAmount' => $entry->getCheckAmount(),
  2915.                     'voucher_number' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['doc_hash'] : '',
  2916.                     'voucher_id' => $entry->getVoucherId(),
  2917.                     'printed' => $entry->getPrinted(),
  2918.                 );
  2919.             }
  2920.             $count_details_by_bank = [];
  2921.             if ($request->request->has('countDetails')) {
  2922.                 $check_query $this->getDoctrine()
  2923.                     ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  2924.                     ->findAll();
  2925.                 $count_details_by_bank = [];
  2926.                 $assigned_books = [];
  2927.                 foreach ($check_query as $entry) {
  2928.                     if (isset($count_details_by_bank[$entry->getAccountsHeadId()])) {
  2929.                         $count_details_by_bank[$entry->getAccountsHeadId()]['total_chk'] += 1;
  2930.                         if ($entry->getAssigned() == 1)
  2931.                             $count_details_by_bank[$entry->getAccountsHeadId()]['total_ass'] += 1;
  2932.                         else
  2933.                             $count_details_by_bank[$entry->getAccountsHeadId()]['total_avail'] += 1;
  2934.                         if (!in_array($entry->getBookNumber(), $assigned_books)) {
  2935.                             $count_details_by_bank[$entry->getAccountsHeadId()]['books'] .= (', ' $entry->getBookNumber());
  2936.                             array_push($assigned_books$entry->getBookNumber());
  2937.                         }
  2938.                     } else {
  2939.                         $count_details_by_bank[$entry->getAccountsHeadId()]['total_chk'] = 1;
  2940.                         $count_details_by_bank[$entry->getAccountsHeadId()]['total_ass'] = 0;
  2941.                         $count_details_by_bank[$entry->getAccountsHeadId()]['books'] = '';
  2942.                         $count_details_by_bank[$entry->getAccountsHeadId()]['total_avail'] = 0;
  2943.                         if ($entry->getAssigned() == 1)
  2944.                             $count_details_by_bank[$entry->getAccountsHeadId()]['total_ass'] = 1;
  2945.                         else
  2946.                             $count_details_by_bank[$entry->getAccountsHeadId()]['total_avail'] = 1;
  2947.                         if (!in_array($entry->getBookNumber(), $assigned_books)) {
  2948.                             $count_details_by_bank[$entry->getAccountsHeadId()]['books'] = (' ' $entry->getBookNumber());
  2949.                             array_push($assigned_books$entry->getBookNumber());
  2950.                         }
  2951.                     }
  2952.                 }
  2953.             }
  2954.             if ($securityCheckFlag == 0) {
  2955.                 foreach ($voucher_list as $key => $entry) {
  2956.                     $v_date $entry['date'];
  2957.                     //                if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
  2958.                     if ($start_date != '' && ($v_date instanceof \DateTime) && ($start_date $v_date))
  2959.                         continue;
  2960.                     //                if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
  2961.                     if ($end_date != '' && ($v_date instanceof \DateTime) && ($end_date $v_date))
  2962.                         continue;
  2963.                     if (!in_array($entry['prMethod'], [34]))
  2964.                         continue;
  2965.                     //                if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
  2966.                     //                    continue;
  2967.                     //                if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
  2968.                     //                    continue;
  2969.                     $trans_details $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(
  2970.                         array(
  2971.                             'transactionId' => $key,
  2972.                             'position' => 'cr'
  2973.                         )
  2974.                     );
  2975.                     foreach ($trans_details as $value) {
  2976.                         $checkDate $entry['date']->format('m/d/Y');
  2977.                         $assignedDate $entry['date']->format('m/d/Y');
  2978.                         $dr_details $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(
  2979.                             array(
  2980.                                 'transactionId' => $key,
  2981.                                 'position' => 'dr'
  2982.                             )
  2983.                         );
  2984.                         $rec_id_list = [];
  2985.                         $rec_narr "";
  2986.                         foreach ($dr_details as $dt) {
  2987.                             $rec_id_list[] = $dt->getAccountsHeadId();
  2988.                             $rec_narr .= $head_list[$dt->getAccountsHeadId()]['name'];
  2989.                             $rec_narr .= ", ";
  2990.                         }
  2991.                         $check_data[] = array(
  2992.                             'checkId' => 0,
  2993.                             'checkNumber' => $entry['prReference'],
  2994.                             'checkNarration' => $rec_narr,
  2995.                             'voucherNarration' => $entry['desc'],
  2996.                             'voucherDate' => $entry['date']->format('m/d/Y'),
  2997.                             'accountNumber' => '',
  2998.                             'checkDate' => $checkDate,
  2999.                             'head' => $head_list[$value->getAccountsHeadId()]['name'],
  3000.                             'head_id' => $value->getAccountsHeadId(),
  3001.                             'received_head' => $rec_narr,
  3002.                             'received_head_id' => 0,
  3003.                             'received_head_id_list' => json_encode($rec_id_list),
  3004.                             'assignedDate' => $assignedDate,
  3005.                             'checkAmount' => $value->getAmount(),
  3006.                             'voucher_number' => $entry['doc_hash'],
  3007.                             'voucher_id' => $key,
  3008.                             'printed' => 1,
  3009.                         );
  3010.                     }
  3011.                 }
  3012.             }
  3013.             if ($check_data) {
  3014.                 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));
  3015.             }
  3016.             return new JsonResponse(array("success" => false'start_date' => $start_date'end_date' => $end_date,));
  3017.         }
  3018.         return new JsonResponse(array("success" => false));
  3019.     }
  3020.     public function GetCheckListForVoucher(Request $request)
  3021.     {
  3022.         $em $this->getDoctrine()->getManager();
  3023.         if ($request->isMethod('POST')) {
  3024.             $cr_table_heads $request->request->get('cr_table_heads', []);
  3025.             $dr_table_heads $request->request->get('dr_table_heads', []);
  3026.             $voucher_heads = [];
  3027.             $v_id $request->request->get('v_id'0);
  3028.             $voucher_list Accounts::VoucherList($em$v_id1);
  3029.             foreach ($voucher_list as $t) {
  3030.                 foreach ($t['det'] as $td)
  3031.                     $voucher_heads[] = $td['head_id'];
  3032.             }
  3033.             $head_list Accounts::HeadList($emarray_merge($cr_table_heads$dr_table_heads$voucher_heads));
  3034.             $checkAssignType $request->request->get('checkAssignType');
  3035.             $cr_table_heads_amount $request->request->get('cr_table_heads_amount');
  3036.             $check_list = [];
  3037.             $check_list_array = [];
  3038.             $check_list_by_ac_head = [];
  3039.             if ($request->request->get('checkModalType') == 'edit') {
  3040.                 //first check if the voucher is already tagged ( usually for edit)
  3041.                 if ($v_id != 0) {
  3042.                     $check_query $this->getDoctrine()
  3043.                         ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  3044.                         ->findBy(
  3045.                             array(
  3046.                                 'voucherId' => $v_id,
  3047.                                 'active' => GeneralConstant::ACTIVE,
  3048.                                 'destroyed' => [0null],
  3049.                                 'securityCheck' => [0null],
  3050.                             ),
  3051.                             array(
  3052.                                 //                            'checkNumber'=>'ASC'
  3053.                                 'CheckId' => 'ASC'
  3054.                             )
  3055.                         );
  3056.                     foreach ($check_query as $entry) {
  3057.                         $checkDate = ($entry->getCheckDate() instanceof \DateTime) ? $entry->getCheckDate()->format('m/d/Y') : '';
  3058.                         $assignedDate = ($entry->getAssignedDate() instanceof \DateTime) ? $entry->getAssignedDate()->format('m/d/Y') : '';
  3059.                         $chk = array(
  3060.                             'checkId' => $entry->getCheckId(),
  3061.                             'checkNumber' => sprintf("%07d"$entry->getCheckNumber()),
  3062.                             'accountNumber' => $entry->getAccountNumber(),
  3063.                             'checkDate' => $checkDate,
  3064.                             'head' => $head_list[$entry->getAccountsHeadId()]['name'],
  3065.                             'head_id' => $entry->getAccountsHeadId(),
  3066.                             'received_head' => isset($head_list[$entry->getRecAccountsHeadId()]) ? $head_list[$entry->getRecAccountsHeadId()]['name'] : '',
  3067.                             'received_head_id' => $entry->getRecAccountsHeadId(),
  3068.                             'received_head_id_list' => $entry->getRecAccountsHeadIdList(),
  3069.                             'assignedDate' => $assignedDate,
  3070.                             'checkAmount' => $entry->getCheckAmount(),
  3071.                             'voucher_number' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['doc_hash'] : '',
  3072.                             'voucher_id' => $entry->getVoucherId(),
  3073.                         );
  3074.                         $check_list_by_ac_head[$entry->getAccountsHeadId()][] = $chk;
  3075.                         $check_list[$entry->getCheckId()] = $chk;
  3076.                     }
  3077.                 }
  3078.                 //now getting un assigned checks for the same heads
  3079.                 $check_query $this->getDoctrine()
  3080.                     ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  3081.                     ->findBy(
  3082.                         array(
  3083.                             'accountsHeadId' => $cr_table_heads,
  3084.                             'active' => GeneralConstant::ACTIVE,
  3085.                             'assigned' => [0null],
  3086.                             'destroyed' => [0null],
  3087.                             'securityCheck' => [0null],
  3088.                         ),
  3089.                         array(
  3090.                             //                            'checkNumber'=>'ASC'
  3091.                             'CheckId' => 'ASC'
  3092.                         )
  3093.                     );
  3094.                 foreach ($check_query as $entry) {
  3095.                     $checkDate = ($entry->getCheckDate() instanceof \DateTime) ? $entry->getCheckDate()->format('m/d/Y') : '';
  3096.                     $assignedDate = ($entry->getAssignedDate() instanceof \DateTime) ? $entry->getAssignedDate()->format('m/d/Y') : '';
  3097.                     $chk = array(
  3098.                         'checkId' => $entry->getCheckId(),
  3099.                         'checkNumber' => sprintf("%07d"$entry->getCheckNumber()),
  3100.                         'accountNumber' => $entry->getAccountNumber(),
  3101.                         'checkDate' => $checkDate,
  3102.                         'head' => $head_list[$entry->getAccountsHeadId()]['name'],
  3103.                         'head_id' => $entry->getAccountsHeadId(),
  3104.                         'received_head' => isset($head_list[$entry->getRecAccountsHeadId()]) ? $head_list[$entry->getRecAccountsHeadId()]['name'] : '',
  3105.                         'received_head_id' => $entry->getRecAccountsHeadId(),
  3106.                         'assignedDate' => $assignedDate,
  3107.                         'checkAmount' => $entry->getCheckAmount(),
  3108.                         'voucher_number' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['doc_hash'] : '',
  3109.                         'voucher_id' => $entry->getVoucherId(),
  3110.                     );
  3111.                     $check_list_by_ac_head[$entry->getAccountsHeadId()][] = $chk;
  3112.                     $check_list[$entry->getCheckId()] = $chk;
  3113.                 }
  3114.                 //                if(empty($check_query))
  3115.                 if ($check_list) {
  3116.                     return new JsonResponse(array(
  3117.                         "success" => true,
  3118.                         "content" => $check_list,
  3119.                         "check_list_by_ac_head" => $check_list_by_ac_head,
  3120.                         "check_list" => $check_list,
  3121.                         'head_list' => $head_list
  3122.                     ));
  3123.                 }
  3124.             }
  3125.             if ($request->request->get('checkModalType') == 'view') {
  3126.                 $check_query $this->getDoctrine()
  3127.                     ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  3128.                     ->findBy(
  3129.                         array(
  3130.                             'voucherId' => $v_id
  3131.                         )
  3132.                     );
  3133.                 foreach ($check_query as $entry) {
  3134.                     $checkDate = ($entry->getCheckDate() instanceof \DateTime) ? $entry->getCheckDate()->format('m/d/Y') : '';
  3135.                     $assignedDate = ($entry->getAssignedDate() instanceof \DateTime) ? $entry->getAssignedDate()->format('m/d/Y') : '';
  3136.                     $chk = array(
  3137.                         'checkId' => $entry->getCheckId(),
  3138.                         'checkNumber' => sprintf("%07d"$entry->getCheckNumber()),
  3139.                         'accountNumber' => $entry->getAccountNumber(),
  3140.                         'checkDate' => $checkDate,
  3141.                         'checkNarration' => $entry->getCheckNarration(),
  3142.                         'head' => $head_list[$entry->getAccountsHeadId()]['name'],
  3143.                         'head_id' => $entry->getAccountsHeadId(),
  3144.                         'printed' => $entry->getPrinted(),
  3145.                         'received_head' => isset($head_list[$entry->getRecAccountsHeadId()]) ? $head_list[$entry->getRecAccountsHeadId()]['name'] : '',
  3146.                         'received_head_id' => $entry->getRecAccountsHeadId(),
  3147.                         'received_head_id_list' => $entry->getRecAccountsHeadIdList(),
  3148.                         'assignedDate' => $assignedDate,
  3149.                         'checkAmount' => $entry->getCheckAmount(),
  3150.                         'voucher_number' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['doc_hash'] : '',
  3151.                         'voucher_id' => $entry->getVoucherId(),
  3152.                     );
  3153.                     $check_list_by_ac_head[$entry->getAccountsHeadId()][] = $chk;
  3154.                     $check_list[$entry->getCheckId()] = $chk;
  3155.                     $check_list_array[] = $chk;
  3156.                 }
  3157.                 if (!empty($check_list)) {
  3158.                     return new JsonResponse(array(
  3159.                         "success" => true,
  3160.                         "content" => $check_list,
  3161.                         //                        "check_list_by_ac_head"=>$check_list_by_ac_head,
  3162.                         "check_list" => $check_list_array,
  3163.                         'head_list' => $head_list
  3164.                     ));
  3165.                 }
  3166.             }
  3167.             return new JsonResponse(array("success" => false));
  3168.         }
  3169.         return new JsonResponse(array("success" => false));
  3170.     }
  3171.     public function GetCheckListForBrs(Request $request)
  3172.     {
  3173.         $em $this->getDoctrine()->getManager();
  3174.         if ($request->isMethod('POST')) {
  3175.             $bank_head $request->request->get('bank_head');
  3176.             $statement_date $request->request->get('statement_date');
  3177.             $statement_date_dt = new \DateTime($statement_date);
  3178.             $statement_date_str $statement_date_dt->format('Y-m-d');
  3179.             $head_list Accounts::HeadList($em);
  3180.             //            $voucher_list=Accounts::VoucherList($em);
  3181.             $voucher_list Accounts::VoucherListForBrs($em$bank_head);
  3182.             $check_list = [];
  3183.             $check_list_array = [];
  3184.             $check_list_by_ac_head = [];
  3185.             $get_kids_sql "SELECT * FROM acc_check ";
  3186.             //            $get_kids_sql.="  Where status=3 and check_date <='".$statement_date_str." 00:00:00' and ( rec_accounts_head_id=".$bank_head;
  3187.             $get_kids_sql .= "  Where status=3 and ledger_hit_date <='" $statement_date_str " 00:00:00' and ( rec_accounts_head_id=" $bank_head;
  3188.             //            $get_kids_sql.="  Where status=3 and transaction_date <='".$statement_date_str." 00:00:00' and ( rec_accounts_head_id=".$bank_head;
  3189.             $get_kids_sql .= "  or accounts_head_id=" $bank_head ") ";
  3190.             $get_kids_sql .= ' ORDER BY check_id ASC';
  3191.             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  3192.             
  3193.             $query_output $stmt;
  3194.             if (!empty($query_output)) {
  3195.                 foreach ($query_output as $entry) {
  3196.                     //                    if($entry['type']==1)
  3197.                     //                    {
  3198.                     //                        $sub=($entry['rec_accounts_head_id']==$bank_head?0:$entry['check_amount']);
  3199.                     //                        $add=($entry['rec_accounts_head_id']==$bank_head?$entry['check_amount']:0);
  3200.                     //                    }
  3201.                     //                    if($entry['type']==2)
  3202.                     //                    {
  3203.                     $sub = ($entry['rec_accounts_head_id'] == $bank_head $entry['check_amount']);
  3204.                     $add = ($entry['rec_accounts_head_id'] == $bank_head $entry['check_amount'] : 0);
  3205.                     //                    }
  3206.                     $checkDate = ($entry['check_date'] instanceof \DateTime) ? $entry['check_date']->format('m-d-Y') : (new \DateTime($entry['check_date']))->format('m-d-Y');
  3207.                     $assignedDate = ($entry['assigned_date'] instanceof \DateTime) ? $entry['assigned_date']->format('m-d-Y') : '';
  3208.                     $chk = array(
  3209.                         'checkId' => $entry['check_id'],
  3210.                         'checkNumber' => $entry['check_number'],
  3211.                         'accountNumber' => $entry['acc_number'],
  3212.                         'checkDate' => $checkDate,
  3213.                         'head' => $head_list[$entry['accounts_head_id']]['name'],
  3214.                         'head_id' => $entry['accounts_head_id'],
  3215.                         'check_type' => $entry['type'],
  3216.                         'received_head' => isset($head_list[$entry['rec_accounts_head_id']]) ? $head_list[$entry['rec_accounts_head_id']]['name'] : '',
  3217.                         'received_head_id' => $entry['rec_accounts_head_id'],
  3218.                         'assignedDate' => $assignedDate,
  3219.                         'checkAmount' => $entry['check_amount'],
  3220.                         'sub' => $sub,
  3221.                         'add' => $add,
  3222.                         'received_head_id_list' => ($entry['rec_accounts_head_id_list'] == null) ? [] : json_decode($entry['rec_accounts_head_id_list'], true),
  3223.                         'voucherNumber' => isset($voucher_list[$entry['voucher_id']]) ? $voucher_list[$entry['voucher_id']]['doc_hash'] : '',
  3224.                         'voucherDate' => isset($voucher_list[$entry['voucher_id']]) ? $voucher_list[$entry['voucher_id']]['date']->format('m-d-Y') : '',
  3225.                         'transactionDate' => isset($voucher_list[$entry['voucher_id']]) ? $voucher_list[$entry['voucher_id']]['date']->format('m-d-Y') : '',
  3226.                         'voucher_id' => $entry['voucher_id'],
  3227.                     );
  3228.                     //                    $check_list_by_ac_head[$entry->getAccountsHeadId()][]=$chk;
  3229.                     $check_list[$entry['check_id']] = $chk;
  3230.                     $check_list_array[] = $chk;
  3231.                 }
  3232.             }
  3233.             foreach ($voucher_list as $key => $entry) {
  3234.                 $v_date $entry['date'];
  3235.                 $l_date $entry['ledgerHitDate'];
  3236.                 if ($l_date == null)
  3237.                     $l_date $v_date;
  3238.                 //                if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
  3239.                 //                if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
  3240.                 if ($entry['ledgerHit'] != 1)
  3241.                     continue;
  3242.                 if ($statement_date_dt != '' && ($l_date instanceof \DateTime) && ($statement_date_dt $l_date))
  3243.                     continue;
  3244.                 if ($entry['document_type'] != 6) {
  3245.                     if (!in_array($entry['prMethod'], [34]))
  3246.                         continue;
  3247.                 }
  3248.                 if ($entry['document_type'] == 6) {
  3249.                     if (!in_array($entry['prMethod'], [1]))
  3250.                         continue;
  3251.                 }
  3252.                 if ($entry['provisional'] != 1)
  3253.                     continue;
  3254.                 if (!in_array($bank_head$entry['pendReconIdList']))
  3255.                     continue;
  3256.                 //                if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
  3257.                 //                    continue;
  3258.                 //                if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
  3259.                 //                    continue;
  3260.                 if ($entry['document_type'] == || $entry['document_type'] == 6)
  3261.                     $trans_details $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(
  3262.                         array(
  3263.                             'transactionId' => $key,
  3264.                             'position' => 'cr',
  3265.                             //                        'accountsHeadId'=>$bank_head
  3266.                         )
  3267.                     );
  3268.                 else
  3269.                     $trans_details $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(
  3270.                         array(
  3271.                             'transactionId' => $key,
  3272.                             'position' => 'cr',
  3273.                             'accountsHeadId' => $bank_head
  3274.                         )
  3275.                     );
  3276.                 if (!empty($trans_details)) {
  3277.                     foreach ($trans_details as $k2 => $value) {
  3278.                         $checkDate $entry['date']->format('m/d/Y');
  3279.                         if ($l_date != null)
  3280.                             $ledgerHitDate $entry['ledgerHitDate']->format('m/d/Y');
  3281.                         else
  3282.                             $ledgerHitDate $entry['date']->format('m/d/Y');
  3283.                         $assignedDate $entry['date']->format('m/d/Y');
  3284.                         $dr_details $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(
  3285.                             array(
  3286.                                 'transactionId' => $key,
  3287.                                 'position' => 'dr'
  3288.                             )
  3289.                         );
  3290.                         $rec_id_list = [];
  3291.                         $rec_narr "";
  3292.                         foreach ($dr_details as $dt) {
  3293.                             $rec_id_list[] = $dt->getAccountsHeadId();
  3294.                             $rec_narr .= $head_list[$dt->getAccountsHeadId()]['name'];
  3295.                             $rec_narr .= ", ";
  3296.                         }
  3297.                         $chk = array(
  3298.                             'checkId' => 'v' $key "_" $value->getTransactionDetailsId(),
  3299.                             'checkNumber' => $entry['prReference'],
  3300.                             'prRef' => $entry['earlyPrReference'],
  3301.                             'accountNumber' => '',
  3302.                             'sub' => ($value->getAccountsHeadId() == $bank_head) ? $value->getAmount() : 0,
  3303.                             'add' => ($value->getAccountsHeadId() != $bank_head) ? $value->getAmount() : 0,
  3304.                             'checkDate' => $ledgerHitDate,
  3305.                             'head' => $head_list[$value->getAccountsHeadId()]['name'],
  3306.                             'head_id' => $value->getAccountsHeadId(),
  3307.                             'check_type' => 1,
  3308.                             'received_head' => $rec_narr,
  3309.                             'received_head_id' => 0,
  3310.                             'received_head_id_list' => $rec_id_list,
  3311.                             //                            'received_head_id_list' => json_encode($rec_id_list),
  3312.                             'assignedDate' => $assignedDate,
  3313.                             'checkAmount' => $value->getAmount(),
  3314.                             'voucherNumber' => $entry['doc_hash'],
  3315.                             'voucherDate' => $v_date->format('m-d-Y'),
  3316.                             'transactionDate' => $v_date->format('m-d-Y'),
  3317.                             'voucher_id' => $key,
  3318.                         );
  3319.                         //                    $check_list_by_ac_head[$entry->getAccountsHeadId()][]=$chk;
  3320.                         $check_list['v' $key "_" $value->getTransactionDetailsId()] = $chk;
  3321.                         $check_list_array[] = $chk;
  3322.                     }
  3323.                 }
  3324.             }
  3325.             ///old
  3326.             //            $get_kids_sql="select acc_closing_balance.balance, acc_closing_balance.opening, acc_closing_balance.date,
  3327.             //                        acc_accounts_head.path_tree,
  3328.             //                        acc_accounts_head.head_nature
  3329.             //                        from acc_closing_balance
  3330.             //                        join acc_accounts_head on acc_accounts_head.accounts_head_id=acc_closing_balance.accounts_head_id ";
  3331.             ////        $get_kids_sql.=" Where parent_id in(".implode(",", $path_array).")";
  3332.             //            $get_kids_sql.=" where  acc_accounts_head.accounts_head_id=".$bank_head;
  3333.             //
  3334.             //                $get_kids_sql .=" AND acc_closing_balance.date <='".$statement_date_str." 00:00:00' ";
  3335.             //
  3336.             //
  3337.             //
  3338.             //            $get_kids_sql.=" Order by acc_closing_balance.date desc LIMIT 1";
  3339.             //            $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
  3340.             //            
  3341.             //            $query_output = $stmt;
  3342.             ///old end
  3343.             $head_last_balance_data = [];
  3344.             $head_last_balance 0;
  3345.             //new method
  3346.             $balance_data Accounts::GetBalanceOnDate($em$statement_date_str, []);
  3347.             $head_last_balance $balance_data[$bank_head]['end_balance']['balance'];
  3348.             //new end
  3349.             //            if(!empty($query_output))
  3350.             //            {
  3351.             //                $head_last_balance_data=$query_output[0]   ;
  3352.             //                $head_last_balance=$query_output[0]['balance']   ;
  3353.             //            }
  3354.             //            else
  3355.             //            {
  3356.             //                $head_last_balance_data=array()   ;
  3357.             //                $head_last_balance=$head_list[$bank_head]['opening_balance']   ;
  3358.             //            }
  3359.             //                if($check_list){
  3360.             if ($check_list || $head_last_balance != 0) {
  3361.                 return new JsonResponse(array(
  3362.                     "success" => true,
  3363.                     "content" => $check_list,
  3364.                     //                        "check_list_by_ac_head"=>$check_list_by_ac_head,
  3365.                     'def_date' => $statement_date_dt->format('F d, Y'),
  3366.                     "check_list" => $check_list,
  3367.                     "check_list_array" => $check_list_array,
  3368.                     'head_list' => $head_list,
  3369.                     'head_last_balance_data' => $head_last_balance_data,
  3370.                     'head_last_balance' => $head_last_balance,
  3371.                 ));
  3372.             }
  3373.             return new JsonResponse(array("success" => false));
  3374.         }
  3375.         return new JsonResponse(array("success" => false));
  3376.     }
  3377.     public function CreatePurchaseInvoice(Request $request$id 0)
  3378.     {
  3379.         $em $this->getDoctrine()->getManager();
  3380.         if ($request->isMethod('POST')) {
  3381.             $data $request->request;
  3382.             $entity_id array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice']; //change
  3383.             $dochash $request->request->get('docHash'); //change
  3384.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3385.             $approveRole $request->request->get('approvalRole');
  3386.             $approveHash $request->request->get('approvalHash');
  3387.             if (!DocValidation::isInsertable(
  3388.                 $em,
  3389.                 $entity_id,
  3390.                 $dochash,
  3391.                 $loginId,
  3392.                 $approveRole,
  3393.                 $approveHash,
  3394.                 $id
  3395.             )) {
  3396.                 $this->addFlash(
  3397.                     'error',
  3398.                     'Sorry Couldnot insert Data.'
  3399.                 );
  3400.             } else {
  3401.                 $funcname 'PurchaseInvoice';
  3402.                 $doc_id $id;
  3403.                 DeleteDocument::$funcname($em$doc_id0);
  3404.                 $create_new_pi Accounts::CreatePurchaseInvoice($id$this->getDoctrine()->getManager(), $data$request->getSession()->get(UserConstants::USER_LOGIN_ID));
  3405.                 //now add Approval info
  3406.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3407.                 $approveRole $request->request->get('approvalRole');
  3408.                 $options = array(
  3409.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3410.                     'notification_server' => $this->container->getParameter('notification_server'),
  3411.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  3412.                     'url' => $this->generateUrl(
  3413.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice']]['entity_view_route_path_name']
  3414.                     )
  3415.                 );
  3416.                 System::setApprovalInfo(
  3417.                     $this->getDoctrine()->getManager(),
  3418.                     $options,
  3419.                     array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice'],
  3420.                     $create_new_pi['pi_id'],
  3421.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3422.                 );
  3423.                 System::createEditSignatureHash(
  3424.                     $this->getDoctrine()->getManager(),
  3425.                     array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice'],
  3426.                     $create_new_pi['pi_id'],
  3427.                     $loginId,
  3428.                     $approveRole,
  3429.                     $request->request->get('approvalHash')
  3430.                 );
  3431.                 $this->addFlash(
  3432.                     'success',
  3433.                     'New Invoice Added.'
  3434.                 );
  3435.                 $url $this->generateUrl(
  3436.                     'view_purchase_invoice'
  3437.                 );
  3438.                 System::AddNewNotification(
  3439.                     $this->container->getParameter('notification_enabled'),
  3440.                     $this->container->getParameter('notification_server'),
  3441.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  3442.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  3443.                     "Purchase Invoice : " $dochash " Has Been Created And is Under Processing",
  3444.                     'pos',
  3445.                     System::getPositionIdsByDepartment($em, [GeneralConstant::ACCOUNTS_DEPARTMENTGeneralConstant::PURCHASE_DEPARTMENT]),
  3446.                     'success',
  3447.                     $url "/" $create_new_pi['pi_id'],
  3448.                     "Purchase Bill"
  3449.                 );
  3450.                 return $this->redirect($url "/" $create_new_pi['pi_id']);
  3451.             }
  3452.         }
  3453.         $extData = [];
  3454.         $extDetailsData = [];
  3455.         if ($id == 0) {
  3456.         } else {
  3457.             $extTrans $em->getRepository('ApplicationBundle\\Entity\\PurchaseInvoice')->findOneBy(
  3458.                 array(
  3459.                     'purchaseInvoiceId' => $id///material
  3460.                 )
  3461.             );
  3462.             //now if its not editable, redirect to view
  3463.             if ($extTrans) {
  3464.                 if ($extTrans->getEditFlag() != 1) {
  3465.                     $url $this->generateUrl(
  3466.                         'view_purchase_invoice'
  3467.                     );
  3468.                     return $this->redirect($url "/" $id);
  3469.                 } else {
  3470.                     $extData $extTrans;
  3471.                     $extDetailsData $em->getRepository('ApplicationBundle\\Entity\\PurchaseInvoiceItem')->findBy(
  3472.                         array(
  3473.                             'purchaseInvoiceId' => $id///material
  3474.                         )
  3475.                     );
  3476.                 }
  3477.             } else {
  3478.             }
  3479.         }
  3480.         return $this->render(
  3481.             '@Accounts/pages/input_forms/purchase_invoice.html.twig',
  3482.             array(
  3483.                 'page_title' => 'Purchase Invoice',
  3484.                 'extData' => $extData,
  3485.                 'extDetailsData' => $extDetailsData,
  3486.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  3487.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  3488.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  3489.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  3490.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  3491.                 'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
  3492.                 'grn_list' => Inventory::GrnListForPi($this->getDoctrine()->getManager()),
  3493.                 'grn_list_array' => Inventory::GrnListForPiArray($this->getDoctrine()->getManager()),
  3494.                 'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '')
  3495.                 //                'dt_debug'=>$data
  3496.                 //                'po'=>Inventory::getPurchaseOrderList
  3497.             )
  3498.         );
  3499.     }
  3500.     public function CreateServicePurchaseInvoice(Request $request$id 0)
  3501.     {
  3502.         $em $this->getDoctrine()->getManager();
  3503.         if ($request->isMethod('POST')) {
  3504.             $data $request->request;
  3505.             $entity_id array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice']; //change
  3506.             $dochash $request->request->get('docHash'); //change
  3507.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3508.             $approveRole $request->request->get('approvalRole');
  3509.             $approveHash $request->request->get('approvalHash');
  3510.             if (!DocValidation::isInsertable(
  3511.                 $em,
  3512.                 $entity_id,
  3513.                 $dochash,
  3514.                 $loginId,
  3515.                 $approveRole,
  3516.                 $approveHash,
  3517.                 $id
  3518.             )) {
  3519.                 $this->addFlash(
  3520.                     'error',
  3521.                     'Sorry Couldnot insert Data.'
  3522.                 );
  3523.             } else {
  3524.                 $funcname 'PurchaseInvoice';
  3525.                 $doc_id $id;
  3526.                 DeleteDocument::$funcname($em$doc_id0);
  3527.                 $create_new_pi Accounts::CreatePurchaseInvoice($id$this->getDoctrine()->getManager(), $data$request->getSession()->get(UserConstants::USER_LOGIN_ID));
  3528.                 //now add Approval info
  3529.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3530.                 $approveRole $request->request->get('approvalRole');
  3531.                 $options = array(
  3532.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3533.                     'notification_server' => $this->container->getParameter('notification_server'),
  3534.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  3535.                     'url' => $this->generateUrl(
  3536.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice']]['entity_view_route_path_name']
  3537.                     )
  3538.                 );
  3539.                 System::setApprovalInfo(
  3540.                     $this->getDoctrine()->getManager(),
  3541.                     $options,
  3542.                     array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice'],
  3543.                     $create_new_pi['pi_id'],
  3544.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3545.                 );
  3546.                 System::createEditSignatureHash(
  3547.                     $this->getDoctrine()->getManager(),
  3548.                     array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice'],
  3549.                     $create_new_pi['pi_id'],
  3550.                     $loginId,
  3551.                     $approveRole,
  3552.                     $request->request->get('approvalHash')
  3553.                 );
  3554.                 $this->addFlash(
  3555.                     'success',
  3556.                     'New Invoice Added.'
  3557.                 );
  3558.                 $url $this->generateUrl(
  3559.                     'view_purchase_invoice'
  3560.                 );
  3561.                 System::AddNewNotification(
  3562.                     $this->container->getParameter('notification_enabled'),
  3563.                     $this->container->getParameter('notification_server'),
  3564.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  3565.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  3566.                     "Purchase Invoice : " $dochash " Has Been Created And is Under Processing",
  3567.                     'pos',
  3568.                     System::getPositionIdsByDepartment($em, [GeneralConstant::ACCOUNTS_DEPARTMENTGeneralConstant::PURCHASE_DEPARTMENT]),
  3569.                     'success',
  3570.                     $url "/" $create_new_pi['pi_id'],
  3571.                     "Purchase Bill"
  3572.                 );
  3573.                 return $this->redirect($url "/" $create_new_pi['pi_id']);
  3574.             }
  3575.         }
  3576.         $extData = [];
  3577.         $extDetailsData = [];
  3578.         if ($id == 0) {
  3579.         } else {
  3580.             $extTrans $em->getRepository('ApplicationBundle\\Entity\\PurchaseInvoice')->findOneBy(
  3581.                 array(
  3582.                     'purchaseInvoiceId' => $id///material
  3583.                 )
  3584.             );
  3585.             //now if its not editable, redirect to view
  3586.             if ($extTrans) {
  3587.                 if ($extTrans->getEditFlag() != 1) {
  3588.                     $url $this->generateUrl(
  3589.                         'view_purchase_invoice'
  3590.                     );
  3591.                     return $this->redirect($url "/" $id);
  3592.                 } else {
  3593.                     $extData $extTrans;
  3594.                     $extDetailsData $em->getRepository('ApplicationBundle\\Entity\\PurchaseInvoiceItem')->findBy(
  3595.                         array(
  3596.                             'purchaseInvoiceId' => $id///material
  3597.                         )
  3598.                     );
  3599.                 }
  3600.             } else {
  3601.             }
  3602.         }
  3603.         return $this->render(
  3604.             '@Accounts/pages/input_forms/service_purchase_invoice.html.twig',
  3605.             array(
  3606.                 'page_title' => 'Service Purchase Invoice',
  3607.                 'extData' => $extData,
  3608.                 'extDetailsData' => $extDetailsData,
  3609.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  3610.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  3611.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  3612.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  3613.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  3614.                 'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
  3615.                 'grn_list' => Inventory::GrnListForPi($this->getDoctrine()->getManager()),
  3616.                 'grn_list_array' => Inventory::GrnListForPiArray($this->getDoctrine()->getManager()),
  3617.                 'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '')
  3618.                 //                'dt_debug'=>$data
  3619.                 //                'po'=>Inventory::getPurchaseOrderList
  3620.             )
  3621.         );
  3622.     }
  3623.     //=========================================================================
  3624.     //  Previous CreateExpenseInvoice
  3625.     //=========================================================================
  3626.     /*
  3627.         public function CreateExpenseInvoice(Request $request, $id = 0)
  3628.         {
  3629.             $em = $this->getDoctrine()->getManager();
  3630.             if ($request->isMethod('POST')) {
  3631.                 $data = $request->request;
  3632.                 $expBillType = $data->get('expenseTypeId');
  3633.                 foreach ($data->get('expBillCheckMarkedExpense') as $row) {
  3634.                     $entity_id = array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice']; //change
  3635.                     $result = $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')
  3636.                         ->findBy(
  3637.                             array(
  3638.                                 'typeHash' => 'EI',
  3639.                                 'prefixHash' => $data->get('expBillTypeId')[$row],
  3640.                                 'assocHash' => $data->get('expBillPartyHeadId')[$row],
  3641.                             )
  3642.                         );
  3643.                     $count = count($result);
  3644.                     $count++;
  3645.                     $dochash = 'EI/' . $data->get('expBillTypeId')[$row] . '/' . $data->get('expBillPartyHeadId')[$row] . '/' . $count; //change
  3646.                     $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3647.                     $approveRole = $request->request->get('approvalRole');
  3648.                     $approveHash = $request->request->get('approvalHash');
  3649.                     if (!DocValidation::isInsertable(
  3650.                         $em,
  3651.                         $entity_id,
  3652.                         $dochash,
  3653.                         $loginId,
  3654.                         $approveRole,
  3655.                         $approveHash,
  3656.                         $id
  3657.                     )) {
  3658.                         $this->addFlash(
  3659.                             'error',
  3660.                             'Sorry Couldnot insert Data.'
  3661.                         );
  3662.                     } else {
  3663.                         $new_ei = Accounts::CreateExpenseInvoice(
  3664.                             $this->getDoctrine()->getManager(),
  3665.                             $data,
  3666.                             $row,
  3667.                             $expBillType,
  3668.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3669.                         );
  3670.                         //now add Approval info
  3671.                         $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3672.                         $approveRole = $request->request->get('approvalRole');
  3673.                         $options = array(
  3674.                             'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3675.                             'notification_server' => $this->container->getParameter('notification_server'),
  3676.                             'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  3677.                             'url' => $this->generateUrl(
  3678.                                 GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice']]['entity_view_route_path_name']
  3679.                             )
  3680.                         );
  3681.                         System::setApprovalInfo(
  3682.                             $this->getDoctrine()->getManager(),
  3683.                             $options,
  3684.                             array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
  3685.                             $new_ei['ei_id'],
  3686.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3687.                         );
  3688.                         System::createEditSignatureHash(
  3689.                             $this->getDoctrine()->getManager(),
  3690.                             array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
  3691.                             $new_ei['ei_id'],
  3692.                             $loginId,
  3693.                             $approveRole,
  3694.                             $request->request->get('approvalHash')
  3695.                         );
  3696.                     }
  3697.                 }
  3698.             }
  3699.             $extData = $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')
  3700.                 ->findOneBy(
  3701.                     array(
  3702.                         'expenseInvoiceId' => $id,
  3703.                     )
  3704.                 );
  3705.             if (!$extData)
  3706.                 $extData = [];
  3707.             return $this->render(
  3708.                 '@Accounts/pages/input_forms/expense_bill.html.twig',
  3709.                 array(
  3710.                     'page_title' => 'Expense Bills',
  3711.                     'extData' => $extData,
  3712.                     'party_list' => Accounts::getParentLedgerHeads($this->getDoctrine()->getManager(), 'ep'),
  3713.                     'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  3714.                     'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  3715.                     'supplier_list_by_ac_head' => Accounts::SupplierListByAcHead($this->getDoctrine()->getManager()),
  3716.                     'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  3717.                     'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  3718.                     'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  3719.                     'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
  3720.                     'grn_list' => Inventory::GrnListForEi($this->getDoctrine()->getManager(), 1),
  3721.                     'grn_list_array' => Inventory::GrnListForEiArray($this->getDoctrine()->getManager(), 1),
  3722.                     //                'po'=>Inventory::getPurchaseOrderList
  3723.                 )
  3724.             );
  3725.         }
  3726.     */
  3727.     public function CreateExpenseInvoice(Request $request$id 0)
  3728.     {
  3729.         $em     $this->getDoctrine()->getManager();
  3730.         $em_goc $this->getDoctrine()->getManager('company_group');
  3731.         // ====================================================================
  3732.         // POST – Create or Edit
  3733.         // ====================================================================
  3734.         if ($request->isMethod('POST')) {
  3735.             $loginId     $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3736.             $approveRole $request->request->get('approvalRole');
  3737.             $approveHash $request->request->get('approvalHash');
  3738.             // Verify approval signature before doing anything
  3739.             if (!DocValidation::isSignatureOk($em$loginId$approveHash)) {
  3740.                 return new JsonResponse([
  3741.                     'success'   => false,
  3742.                     'errorText' => 'Approval Hash Mismatch',
  3743.                     'errorStr'  => 'Approval Hash Mismatch',
  3744.                 ]);
  3745.             }
  3746.             // Build cost-distribution map from parallel arrays
  3747.             $exp_distribution_poitemId $request->request->get('exp_distribution_poitemId', []);
  3748.             $exp_distribution_amount   $request->request->get('exp_distribution_amount', []);
  3749.             $costDistributionData = [];
  3750.             foreach ($exp_distribution_poitemId as $k => $poItemId) {
  3751.                 $costDistributionData[$poItemId] = [
  3752.                     'poItemId' => $poItemId,
  3753.                     'amount'   => $exp_distribution_amount[$k],
  3754.                 ];
  3755.             }
  3756.             // Normalise any date string to Y-m-d, defaulting to today
  3757.             $normaliseDate = static function (string $raw): string {
  3758.                 if ($raw === '') return date('Y-m-d');
  3759.                 $ts strtotime($raw);
  3760.                 return ($ts !== false) ? date('Y-m-d'$ts) : date('Y-m-d');
  3761.             };
  3762.             // ----------------------------------------------------------------
  3763.             // Build $expenseDataList from whichever input path was used.
  3764.             // Every row is treated as a fully independent invoice (no parent/child).
  3765.             //
  3766.             // PATH A – flat arrays from the Twig form  (expenseDate[], …)
  3767.             // PATH B – JSON blob in `expenseData`       (mobile / API)
  3768.             // PATH C – classic single-field POST        (legacy fallback)
  3769.             // ----------------------------------------------------------------
  3770.             $expenseDataList = [];
  3771.             $flatDates $request->request->get('expenseDate', []);
  3772.             if (!empty($flatDates) && is_array($flatDates)) {
  3773.                 // PATH A
  3774.                 $flatTypes            $request->request->get('expenseType', []);
  3775.                 $flatSubTypes         $request->request->get('expenseSubType', []);
  3776.                 $flatDocIds           $request->request->get('docId', []);
  3777.                 $flatDirectProjectIds $request->request->get('directProjectId', []);
  3778.                 $flatAmounts          $request->request->get('expenseAmount', []);
  3779.                 $flatExpenseIds       $request->request->get('expenseId', []);
  3780.                 $flatCcIds            $request->request->get('ccId', []);
  3781.                 $flatToBePaidTo       $request->request->get('expenseToBePaidTo', []);
  3782.                 $flatCurrencyIds      $request->request->get('currencyId', []);
  3783.                 $flatCurrRates        $request->request->get('currencyMultiplyRate', []);
  3784.                 $flatFroms            $request->request->get('expenseFrom', []);
  3785.                 $flatFromNotes        $request->request->get('expenseFromNote', []);
  3786.                 $flatTos              $request->request->get('expenseTo', []);
  3787.                 $flatToNotes          $request->request->get('expenseToNote', []);
  3788.                 $flatDescs            $request->request->get('description', []);
  3789.                 $flatMarkers          $request->request->get('expenseMarkerHash', []);
  3790.                 $flatWbsCodes         $request->request->get('wbsCode', []);
  3791.                 $flatWbsActivityNames $request->request->get('wbsActivityName', []);
  3792.                 $flatUploaded         $request->request->get('uploadedFile', []);
  3793.                 $flatInvoiceIds       $request->request->get('invoiceId', []);
  3794.                 $flatInvoiceBalancing $request->request->get('invoiceBalancing', []);
  3795.                 $rowCount count($flatDates);
  3796.                 for ($i 0$i $rowCount$i++) {
  3797.                     $toNote = (string)($flatToNotes[$i] ?? '');
  3798.                     $toNote trim($toNote) === '0' '' $toNote;
  3799.                     $expenseDataList[] = [
  3800.                         'expenseType'                    => (int)($flatTypes[$i]        ?? 0),
  3801.                         'expenseSubType'                 => (int)($flatSubTypes[$i]     ?? 0),
  3802.                         'expenseId'                      => (int)($flatExpenseIds[$i]   ?? 0),
  3803.                         'ccId'                           => (int)($flatCcIds[$i]        ?? 0),
  3804.                         'currencyId'                     => (int)($flatCurrencyIds[$i]  ?? 0),
  3805.                         'currencyMultiply'               => 1,
  3806.                         'currencyMultiplyRate'           => (float)($flatCurrRates[$i]  ?? 1),
  3807.                         'docId'                          => (int)($flatDocIds[$i]       ?? 0),
  3808.                         'directProjectId'                => (int)($flatDirectProjectIds[$i] ?? 0),
  3809.                         'expenseToBePaidTo'              => $flatToBePaidTo[$i]         ?? 0,
  3810.                         'expenseFrom'                    => (int)($flatFroms[$i]        ?? 0),
  3811.                         'expenseFromNote'                => (string)($flatFromNotes[$i] ?? ''),
  3812.                         'expenseTo'                      => (int)($flatTos[$i]          ?? 0),
  3813.                         'expenseToNote'                  => $toNote,
  3814.                         'expenseAmount'                  => (float)($flatAmounts[$i]    ?? 0),
  3815.                         'previousAdvanceAmount'          => 0,
  3816.                         'checkDate'                      => '',
  3817.                         'checkNumber'                    => '',
  3818.                         'checkNarration'                 => '',
  3819.                         'checkId'                        => 0,
  3820.                         'description'                    => (string)($flatDescs[$i]     ?? ''),
  3821.                         'expenseMarkerHash'              => (string)($flatMarkers[$i]   ?? ''),
  3822.                         'markerHash'                     => (string)($flatMarkers[$i]   ?? ''),
  3823.                         'wbsCode'                        => (string)($flatWbsCodes[$i] ?? ''),
  3824.                         'wbsActivityName'                => (string)($flatWbsActivityNames[$i] ?? ''),
  3825.                         'expenseDate'                    => $normaliseDate((string)($flatDates[$i] ?? '')),
  3826.                         'invoiceBalancing'               => (int)($flatInvoiceBalancing[$i] ?? 0),
  3827.                         'attachedFile'                   => [],
  3828.                         'uploadedFile'                   => (string)($flatUploaded[$i]  ?? ''),
  3829.                         'expenseInvocationStrategyOnGrn' => null,
  3830.                         'expenseInvocationTypeOnItems'   => null,
  3831.                         'isChildInvoice'                 => 0,
  3832.                         'costDistributionData'           => $costDistributionData,
  3833.                         // Read the "distribute on product (add to inventory cost)" checkbox — the same POST
  3834.                         // field PATH C uses. Hardcoding 0 here (the Feb-2026 flat-array refactor) silently
  3835.                         // discarded the user's choice: CalibrateProductPriceWithExpense then spread the
  3836.                         // expense PROPORTIONALLY over every GRN line (grn_price * fraction_increase) instead
  3837.                         // of using the explicit per-product amounts typed into exp_distribution_amount[].
  3838.                         'expenseDistributionOnProduct'   => (int) $request->request->get('exp_check_expense_distribution_on_product'0),
  3839.                         'expenseSubCategory'             => 0,
  3840.                         'expenseSubCategoryOption'       => 0,
  3841.                         'expense_sub_category'           => 0,
  3842.                         'expense_sub_category_option'    => 0,
  3843.                         'invoiceId'                      => (int)($flatInvoiceIds[$i]   ?? 0),
  3844.                     ];
  3845.                 }
  3846.             } else {
  3847.                 $expense_data $request->request->get('expenseData', []);
  3848.                 $expense_type $request->request->get('expense_type'0);
  3849.                 if (is_string($expense_data)) {
  3850.                     $expense_data json_decode($expense_datatrue);
  3851.                 }
  3852.                 if (!empty($expense_data)) {
  3853.                     // PATH B – JSON / mobile
  3854.                     $currTs = (new \DateTime())->format('U');
  3855.                     foreach ($expense_data as $idx => $expData) {
  3856.                         // Save embedded base64 image to disk
  3857.                         if (isset($expData['imageBase64'])) {
  3858.                             $imgData   base64_decode(
  3859.                                 preg_replace('#^data:image/\w+;base64,#i'''$expData['imageBase64'])
  3860.                             );
  3861.                             $fileName  $currTs md5(uniqid()) . '.png';
  3862.                             $storePath 'uploads/ExpenseInvoice/';
  3863.                             MiscActions::RemoveExpiredFiles($em_goc);
  3864.                             $uplDir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  3865.                             if (!file_exists($uplDir)) {
  3866.                                 mkdir($uplDir0777true);
  3867.                             }
  3868.                             $fp $uplDir $fileName;
  3869.                             if (file_exists($fp)) { chmod($fp0755); unlink($fp); }
  3870.                             file_put_contents(
  3871.                                 $this->container->getParameter('kernel.root_dir')
  3872.                                     . '/../web/uploads/ExpenseInvoice/' $fileName,
  3873.                                 $imgData
  3874.                             );
  3875.                             $expense_data[$idx]['uploadedFile'] = $storePath $fileName;
  3876.                         }
  3877.                         if (!isset($expData['attachedFile'])) {
  3878.                             $expense_data[$idx]['attachedFile'] = [];
  3879.                         }
  3880.                         $expense_data[$idx]['expenseDate']    = $normaliseDate((string)($expData['expenseDate'] ?? ''));
  3881.                         $expense_data[$idx]['isChildInvoice'] = 0;
  3882.                         $expenseDataList[] = $expense_data[$idx];
  3883.                     }
  3884.                 } else {
  3885.                     // PATH C – legacy single-field POST
  3886.                     $expenseDataList[] = [
  3887.                         'expenseType'                    => $expense_type,
  3888.                         'currencyId'                     => $request->request->get('expense_currency_id'0),
  3889.                         'currencyMultiply'               => $request->request->get('expense_currency_multiply'1),
  3890.                         'currencyMultiplyRate'           => $request->request->get('expense_currency_multiply_rate'1),
  3891.                         'expenseSubType'                 => $request->request->get('expense_sub_type'0),
  3892.                         'expenseId'                      => $request->request->get('expense_id'0),
  3893.                         'ccId'                           => $request->request->get('ccId'0),
  3894.                         'docId'                          => $expense_type == $request->request->get('poId')
  3895.                             : ($expense_type == $request->request->get('soId')
  3896.                                 : ($expense_type == $request->request->get('opportunityId'$request->request->get('leadId'))
  3897.                                     : ($expense_type == $request->request->get('tour_id') : 0))),
  3898.                         'expenseToBePaidTo'              => $request->request->get('expense_to_be_paid_to'0),
  3899.                         'expenseFrom'                    => $request->request->get('expense_from'0),
  3900.                         'checkDate'                      => $request->request->get('check_date'''),
  3901.                         'checkNumber'                    => $request->request->get('check_number'''),
  3902.                         'checkNarration'                 => $request->request->get('check_narration'''),
  3903.                         'checkId'                        => $request->request->get('check_id'0),
  3904.                         'expenseFromNote'                => $request->request->get('expense_from_note'''),
  3905.                         'expenseTo'                      => $request->request->get('expense_to_' $expense_type0),
  3906.                         'expenseToNote'                  => $request->request->get('expense_to_note_' $expense_type''),
  3907.                         'expenseAmount'                  => $request->request->get('expense_amount'''),
  3908.                         'previousAdvanceAmount'          => $request->request->get('prev_advance_amount'0),
  3909.                         'description'                    => $request->request->get('description'''),
  3910.                         'expenseMarkerHash'              => $request->request->get('markerHash'''),
  3911.                         'markerHash'                     => $request->request->get('markerHash'''),
  3912.                         'wbsCode'                        => $request->request->get('wbsCode'''),
  3913.                         'wbsActivityName'                => $request->request->get('wbsActivityName'''),
  3914.                         'expenseDate'                    => $normaliseDate((string)$request->request->get('expense_date''')),
  3915.                         'expenseInvocationStrategyOnGrn' => $request->request->get('expenseInvocationStrategyOnGrn'null),
  3916.                         'expenseInvocationTypeOnItems'   => $request->request->get('expenseInvocationTypeOnItems'null),
  3917.                         'invoiceBalancing'               => $request->request->has('auto_balance' $expense_type)
  3918.                             ? $request->request->get('auto_balance' $expense_type) : 0,
  3919.                         'attachedFile'                   => $request->files->get('file', []),
  3920.                         'expenseSubCategory'             => $request->request->get('expense_sub_category'0),
  3921.                         'expenseSubCategoryOption'       => $request->request->get('expense_sub_category_option'0),
  3922.                         'uploadedFile'                   => $request->request->get('uploadedFile'''),
  3923.                         'expenseDistributionOnProduct'   => $request->request->get('exp_check_expense_distribution_on_product'0),
  3924.                         'isChildInvoice'                 => 0,
  3925.                         'costDistributionData'           => $costDistributionData,
  3926.                         'expense_sub_category'           => $request->request->get('expense_sub_category'0),
  3927.                         'expense_sub_category_option'    => $request->request->get('expense_sub_category_option'0),
  3928.                     ];
  3929.                 }
  3930.             }
  3931.             $isEdit = ($id 0);
  3932.             // Resolves _OWN_ / _OWN_ADVANCE_ to the employee's ledger head
  3933.             $resolveOwnHead = function (string $headField, array $expData, array &$data) use ($em$request): ?JsonResponse {
  3934.                 $sql  "SELECT accounts_head_id, advance_head_id, employee_id, user_id
  3935.                         FROM employee
  3936.                         WHERE user_id = " . (int)$request->getSession()->get(UserConstants::USER_ID) . "
  3937.                         LIMIT 1";
  3938.                 $rows $em->getConnection()->fetchAllAssociative($sql);
  3939.                 if (empty($rows)) {
  3940.                     return new JsonResponse(['success' => false'errorText' => 'You are not listed as Employee''errorStr' => 'You are not listed as Employee']);
  3941.                 }
  3942.                 if (empty($rows[0][$headField]) || $rows[0][$headField] == 0) {
  3943.                     $label = ($headField === 'advance_head_id') ? 'Employee Advance Head' 'Employee Head';
  3944.                     return new JsonResponse(['success' => false'errorText' => "Could not Find $label"'errorStr' => "Could not Find $label"]);
  3945.                 }
  3946.                 $data['party_head_id']          = $rows[0][$headField];
  3947.                 $data['description']            = $expData['expenseToNote'];
  3948.                 $data['personal_expense_flag']  = 1;
  3949.                 $data['expense_of_user_id']     = $rows[0]['user_id'];
  3950.                 $data['expense_of_employee_id'] = $rows[0]['employee_id'];
  3951.                 return null;
  3952.             };
  3953.             // ----------------------------------------------------------------
  3954.             // Save each row as its own independent invoice.
  3955.             // All tracking arrays are declared OUTSIDE the loop so they
  3956.             // accumulate entries across all iterations.
  3957.             // ----------------------------------------------------------------
  3958.             $new_ei            = [];
  3959.             $lastSavedEiId     0;
  3960.             $lastSavedEiResult = [];
  3961.             $firstSavedEiId    0;
  3962.             $allSavedIds       = [];   
  3963.             $allDocAmounts     = [];   
  3964.             $allDocHash        = [];
  3965.             foreach ($expenseDataList as $expData) {
  3966.                 $expBillType = (int)($expData['expenseType'] ?? 0);
  3967.                 // For edit: use each row's own invoiceId; fall back to $id for single-row edits
  3968.                 $currentEiId = ($isEdit && !empty($expData['invoiceId']))
  3969.                     ? (int)$expData['invoiceId']
  3970.                     : ($isEdit $id 0);
  3971.                 $data = [
  3972.                     'doc_id'                         => $expData['docId']               ?? 0,
  3973.                     'expense_id'                     => $expData['expenseId']           ?? 0,
  3974.                     'party_id'                       => '',
  3975.                     'party_head_id'                  => $expData['expenseToBePaidTo']   ?? 0,
  3976.                     'advance_amount_to_assign'       => (float)($expData['previousAdvanceAmount'] ?? 0),
  3977.                     'invoice_amount'                 => (float)($expData['expenseAmount'] ?? 0),
  3978.                     'description'                    => $expData['description']         ?? '',
  3979.                     'expense_to_note'                => $expData['expenseToNote']       ?? '',
  3980.                     'expense_from_note'              => $expData['expenseFromNote']     ?? '',
  3981.                     'wbsCode'                        => $expData['wbsCode']             ?? '',
  3982.                     'wbsActivityName'                => $expData['wbsActivityName']     ?? '',
  3983.                     'currencyId'                     => $expData['currencyId']          ?? 0,
  3984.                     'currencyMultiply'               => $expData['currencyMultiply']    ?? 1,
  3985.                     'currencyMultiplyRate'           => $expData['currencyMultiplyRate'] ?? 1,
  3986.                     'date'                           => $expData['expenseDate'],
  3987.                     'file'                           => $expData['attachedFile']        ?? [],
  3988.                     'uploadedFile'                   => $expData['uploadedFile']        ?? '',
  3989.                     'expense_from'                   => $expData['expenseFrom']         ?? 0,
  3990.                     'check_date'                     => $expData['checkDate']           ?? '',
  3991.                     'check_number'                   => $expData['checkNumber']         ?? '',
  3992.                     'check_narration'                => $expData['checkNarration']      ?? '',
  3993.                     'check_id'                       => $expData['checkId']             ?? 0,
  3994.                     'expenseMarkerHash'              => $expData['markerHash']          ?? '',
  3995.                     'expenseSubCategory'             => $expData['expense_sub_category']        ?? 0,
  3996.                     'expenseSubCategoryOption'       => $expData['expense_sub_category_option'] ?? 0,
  3997.                     'invoiceBalancing'               => $expData['invoiceBalancing']    ?? 0,
  3998.                     'expenseInvocationStrategyOnGrn' => $expData['expenseInvocationStrategyOnGrn'] ?? null,
  3999.                     'expenseInvocationTypeOnItems'   => $expData['expenseInvocationTypeOnItems']   ?? null,
  4000.                     'expenseDistributionOnProduct'   => $expData['expenseDistributionOnProduct']   ?? 0,
  4001.                     'costDistributionData'           => $expData['costDistributionData'] ?? [],
  4002.                 ];
  4003.                 if ($request->request->has('latitude')) {
  4004.                     $data['latitude']  = $request->request->get('latitude');
  4005.                     $data['longitude'] = $request->request->get('longitude');
  4006.                 }
  4007.                 // Resolve marker hash → accounts_head_id
  4008.                 if (!empty($expData['expenseMarkerHash'])) {
  4009.                     $sql  "SELECT accounts_head_id FROM acc_accounts_head
  4010.                             WHERE marker_hash LIKE '%" $expData['expenseMarkerHash'] . "%'
  4011.                             LIMIT 1";
  4012.                     $rows $em->getConnection()->fetchAllAssociative($sql);
  4013.                     if (empty($rows)) {
  4014.                         return new JsonResponse(['success' => false'errorText' => 'Could not find relevant Expense Head']);
  4015.                     }
  4016.                     $data['expense_id'] = $rows[0]['accounts_head_id'];
  4017.                 }
  4018.                 // Resolve _OWN_ / _OWN_ADVANCE_ to employee ledger head
  4019.                 $paidTo $expData['expenseToBePaidTo'] ?? 0;
  4020.                 if ($paidTo == '_OWN_' || $paidTo == -1) {
  4021.                     $err $resolveOwnHead('accounts_head_id'$expData$data);
  4022.                     if ($err) return $err;
  4023.                 }
  4024.                 if ($paidTo == '_OWN_ADVANCE_' || $paidTo == -2) {
  4025.                     $err $resolveOwnHead('advance_head_id'$expData$data);
  4026.                     if ($err) return $err;
  4027.                 }
  4028.                 $new_ei = [];
  4029.                 // Resolve which project this expense belongs to so it shows in the project cost
  4030.                 // report. A Direct Project id (project with no sales order) wins; otherwise derive
  4031.                 // it from the tagged Sales Order (type 2). Previously projectId was hard-coded 0,
  4032.                 // so SO/project-tagged expenses saved with project_id = 0.
  4033.                 $resolvedProjectId = (int)($expData['directProjectId'] ?? 0);
  4034.                 if ($resolvedProjectId <= && $expBillType == && (int)($expData['docId'] ?? 0) > 0) {
  4035.                     $soForProj $em->getRepository('ApplicationBundle\\Entity\\SalesOrder')->findOneBy(
  4036.                         array('salesOrderId' => (int)$expData['docId'])
  4037.                     );
  4038.                     if ($soForProj) {
  4039.                         $resolvedProjectId = (int)$soForProj->getProjectId();
  4040.                     }
  4041.                 }
  4042.                 switch ($expBillType) {
  4043.                     case 0// General
  4044.                     case 1// PO-linked
  4045.                     case 2// SO-linked
  4046.                     case 3// Lead-linked
  4047.                     case 5// Tour/travel
  4048.                         if ($isEdit) {
  4049.                             $new_ei Accounts::EditExpenseInvoiceFromAddExpense(
  4050.                                 $this->getDoctrine()->getManager(),
  4051.                                 $data''$expBillType$loginId,
  4052.                                 0$resolvedProjectId0,
  4053.                                 (int)($expData['ccId'] ?? 0),
  4054.                                 000,
  4055.                                 $currentEiId
  4056.                             );
  4057.                         } else {
  4058.                             $new_ei Accounts::CreateExpenseInvoiceFromAddExpense(
  4059.                                 $this->getDoctrine()->getManager(),
  4060.                                 $data''$expBillType$loginId,
  4061.                                 0$resolvedProjectId0,
  4062.                                 (int)($expData['ccId'] ?? 0),
  4063.                                 00
  4064.                             );
  4065.                         }
  4066.                         break;
  4067.                     default:
  4068.                         continue 2;
  4069.                 }
  4070.                 // Register each successfully saved invoice
  4071.                 if (!empty($new_ei['ei_id'])) {
  4072.                     $savedEiId = (int)$new_ei['ei_id'];
  4073.                     $allSavedIds[]             = $savedEiId;
  4074.                     $allDocAmounts[$savedEiId] = (float)($expData['expenseAmount'] ?? 0);
  4075.                     $allDocHash[$savedEiId]     = $new_ei['ei_doc_hash'] ?? '';
  4076.                     $eiEntityId array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'];
  4077.                     $options = [
  4078.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4079.                         'notification_server'  => $this->container->getParameter('notification_server'),
  4080.                         'appId'                => $request->getSession()->get(UserConstants::USER_APP_ID),
  4081.                         'url'                  => $this->generateUrl(
  4082.                             GeneralConstant::$Entity_list_details[$eiEntityId]['entity_view_route_path_name']
  4083.                         ),
  4084.                     ];
  4085.                     System::setApprovalInfo(
  4086.                         $this->getDoctrine()->getManager(),
  4087.                         $options$eiEntityId$savedEiId$loginId
  4088.                     );
  4089.                     System::createEditSignatureHash(
  4090.                         $this->getDoctrine()->getManager(),
  4091.                         $eiEntityId$savedEiId$loginId$approveRole$approveHash
  4092.                     );
  4093.                     if ($firstSavedEiId === 0) {
  4094.                         $firstSavedEiId $savedEiId;
  4095.                     }
  4096.                     $lastSavedEiId     $savedEiId;
  4097.                     $lastSavedEiResult $new_ei;
  4098.                 }
  4099.             }
  4100.             // END foreach
  4101.             // Use the last saved invoice for response URLs
  4102.             $responseEi = !empty($lastSavedEiResult) ? $lastSavedEiResult : [];
  4103.             $eiEntityId      array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'];
  4104.             $eiEntityDetails GeneralConstant::$Entity_list_details[$eiEntityId];
  4105.             $viewUrl  $this->generateUrl(
  4106.                 $eiEntityDetails['entity_view_route_path_name'],
  4107.                 ['id' => $responseEi['ei_id'] ?? 0]
  4108.             );
  4109.             $printUrl = isset($eiEntityDetails['entity_print_route_path_name'])
  4110.                 ? $this->generateUrl(
  4111.                     $eiEntityDetails['entity_print_route_path_name'],
  4112.                     ['id' => $responseEi['ei_id'] ?? 0]
  4113.                 )
  4114.                 : $viewUrl;
  4115.             return new JsonResponse([
  4116.                 'success'         => true,
  4117.                 'docId'           => $responseEi['ei_id']      ?? '',
  4118.                 'docHash'         => $responseEi['ei_doc_hash'] ?? '',
  4119.                 'documentId'      => $responseEi['ei_id']      ?? '',
  4120.                 'documentHash'    => $responseEi['ei_doc_hash'] ?? '',
  4121.                 'documentAmount'  => (float)($expenseDataList[0]['expenseAmount'] ?? 0),
  4122.                 'allDocIds'       => $allSavedIds,     
  4123.                 'allDocAmounts'   => $allDocAmounts,  
  4124.                 'allDocHashes'    => $allDocHash
  4125.                 'viewUrl'         => $viewUrl,
  4126.                 'docPrintMainUrl' => $printUrl,
  4127.                 'isEdit'          => $isEdit,
  4128.             ]);
  4129.         }
  4130.         // ====================================================================
  4131.         // GET – Render form; pre-fill when $id > 0 (edit mode)
  4132.         // ====================================================================
  4133.         $extData      = [];
  4134.         $existingRows = [];
  4135.         if ($id 0) {
  4136.             $extData $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')
  4137.                 ->findOneBy(['expenseInvoiceId' => $id]);
  4138.             if ($extData) {
  4139.                 $existingRows[] = [
  4140.                     'id'                             => $extData->getExpenseInvoiceId(),
  4141.                     'expenseType'                    => $extData->getExpenseTypeId(),
  4142.                     'expenseSubType'                 => $extData->getExpenseSubcategory()   ?? 0,
  4143.                     'expenseId'                      => $extData->getPartyId(),
  4144.                     'ccId'                           => $extData->getCostCenterId()         ?? 0,
  4145.                     'currencyId'                     => $extData->getCurrency()             ?? 0,
  4146.                     'currencyMultiply'               => $extData->getCurrencyMultiply()     ?? 1,
  4147.                     'currencyMultiplyRate'           => $extData->getCurrencyMultiplyRate() ?? 1,
  4148.                     'docId'                          => $extData->getPurchaseOrderId()      ?? 0,
  4149.                     'docIdtext'                      => '',
  4150.                     'expenseToBePaidTo'              => $extData->getPartyHeadId()          ?? 0,
  4151.                     'expenseFrom'                    => $extData->getExpenseFrom()           ?? 0,
  4152.                     'expenseFromNote'                => $extData->getExpenseFromNote()       ?? '',
  4153.                     'expenseTo'                      => 0,
  4154.                     'expenseToNote'                  => $extData->getExpenseToNote()         ?? '',
  4155.                     'expenseAmount'                  => $extData->getInvoiceAmount()         ?? 0,
  4156.                     'previousAdvanceAmount'          => $extData->getAdvanceAmount()         ?? 0,
  4157.                     'checkDate'                      => '',
  4158.                     'checkNumber'                    => '',
  4159.                     'checkNarration'                 => '',
  4160.                     'checkId'                        => 0,
  4161.                     'description'                    => $extData->getDescription()           ?? '',
  4162.                     'expenseMarkerHash'              => $extData->getMarkerHash()            ?? '',
  4163.                     'wbsCode'                        => $extData->getWbsCode()              ?? '',
  4164.                     'wbsActivityName'                => $extData->getWbsActivityName()      ?? '',
  4165.                     'expenseDate'                    => $extData->getExpenseInvoiceDate()
  4166.                         ? $extData->getExpenseInvoiceDate()->format('F d, Y')
  4167.                         : date('F d, Y'),
  4168.                     'invoiceBalancing'               => 0,
  4169.                     'uploadedFile'                   => $extData->getFiles()                 ?? '',
  4170.                     'attachedFile'                   => [],
  4171.                     'expenseInvocationStrategyOnGrn' => $extData->getExpenseInvocationStrategyOnGrn(),
  4172.                     'expenseInvocationTypeOnItems'   => $extData->getExpenseInvocationTypeOnItems(),
  4173.                     'isChildInvoice'                 => 0,
  4174.                     'refId'                          => 0,
  4175.                     'invoiceId'                      => $extData->getExpenseInvoiceId(),
  4176.                 ];
  4177.             } else {
  4178.                 $extData = [];
  4179.             }
  4180.         }
  4181.         return $this->render(
  4182.             '@Accounts/pages/input_forms/expense_bill.html.twig',
  4183.             [
  4184.                 'page_title'               => $id 'Edit Expense Bill' 'Create Expense Bill',
  4185.                 'isEdit'                   => ($id 0),
  4186.                 'editId'                   => $id,
  4187.                 'extData'                  => $extData,
  4188.                 'existingRows'             => $existingRows,
  4189.                 'party_list'               => Accounts::getParentLedgerHeads($em'ep'),
  4190.                 'warehouse'                => Inventory::WarehouseListArray($em),
  4191.                 'supplier'                 => Inventory::ProductSupplierList($em),
  4192.                 'supplier_list_by_ac_head' => Accounts::SupplierListByAcHead($em),
  4193.                 'supplier_list_array'      => Inventory::ProductSupplierListArray($em),
  4194.                 'po_list_array'            => Purchase::PurchaseOrderListArray($em),
  4195.                 'po_list'                  => Purchase::PurchaseOrderList($em),
  4196.                 'product_list'             => Inventory::ProductList($em),
  4197.                 'grn_list'                 => Inventory::GrnListForEi($em1),
  4198.                 'grn_list_array'           => Inventory::GrnListForEiArray($em1),
  4199.             ]
  4200.         );
  4201.     }
  4202.   public function PendingInvoiceList(Request $request)
  4203.     {
  4204.         return $this->render(
  4205.             '@Accounts/pages/list/pending_list.html.twig',
  4206.             array(
  4207.                 'page_title' => 'Pending Invoices'
  4208.             )
  4209.         );
  4210.     }
  4211.     public function SalesInvoiceList(Request $request)
  4212.     {
  4213.         $em $this->getDoctrine()->getManager();
  4214.         $session $request->getSession();
  4215.         $companyId $this->getLoggedUserCompanyId($request);
  4216.         $userRestrictions = [];
  4217.         $selectiveDocumentsFlag 0;
  4218.         $allowedLoginIds = [];
  4219.         $canSeeAllSo 1;
  4220.         $allowedSpIds 'all';
  4221.         $allowedClientIds 'all';
  4222.         $allowedLoginIds 'all';
  4223.         $salesPersonList Client::SalesPersonList($this->getDoctrine()->getManager());
  4224.         $clientList SalesOrderM::GetClientList($em, [], $companyId);
  4225.         $userType $session->get(UserConstants::USER_TYPE);
  4226.         $userId $session->get(UserConstants::USER_ID);
  4227.         $selectiveQryArray = array('status' => GeneralConstant::ACTIVE);
  4228.         if ($userType == UserConstants::USER_TYPE_CLIENT) {
  4229.             $selectiveQryArray['clientId'] = $session->get(UserConstants::CLIENT_ID);
  4230.             $allowedClientIds = [$session->get(UserConstants::CLIENT_ID)];
  4231.         }
  4232.         if ($userType == UserConstants::USER_TYPE_GENERAL) {
  4233.             $userRestrictions Users::getUserApplicationAccessSettings($em$userId)['options'];
  4234.             $selectiveDocumentsFlag 1//by default will show only selective
  4235.             if (isset($userRestrictions['canSeeAllSo'])) {
  4236.                 if ($userRestrictions['canSeeAllSo'] == 1) {
  4237.                     $selectiveDocumentsFlag 0;
  4238.                     $canSeeAllSo 1;
  4239.                 }
  4240.             }
  4241.             if ($selectiveDocumentsFlag == 1) {
  4242.                 $allowedLoginIds MiscActions::getLoginIdsByUserId($em$session->get(UserConstants::USER_ID));
  4243.             }
  4244.         }
  4245.         $q $this->getDoctrine()
  4246.             ->getRepository('ApplicationBundle\\Entity\\SalesInvoice')
  4247.             ->findBy(
  4248.                 $selectiveQryArray
  4249.             );
  4250.         $stage_list = array(
  4251.             => 'Pending',
  4252.             => 'Complete',
  4253.             => 'Pending Payment',
  4254.         );
  4255.         $data = [];
  4256.         $salesOrders SalesOrderM::SalesOrderList($em);
  4257.         foreach ($q as $entry) {
  4258.             $clientId $entry->getClientId();
  4259.             $spId $clientList[$entry->getClientId()]['sales_person_id'];
  4260.             //            $client=$em->getRepository('ApplicationBundle\\Entity\\AccClients')
  4261.             //                ->findOneBy(
  4262.             //                    array(
  4263.             //                        'clientId'=>$clientId
  4264.             //                    )
  4265.             //                );
  4266.             if ($selectiveDocumentsFlag == 1) {
  4267.                 //1st check by sales person
  4268.                 $spCheckFailed 1;
  4269.                 if (isset($salesPersonList[$spId])) {
  4270.                     if ($salesPersonList[$spId]['userId'] == $userId) {
  4271.                         $spCheckFailed 0;
  4272.                     }
  4273.                 }
  4274.                 if ($spCheckFailed == 0) {
  4275.                 } else if (in_array($entry->getCreatedLoginId(), $allowedLoginIds) || in_array($entry->getEditedLoginId(), $allowedLoginIds)) {
  4276.                 } else {
  4277.                     continue;
  4278.                 }
  4279.             }
  4280.             $data[] = array(
  4281.                 'doc_date' => $entry->getSalesInvoiceDate(),
  4282.                 'doc_date_str' => $entry->getSalesInvoiceDate()->format('F d, Y'),
  4283.                 'id' => $entry->getSalesInvoiceId(),
  4284.                 'doc_hash' => $entry->getDocumentHash(),
  4285.                 'invoice_amount' => $entry->getInvoiceAmount(),
  4286.                 'sales_order_id' => $entry->getSalesOrderId(),
  4287.                 'sales_person_id' => $spId,
  4288.                 'sales_person_name' => isset($salesPersonList[$spId]) ? $salesPersonList[$spId]['name'] : '',
  4289.                 'so_amount' => $entry->getSoAmount(),
  4290.                 'client_name' => $clientList[$clientId]['client_name'],
  4291.                 'client_code' => $clientList[$clientId]['client_code'],
  4292.                 'client_contact_number' => $clientList[$clientId]['contact_number'],
  4293.                 'sales_order_name' => isset($salesOrders[$entry->getSalesOrderId()]) ? $salesOrders[$entry->getSalesOrderId()]['name'] : '',
  4294.                 'sales_or_service' => $entry->getSalesOrService(),
  4295.                 'stage' => GeneralConstant::stageLabel($stage_list$entry->getStage())
  4296.             );
  4297.         }
  4298.         if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  4299.             return new JsonResponse(
  4300.                 array(
  4301.                     'page_title' => 'Sales Invoices',
  4302.                     'data' => $data,
  4303.                     'userType' => $userType,
  4304.                     'orderConfirmationPendingFlag' => 0,
  4305.                     'users' => Users::getUserListById($em),
  4306.                     'canSeeAllSo' => $canSeeAllSo,
  4307.                     'allowedSpIds' => $allowedSpIds,
  4308.                     'allowedClientIds' => $allowedClientIds,
  4309.                     'allowedLoginIds' => $allowedLoginIds,
  4310.                     'sales_person_list' => $salesPersonList,
  4311.                     'success' => empty($data) ? false true
  4312.                 )
  4313.             );
  4314.         }
  4315.         return $this->render(
  4316.             '@Accounts/pages/list/sales_invoices.html.twig',
  4317.             array(
  4318.                 'page_title' => 'Sales Invoices',
  4319.                 'data' => $data,
  4320.                 'canSeeAllSo' => $canSeeAllSo,
  4321.                 'allowedSpIds' => $allowedSpIds,
  4322.                 'allowedClientIds' => $allowedClientIds,
  4323.                 'allowedLoginIds' => $allowedLoginIds,
  4324.             )
  4325.         );
  4326.     }
  4327.     public function PurchaseInvoiceList(Request $request)
  4328.     {
  4329.         $q $this->getDoctrine()
  4330.             ->getRepository('ApplicationBundle\\Entity\\PurchaseInvoice')
  4331.             ->findBy(
  4332.                 array(
  4333.                     'status' => GeneralConstant::ACTIVE,
  4334.                 )
  4335.             );
  4336.         $stage_list = array(
  4337.             => 'Pending',
  4338.             => 'Complete',
  4339.             => 'Pending Payment',
  4340.         );
  4341.         $data = [];
  4342.         foreach ($q as $entry) {
  4343.             $data[] = array(
  4344.                 'doc_date' => $entry->getPurchaseInvoiceDate(),
  4345.                 'id' => $entry->getPurchaseInvoiceId(),
  4346.                 'doc_hash' => $entry->getDocumentHash(),
  4347.                 'invoice_amount' => $entry->getInvoiceAmount(),
  4348.                 'stage' => GeneralConstant::stageLabel($stage_list$entry->getStage())
  4349.             );
  4350.         }
  4351. //        return new JsonResponse($data);
  4352.         return $this->render(
  4353.             '@Accounts/pages/list/purchase_invoices.html.twig',
  4354.             array(
  4355.                 'page_title' => 'Purchase Invoices',
  4356.                 'data' => $data
  4357.             )
  4358.         );
  4359.     }
  4360.     public function ViewSalesInvoice(Request $request$id)
  4361.     {
  4362.         $em $this->getDoctrine()->getManager();
  4363.         $absoluteUrl $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  4364.         $dt SalesOrderM::GetSalesInvoiceDetails($em$id);
  4365.         // Singapore InvoiceNow: show the "Send via InvoiceNow" action + last transmission
  4366.         // only for SG-registered companies (Peppol / PINT-SG is the SG e-invoicing scheme).
  4367.         $einvoiceEnabled = (\ApplicationBundle\Command\Support\JurisdictionGuard::companyCountryCode($em->getConnection()) === 'SG');
  4368.         $einvoiceLast null;
  4369.         $paynowPayload '';
  4370.         $paynowAmount 0.0;
  4371.         if ($einvoiceEnabled) {
  4372.             $conn $em->getConnection();
  4373.             try {
  4374.                 $einvoiceLast $conn->fetchAssociative(
  4375.                     "SELECT status, transmission_id, acknowledgement_id, transmitted_at
  4376.                      FROM peppol_transmission
  4377.                      WHERE sales_invoice_id = :i AND direction = 'out'
  4378.                      ORDER BY id DESC LIMIT 1",
  4379.                     ['i' => (int) $id]
  4380.                 ) ?: null;
  4381.             } catch (\Throwable $e) {
  4382.                 $einvoiceLast null;
  4383.             }
  4384.             // PayNow / SGQR: a scan-to-pay QR for the payee (UEN or mobile, per settings) + balance.
  4385.             try {
  4386.                 $co $conn->fetchAssociative("SELECT name, uen FROM company ORDER BY id LIMIT 1") ?: [];
  4387.                 $si $conn->fetchAssociative(
  4388.                     "SELECT invoice_amount, due_amount, document_hash FROM sales_invoice WHERE sales_invoice_id = :i LIMIT 1",
  4389.                     ['i' => (int) $id]) ?: [];
  4390.                 if ($si) {
  4391.                     $paynowAmount = (float) (($si['due_amount'] ?? 0) > $si['due_amount'] : ($si['invoice_amount'] ?? 0));
  4392.                     $paynowPayload = \ApplicationBundle\Modules\Tax\Service\PayNowQrBuilder::forInvoice(
  4393.                         $conn1$paynowAmount, (string) ($co['name'] ?? 'NA'),
  4394.                         (string) ($si['document_hash'] ?? ('SI' $id)));
  4395.                 }
  4396.             } catch (\Throwable $e) {
  4397.                 $paynowPayload '';
  4398.             }
  4399.         }
  4400.         return $this->render(
  4401. //            '@Accounts/pages/views/view_sales_invoice.html.twig',
  4402.             '@Accounts/pages/views/view_sales_invoice_demo.html.twig',
  4403.             array(
  4404.                 'page_title' => 'View',
  4405.                 'data' => $dt,
  4406.                 'absoluteUrl' => $absoluteUrl,
  4407.                 'auto_created' => $dt['auto_created'],
  4408.                 'einvoice_enabled' => $einvoiceEnabled,
  4409.                 'einvoice_last' => $einvoiceLast,
  4410.                 'einvoice_flash' => $request->getSession()->getFlashBag()->get('einv_ok')[0] ?? ($request->getSession()->getFlashBag()->get('einv_err')[0] ?? null),
  4411.                 'paynow_payload' => $paynowPayload,
  4412.                 'paynow_amount' => $paynowAmount,
  4413.                 'approval_data' => System::checkIfApprovalExists(
  4414.                     $em,
  4415.                     array_flip(GeneralConstant::$Entity_list)['SalesInvoice'],
  4416.                     $id,
  4417.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  4418.                 ),
  4419.                 'document_log' => $dt['auto_created'] == System::getDocumentLog(
  4420.                     $this->getDoctrine()->getManager(),
  4421.                     array_flip(GeneralConstant::$Entity_list)['SalesInvoice'],
  4422.                     $id,
  4423.                     $dt['created_by'],
  4424.                     $dt['edited_by']
  4425.                 ) : []
  4426.             )
  4427.         );
  4428.     }
  4429.     public function CorrectCheckProblem(Request $request)
  4430.     {
  4431.         $em $this->getDoctrine()->getManager();
  4432.         $check_list_in_brs = array();
  4433.         $docData $em->getRepository('ApplicationBundle\\Entity\\Brs')->findBy(
  4434.             array(
  4435.                 //                'brsId'=>$id
  4436.                 //            'approved'=>1
  4437.             )
  4438.         );
  4439.         foreach ($docData as $doc) {
  4440.             $details_data json_decode($doc->getData(), true);
  4441.             if ($details_data) {
  4442.                 $pending_check_no_list = [];
  4443.                 if (isset($details_data["pending_cn"])) {
  4444.                     foreach ($details_data["pending_cn"] as $key => $value) {
  4445.                         if (!isset($check_list_in_brs[$value])) {
  4446.                             $check_list_in_brs[$value] = array(
  4447.                                 'check_amount' => 0,
  4448.                                 'narration' => ""
  4449.                             );
  4450.                         }
  4451.                         if (isset($details_data["pending_check_amount"])) {
  4452.                             if ($check_list_in_brs[$value]['check_amount'] == 0)
  4453.                                 $check_list_in_brs[$value]['check_amount'] = $details_data["pending_check_amount"][$key];
  4454.                         }
  4455.                     }
  4456.                 }
  4457.                 if (isset($details_data["cleared_cn"])) {
  4458.                     foreach ($details_data["cleared_cn"] as $key => $value) {
  4459.                         if (!isset($check_list_in_brs[$value])) {
  4460.                             $check_list_in_brs[$value] = array(
  4461.                                 'check_amount' => 0,
  4462.                                 'narration' => ""
  4463.                             );
  4464.                         }
  4465.                         if (isset($details_data["cleared_check_amount"])) {
  4466.                             if ($check_list_in_brs[$value]['check_amount'] == 0)
  4467.                                 $check_list_in_brs[$value]['check_amount'] = $details_data["cleared_check_amount"][$key];
  4468.                         }
  4469.                     }
  4470.                 }
  4471.             }
  4472.         }
  4473.         foreach ($check_list_in_brs as $key => $value) {
  4474.             $ck $em->getRepository('ApplicationBundle\\Entity\\AccCheck')->findOneBy(
  4475.                 array(
  4476.                     //                'brsId'=>$id
  4477.                     'checkNumber' => $key
  4478.                 )
  4479.             );
  4480.             if ($ck) {
  4481.                 $ck->setCheckAmount($value['check_amount']);
  4482.                 $ck->setAssigned(1);
  4483.                 if ($ck->getCheckDate() == null)
  4484.                     $ck->setCheckDate($ck->getLedgerHitDate());
  4485.                 if ($ck->getVoucherId() == null)
  4486.                     $ck->setVoucherId(0);
  4487.                 $em->flush();
  4488.             }
  4489.         }
  4490.         //        $dt=Accounts::GetBrsDetails($em,$id);
  4491.         return new JsonResponse($check_list_in_brs);
  4492.     }
  4493.     public function ViewBrs(Request $request$id)
  4494.     {
  4495.         $em $this->getDoctrine()->getManager();
  4496.         $dt Accounts::GetBrsDetails($em$id);
  4497.         return $this->render(
  4498.             '@Accounts/pages/views/brs_view.html.twig',
  4499.             array(
  4500.                 'page_title' => 'BRS',
  4501.                 'data' => $dt,
  4502.                 'auto_created' => $dt['auto_created'],
  4503.                 'approval_data' => System::checkIfApprovalExists(
  4504.                     $em,
  4505.                     array_flip(GeneralConstant::$Entity_list)['Brs'],
  4506.                     $id,
  4507.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  4508.                 ),
  4509.                 'document_log' => $dt['auto_created'] == System::getDocumentLog(
  4510.                     $this->getDoctrine()->getManager(),
  4511.                     array_flip(GeneralConstant::$Entity_list)['Brs'],
  4512.                     $id,
  4513.                     $dt['created_by'],
  4514.                     $dt['edited_by']
  4515.                 ) : []
  4516.             )
  4517.         );
  4518.     }
  4519.     public function PrintBrs(Request $request$id)
  4520.     {
  4521.         $em $this->getDoctrine()->getManager();
  4522.         $data Accounts::GetBrsDetails($em$id);
  4523.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  4524.         $document_mark = array(
  4525.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  4526.             'copy' => ''
  4527.         );
  4528.         return $this->render(
  4529.             '@Accounts/pages/print/print_brs.html.twig',
  4530.             array(
  4531.                 'export' => 'print',
  4532.                 'page_title' => 'BRS' $data['doc_hash'],
  4533.                 'data' => $data,
  4534.                 'document_mark_image' => $document_mark['original'],
  4535.                 'company_name' => $company_data->getName(),
  4536.                 'company_data' => $company_data,
  4537.                 'company_address' => $company_data->getAddress(),
  4538.                 'company_image' => $company_data->getImage(),
  4539.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  4540.                 'page_header' => 'BRS',
  4541.                 'document_type' => 'Sales Bill',
  4542.                 'page_header_sub' => 'Add',
  4543.                 //                'type_list'=>$type_list,
  4544.                 //                'mis_data'=>$mis_data,
  4545.                 //                'mis_print'=>$mis_print,
  4546.                 'item_data' => [],
  4547.                 'received' => 2,
  4548.                 'return' => 1,
  4549.                 'total_w_vat' => 1,
  4550.                 'total_vat' => 1,
  4551.                 'total_wo_vat' => 1,
  4552.                 'invoice_id' => 'abcd1234',
  4553.                 'created_by' => 'created by',
  4554.                 'created_at' => '',
  4555.                 'red' => 0,
  4556.             )
  4557.         );
  4558.     }
  4559.     public function ViewFinancialBudget(Request $request$id)
  4560.     {
  4561.         $em $this->getDoctrine()->getManager();
  4562.         $dt Accounts::GetFinancialBudgetDetails($em$id);
  4563.         return $this->render(
  4564.             '@Accounts/pages/views/financial_budget.html.twig',
  4565.             array(
  4566.                 'page_title' => 'Financial Budget',
  4567.                 'data' => $dt,
  4568.                 'auto_created' => $dt['auto_created'],
  4569.                 'approval_data' => System::checkIfApprovalExists(
  4570.                     $em,
  4571.                     array_flip(GeneralConstant::$Entity_list)['FinancialBudget'],
  4572.                     $id,
  4573.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  4574.                 ),
  4575.                 'document_log' => $dt['auto_created'] == System::getDocumentLog(
  4576.                     $this->getDoctrine()->getManager(),
  4577.                     array_flip(GeneralConstant::$Entity_list)['FinancialBudget'],
  4578.                     $id,
  4579.                     $dt['created_by'],
  4580.                     $dt['edited_by']
  4581.                 ) : []
  4582.             )
  4583.         );
  4584.     }
  4585.     public function PrintFinancialBudget(Request $request$id)
  4586.     {
  4587.         $em $this->getDoctrine()->getManager();
  4588.         $data Accounts::GetFinancialBudgetDetails($em$id);
  4589.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  4590.         $document_mark = array(
  4591.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  4592.             'copy' => ''
  4593.         );
  4594.         return $this->render(
  4595.             '@Accounts/pages/print/financial_budget.html.twig',
  4596.             array(
  4597.                 'export' => 'print',
  4598.                 'page_title' => 'Financial Budget' $data['doc_hash'],
  4599.                 'data' => $data,
  4600.                 'document_mark_image' => $document_mark['original'],
  4601.                 'company_name' => $company_data->getName(),
  4602.                 'company_data' => $company_data,
  4603.                 'company_address' => $company_data->getAddress(),
  4604.                 'company_image' => $company_data->getImage(),
  4605.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  4606.                 'page_header' => 'BRS',
  4607.                 'document_type' => 'Sales Bill',
  4608.                 'page_header_sub' => 'Add',
  4609.                 //                'type_list'=>$type_list,
  4610.                 //                'mis_data'=>$mis_data,
  4611.                 //                'mis_print'=>$mis_print,
  4612.                 'item_data' => [],
  4613.                 'received' => 2,
  4614.                 'return' => 1,
  4615.                 'total_w_vat' => 1,
  4616.                 'total_vat' => 1,
  4617.                 'total_wo_vat' => 1,
  4618.                 'invoice_id' => 'abcd1234',
  4619.                 'created_by' => 'created by',
  4620.                 'created_at' => '',
  4621.                 'red' => 0,
  4622.             )
  4623.         );
  4624.     }
  4625.     public function PrintSalesInvoice(Request $request$id)
  4626.     {
  4627.         $em $this->getDoctrine()->getManager();
  4628.         if ($id != 0)
  4629.             $data SalesOrderM::GetSalesInvoiceDetails($em$id);
  4630.         else if ($request->query->has('printType'))
  4631.             $data SalesOrderM::GetSalesInvoiceDetails(
  4632.                 $em,
  4633.                 $id,
  4634.                 $request->query->get('printType'),
  4635.                 $request->query->get('invoiceIds', []),
  4636.                 $request->query->get('soId'0)
  4637.             );
  4638.         // Nothing to print (bad id / order with no invoices): show a clean message instead of
  4639.         // letting the template blow up on data.si_data_array[0].
  4640.         if (empty($data) || empty($data['si_data_array'])) {
  4641.             return new \Symfony\Component\HttpFoundation\Response(
  4642.                 '<div style="font-family:sans-serif;padding:48px;text-align:center;color:#666;font-size:15px;">'
  4643.                 'No invoice found to print' . ($id != ' (invoice #' . (int) $id ')' : (' for order #' . (int) $request->query->get('soId'0))) . '.</div>',
  4644.                 200
  4645.             );
  4646.         }
  4647.         // S2.3 — register in Document Variant Engine (additive, non-blocking)
  4648.         if (!empty($data['si_data'])) {
  4649.             try {
  4650.                 $invoiceVariant $request->query->get('invoiceVariant''final');
  4651.                 DocumentRegistry::register(
  4652.                     $em,
  4653.                     in_array($invoiceVariant, ['commercial','customs','lc','import','credit_note','proforma']) ? $invoiceVariant 'final',
  4654.                     'SalesInvoice',
  4655.                     (int)$id,
  4656.                     [
  4657.                         'tenantId'       => $data['si_data']->getCompanyId(),
  4658.                         'customerId'     => $data['si_data']->getClientId(),
  4659.                         'projectId'      => $data['si_data']->getProjectId(),
  4660.                         'documentNumber' => isset($data['doc_hash']) ? $data['doc_hash'] : null,
  4661.                         'currency'       => $data['si_data']->getCurrency(),
  4662.                         'createdBy'      => $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  4663.                     ]
  4664.                 );
  4665.             } catch (\Exception $e) { /* registry is non-blocking */ }
  4666.         }
  4667.         //        $company_data = Company::getCompanyData($em, $this->getLoggedUserCompanyId($request));
  4668.         $company_data Company::getCompanyData($em$data['si_data']->getCompanyId());
  4669.         // PayNow / SGQR scan-to-pay QR on the customer-facing invoice (SG companies only).
  4670.         $paynow_payload '';
  4671.         $paynow_amount 0.0;
  4672.         $paynow_show_on_pdf true;
  4673.         try {
  4674.             $conn $em->getConnection();
  4675.             if (\ApplicationBundle\Command\Support\JurisdictionGuard::companyCountryCode($conn) === 'SG') {
  4676.                 $due = (float) $data['si_data']->getDueAmount();
  4677.                 $paynow_amount $due $due : (float) $data['si_data']->getInvoiceAmount();
  4678.                 $paynow_payload = \ApplicationBundle\Modules\Tax\Service\PayNowQrBuilder::forInvoice(
  4679.                     $conn, (int) $data['si_data']->getCompanyId(), $paynow_amount,
  4680.                     (string) $company_data->getName(), (string) $data['si_data']->getDocumentHash());
  4681.                 $paynow_show_on_pdf = \ApplicationBundle\Modules\Tax\Service\PayNowQrBuilder::showOnPdf($conn);
  4682.             }
  4683.         } catch (\Throwable $e) {
  4684.             $paynow_payload '';
  4685.         }
  4686.         $document_mark = array(
  4687.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  4688.             'copy' => ''
  4689.         );
  4690.         $printTemplate CountryTemplateResolver::resolve(
  4691.             $this->get('twig'),
  4692.             $em,
  4693.             $data['si_data']->getCompanyId(),
  4694.             '@Accounts/pages/print/print_sales_invoice.html.twig'
  4695.         );
  4696.         $taxMarkers TaxMarkerLookup::forCompany($em$data['si_data']->getCompanyId());
  4697.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  4698.             $html $this->renderView(
  4699.                 $printTemplate,
  4700.                 array(
  4701.                     //full array here
  4702.                     'pdf' => true,
  4703.                     'page_title' => 'Sales Bill ' $data['doc_hash'],
  4704.                     'data' => $data,
  4705.                     'export' => 'pdf,print',
  4706.                     'document_mark_image' => $document_mark['original'],
  4707.                     'company_name' => $company_data->getName(),
  4708.                     'company_data' => $company_data,
  4709.                     'company_address' => $company_data->getAddress(),
  4710.                     'company_image' => $company_data->getImage(),
  4711.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  4712.                     'page_header' => 'New Product',
  4713.                     'document_type' => 'Sales Bill',
  4714.                     'page_header_sub' => 'Add',
  4715.                     //                'type_list'=>$type_list,
  4716.                     //                'mis_data'=>$mis_data,
  4717.                     //                'mis_print'=>$mis_print,
  4718.                     'item_data' => [],
  4719.                     'received' => 2,
  4720.                     'return' => 1,
  4721.                     'total_w_vat' => 1,
  4722.                     'total_vat' => 1,
  4723.                     'total_wo_vat' => 1,
  4724.                     'invoice_id' => 'abcd1234',
  4725.                     'created_by' => 'created by',
  4726.                     'created_at' => '',
  4727.                     'red' => 0,
  4728.                     'taxMarkers' => $taxMarkers,
  4729.                     'paynow_payload' => $paynow_payload,
  4730.                     'paynow_amount' => $paynow_amount,
  4731.                     'paynow_show_on_pdf' => $paynow_show_on_pdf,
  4732.                 )
  4733.             );
  4734.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  4735.                 //                'orientation' => 'landscape',
  4736.                 //                'enable-javascript' => true,
  4737.                 //                'javascript-delay' => 1000,
  4738.                 'no-stop-slow-scripts' => false,
  4739.                 'no-background' => false,
  4740.                 'lowquality' => false,
  4741.                 'encoding' => 'utf-8',
  4742.                 //            'images' => true,
  4743.                 //            'cookie' => array(),
  4744.                 'dpi' => 300,
  4745.                 'image-dpi' => 300,
  4746.                 //                'enable-external-links' => true,
  4747.                 //                'enable-internal-links' => true
  4748.             ));
  4749.             return new Response(
  4750.                 $pdf_response,
  4751.                 200,
  4752.                 array(
  4753.                     'Content-Type' => 'application/pdf',
  4754.                     'Content-Disposition' => 'attachment; filename="sales_invoice_' $id '.pdf"'
  4755.                 )
  4756.             );
  4757.         }
  4758.         return $this->render(
  4759.             $printTemplate,
  4760.             array(
  4761.                 'page_title' => 'Sales Bill ' $data['doc_hash'],
  4762.                 'data' => $data,
  4763.                 'export' => 'pdf,print',
  4764.                 'document_mark_image' => $document_mark['original'],
  4765.                 'company_name' => $company_data->getName(),
  4766.                 'company_data' => $company_data,
  4767.                 'company_address' => $company_data->getAddress(),
  4768.                 'company_image' => $company_data->getImage(),
  4769.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  4770.                 'page_header' => 'New Product',
  4771.                 'document_type' => 'Sales Bill',
  4772.                 'page_header_sub' => 'Add',
  4773.                 //                'type_list'=>$type_list,
  4774.                 //                'mis_data'=>$mis_data,
  4775.                 //                'mis_print'=>$mis_print,
  4776.                 'item_data' => [],
  4777.                 'received' => 2,
  4778.                 'return' => 1,
  4779.                 'total_w_vat' => 1,
  4780.                 'total_vat' => 1,
  4781.                 'total_wo_vat' => 1,
  4782.                 'invoice_id' => 'abcd1234',
  4783.                 'created_by' => 'created by',
  4784.                 'created_at' => '',
  4785.                 'red' => 0,
  4786.                 'taxMarkers' => $taxMarkers,
  4787.                 'paynow_payload' => $paynow_payload,
  4788.                 'paynow_amount' => $paynow_amount,
  4789.                 'paynow_show_on_pdf' => $paynow_show_on_pdf,
  4790.             )
  4791.         );
  4792.     }
  4793.     public function GetPurchaseInvoiceBalancingData(Request $request)
  4794.     {
  4795.         $heads $request->request->get('heads');
  4796.         $ids $request->request->get('ids');
  4797.         $em $this->getDoctrine()->getManager();
  4798.         return new JsonResponse(array(
  4799.             "success" => false,
  4800.             "content" => Accounts::GetPurchaseInvoiceBalancingData($em$heads$ids)
  4801.         ));
  4802.     }
  4803.     public function GetSalesInvoiceBalancingData(Request $request)
  4804.     {
  4805.         $heads $request->request->get('heads');
  4806.         $ids $request->request->get('ids');
  4807.         $em $this->getDoctrine()->getManager();
  4808.         return new JsonResponse(array(
  4809.             "success" => false,
  4810.             "content" => Accounts::GetSalesInvoiceBalancingData($em$heads$ids)
  4811.         ));
  4812.     }
  4813.     public function GetSelectedHeadsHistory(Request $request$mis_start_date ''$mis_end_date '')
  4814.     {
  4815.         $em $this->getDoctrine()->getManager();
  4816.         $start_date "";
  4817.         $end_date "";
  4818.         //        $em=$this->getDoctrine()->getManager();
  4819.         if ($mis_start_date != '' && $mis_start_date != 0)
  4820.             $start_date $mis_start_date;
  4821.         if ($mis_end_date != '' && $mis_start_date != 0)
  4822.             $end_date $mis_start_date;
  4823.         $engine $this->container->get('twig');
  4824.         $pids array_unique(explode("::"$_POST["pids"]));
  4825.         $Content $engine->render(
  4826.             '@Accounts/pages/report/selected_head_details.html.twig',
  4827.             Accounts::GetVoucherMisDetails($em$pids$start_date$end_date)
  4828.         );
  4829.         //        $stockPosition=$engine->render('@Sales/pages/report/selected_products_stock_position.html.twig', array('pSalesDetails'=>$ProductSales));
  4830.         return new JsonResponse(array("success" => false"content" => $Content));
  4831.         //        return new JsonResponse(array("success"=>false,"content"=>$Content, "stockPosition"=>$stockPosition));
  4832.     }
  4833.     public function EditVoucher(Request $request$id)
  4834.     {
  4835.         $em $this->getDoctrine()->getManager();
  4836.         $Transaction $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  4837.             'transactionId' => $id,
  4838.             'editFlag' => 1,
  4839.             'lockFlag' => [0null],
  4840.             'disabledFlag' => [0null],
  4841.         ));
  4842.         if ($Transaction) {
  4843.             if ($Transaction->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  4844.                 return $this->redirectToRoute('edit_journal_voucher', array('id' => $id));
  4845.             }
  4846.         } else {
  4847.             //            $this->container->get("session")->setFlash("error", "Pikachu is not allowed");
  4848.             $this->addFlash(
  4849.                 'error',
  4850.                 'The Action was not allowed.'
  4851.             );
  4852.             $url $request->headers->get("referer");
  4853.             //            return $this->render('@Purchase/pages/list_tables/quotation.html.twig',
  4854.             //                array(
  4855.             //                    'page_title'=>'Quotation Calculator'
  4856.             //
  4857.             //                )
  4858.             //            );
  4859.             return new RedirectResponse($url);
  4860.         }
  4861.         //
  4862.         //
  4863.         //        return $this->render('@Accounts/pages/input_forms/journal_voucher.html.twig',
  4864.         //            array(
  4865.         //                'page_title'=>'Create Journal Voucher'
  4866.         //            )
  4867.         //        );
  4868.     }
  4869.     public function RefreshDocHash(Request $request$entity_id)
  4870.     {
  4871.         //        $response = new StreamedResponse();
  4872.         //        $response->setCallback(function () {
  4873.         $em $this->getDoctrine()->getManager();
  4874.         $assign_list = array();
  4875.         $new_cc $em
  4876.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  4877.             ->findOneBy(
  4878.                 array(
  4879.                     'name' => 'accounting_year_start',
  4880.                 )
  4881.             );
  4882.         $query "SELECT transaction_id, type_hash, prefix_hash, assoc_hash, number_hash from  acc_transactions  where status=" GeneralConstant::ACTIVE;
  4883.         $date_start "";
  4884.         $date_start_str "";
  4885.         if ($new_cc) {
  4886.             $date_start = new \DateTime($new_cc->getData());
  4887.             $date_start_str $date_start->format('Y-m-d');
  4888.         }
  4889.         if ($new_cc)
  4890.             $query .= " AND transaction_date>= '" $date_start_str " 00:00:00' ";
  4891.         $query .= " ORDER BY transaction_date ASC";
  4892.         $stmt $em->getConnection()->fetchAllAssociative($query);
  4893.         
  4894.         $Transactions $stmt;
  4895.         $update_qry "";
  4896.         foreach ($Transactions as $entry) {
  4897.             if (isset($assign_list[$entry['type_hash'] . '_' $entry['prefix_hash'] . '_' $entry['assoc_hash']])) {
  4898.                 $to_be_assigned $assign_list[$entry['type_hash'] . '_' $entry['prefix_hash'] . '_' $entry['assoc_hash']]['last_no_hash'] + 1;
  4899.                 if ($to_be_assigned == $entry['number_hash']) {
  4900.                 } else {
  4901.                     $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'
  4902.                     where transaction_id=" $entry['transaction_id'] . "; ";
  4903.                 }
  4904.                 $assign_list[$entry['type_hash'] . '_' $entry['prefix_hash'] . '_' $entry['assoc_hash']]['last_no_hash'] = $to_be_assigned;
  4905.             } else {
  4906.                 $assign_list[$entry['type_hash'] . '_' $entry['prefix_hash'] . '_' $entry['assoc_hash']]['last_no_hash'] = $entry['number_hash'];
  4907.             }
  4908.         }
  4909.         $stmt $em->getConnection()->fetchAllAssociative($update_qry);
  4910.         
  4911.         //        $Transactions=$stmt;
  4912.         return $this->redirectToRoute('dashboard');
  4913.     }
  4914.     public function RefreshTransactions(Request $request)
  4915.     {
  4916.         //        $response = new StreamedResponse();
  4917.         //        $response->setCallback(function () {
  4918.         $em $this->getDoctrine()->getManager();
  4919.         //1st get all brscleared vids for heads
  4920.         $brs_cleared_vids_by_head = [];
  4921.         $Transaction $em->getRepository('ApplicationBundle\\Entity\\Brs')->findBy(
  4922.             array(
  4923.                 //                'approved'=>GeneralConstant::APPROVED,
  4924.                 //                'transactionId'=>$tids
  4925.                 //            'ledgerHit'=>1,
  4926.             )
  4927.         );
  4928.         foreach ($Transaction as $doc) {
  4929.             $data json_decode($doc->getData(), true);
  4930.             if (isset($data['cleared_check_id'])) {
  4931.                 $check_ids $data['cleared_check_id'];
  4932.                 //                $recon_dates=$data['recon_date'];
  4933.                 $v_ids $data['cleared_vid'];
  4934.                 foreach ($v_ids as $vid) {
  4935.                     if (isset($brs_cleared_vids_by_head[$doc->getAccountsHeadId()])) {
  4936.                         $brs_cleared_vids_by_head[$doc->getAccountsHeadId()][] = $vid;
  4937.                     } else {
  4938.                         $brs_cleared_vids_by_head[$doc->getAccountsHeadId()] = [$vid];
  4939.                     }
  4940.                 }
  4941.             }
  4942.             //            $tids[]=$d->getTransactionId();
  4943.         }
  4944.         $bank_settings $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  4945.             'name' => 'bank_parents'
  4946.         ));
  4947.         $bank_id_list = [];
  4948.         if ($bank_settings)
  4949.             $bank_id_list json_decode($bank_settings->getData());
  4950.         $head_list Accounts::HeadListFullPath($em);
  4951.         $bank_head_list = [];
  4952.         $bank_head_list_array = [];
  4953.         foreach ($head_list as $k => $v) {
  4954.             //            if($k==210)
  4955.             //                continue;
  4956.             foreach ($bank_id_list as $bid) {
  4957.                 $q_str '/' $bid '/';
  4958.                 $path_string $v['path'];
  4959.                 $debug_it[] = [$q_str$path_stringstrpos($path_string$q_str)];
  4960.                 if (strpos($path_string$q_str) !== false) {
  4961.                     $bank_head_list[$k] = $v;
  4962.                     $bank_head_list_array[] = $k;
  4963.                 } else {
  4964.                 }
  4965.             }
  4966.         }
  4967.         ///temporarily adding pending reconlist for vouchers
  4968.         $Transaction $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findBy(
  4969.             array(
  4970.                 'approved' => GeneralConstant::APPROVED,
  4971.                 //                'transactionId'=>$tids
  4972.                 //            'ledgerHit'=>1,
  4973.             )
  4974.         );
  4975.         foreach ($Transaction as $d) {
  4976.             $tids[] = $d->getTransactionId();
  4977.         }
  4978.         $TransactionDetails $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(
  4979.             array(
  4980.                 'accountsHeadId' => $tids,
  4981.                 //            'ledgerHit'=>1,
  4982.             )
  4983.         );
  4984.         $det_by_trans_id = [];
  4985.         foreach ($TransactionDetails as $d) {
  4986.             if (in_array($d->getAccountsHeadId(), $bank_head_list_array)) {
  4987.                 if (isset($brs_cleared_vids_by_head[$d->getAccountsHeadId()])) {
  4988.                     if (in_array($d->getTransactionId(), $brs_cleared_vids_by_head[$d->getAccountsHeadId()])) {
  4989.                         continue;
  4990.                     }
  4991.                 }
  4992.                 if (isset($det_by_trans_id[$d->getTransactionId()])) {
  4993.                     $det_by_trans_id[$d->getTransactionId()]['pendReconIdList'][] = $d->getAccountsHeadId();
  4994.                 } else {
  4995.                     $det_by_trans_id[$d->getTransactionId()] = array(
  4996.                         'pendReconIdList' => [$d->getAccountsHeadId()]
  4997.                     );
  4998.                 }
  4999.             }
  5000.         }
  5001.         foreach ($det_by_trans_id as $tid => $d) {
  5002.             $Transaction $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(
  5003.                 array(
  5004.                     'approved' => GeneralConstant::APPROVED,
  5005.                     'transactionId' => $tid
  5006.                     //            'ledgerHit'=>1,
  5007.                 )
  5008.             );
  5009.             if ($Transaction) {
  5010.                 if (empty($d['pendReconIdList'])) {
  5011.                     $Transaction->setProvisional(0);
  5012.                     $Transaction->setPendingReconciliationIdList(json_encode([]));
  5013.                 } else {
  5014.                     $Transaction->setPendingReconciliationIdList(json_encode($d['pendReconIdList']));
  5015.                     $Transaction->setProvisional(1);
  5016.                 }
  5017.                 $em->flush();
  5018.             }
  5019.         }
  5020.         //            echo 'Refreshing  Transactions\n';
  5021.         //            flush();
  5022.         //
  5023.         //            $new_cc = $em
  5024.         //                ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  5025.         //                ->findOneBy(
  5026.         //                    array(
  5027.         //                        'name' => 'accounting_year_start',
  5028.         //                    )
  5029.         //                );
  5030.         //
  5031.         //            $query="UPDATE  acc_transactions set ledger_hit=0  ";
  5032.         //            $date_start="";
  5033.         //            $date_start_str="";
  5034.         //            if($new_cc) {
  5035.         //                $date_start = new \DateTime($new_cc->getData());
  5036.         //                $date_start_str=$date_start->format('Y-m-d');
  5037.         //            }
  5038.         //            if($new_cc)
  5039.         //                $query.=" where transaction_date>= '".$date_start_str." 00:00:00' ";
  5040.         //
  5041.         //
  5042.         //            $stmt = $em->getConnection()->fetchAllAssociative($query);
  5043.         //            
  5044.         //            echo 'Refreshing  Transactions\n';
  5045.         //            flush();
  5046.         //            sleep(2);
  5047.         //
  5048.         //            $Transactions=$em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  5049.         //                    'approved'=>1,
  5050.         //                    'ledgerHit'=>0
  5051.         //                )
  5052.         //                ,array(
  5053.         //                    'transactionDate'=>'ASC'
  5054.         //                ));
  5055.         ////            foreach($Transactions as $test)
  5056.         ////            {
  5057.         ////                echo 'processing v_id'.$test->getTransactionId().'\n';
  5058.         ////                flush();
  5059.         //        if($Transactions) {
  5060.         //            ApprovalFunction::AccTransactions($em, $Transactions->getTransactionId());
  5061.         //            return $this->redirectToRoute('refresh_transactions');
  5062.         //        }
  5063.         //        else
  5064.         //            return $this->redirectToRoute('dashboard');
  5065.         //
  5066.         //
  5067.         //                sleep(2);
  5068.         //
  5069.         ////                return $this->redirectToRoute('refresh_transactions');
  5070.         //
  5071.         //            }
  5072.         ////            echo 'Hello World';
  5073.         ////            flush();
  5074.         ////            sleep(2);
  5075.         ////            echo 'Hello World';
  5076.         ////            flush();
  5077.         //        });
  5078.         //        $response->send();
  5079.         //        $httpKernel->terminate($request, $response);
  5080.         //        ApprovalFunction::AccTransactions($em,$id);
  5081.         //        $done=MiscActions::refreshTransactions($em);
  5082.         //
  5083.         //        $this->addFlash(
  5084.         //            'success',
  5085.         //            'The Action was Successful.'
  5086.         //        );
  5087.         //
  5088.         //
  5089.         //
  5090.         return $this->redirectToRoute('dashboard');
  5091.     }
  5092.     public function RefreshDatabase(Request $request$refdate '')
  5093.     {
  5094.         $em $this->getDoctrine()->getManager();
  5095.         if ($refdate == '')
  5096.             $refdate '2018-11-10';
  5097.         ////starting correcting the delivery confirmations
  5098.         //1st get the required delivery confirmation list
  5099.         $get_kids_sql " SELECT *  FROM `delivery_confirmation` WHERE `delivery_confirmation_date` >= '" $refdate " 00:00:00'
  5100. ORDER BY `delivery_confirmation`.`delivery_confirmation_id` ASC";
  5101.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  5102.         
  5103.         $get_kids $stmt;
  5104.         $dc_id_list = [];
  5105.         $dc_det_by_id = [];
  5106.         foreach ($get_kids as $kid) {
  5107.             $dc_id_list[] = $kid['delivery_confirmation_id'];
  5108.             $dc_det_by_id[$kid['delivery_confirmation_id']] = $kid;
  5109.         }
  5110.         //now
  5111.         foreach ($dc_id_list as $k => $dc_id) {
  5112.             //1st get delivery receipt date
  5113.             $dr $em->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')
  5114.                 ->findOneBy(
  5115.                     array(
  5116.                         'deliveryReceiptId' => $dc_det_by_id[$dc_id]['delivery_receipt_id'],
  5117.                     )
  5118.                 );
  5119.             if ($dr) {
  5120.                 $todate = new \Datetime();
  5121.                 $next_one_date $todate->format('Y-m-d') . ' 23:59:59';
  5122.                 if (isset($dc_id_list[$k 1]))
  5123.                     $next_one_date $dc_det_by_id[$dc_id_list[$k 1]]['created_at'];
  5124.                 $qry "select * from sales_invoice where sales_invoice_date>='" $dc_det_by_id[$dc_id]['created_at'] .
  5125.                     "' and sales_invoice_date< '" $next_one_date "' ORDER BY `sales_invoice`.`sales_invoice_date` ASC limit 1";
  5126.                 $stmt $em->getConnection()->fetchAllAssociative($qry);
  5127.                 
  5128.                 $get_kids $stmt;
  5129.                 if (!empty($get_kids)) {
  5130.                     $voucher_list json_decode($get_kids[0]['voucher_ids'], true);
  5131.                     $qry1 "update sales_invoice set
  5132.                    sales_invoice_date='" $dr->getDeliveryReceiptDate()->format('Y-m-d H:i:s') . "' ,
  5133.                    receipt_id_list='" json_encode([$dr->getDeliveryReceiptId()]) . "'
  5134.                    where sales_invoice_id=" $get_kids[0]['sales_invoice_id'];
  5135.                     $stmt $em->getConnection()->executeStatement($qry1);
  5136.                     
  5137.                     $qry1 "update  acc_transactions set
  5138.                     transaction_date='" $dr->getDeliveryReceiptDate()->format('Y-m-d H:i:s') . "' ,
  5139.                     ledger_hit_date='" $dr->getDeliveryReceiptDate()->format('Y-m-d H:i:s') . "'
  5140.                     where transaction_id in (" implode(', '$voucher_list) . ")";
  5141.                     $stmt $em->getConnection()->executeStatement($qry1);
  5142.                     
  5143.                     $qry1 "update  acc_transaction_details set
  5144.                     transaction_date='" $dr->getDeliveryReceiptDate()->format('Y-m-d H:i:s') . "' ,
  5145.                     ledger_hit_date='" $dr->getDeliveryReceiptDate()->format('Y-m-d H:i:s') . "'
  5146.                     where transaction_id in (" implode(', '$voucher_list) . ")";
  5147.                     $stmt $em->getConnection()->executeStatement($qry1);
  5148.                     
  5149.                     //            $get_kids=$stmt;
  5150.                 }
  5151.             }
  5152.         }
  5153.         //            MiscActions::refreshDatabase($em);
  5154.         $this->addFlash(
  5155.             'success',
  5156.             'The Action was Successful.'
  5157.         );
  5158.         return $this->redirectToRoute('dashboard');
  5159.     }
  5160.     public function RefreshClosing(Request $request)
  5161.     {
  5162.         // GATE (2026-07-26). This console rewrites a live tenant's stock and GL
  5163.         // balances wholesale, yet was reachable by ANY logged-in user — the class
  5164.         // declares only SessionCheckInterface. Same rule as the Rebuild & Rectify
  5165.         // console and /tenant-reset: super-users only.
  5166.         $denial = \ApplicationBundle\Modules\Accounts\Support\RebuildAccessGuard::previewDenial($request->getSession());
  5167.         if ($denial !== '') {
  5168.             if ($request->isMethod('POST') || $request->isXmlHttpRequest()) {
  5169.                 return new JsonResponse(array('success' => false'error' => $denial), 403);
  5170.             }
  5171.             throw $this->createAccessDeniedException($denial);
  5172.         }
  5173.         $em $this->getDoctrine()->getManager();
  5174.         $debug_data = [];
  5175.         $autoStartFixedAssetDepreciation 0;
  5176.         $autoStartLedgerHit 0;
  5177.         $autoStartInventoryRefresh 0;
  5178.         $inventoryRefreshed 0;
  5179.         $modifyAccTransFlag 0;
  5180.         $lastRefreshDate '';
  5181.         if ($request->query->has('rectifyGrnExpIdTag')) {
  5182.             $pos $em->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')->findBy(array(
  5183.                 'approved' => 1,
  5184.                 //                            'ledgerHit' => 0
  5185.             ));
  5186.             foreach ($pos as $po) {
  5187.                 $Grns $em->getRepository('ApplicationBundle\\Entity\\Grn')->findBy(
  5188.                     array(
  5189.                         'purchaseOrderId' => $po->getPurchaseOrderId(),
  5190.                         'approved' => 1,
  5191.                         //                            'ledgerHit' => 0
  5192.                     ),
  5193.                     array(
  5194.                         'grnDate' => 'asc'
  5195.                     )
  5196.                 );
  5197.                 $eis $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')->findBy(
  5198.                     array(
  5199.                         'purchaseOrderId' => $po->getPurchaseOrderId(),
  5200.                         'approved' => 1,
  5201.                         //                            'ledgerHit' => 0
  5202.                     ),
  5203.                     array(
  5204.                         'expenseInvoiceDate' => 'asc'
  5205.                     )
  5206.                 );
  5207.                 $first_grn_found 0;
  5208.                 foreach ($Grns as $grn) {
  5209.                     $grn->setExpenseAmount(0);
  5210.                     $grn->setExpensePendingBalanceAmount(0);
  5211.                     $em->flush();
  5212.                     if ($first_grn_found == 1) continue;
  5213.                     //                    if ($grn->getExpenseAmount() == 0 || $grn->getExpenseAmount() == null || $grn->getExpenseAmount() == '')
  5214.                     //                        continue;
  5215.                     $grnExpAmount $grn->getExpenseAmount();
  5216.                     $conditionFailed 1;
  5217.                     $chkAmount 0;
  5218.                     $total_price_value 0;
  5219.                     $tot_expense 0;
  5220.                     $eisObjList = [];
  5221.                     $passedEiIds = [];
  5222.                     $eiIds = [];
  5223.                     $passedEis = [];
  5224.                     $eiAmounts = [];
  5225.                     $grnItems $em->getRepository('ApplicationBundle\\Entity\\GrnItem')
  5226.                         ->findBy(
  5227.                             array(
  5228.                                 'grnId' => $grn->getGrnId()
  5229.                             )
  5230.                         );
  5231.                     foreach ($grnItems as $key => $entry) {
  5232.                         $total_price_value += $entry->getLocalPrice() * $entry->getQty();
  5233.                     }
  5234.                     foreach ($eis as $ei) {
  5235.                         $ei->setGrnIds(json_encode([]));
  5236.                         $em->flush();
  5237.                         $eiAmounts[$ei->getExpenseInvoiceId()] = $ei->getInvoiceAmount();
  5238.                         $eisObjList[$ei->getExpenseInvoiceId()] = $ei;
  5239.                         $eiIds[] = $ei->getExpenseInvoiceId();
  5240.                         if ($ei->getExpenseInvoiceDate() <= $grn->getGrnDate()) {
  5241.                             $passedEiIds[] = $ei->getExpenseInvoiceId();
  5242.                             $passedEis[$ei->getExpenseInvoiceId()] = $ei;
  5243.                             $tot_expense += ($ei->getInvoiceAmount());
  5244.                         }
  5245.                     }
  5246.                     //adding frm po ended
  5247.                     $expense_mult = ($total_price_value != ? (($total_price_value $tot_expense) / $total_price_value) : 0);
  5248.                     foreach ($grnItems as $key => $entry) {
  5249.                         $entry->setPriceWithExpense($entry->getLocalPrice() * $expense_mult);
  5250.                     }
  5251.                     $grn->setExpenseAmount($tot_expense);
  5252.                     $grn->setExpensePendingBalanceAmount($tot_expense);
  5253.                     //                    if ($conditionFailed == 0) {
  5254.                     foreach ($passedEis as $ei) {
  5255.                         $ei->setGrnIds(json_encode([$grn->getGrnId()]));
  5256.                         $em->flush();
  5257.                     }
  5258.                     //                    }
  5259.                     $first_grn_found 1;
  5260.                 }
  5261.             }
  5262.         }
  5263.         if ($request->query->has('autoStartLedgerHit'))
  5264.             $autoStartLedgerHit 1;
  5265.         if ($request->query->has('autoStartInventoryRefresh'))
  5266.             $autoStartInventoryRefresh $request->query->get('autoStartInventoryRefresh');
  5267.         if ($request->query->has('modifyAccTransFlag'))
  5268.             $modifyAccTransFlag $request->query->get('modifyAccTransFlag');
  5269.         if ($request->query->has('inventoryRefreshed'))
  5270.             $inventoryRefreshed $request->query->get('inventoryRefreshed');
  5271.         if ($request->query->has('lastRefreshDate'))
  5272.             $lastRefreshDate $request->query->get('lastRefreshDate');
  5273.         if ($request->query->has('autoStartFixedAssetDepreciation'))
  5274.             $autoStartFixedAssetDepreciation 1;
  5275.         if ($request->isMethod('POST')) {
  5276.             //            $Transaction = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  5277.             //                'approved' => 1,
  5278.             //                'ledgerHit' => 0
  5279.             //            ));
  5280.             if ($request->request->has('fixedAssetDep')) {
  5281.                 $apData FixedAsset::TakeDepreciationActionBook($em, [], $this->getLoggedUserCompanyId($request));
  5282.                 $ap $apData['continueFlag'];
  5283.                 if ($ap == 1) {
  5284.                     //                        $skip_ids[] = $get_kids[0]['transaction_id'];
  5285.                     return new JsonResponse(array(
  5286.                         "success" => true,
  5287.                         'workData' => $apData
  5288.                     ));
  5289.                 } else {
  5290.                     return new JsonResponse(array(
  5291.                         "success" => false,
  5292.                         'workData' => $apData
  5293.                     ));
  5294.                 }
  5295.             } else {
  5296.                 $skip_ids = [];
  5297.                 if ($request->request->has('skipIds'))
  5298.                     $skip_ids $request->request->get('skipIds');
  5299.                 $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';
  5300.                 //                $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';
  5301.                 $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  5302.                 
  5303.                 $get_kids $stmt;
  5304.                 $vid 0;
  5305.                 $vname '';
  5306.                 if (!empty($get_kids)) {
  5307.                     $ap ApprovalFunction::AccTransactions($em$get_kids[0]['transaction_id']);
  5308.                     if ($ap == 0)
  5309.                         $skip_ids[] = $get_kids[0]['transaction_id'];
  5310.                     return new JsonResponse(array(
  5311.                         "success" => true,
  5312.                         "debugData" => $ap,
  5313.                         "v_id" => $get_kids[0]['transaction_id'],
  5314.                         "v_name" => $get_kids[0]['document_hash'],
  5315.                         "skip_ids" => $skip_ids,
  5316.                     ));
  5317.                 } else {
  5318.                     return new JsonResponse(array(
  5319.                         "success" => false,
  5320.                         "v_id" => 0,
  5321.                         "v_name" => "",
  5322.                         "skip_ids" => $skip_ids,
  5323.                     ));
  5324.                 }
  5325.             }
  5326.         }
  5327.         //        MiscActions::refreshDatabase($em);
  5328.         return $this->render(
  5329.             '@Application/pages/accounts/settings/refresh_combo_action.html.twig',
  5330.             array(
  5331.                 'page_title' => 'Debug',
  5332.                 'debug_data' => $debug_data,
  5333.                 'autoStartLedgerHit' => $autoStartLedgerHit,
  5334.                 'autoStartInventoryRefresh' => $autoStartInventoryRefresh,
  5335.                 'inventoryRefreshed' => $inventoryRefreshed,
  5336.                 'modifyAccTransFlag' => $modifyAccTransFlag,
  5337.                 'lastRefreshDate' => $lastRefreshDate,
  5338.                 'autoStartFixedAssetDepreciation' => $autoStartFixedAssetDepreciation,
  5339.                 //                'voucherDetails'=>$v_details,
  5340.                 //                'heads'=>Accounts::HeadList($em),
  5341.                 //                'transaction'=>$Transaction
  5342.             )
  5343.         );
  5344.         //        return $this->redirectToRoute('dashboard');
  5345.     }
  5346.     public function ResetClosing(Request $request)
  5347.     {
  5348.         $em $this->getDoctrine()->getManager();
  5349.         $debug_data = [];
  5350.         if ($request->isMethod('POST')) {
  5351.             //            $Transaction = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  5352.             //                'approved' => 1,
  5353.             //                'ledgerHit' => 0
  5354.             //            ));
  5355.             $skip_ids = [];
  5356.             if ($request->request->has('skipIds'))
  5357.                 $skip_ids $request->request->get('skipIds');
  5358.             $get_kids_sql '     UPDATE `acc_accounts_head` SET `current_balance`=opening_balance,`current_balance_reconciled`=opening_balance WHERE 1;
  5359.     UPDATE `acc_transactions` SET `ledger_hit`=0 WHERE 1;
  5360.     UPDATE `acc_transaction_details` SET `ledger_hit`=0 WHERE 1;
  5361.     UPDATE `acc_clients` SET `client_due`=(select opening_balance from acc_accounts_head
  5362.     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;
  5363.     UPDATE `acc_clients` SET `initial_opening_balance`=(select opening_balance from acc_accounts_head
  5364.     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;
  5365.     UPDATE `acc_clients` SET `client_due`=(select sum(opening_balance) from acc_accounts_head
  5366.     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;
  5367.      UPDATE `acc_clients` SET `initial_opening_balance`=(select sum(opening_balance) from acc_accounts_head
  5368.     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;
  5369.     UPDATE `acc_clients` SET `client_received`=0 where 1;
  5370.     UPDATE `acc_suppliers` SET `supplier_due`=(select opening_balance from acc_accounts_head
  5371.     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;
  5372.     UPDATE `acc_suppliers` SET `supplier_due`=(select sum(opening_balance) from acc_accounts_head
  5373.     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;
  5374.     UPDATE `acc_suppliers` SET `supplier_paid`=0 where 1;
  5375.     truncate `acc_closing_balance`;
  5376.     truncate `acc_actual_closing_balance`;
  5377.     truncate `monthly_summary`;
  5378. UPDATE company SET revenue=0, asset=0, liability=0, expense=0, payable=0 , receivable=0, net_worth=0, monthly_growth=0 WHERE 1;';
  5379.             //UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
  5380.             $stmt $em->getConnection()->executeStatement($get_kids_sql);
  5381.             
  5382.             //            $get_kids=$stmt;
  5383.             $vid 0;
  5384.             $vname '';
  5385.             $head_list = [];
  5386.             $headDataList = [];
  5387.             //            $curr_id = $head_id;
  5388.             $get_kids_sql 'select * from acc_accounts_head where accounts_head_id not in (select distinct parent_id from acc_accounts_head) ;';
  5389.             //UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
  5390.             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  5391.             
  5392.             $query $stmt;
  5393.             if (!empty($query)) ///exists so lets edit rather than creating new
  5394.             {
  5395.                 foreach ($query as $entry) {
  5396.                     if (!isset($headDataList[$entry['company_id']]))
  5397.                         $headDataList[$entry['company_id']] = array();
  5398.                     $primary_head_data = array();
  5399.                     $primary_head_data['id'] = $entry['accounts_head_id'];
  5400.                     $primary_head_data['addition'] = $entry['current_balance'];
  5401.                     $primary_head_data['headNature'] = $entry['head_nature'];
  5402.                     $primary_head_data['headType'] = $entry['type'];
  5403.                     $primary_head_data['pathTree'] = $entry['path_tree'];
  5404.                     $headDataList[$entry['company_id']][] = $primary_head_data;
  5405.                 }
  5406.             }
  5407.             foreach ($headDataList as $companyId => $headDataDetails) {
  5408.                 Company::updateMonthlySummary($em$headDataDetails$companyId'_opening_date_''_ALL_');
  5409.             }
  5410.             return new JsonResponse(array(
  5411.                 "success" => true,
  5412.                 "skip_ids" => $skip_ids,
  5413.             ));
  5414.         }
  5415.         //        MiscActions::refreshDatabase($em);
  5416.         //        return $this->redirectToRoute('dashboard');
  5417.     }
  5418.     public function GetNonLedgerHitVoucherCount(Request $request)
  5419.     {
  5420.         $em $this->getDoctrine()->getManager();
  5421.         $debug_data = [];
  5422.         //            $Transaction = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  5423.         //                'approved' => 1,
  5424.         //                'ledgerHit' => 0
  5425.         //            ));
  5426.         $skip_ids = [];
  5427.         $v_count 0;
  5428.         if ($request->request->has('skipIds'))
  5429.             $skip_ids $request->request->get('skipIds');
  5430.         $get_kids_sql 'select count(transaction_id) v_count from acc_transactions where approved=1 and ledger_hit=0 ';
  5431.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  5432.         
  5433.         $get_kids $stmt;
  5434.         if (!empty($get_kids))
  5435.             $v_count = ($get_kids[0]['v_count']);
  5436.         $vid 0;
  5437.         $vname '';
  5438.         return new JsonResponse(array(
  5439.             "success" => true,
  5440.             "v_count" => $v_count,
  5441.             "skip_ids" => $skip_ids,
  5442.         ));
  5443.         //        MiscActions::refreshDatabase($em);
  5444.         //        return $this->redirectToRoute('dashboard');
  5445.     }
  5446.     public function RefreshPath(Request $request$id 0)
  5447.     {
  5448.         $em $this->getDoctrine()->getManager();
  5449.         $head_id $id;
  5450.         $get_kids_sql " SELECT accounts_head_id FROM acc_accounts_head
  5451.                             WHERE acc_accounts_head.accounts_head_id >" $head_id " limit 1";
  5452.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  5453.         
  5454.         $head $stmt;
  5455.         if (!empty($head)) {
  5456.             Accounts::AddHeadPath($em$head[0]['accounts_head_id']);
  5457.             return new JsonResponse(array(
  5458.                 "success" => true,
  5459.                 "last_id" => $head[0]['accounts_head_id'],
  5460.                 //                "r"=>$r,
  5461.                 //                "debug_data"=>System::encryptSignature($r)
  5462.             ));
  5463.         } else {
  5464.             return new JsonResponse(array(
  5465.                 "success" => false,
  5466.                 "last_id" => $head_id,
  5467.                 //                "r"=>$r,
  5468.                 //                "debug_data"=>System::encryptSignature($r)
  5469.             ));
  5470.         }
  5471.         //        return $this->redirectToRoute('dashboard');
  5472.     }
  5473.     public function RefreshHeadNature(Request $request$id 0)
  5474.     {
  5475.         $em $this->getDoctrine()->getManager();
  5476.         $head_id $id;
  5477.         $assetParentHead $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findOneBy(array(
  5478.             'type' => AccountsConstant::ASSET,
  5479.             'head_level' => 1
  5480.         ));
  5481.         $libParentHead $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findOneBy(array(
  5482.             'type' => AccountsConstant::LIABILITY,
  5483.             'head_level' => 1
  5484.         ));
  5485.         $incParentHead $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findOneBy(array(
  5486.             'type' => AccountsConstant::INCOME,
  5487.             'head_level' => 1
  5488.         ));
  5489.         $expParentHead $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findOneBy(array(
  5490.             'type' => AccountsConstant::EXPENSE,
  5491.             'head_level' => 1
  5492.         ));
  5493.         if ($assetParentHead) {
  5494.             $stmt $em->getConnection()->executeStatement("update acc_accounts_head set head_nature='dr' , `type`='ast' where path_tree like '%/" $assetParentHead->getAccountsHeadId() . "/%' ");
  5495.             
  5496.             //            $head=$stmt;
  5497.         }
  5498.         if ($expParentHead) {
  5499.             $stmt $em->getConnection()->executeStatement("update acc_accounts_head set head_nature='dr' , `type`='exp' where path_tree like '%/" $expParentHead->getAccountsHeadId() . "/%' ");
  5500.             
  5501.             //            $head=$stmt;
  5502.         }
  5503.         if ($incParentHead) {
  5504.             $stmt $em->getConnection()->executeStatement("update acc_accounts_head set head_nature='cr' , `type`='inc' where path_tree like '%/" $incParentHead->getAccountsHeadId() . "/%' ");
  5505.             
  5506.             //            $head=$stmt;
  5507.         }
  5508.         if ($libParentHead) {
  5509.             $stmt $em->getConnection()->executeStatement("update acc_accounts_head set head_nature='cr' , `type`='lib' where path_tree like '%/" $libParentHead->getAccountsHeadId() . "/%' ");
  5510.             
  5511.             //            $head=$stmt;
  5512.         }
  5513.         if (!empty($head)) {
  5514.             return new JsonResponse(array(
  5515.                 "success" => true,
  5516.                 "last_id" => $head[0]['accounts_head_id'],
  5517.                 //                "r"=>$r,
  5518.                 //                "debug_data"=>System::encryptSignature($r)
  5519.             ));
  5520.         } else {
  5521.             return new JsonResponse(array(
  5522.                 "success" => false,
  5523.                 "last_id" => $head_id,
  5524.                 //                "r"=>$r,
  5525.                 //                "debug_data"=>System::encryptSignature($r)
  5526.             ));
  5527.         }
  5528.         //        return $this->redirectToRoute('dashboard');
  5529.     }
  5530.     public function RefreshCombo(Request $request)
  5531.     {
  5532.         $em $this->getDoctrine()->getManager();
  5533.         $debug_data = [];
  5534.         //test
  5535.         $wrong_voucher_list = [];
  5536.         $ind_voucherAmounts = [];
  5537.         $ind_voucherIds = [];
  5538.         //        $ind_voucherAmounts=[];
  5539.         $transactions $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  5540.             ->findBy(
  5541.                 array(
  5542.                     'approved' => 1,
  5543.                     'ledgerHit' => 1,
  5544.                 )
  5545.             );
  5546.         foreach ($transactions as $d) {
  5547.             $ind_voucherAmounts[$d->getTransactionId()] = 0;
  5548.             $ind_voucherIds[] = $d->getTransactionId();
  5549.         }
  5550.         $transactions $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')
  5551.             ->findBy(
  5552.                 array(
  5553.                     'transactionId' => $ind_voucherIds,
  5554.                 )
  5555.             );
  5556.         foreach ($transactions as $d) {
  5557.             if ($d->getPosition() == 'cr')
  5558.                 $ind_voucherAmounts[$d->getTransactionId()] += $d->getAmount();
  5559.             elseif ($d->getPosition() == 'dr')
  5560.                 $ind_voucherAmounts[$d->getTransactionId()] -= $d->getAmount();
  5561.         }
  5562.         foreach ($ind_voucherAmounts as $k => $d) {
  5563.             if ($d >= || $d <= -1)
  5564.                 $wrong_voucher_list[$k] = $d;
  5565.         }
  5566.         $debug_data $wrong_voucher_list;
  5567.         //test ends
  5568.         return new JsonResponse(
  5569.             $debug_data
  5570.         );
  5571.         //        return $this->render(
  5572.         //            'ApplicationBundle:pages/accounts/settings:refresh_combo_action.html.twig',
  5573.         //            array(
  5574.         //                'page_title' => 'Refresh',
  5575.         //                'debug_data' => $debug_data,
  5576.         //                'autoStartLedgerHit' => 0,
  5577.         //                'autoStartInventoryRefresh' => 0,
  5578.         //                'inventoryRefreshed' => 0,
  5579.         //                'lastRefreshDate' => '',
  5580.         //                'autoStartFixedAssetDepreciation' => 0,
  5581.         //
  5582.         //                //                'voucherDetails'=>$v_details,
  5583.         //                //                'heads'=>Accounts::HeadList($em),
  5584.         //                //                'transaction'=>$Transaction
  5585.         //            )
  5586.         //        );
  5587.         //        return $this->redirectToRoute('dashboard');
  5588.     }
  5589.     /**
  5590.      * Core A — recompute acc_accounts_head.current_balance from the ledger.
  5591.      *
  5592.      * Two modes:
  5593.      *   - per-voucher: POST/GET transaction id (?id= or ?transaction_id=) → rebuilds
  5594.      *     only the heads that voucher touches (+ their subtree/ancestor chains).
  5595.      *     This is the on-page "Recompute balances" fix for the voucher view and the
  5596.      *     hook for the inline amount editor (so editing an amount can no longer
  5597.      *     leave current_balance stale, as it did on the NETZE tenant).
  5598.      *   - full: ?all=1 → rebuilds every ledger-backed head in the tenant.
  5599.      *
  5600.      * Dry-run unless ?apply=1. Unbacked heads (no ledger rows behind them, e.g.
  5601.      * unposted opening balances) are reported but never written unless
  5602.      * ?include_unbacked=1.
  5603.      */
  5604.     public function RebuildVoucherBalances(Request $request)
  5605.     {
  5606.         $em $this->getDoctrine()->getManager();
  5607.         $apply           = (int) $request->get('apply'0) === 1;
  5608.         $includeUnbacked = (int) $request->get('include_unbacked'0) === 1;
  5609.         $all             = (int) $request->get('all'0) === 1;
  5610.         $txId            $request->get('id'$request->get('transaction_id'null));
  5611.         $headIds = [];
  5612.         if (!$all) {
  5613.             if ($txId === null || $txId === '') {
  5614.                 return new JsonResponse(['ok' => 0'error' => 'Provide a transaction id, or all=1 for a full rebuild.'], 400);
  5615.             }
  5616.             $details $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')
  5617.                 ->findBy(array('transactionId' => (int) $txId));
  5618.             foreach ($details as $d) {
  5619.                 $headIds[] = (int) $d->getAccountsHeadId();
  5620.             }
  5621.             if (empty($headIds)) {
  5622.                 return new JsonResponse(['ok' => 0'error' => 'No ledger lines found for transaction ' $txId '.'], 404);
  5623.             }
  5624.         }
  5625.         try {
  5626.             $result = \ApplicationBundle\Modules\Accounts\Service\LedgerRebuildService::recompute($em, [
  5627.                 'headIds'         => $headIds,
  5628.                 'apply'           => $apply,
  5629.                 'includeUnbacked' => $includeUnbacked,
  5630.             ]);
  5631.         } catch (\Throwable $e) {
  5632.             return new JsonResponse(['ok' => 0'error' => $e->getMessage()], 500);
  5633.         }
  5634.         return new JsonResponse(array_merge(
  5635.             ['ok' => 1'scope' => $all 'all' : ('transaction:' $txId)],
  5636.             $result['summary'],
  5637.             ['rows' => array_slice($result['rows'], 0100)]
  5638.         ));
  5639.     }
  5640.     public function OpeningHeadBalanceForce(Request $request)
  5641.     {
  5642.         $em $this->getDoctrine()->getManager();
  5643.         $new_cc $this->getDoctrine()
  5644.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  5645.             ->findOneBy(
  5646.                 array(
  5647.                     'name' => 'accounting_year_start',
  5648.                 )
  5649.             );
  5650.         $start_date_str $new_cc $new_cc->getData() : "";
  5651.         $start_date = new \DateTime($start_date_str);
  5652.         $query_head_list = [];
  5653.         $head_list = [];
  5654.         $debug_data = [];
  5655.         $customer_heads = [];
  5656.         $get_kids_sql '     select distinct  `accounts_head_id` from acc_clients where 1;';
  5657.         //UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
  5658.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  5659.         
  5660.         $get_kids $stmt;
  5661.         foreach ($get_kids as $kid)
  5662.             $customer_heads[] = $kid['accounts_head_id'];
  5663.         $get_kids_sql '     select distinct  `advance_head_id` from acc_clients where 1;';
  5664.         //UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
  5665.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  5666.         
  5667.         $get_kids $stmt;
  5668.         foreach ($get_kids as $kid)
  5669.             $customer_heads[] = $kid['advance_head_id'];
  5670.         if ($request->isMethod('POST')) {
  5671.             $data = [];
  5672.             if ($request->request->has('dataHere'))
  5673.                 $data json_decode($request->request->get('dataHere'), true);
  5674.             if (!empty($data)) {
  5675.                 if (isset($data['head_id'])) {
  5676.                     //1st get all head data
  5677.                     $get_kids_sql '     UPDATE `acc_accounts_head` SET opening_balance=0 WHERE 1;';
  5678.                     //UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
  5679.                     $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  5680.                     
  5681.                     $em->flush();
  5682.                     $get_kids_sql "SELECT acc_accounts_head.name,
  5683. acc_accounts_head.opening_balance,
  5684. acc_accounts_head.current_balance,
  5685. acc_accounts_head.current_balance_reconciled,
  5686. acc_accounts_head.path_tree,
  5687. acc_accounts_head.head_nature,
  5688.  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
  5689. on acc_accounts_head.parent_id=b.accounts_head_id WHERE  acc_accounts_head.company_id=" .
  5690.                         $this->getLoggedUserCompanyId($request) . "  ORDER BY name ASC";
  5691.                     $get_kids_sql .= '';
  5692.                     $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  5693.                     
  5694.                     $get_kids $stmt;
  5695.                     foreach ($get_kids as $kid) {
  5696.                         $m = array();
  5697.                         $par_list array_filter(explode('/'$kid["path_tree"]));
  5698.                         $m["id"] = $kid["accounts_head_id"];
  5699.                         $m["value"] = $kid["accounts_head_id"];
  5700.                         $m["text"] = $kid["name"] . (($kid["advance_of"] == null || $kid["advance_of"] == 0) ? '' ' (Advance)');
  5701.                         $m["parent_name"] = $kid["parent_name"];
  5702.                         $m["type"] = $kid["type"];
  5703.                         $m["head_nature"] = $kid["head_nature"];
  5704.                         $m["opening"] = $kid["opening_balance"];
  5705.                         //                        $m["opening"] = 0;
  5706.                         $m["newOpening"] = 0;
  5707.                         $m["newCurrentBalance"] = 0;
  5708.                         $m["newCurrentBalanceReconciled"] = 0;
  5709.                         $m["current_balance"] = $kid["current_balance"];
  5710.                         $m["reconciled_balance"] = $kid["current_balance_reconciled"];
  5711.                         $m["parent_id"] = $kid["parent_id"];
  5712.                         $m["allParents"] = $par_list;
  5713.                         $m["cc_enabled"] = $kid["cc_enabled"];
  5714.                         $m["child_total_balance"] = 0;
  5715.                         $head_list[$kid["accounts_head_id"]] = $m;
  5716.                     }
  5717.                     //next check the change in opening
  5718.                     foreach ($data['head_id'] as $k => $h) {
  5719.                         if (isset($head_list[$h])) {
  5720.                             $to_add 0;
  5721.                             //                            $to_add=(1*$data['head_opening'][$k])-(1*$head_list[$h]['opening']);
  5722.                             $child_nature $head_list[$h]['head_nature'];
  5723.                             //                            if(!isset($head_list[$h]['to_add']))
  5724.                             //                            {
  5725.                             //                                $head_list[$h]['to_add']=$to_add;
  5726.                             //                            }
  5727.                             //                            $head_list[$h]['opening']=$head_list[$h]['opening']+$to_add;
  5728.                             //                            $head_list[$h]['current_balance']=$head_list[$h]['current_balance']+$to_add;
  5729.                             //                            $head_list[$h]['reconciled_balance']=$head_list[$h]['reconciled_balance']+$to_add;
  5730.                             $to_add_cb = (str_replace(","""$data['head_opening'][$k]));
  5731.                             $head_list[$h]['newOpening'] = $head_list[$h]['newOpening'] + $to_add_cb;
  5732.                             $head_list[$h]['newCurrentBalance'] = $head_list[$h]['newCurrentBalance'] + $to_add_cb;
  5733.                             $head_list[$h]['newCurrentBalanceReconciled'] = $head_list[$h]['newCurrentBalanceReconciled'] + $to_add_cb;
  5734.                             $head_list[$h]['child_total_balance'] = $head_list[$h]['child_total_balance'] + $to_add_cb;
  5735.                             //                            if($to_add!=0)
  5736.                             {
  5737.                                 foreach ($head_list[$h]['allParents'] as $par) {
  5738.                                     if (isset($head_list[$par])) {
  5739.                                         $to_add_par 0;
  5740.                                         $to_add_cb = ($child_nature == $head_list[$par]['head_nature']) ? ($to_add_cb) : ((-1) * $to_add_cb);
  5741.                                         if (!isset($head_list[$par]['child_total_balance'])) {
  5742.                                             $head_list[$par]['child_total_balance'] = $to_add_cb;
  5743.                                         } else {
  5744.                                             $head_list[$par]['child_total_balance'] = $head_list[$par]['child_total_balance'] + $to_add_cb;
  5745.                                         }
  5746.                                         $head_list[$par]['newOpening'] = $head_list[$par]['newOpening'] + $to_add_cb;
  5747.                                         $head_list[$par]['newCurrentBalance'] = $head_list[$par]['newCurrentBalance'] + $to_add_cb;
  5748.                                         $head_list[$par]['newCurrentBalanceReconciled'] = $head_list[$par]['newCurrentBalanceReconciled'] + $to_add_cb;
  5749.                                     }
  5750.                                 }
  5751.                             }
  5752.                         }
  5753.                     }
  5754.                     foreach ($head_list as $k => $head) {
  5755.                         //                        if (isset($head['to_add']) && $head['to_add'] != 0) {
  5756.                         //                        $query_head_list[]=$k;
  5757.                         //                        }
  5758.                         if (isset($head['child_total_balance'])) {
  5759.                             if ($head['newOpening'] != $head['opening']) {
  5760.                                 $to_add $head['newOpening'] - $head['opening'];
  5761.                                 $head_list[$k]['to_add'] = $head['newOpening'] - $head['opening'];
  5762.                                 $head_list[$k]['opening'] = $head['opening'] + $to_add;
  5763.                                 $head_list[$k]['current_balance'] = $head['current_balance'] + $to_add;
  5764.                                 $head_list[$k]['reconciled_balance'] = $head['reconciled_balance'] + $to_add;
  5765.                                 $query_head_list[] = $k;
  5766.                             }
  5767.                         }
  5768.                     }
  5769.                     //if no change then dont use  that
  5770.                     //add teh change to all the closings found in that criteria be ware of the head natures
  5771.                     $closings $em->getRepository('ApplicationBundle\\Entity\\AccClosingBalance')->findBy(
  5772.                         array(
  5773.                             'accountsHeadId' => $query_head_list
  5774.                         )
  5775.                     );
  5776.                     foreach ($closings as $closing) {
  5777.                         //check if the date is >= to start_date
  5778.                         if ($closing->getDate() >= $start_date) {
  5779.                             $to_add = isset($head_list[$closing->getAccountsHeadId()]['to_add']) ? $head_list[$closing->getAccountsHeadId()]['to_add'] : 0;
  5780.                             if ($to_add != 0) {
  5781.                                 $closing->setOpening($closing->getOpening() + $to_add);
  5782.                                 $closing->setBalance($closing->getBalance() + $to_add);
  5783.                                 //                                            $closing->setAddition($closing->getAddition() + $to_add);
  5784.                             }
  5785.                         }
  5786.                     }
  5787.                     $em->flush();
  5788.                     //add teh change to all the actual closings found in that criteria be ware of the head natures
  5789.                     $closings $em->getRepository('ApplicationBundle\\Entity\\AccActualClosingBalance')->findBy(
  5790.                         array(
  5791.                             'accountsHeadId' => $query_head_list
  5792.                         )
  5793.                     );
  5794.                     foreach ($closings as $closing) {
  5795.                         //check if the date is >= to start_date
  5796.                         if ($closing->getDate() >= $start_date) {
  5797.                             $to_add = isset($head_list[$closing->getAccountsHeadId()]['to_add']) ? $head_list[$closing->getAccountsHeadId()]['to_add'] : 0;
  5798.                             if ($to_add != 0) {
  5799.                                 $closing->setOpening($closing->getOpening() + $to_add);
  5800.                                 $closing->setBalance($closing->getBalance() + $to_add);
  5801.                                 //                                            $closing->setAddition($closing->getAddition() + $to_add);
  5802.                             }
  5803.                         }
  5804.                     }
  5805.                     $em->flush();
  5806.                     //add teh change to all the Heads found in that criteria be ware of the head natures
  5807.                     $heads $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findBy(
  5808.                         array(
  5809.                             'accountsHeadId' => $query_head_list
  5810.                         )
  5811.                     );
  5812.                     foreach ($heads as $head) {
  5813.                         $to_add = isset($head_list[$head->getAccountsHeadId()]['to_add']) ? $head_list[$head->getAccountsHeadId()]['to_add'] : 0;
  5814.                         if ($to_add != 0) {
  5815.                             $head->setOpeningBalance($head_list[$head->getAccountsHeadId()]['opening']);
  5816.                             $head->setCurrentBalance($head_list[$head->getAccountsHeadId()]['current_balance']);
  5817.                             $head->setCurrentBalanceReconciled($head_list[$head->getAccountsHeadId()]['reconciled_balance']);
  5818.                         }
  5819.                     }
  5820.                     $em->flush();
  5821.                 }
  5822.             }
  5823.             $this->addFlash(
  5824.                 'success',
  5825.                 'The Action was Successful.'
  5826.             );
  5827.             //            MiscActions::refreshTransactions($em);
  5828.             //            return $this->redirectToRoute('dashboard');
  5829.             $debug_data $head_list;
  5830.         }
  5831.         $child_head_list Accounts::getParentLedgerHeads($em'''', []);
  5832.         return $this->render(
  5833.             '@Accounts/pages/input_forms/opening_head_balance_assign.html.twig',
  5834.             array(
  5835.                 'page_title' => 'Assign Head Opening',
  5836.                 'head_list' => $child_head_list,
  5837.                 'customer_heads' => $customer_heads,
  5838.                 'start_date' => $start_date,
  5839.                 'mod_head_list' => $head_list,
  5840.                 'query_head_list' => $query_head_list,
  5841.                 'debug_data' => $debug_data
  5842.                 //                'voucherDetails'=>$v_details,
  5843.                 //                'heads'=>Accounts::HeadList($em),
  5844.                 //                'transaction'=>$Transaction
  5845.             )
  5846.         );
  5847.     }
  5848.     public function OpeningHeadBalance(Request $request)
  5849.     {
  5850.         $em $this->getDoctrine()->getManager();
  5851.         $new_cc $this->getDoctrine()
  5852.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  5853.             ->findOneBy(
  5854.                 array(
  5855.                     'name' => 'accounting_year_start',
  5856.                 )
  5857.             );
  5858.         $start_date_str $new_cc $new_cc->getData() : "";
  5859.         $start_date = new \DateTime($start_date_str);
  5860.         $query_head_list = [];
  5861.         $head_list = [];
  5862.         $debug_data = [];
  5863.         $customer_heads = [];
  5864.         $get_kids_sql '     select distinct  `accounts_head_id` from acc_clients where 1;';
  5865.         //UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
  5866.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  5867.         
  5868.         $get_kids $stmt;
  5869.         foreach ($get_kids as $kid)
  5870.             $customer_heads[] = $kid['accounts_head_id'];
  5871.         $get_kids_sql '     select distinct  `advance_head_id` from acc_clients where 1;';
  5872.         //UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
  5873.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  5874.         
  5875.         $get_kids $stmt;
  5876.         foreach ($get_kids as $kid)
  5877.             $customer_heads[] = $kid['advance_head_id'];
  5878.         if ($request->isMethod('POST')) {
  5879.             $data = [];
  5880.             if ($request->request->has('dataHere'))
  5881.                 $data json_decode($request->request->get('dataHere'), true);
  5882.             if (!empty($data)) {
  5883.                 if (isset($data['head_id'])) {
  5884.                     //1st get all head data
  5885.                     $get_kids_sql "SELECT acc_accounts_head.name,
  5886. acc_accounts_head.opening_balance,
  5887. acc_accounts_head.current_balance,
  5888. acc_accounts_head.current_balance_reconciled,
  5889. acc_accounts_head.path_tree,
  5890. acc_accounts_head.head_nature,
  5891.  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
  5892. on acc_accounts_head.parent_id=b.accounts_head_id WHERE  acc_accounts_head.company_id=" .
  5893.                         $this->getLoggedUserCompanyId($request) . "  ORDER BY name ASC";
  5894.                     $get_kids_sql .= '';
  5895.                     $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  5896.                     
  5897.                     $get_kids $stmt;
  5898.                     foreach ($get_kids as $kid) {
  5899.                         $m = array();
  5900.                         $par_list array_filter(explode('/'$kid["path_tree"]));
  5901.                         $m["id"] = $kid["accounts_head_id"];
  5902.                         $m["value"] = $kid["accounts_head_id"];
  5903.                         $m["text"] = $kid["name"] . (($kid["advance_of"] == null || $kid["advance_of"] == 0) ? '' ' (Advance)');
  5904.                         $m["parent_name"] = $kid["parent_name"];
  5905.                         $m["type"] = $kid["type"];
  5906.                         $m["head_nature"] = $kid["head_nature"];
  5907.                         $m["opening"] = $kid["opening_balance"];
  5908.                         $m["newOpening"] = 0;
  5909.                         $m["newCurrentBalance"] = 0;
  5910.                         $m["newCurrentBalanceReconciled"] = 0;
  5911.                         $m["current_balance"] = $kid["current_balance"];
  5912.                         $m["reconciled_balance"] = $kid["current_balance_reconciled"];
  5913.                         $m["parent_id"] = $kid["parent_id"];
  5914.                         $m["allParents"] = $par_list;
  5915.                         $m["cc_enabled"] = $kid["cc_enabled"];
  5916.                         $m["child_total_balance"] = 0;
  5917.                         $head_list[$kid["accounts_head_id"]] = $m;
  5918.                     }
  5919.                     //next check the change in opening
  5920.                     foreach ($data['head_id'] as $k => $h) {
  5921.                         if (isset($head_list[$h])) {
  5922.                             $to_add 0;
  5923.                             //                            $to_add=(1*$data['head_opening'][$k])-(1*$head_list[$h]['opening']);
  5924.                             $child_nature $head_list[$h]['head_nature'];
  5925.                             //                            if(!isset($head_list[$h]['to_add']))
  5926.                             //                            {
  5927.                             //                                $head_list[$h]['to_add']=$to_add;
  5928.                             //                            }
  5929.                             //                            $head_list[$h]['opening']=$head_list[$h]['opening']+$to_add;
  5930.                             //                            $head_list[$h]['current_balance']=$head_list[$h]['current_balance']+$to_add;
  5931.                             //                            $head_list[$h]['reconciled_balance']=$head_list[$h]['reconciled_balance']+$to_add;
  5932.                             $to_add_cb = (str_replace(","""$data['head_opening'][$k]));
  5933.                             $head_list[$h]['newOpening'] = $head_list[$h]['newOpening'] + $to_add_cb;
  5934.                             $head_list[$h]['newCurrentBalance'] = $head_list[$h]['newCurrentBalance'] + $to_add_cb;
  5935.                             $head_list[$h]['newCurrentBalanceReconciled'] = $head_list[$h]['newCurrentBalanceReconciled'] + $to_add_cb;
  5936.                             $head_list[$h]['child_total_balance'] = $head_list[$h]['child_total_balance'] + $to_add_cb;
  5937.                             //                            if($to_add!=0)
  5938.                             {
  5939.                                 foreach ($head_list[$h]['allParents'] as $par) {
  5940.                                     if (isset($head_list[$par])) {
  5941.                                         $to_add_par 0;
  5942.                                         $to_add_cb = ($child_nature == $head_list[$par]['head_nature']) ? ($to_add_cb) : ((-1) * $to_add_cb);
  5943.                                         if (!isset($head_list[$par]['child_total_balance'])) {
  5944.                                             $head_list[$par]['child_total_balance'] = $to_add_cb;
  5945.                                         } else {
  5946.                                             $head_list[$par]['child_total_balance'] = $head_list[$par]['child_total_balance'] + $to_add_cb;
  5947.                                         }
  5948.                                         $head_list[$par]['newOpening'] = $head_list[$par]['newOpening'] + $to_add_cb;
  5949.                                         $head_list[$par]['newCurrentBalance'] = $head_list[$par]['newCurrentBalance'] + $to_add_cb;
  5950.                                         $head_list[$par]['newCurrentBalanceReconciled'] = $head_list[$par]['newCurrentBalanceReconciled'] + $to_add_cb;
  5951.                                     }
  5952.                                 }
  5953.                             }
  5954.                         }
  5955.                     }
  5956.                     foreach ($head_list as $k => $head) {
  5957.                         //                        if (isset($head['to_add']) && $head['to_add'] != 0) {
  5958.                         //                        $query_head_list[]=$k;
  5959.                         //                        }
  5960.                         if (isset($head['child_total_balance'])) {
  5961.                             if ($head['newOpening'] != $head['opening']) {
  5962.                                 $to_add $head['newOpening'] - $head['opening'];
  5963.                                 $head_list[$k]['to_add'] = $head['newOpening'] - $head['opening'];
  5964.                                 $head_list[$k]['opening'] = $head['opening'] + $to_add;
  5965.                                 $head_list[$k]['current_balance'] = $head['current_balance'] + $to_add;
  5966.                                 $head_list[$k]['reconciled_balance'] = $head['reconciled_balance'] + $to_add;
  5967.                                 $query_head_list[] = $k;
  5968.                             }
  5969.                         }
  5970.                     }
  5971.                     //if no change then dont use  that
  5972.                     //add teh change to all the closings found in that criteria be ware of the head natures
  5973.                     $closings $em->getRepository('ApplicationBundle\\Entity\\AccClosingBalance')->findBy(
  5974.                         array(
  5975.                             'accountsHeadId' => $query_head_list
  5976.                         )
  5977.                     );
  5978.                     foreach ($closings as $closing) {
  5979.                         //check if the date is >= to start_date
  5980.                         if ($closing->getDate() >= $start_date) {
  5981.                             $to_add = isset($head_list[$closing->getAccountsHeadId()]['to_add']) ? $head_list[$closing->getAccountsHeadId()]['to_add'] : 0;
  5982.                             if ($to_add != 0) {
  5983.                                 $closing->setOpening($closing->getOpening() + $to_add);
  5984.                                 $closing->setBalance($closing->getBalance() + $to_add);
  5985.                                 //                                            $closing->setAddition($closing->getAddition() + $to_add);
  5986.                             }
  5987.                         }
  5988.                     }
  5989.                     $em->flush();
  5990.                     //add teh change to all the actual closings found in that criteria be ware of the head natures
  5991.                     $closings $em->getRepository('ApplicationBundle\\Entity\\AccActualClosingBalance')->findBy(
  5992.                         array(
  5993.                             'accountsHeadId' => $query_head_list
  5994.                         )
  5995.                     );
  5996.                     foreach ($closings as $closing) {
  5997.                         //check if the date is >= to start_date
  5998.                         if ($closing->getDate() >= $start_date) {
  5999.                             $to_add = isset($head_list[$closing->getAccountsHeadId()]['to_add']) ? $head_list[$closing->getAccountsHeadId()]['to_add'] : 0;
  6000.                             if ($to_add != 0) {
  6001.                                 $closing->setOpening($closing->getOpening() + $to_add);
  6002.                                 $closing->setBalance($closing->getBalance() + $to_add);
  6003.                                 //                                            $closing->setAddition($closing->getAddition() + $to_add);
  6004.                             }
  6005.                         }
  6006.                     }
  6007.                     $em->flush();
  6008.                     //add teh change to all the Heads found in that criteria be ware of the head natures
  6009.                     $heads $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findBy(
  6010.                         array(
  6011.                             'accountsHeadId' => $query_head_list
  6012.                         )
  6013.                     );
  6014.                     foreach ($heads as $head) {
  6015.                         $to_add = isset($head_list[$head->getAccountsHeadId()]['to_add']) ? $head_list[$head->getAccountsHeadId()]['to_add'] : 0;
  6016.                         if ($to_add != 0) {
  6017.                             $head->setOpeningBalance($head_list[$head->getAccountsHeadId()]['opening']);
  6018.                             $head->setCurrentBalance($head_list[$head->getAccountsHeadId()]['current_balance']);
  6019.                             $head->setCurrentBalanceReconciled($head_list[$head->getAccountsHeadId()]['reconciled_balance']);
  6020.                         }
  6021.                     }
  6022.                     $em->flush();
  6023.                 }
  6024.             }
  6025.             $this->addFlash(
  6026.                 'success',
  6027.                 'The Action was Successful.'
  6028.             );
  6029.             //            MiscActions::refreshTransactions($em);
  6030.             //            return $this->redirectToRoute('dashboard');
  6031.             $debug_data $head_list;
  6032.         }
  6033.         $child_head_list Accounts::getParentLedgerHeads($em'''', []);
  6034.         return $this->render(
  6035.             '@Accounts/pages/input_forms/opening_head_balance_assign.html.twig',
  6036.             array(
  6037.                 'page_title' => 'Assign Head Opening',
  6038.                 'head_list' => $child_head_list,
  6039.                 'start_date' => $start_date,
  6040.                 'mod_head_list' => $head_list,
  6041.                 'query_head_list' => $query_head_list,
  6042.                 'customer_heads' => $customer_heads,
  6043.                 'debug_data' => $debug_data
  6044.                 //                'voucherDetails'=>$v_details,
  6045.                 //                'heads'=>Accounts::HeadList($em),
  6046.                 //                'transaction'=>$Transaction
  6047.             )
  6048.         );
  6049.     }
  6050.     public function EditJournalVoucher(Request $request$id)
  6051.     {
  6052.         $v_details = [];
  6053.         $Transaction = [];
  6054.         if ($id != 0) {
  6055.             $em $this->getDoctrine()->getManager();
  6056.             $Transaction $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  6057.                 'transactionId' => $id,
  6058.                 'editFlag' => 1,
  6059.                 'lockFlag' => [0null],
  6060.                 'disabledFlag' => [0null],
  6061.             ));
  6062.             if ($Transaction) {
  6063.                 $v_details Accounts::GetVoucherDetails($em$id);
  6064.             } else {
  6065.                 //            $this->container->get("session")->setFlash("error", "Pikachu is not allowed");
  6066.                 $this->addFlash(
  6067.                     'error',
  6068.                     'The Action was not allowed.'
  6069.                 );
  6070.             }
  6071.         }
  6072.         if ($request->isMethod('POST')) {
  6073.             //            Generic::debugMessage($_POST);
  6074.             $em $this->getDoctrine()->getManager();
  6075.             $entity_id array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
  6076.             $dochash $request->request->get('voucherNumber'); //change
  6077.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6078.             $approveRole $request->request->get('approvalRole');
  6079.             $approveHash $request->request->get('approvalHash');
  6080.             if (!DocValidation::isEditable(
  6081.                 $em,
  6082.                 $entity_id,
  6083.                 $dochash,
  6084.                 $loginId,
  6085.                 $approveRole,
  6086.                 $approveHash
  6087.             )) {
  6088.                 $this->addFlash(
  6089.                     'error',
  6090.                     'Sorry Couldnot insert Data.'
  6091.                 );
  6092.             } else {
  6093.                 // ── Ledger-integrity pre-flight (same defect as the create path) ──
  6094.                 // MUST stay above DeleteDocument: this action deletes the existing voucher before
  6095.                 // rewriting its legs, so refusing after the delete would destroy the user's voucher
  6096.                 // and leave nothing behind.
  6097.                 $balanceCheck VoucherBalanceGuard::check(
  6098.                     $request->request->get('drAmount'),
  6099.                     $request->request->get('crAmount'),
  6100.                     $request->request->get('currencyMultiplyRate')
  6101.                 );
  6102.                 if (!$balanceCheck['balanced']) {
  6103.                     if ($request->request->has('returnJson')) {
  6104.                         return new JsonResponse(array(
  6105.                             'success' => false,
  6106.                             'error' => $balanceCheck['message'],
  6107.                         ));
  6108.                     }
  6109.                     $this->addFlash('error'$balanceCheck['message']);
  6110.                     return $this->redirect($this->generateUrl('edit_journal_voucher', array('id' => $id)));
  6111.                 }
  6112.                 //1st delete the doc
  6113.                 $funcname 'AccTransactions';
  6114.                 $doc_id $request->request->get('extTransId');
  6115.                 DeleteDocument::$funcname($em$doc_id0);
  6116.                 $ledgerHeads $request->request->get('ledgerHeads');
  6117.                 $notes $request->request->get('trNote');
  6118.                 $costCenters $request->request->get('costCenters');
  6119.                 $drAmount $request->request->get('drAmount');
  6120.                 $crAmount $request->request->get('crAmount');
  6121.                 $check_allowed 0;
  6122.                 if ($request->request->has('check_allowed'))
  6123.                     $check_allowed 1;
  6124.                 $em_goc $this->getDoctrine()->getManager('company_group');
  6125.                 $post_data $request->request;
  6126.                 $TransID Accounts::EditExistingTrans(
  6127.                     $this->getDoctrine()->getManager(),
  6128.                     $doc_id,
  6129.                     $request->request->get('date'),
  6130.                     array_sum($request->request->get('drAmount')),
  6131.                     AccountsConstant::VOUCHER_JOURNAL,
  6132.                     $request->request->get('description'),
  6133.                     (empty($request->request->get('voucherNumber')) ? Generic::simpleRandString() : $request->request->get('voucherNumber')),
  6134.                     $request->request->get('type_hash'),
  6135.                     $request->request->get('prefix_hash'),
  6136.                     $request->request->get('assoc_hash'),
  6137.                     $request->request->get('number_hash'),
  6138.                     $check_allowed,
  6139.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6140.                     $this->getLoggedUserCompanyId($request)
  6141.                 );
  6142.                 for ($i 0$i count($ledgerHeads); $i++) {
  6143.                     if (!empty($drAmount[$i]) && $drAmount[$i] != 0) {
  6144.                         Accounts::CreateNewTransactionDetails(
  6145.                             $this->getDoctrine()->getManager(),
  6146.                             $request->request->get('date'),
  6147.                             $TransID,
  6148.                             Generic::CurrToInt($drAmount[$i]),
  6149.                             $ledgerHeads[$i],
  6150.                             $notes[$i],
  6151.                             AccountsConstant::DEBIT,
  6152.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  6153.                             [],
  6154.                             [],
  6155.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6156.                         );
  6157.                     }
  6158.                     if (!empty($crAmount[$i]) && $crAmount[$i] != 0) {
  6159.                         Accounts::CreateNewTransactionDetails(
  6160.                             $this->getDoctrine()->getManager(),
  6161.                             $request->request->get('date'),
  6162.                             $TransID,
  6163.                             Generic::CurrToInt($crAmount[$i]),
  6164.                             $ledgerHeads[$i],
  6165.                             $notes[$i],
  6166.                             AccountsConstant::CREDIT,
  6167.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  6168.                             [],
  6169.                             [],
  6170.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6171.                         );
  6172.                     }
  6173.                 }
  6174.                 //now add Approval info
  6175.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6176.                 $approveRole 2;  //created
  6177.                 $options = array(
  6178.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6179.                     'notification_server' => $this->container->getParameter('notification_server'),
  6180.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6181.                     'url' => $this->generateUrl(
  6182.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AccTransactions']]['entity_view_route_path_name']
  6183.                     )
  6184.                 );
  6185.                 System::setApprovalInfo(
  6186.                     $this->getDoctrine()->getManager(),
  6187.                     $options,
  6188.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  6189.                     $TransID,
  6190.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6191.                     3    //journal voucher
  6192.                 );
  6193.                 System::createEditSignatureHash(
  6194.                     $this->getDoctrine()->getManager(),
  6195.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  6196.                     $TransID,
  6197.                     $loginId,
  6198.                     $approveRole,
  6199.                     $request->request->get('approvalHash')
  6200.                 );
  6201.                 $trans_here $this->getDoctrine()
  6202.                     ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  6203.                     ->findOneBy(
  6204.                         array(
  6205.                             'transactionId' => $TransID
  6206.                         )
  6207.                     );
  6208.                 //notify
  6209.                 System::AddNewNotification(
  6210.                     $this->container->getParameter('notification_enabled'),
  6211.                     $this->container->getParameter('notification_server'),
  6212.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  6213.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  6214.                     "Journal Voucher : " $trans_here->getDocumentHash() . " is Created Right Now",
  6215.                     'all',
  6216.                     "",
  6217.                     'success',
  6218.                     "",
  6219.                     "Journal"
  6220.                 );
  6221.                 $this->addFlash(
  6222.                     'success',
  6223.                     'New Transaction Added.'
  6224.                 );
  6225.             }
  6226.         }
  6227.         return $this->render(
  6228.             '@Accounts/pages/input_forms/journal_voucher.html.twig',
  6229.             array(
  6230.                 'page_title' => 'Edit Journal Voucher',
  6231.                 'voucherDetails' => $v_details,
  6232.                 //                'heads'=>Accounts::HeadList($em),
  6233.                 'transaction' => $Transaction
  6234.             )
  6235.         );
  6236.     }
  6237.     public function CancelCheck(Request $request$voucherId 0)
  6238.     {
  6239.         $em $this->getDoctrine()->getManager();
  6240.         if ($request->isMethod('POST')) {
  6241.             //            Generic::debugMessage($_POST);
  6242.             $em $this->getDoctrine()->getManager();
  6243.             $entity_id array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
  6244.             $dochash $request->request->get('voucherNumber'); //change
  6245.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6246.             $approveRole $request->request->get('approvalRole');
  6247.             $approveHash $request->request->get('approvalHash');
  6248.             if (!DocValidation::isInsertable(
  6249.                 $em,
  6250.                 $entity_id,
  6251.                 $dochash,
  6252.                 $loginId,
  6253.                 $approveRole,
  6254.                 $approveHash,
  6255.                 $voucherId
  6256.             )) {
  6257.                 $this->addFlash(
  6258.                     'error',
  6259.                     'Sorry Couldnot insert Data.'
  6260.                 );
  6261.             } else {
  6262.                 $funcname 'AccTransactions';
  6263.                 $doc_id $voucherId;
  6264.                 DeleteDocument::$funcname($em$doc_id0);
  6265.                 $ledgerHeads $request->request->get('ledgerHeads');
  6266.                 $notes $request->request->get('trNote');
  6267.                 $costCenters $request->request->get('costCenters');
  6268.                 $drAmount $request->request->get('drAmount');
  6269.                 $crAmount $request->request->get('crAmount');
  6270.                 $check_allowed 0;
  6271.                 if ($request->request->has('check_allowed'))
  6272.                     $check_allowed 1;
  6273.                 $TransID Accounts::CreateNewTransaction(
  6274.                     $voucherId,
  6275.                     $this->getDoctrine()->getManager(),
  6276.                     $request->request->get('date'),
  6277.                     array_sum($request->request->get('drAmount')),
  6278.                     AccountsConstant::VOUCHER_JOURNAL,
  6279.                     $request->request->get('description'),
  6280.                     (empty($request->request->get('voucherNumber')) ? Generic::simpleRandString() : $request->request->get('voucherNumber')),
  6281.                     $request->request->get('type_hash'),
  6282.                     $request->request->get('prefix_hash'),
  6283.                     $request->request->get('assoc_hash'),
  6284.                     $request->request->get('number_hash'),
  6285.                     $check_allowed,
  6286.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6287.                     $this->getLoggedUserCompanyId($request)
  6288.                 );
  6289.                 for ($i 0$i count($ledgerHeads); $i++) {
  6290.                     if (!empty($drAmount[$i]) && $drAmount[$i] != 0) {
  6291.                         Accounts::CreateNewTransactionDetails(
  6292.                             $this->getDoctrine()->getManager(),
  6293.                             $request->request->get('date'),
  6294.                             $TransID,
  6295.                             Generic::CurrToInt($drAmount[$i]),
  6296.                             $ledgerHeads[$i],
  6297.                             $notes[$i],
  6298.                             AccountsConstant::DEBIT,
  6299.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  6300.                             [],
  6301.                             [],
  6302.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6303.                         );
  6304.                     }
  6305.                     if (!empty($crAmount[$i]) && $crAmount[$i] != 0) {
  6306.                         Accounts::CreateNewTransactionDetails(
  6307.                             $this->getDoctrine()->getManager(),
  6308.                             $request->request->get('date'),
  6309.                             $TransID,
  6310.                             Generic::CurrToInt($crAmount[$i]),
  6311.                             $ledgerHeads[$i],
  6312.                             $notes[$i],
  6313.                             AccountsConstant::CREDIT,
  6314.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  6315.                             [],
  6316.                             [],
  6317.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6318.                         );
  6319.                     }
  6320.                 }
  6321.                 //now add Approval info
  6322.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6323.                 $approveRole $request->request->get('approvalRole');
  6324.                 $options = array(
  6325.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6326.                     'notification_server' => $this->container->getParameter('notification_server'),
  6327.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6328.                     'url' => $this->generateUrl(
  6329.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AccTransactions']]['entity_view_route_path_name']
  6330.                     )
  6331.                 );
  6332.                 System::setApprovalInfo(
  6333.                     $this->getDoctrine()->getManager(),
  6334.                     $options,
  6335.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  6336.                     $TransID,
  6337.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6338.                     3    //journal voucher
  6339.                 );
  6340.                 System::createEditSignatureHash(
  6341.                     $this->getDoctrine()->getManager(),
  6342.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  6343.                     $TransID,
  6344.                     $loginId,
  6345.                     $approveRole,
  6346.                     $request->request->get('approvalHash')
  6347.                 );
  6348.                 $trans_here $this->getDoctrine()
  6349.                     ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  6350.                     ->findOneBy(
  6351.                         array(
  6352.                             'transactionId' => $TransID
  6353.                         )
  6354.                     );
  6355.                 //notify
  6356.                 $this->addFlash(
  6357.                     'success',
  6358.                     'New Transaction Added.'
  6359.                 );
  6360.                 $url $this->generateUrl(
  6361.                     'view_voucher'
  6362.                 );
  6363.                 System::AddNewNotification(
  6364.                     $this->container->getParameter('notification_enabled'),
  6365.                     $this->container->getParameter('notification_server'),
  6366.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  6367.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  6368.                     "Journal Voucher : " $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
  6369.                     'pos',
  6370.                     System::getPositionIdsByDepartment($emGeneralConstant::ACCOUNTS_DEPARTMENT),
  6371.                     'success',
  6372.                     $url "/" $TransID,
  6373.                     "Journal"
  6374.                 );
  6375.                 return $this->redirect($url "/" $TransID);
  6376.             }
  6377.         }
  6378.         //for edits
  6379.         $extVoucherData = [];
  6380.         $extVoucherDetailsData = [];
  6381.         if ($voucherId == 0) {
  6382.         } else {
  6383.             $extTrans $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(
  6384.                 array(
  6385.                     'transactionId' => $voucherId///material
  6386.                 )
  6387.             );
  6388.             //now if its not editable, redirect to view
  6389.             if ($extTrans) {
  6390.                 if ($extTrans->getEditFlag() != 1) {
  6391.                     $url $this->generateUrl(
  6392.                         'view_voucher'
  6393.                     );
  6394.                     return $this->redirect($url "/" $voucherId);
  6395.                 } else {
  6396.                     $extVoucherData $extTrans;
  6397.                     $extVoucherDetailsData Accounts::GetVoucherDataForEdit($em$voucherId);
  6398.                 }
  6399.             } else {
  6400.             }
  6401.         }
  6402.         return $this->render(
  6403.             '@Accounts/pages/input_forms/journal_voucher.html.twig',
  6404.             array(
  6405.                 'page_title' => 'Create Journal Voucher',
  6406.                 'transaction' => [],
  6407.                 'extVoucherData' => $extVoucherData,
  6408.                 'extVoucherDetailsData' => $extVoucherDetailsData
  6409.             )
  6410.         );
  6411.     }
  6412.     public function ToggleActiveCheck(Request $request$id 0)
  6413.     {
  6414.         $em $this->getDoctrine()->getManager();
  6415.         $chk $em->getRepository("ApplicationBundle\\Entity\\AccCheck")->findOneBy(array(
  6416.             'CheckId' => $id
  6417.         ));
  6418.         if ($chk) {
  6419.             if ($chk->getActive() == GeneralConstant::ACTIVE) {
  6420.                 $chk->setActive(GeneralConstant::INACTIVE);
  6421.                 $chk->setAssigned(null);
  6422.                 $chk->setVoucherId(null);
  6423.                 $chk->setCheckAmount(null);
  6424.                 $chk->setTransactionDate(null);
  6425.                 $chk->setCheckDate(null);
  6426.                 $chk->setReconDate(null);
  6427.                 $chk->setLedgerHitDate(null);
  6428.                 $chk->setRecAccountsHeadIdList(null);
  6429.                 $chk->setRecAccountsHeadId(null);
  6430.             } else
  6431.                 $chk->setActive(GeneralConstant::ACTIVE);
  6432.             $em->flush();
  6433.         }
  6434.         //            $chk->setActive(GeneralConstant::INACTIVE);
  6435.         $em->flush();
  6436.         //for edits
  6437.         $extVoucherData = [];
  6438.         $extVoucherDetailsData = [];
  6439.         //        if($voucherId==0)
  6440.         //        {
  6441.         //
  6442.         //        }
  6443.         //        else
  6444.         //        {
  6445.         //
  6446.         //            $extTrans=$em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(
  6447.         //                array(
  6448.         //                    'transactionId'=>$voucherId, ///material
  6449.         //
  6450.         //                )
  6451.         //            );
  6452.         //
  6453.         //
  6454.         //            //now if its not editable, redirect to view
  6455.         //            if($extTrans) {
  6456.         //                if ($extTrans->getEditFlag() != 1) {
  6457.         //                    $url = $this->generateUrl(
  6458.         //                        'view_voucher'
  6459.         //                    );
  6460.         //                    return $this->redirect($url . "/" . $voucherId);
  6461.         //                }
  6462.         //                else
  6463.         //                {
  6464.         //                    $extVoucherData=$extTrans;
  6465.         //                    $extVoucherDetailsData=Accounts::GetVoucherDataForEdit($em,$voucherId);
  6466.         //                }
  6467.         //            }
  6468.         //            else
  6469.         //            {
  6470.         //
  6471.         //            }
  6472.         //
  6473.         //        }
  6474.         //
  6475.         //
  6476.         //        return $this->render('@Accounts/pages/input_forms/journal_voucher.html.twig',
  6477.         //            array(
  6478.         //                'page_title'=>'Create Journal Voucher',
  6479.         //                'transaction'=>[],
  6480.         //                'extVoucherData'=>$extVoucherData,
  6481.         //                'extVoucherDetailsData'=>$extVoucherDetailsData
  6482.         //            )
  6483.         //        );
  6484.         return new JsonResponse(array(
  6485.             "success" => $chk true false,
  6486.             "id" => $id,
  6487.             "currStatus" => $chk $chk->getActive() : ''
  6488.             //            "file_path"=>$file_path,
  6489.             //                "r"=>$r,
  6490.             //                "debug_data"=>System::encryptSignature($r)
  6491.         ));
  6492.         //        $url = $this->generateUrl(
  6493.         //            'check_management'
  6494.         //        );
  6495.         //        return $this->redirect($url);
  6496.     }
  6497.     public function CreateFundTransfer(Request $request$id 0)
  6498.     {
  6499.         $em $this->getDoctrine()->getManager();
  6500.         $voucherId $id;
  6501.         if ($request->isMethod('POST')) {
  6502.             //            Generic::debugMessage($_POST);
  6503.             $em $this->getDoctrine()->getManager();
  6504.             MiscActions::RemoveExpiredDocs($em);
  6505.             $numberHash MiscActions::GetNumberHash($em'JV'"GN"$request->request->get('projectId') ?: 0''1);
  6506.             $dochash 'JV' '/' "GN" '/' $request->request->get('projectId') ?: '/' $numberHash;
  6507.             $entity_id array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
  6508.             //            $dochash = $request->request->get('voucherNumber'); //change
  6509.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6510.             $approveRole $request->request->get('approvalRole');
  6511.             $approveHash $request->request->get('approvalHash');
  6512.             if (!DocValidation::isInsertable(
  6513.                 $em,
  6514.                 $entity_id,
  6515.                 $dochash,
  6516.                 $loginId,
  6517.                 $approveRole,
  6518.                 $approveHash,
  6519.                 $id
  6520.             )) {
  6521.                 $this->addFlash(
  6522.                     'error',
  6523.                     'Sorry Couldnot insert Data.'
  6524.                 );
  6525.             } else {
  6526.                 $funcname 'AccTransactions';
  6527.                 $doc_id $voucherId;
  6528.                 DeleteDocument::$funcname($em$doc_id0);
  6529.                 $ledgerHeads $request->request->get('ledgerHeads');
  6530.                 $notes $request->request->get('trNote');
  6531.                 $costCenters $request->request->get('costCenters');
  6532.                 $drAmount $request->request->get('drAmount');
  6533.                 $crAmount $request->request->get('crAmount');
  6534.                 $check_allowed 0;
  6535.                 if ($request->request->has('check_allowed'))
  6536.                     $check_allowed 1;
  6537.                 $em_goc $this->getDoctrine()->getManager('company_group');
  6538.                 $post_data $request->request;
  6539.                 $TransID Accounts::CreateNewTransaction(
  6540.                     $voucherId,
  6541.                     $this->getDoctrine()->getManager(),
  6542.                     $request->request->get('date'),
  6543.                     array_sum($request->request->get('drAmount')),
  6544.                     AccountsConstant::VOUCHER_JOURNAL,
  6545.                     $request->request->get('description'),
  6546.                     (empty($request->request->get('voucherNumber')) ? Generic::simpleRandString() : $request->request->get('voucherNumber')),
  6547.                     $request->request->get('type_hash'),
  6548.                     $request->request->get('prefix_hash'),
  6549.                     $request->request->get('assoc_hash'),
  6550.                     $request->request->get('number_hash'),
  6551.                     $check_allowed,
  6552.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6553.                     $this->getLoggedUserCompanyId($request)
  6554.                 );
  6555.                 $file_path_list = [];
  6556.                 if ($TransID != 0)
  6557.                     if (!empty($request->files)) {
  6558.                         MiscActions::RemoveFilesForEntityDoc($em_goc'AccTransactions'$TransID);
  6559.                         $storePath 'uploads/Voucher/';
  6560.                         $path "";
  6561.                         $file_path "";
  6562.                         $session $request->getSession();
  6563.                         MiscActions::RemoveExpiredFiles($em_goc);
  6564.                         foreach ($request->files as $uploadedFileGG) {
  6565.                             //            if($uploadedFile->getImage())
  6566.                             //                var_dump($uploadedFile->getFile());
  6567.                             //                var_dump($uploadedFile);
  6568.                             $tempD $uploadedFileGG;
  6569.                             if (!is_array($uploadedFileGG)) {
  6570.                                 $uploadedFileGG = array();
  6571.                                 $uploadedFileGG[] = $tempD;
  6572.                             }
  6573.                             foreach ($uploadedFileGG as $uploadedFile) {
  6574.                                 if ($uploadedFile != null) {
  6575.                                     $extension $uploadedFile->guessExtension();
  6576.                                     $size $uploadedFile->getSize();
  6577.                                     $fileName 'TRANS_' $TransID '_' . (md5(uniqid())) . '.' $uploadedFile->guessExtension();
  6578.                                     $path $fileName;
  6579.                                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  6580.                                     if (!file_exists($upl_dir)) {
  6581.                                         mkdir($upl_dir0777true);
  6582.                                     }
  6583.                                     if (file_exists($upl_dir '' $path)) {
  6584.                                         chmod($upl_dir '' $path0755);
  6585.                                         unlink($upl_dir '' $path);
  6586.                                     }
  6587.                                     $file $uploadedFile->move($upl_dir$path);
  6588.                                     $expireNever 1;
  6589.                                     $expireTs 0;
  6590.                                     $EntityFile = new EntityFile();
  6591.                                     $EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path);
  6592.                                     $EntityFile->setName($path);
  6593.                                     $EntityFile->setMarker('_GEN_');
  6594.                                     $EntityFile->setExtension($extension);
  6595.                                     $EntityFile->setExpireTs($expireTs);
  6596.                                     $EntityFile->setSize($size);
  6597.                                     $EntityFile->setRelativePath($storePath $path);
  6598.                                     $EntityFile->setEntityName('AccTransactions');
  6599.                                     $EntityFile->setEntityBundle('ApplicationBundle');
  6600.                                     $EntityFile->setEntityId($TransID);
  6601.                                     $EntityFile->setEntityIdField('transactionId');
  6602.                                     $EntityFile->setModifyFieldSetter('setFiles');
  6603.                                     $EntityFile->setDocIdForApplicant(0);
  6604.                                     $EntityFile->setUserId($session->get(UserConstants::USER_ID0));
  6605.                                     $EntityFile->setAppId($session->get(UserConstants::USER_APP_ID0));
  6606.                                     $EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID0));
  6607.                                     $EntityFile->setUserType($session->get(UserConstants::USER_TYPE0));
  6608.                                     $em_goc->persist($EntityFile);
  6609.                                     $em_goc->flush();
  6610.                                     $EntityFileId $EntityFile->getId();
  6611.                                 }
  6612.                                 if ($path != "")
  6613.                                     $file_path_list[] = ($storePath $path);
  6614.                             }
  6615.                         }
  6616.                         $g_path $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path;
  6617.                         $v $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  6618.                             'transactionId' => $TransID,
  6619.                         ));
  6620.                         if ($v) {
  6621.                             $v->setFiles(implode(','$file_path_list));
  6622.                             $em->flush();
  6623.                         } else {
  6624.                         }
  6625.                     }
  6626.                 for ($i 0$i count($ledgerHeads); $i++) {
  6627.                     if (!empty($drAmount[$i]) && $drAmount[$i] != 0) {
  6628.                         Accounts::CreateNewTransactionDetails(
  6629.                             $this->getDoctrine()->getManager(),
  6630.                             $request->request->get('date'),
  6631.                             $TransID,
  6632.                             Generic::CurrToInt($drAmount[$i]),
  6633.                             $ledgerHeads[$i],
  6634.                             $notes[$i],
  6635.                             AccountsConstant::DEBIT,
  6636.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  6637.                             [],
  6638.                             [],
  6639.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6640.                         );
  6641.                     }
  6642.                     if (!empty($crAmount[$i]) && $crAmount[$i] != 0) {
  6643.                         Accounts::CreateNewTransactionDetails(
  6644.                             $this->getDoctrine()->getManager(),
  6645.                             $request->request->get('date'),
  6646.                             $TransID,
  6647.                             Generic::CurrToInt($crAmount[$i]),
  6648.                             $ledgerHeads[$i],
  6649.                             $notes[$i],
  6650.                             AccountsConstant::CREDIT,
  6651.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  6652.                             [],
  6653.                             [],
  6654.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6655.                         );
  6656.                     }
  6657.                 }
  6658.                 //now add Approval info
  6659.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6660.                 $approveRole $request->request->get('approvalRole');
  6661.                 $options = array(
  6662.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6663.                     'notification_server' => $this->container->getParameter('notification_server'),
  6664.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6665.                     'url' => $this->generateUrl(
  6666.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AccTransactions']]['entity_view_route_path_name']
  6667.                     )
  6668.                 );
  6669.                 System::setApprovalInfo(
  6670.                     $this->getDoctrine()->getManager(),
  6671.                     $options,
  6672.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  6673.                     $TransID,
  6674.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6675.                     3    //journal voucher
  6676.                 );
  6677.                 System::createEditSignatureHash(
  6678.                     $this->getDoctrine()->getManager(),
  6679.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  6680.                     $TransID,
  6681.                     $loginId,
  6682.                     $approveRole,
  6683.                     $request->request->get('approvalHash')
  6684.                 );
  6685.                 $trans_here $this->getDoctrine()
  6686.                     ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  6687.                     ->findOneBy(
  6688.                         array(
  6689.                             'transactionId' => $TransID
  6690.                         )
  6691.                     );
  6692.                 //notify
  6693.                 $this->addFlash(
  6694.                     'success',
  6695.                     'New Transaction Added.'
  6696.                 );
  6697.                 $url $this->generateUrl(
  6698.                     'view_voucher'
  6699.                 );
  6700.                 System::AddNewNotification(
  6701.                     $this->container->getParameter('notification_enabled'),
  6702.                     $this->container->getParameter('notification_server'),
  6703.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  6704.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  6705.                     "Journal Voucher : " $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
  6706.                     'pos',
  6707.                     System::getPositionIdsByDepartment($emGeneralConstant::ACCOUNTS_DEPARTMENT),
  6708.                     'success',
  6709.                     //                    $url . "/" . $TransID,
  6710.                     $url "/" $TransID,
  6711.                     "Journal"
  6712.                 );
  6713.                 return new JsonResponse(
  6714.                     array(
  6715.                         'success' => true,
  6716.                     )
  6717.                 );
  6718.             }
  6719.         }
  6720.         //for edits
  6721.         $extVoucherData = [];
  6722.         $extVoucherDetailsData = [];
  6723.         if ($voucherId == 0) {
  6724.         } else {
  6725.             $extTrans $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(
  6726.                 array(
  6727.                     'transactionId' => $voucherId///material
  6728.                 )
  6729.             );
  6730.             //now if its not editable, redirect to view
  6731.             if ($extTrans) {
  6732.                 if ($extTrans->getEditFlag() != 1) {
  6733.                     $url $this->generateUrl(
  6734.                         'view_voucher'
  6735.                     );
  6736.                     return $this->redirect($url "/" $voucherId);
  6737.                 } else {
  6738.                     $extVoucherData $extTrans;
  6739.                     $extVoucherDetailsData Accounts::GetVoucherDataForEdit($em$voucherId);
  6740.                 }
  6741.             } else {
  6742.             }
  6743.         }
  6744.         return $this->render(
  6745.             '@Accounts/pages/input_forms/journal_voucher.html.twig',
  6746.             array(
  6747.                 'page_title' => 'Create Journal Voucher',
  6748.                 'transaction' => [],
  6749.                 'extVoucherData' => $extVoucherData,
  6750.                 'extVoucherDetailsData' => $extVoucherDetailsData
  6751.             )
  6752.         );
  6753.     }
  6754.     public function CreateFinancialBudget(Request $request$id 0)
  6755.     {
  6756.         $em $this->getDoctrine()->getManager();
  6757.         if ($request->isMethod('POST')) {
  6758.             //            Generic::debugMessage($_POST);
  6759.             $em $this->getDoctrine()->getManager();
  6760.             $entity_id array_flip(GeneralConstant::$Entity_list)['FinancialBudget']; //change
  6761.             $dochash $request->request->get('voucherNumber'); //change
  6762.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6763.             $approveRole $request->request->get('approvalRole');
  6764.             $approveHash $request->request->get('approvalHash');
  6765.             if (!DocValidation::isInsertable(
  6766.                 $em,
  6767.                 $entity_id,
  6768.                 $dochash,
  6769.                 $loginId,
  6770.                 $approveRole,
  6771.                 $approveHash,
  6772.                 $id
  6773.             )) {
  6774.                 $this->addFlash(
  6775.                     'error',
  6776.                     'Sorry Couldnot insert Data.'
  6777.                 );
  6778.             } else {
  6779.                 $funcname 'FinancialBudget';
  6780.                 $doc_id $id;
  6781.                 DeleteDocument::$funcname($em$doc_id0);
  6782.                 $ledgerHeads $request->request->get('ledgerHeads');
  6783.                 $notes = [];
  6784.                 $costCenters $request->request->get('costCenters');
  6785.                 $drAmount $request->request->get('drAmount');
  6786.                 $crAmount $request->request->get('crAmount');
  6787.                 $check_allowed 0;
  6788.                 $BudgetId Accounts::CreateNewBudget(
  6789.                     $id,
  6790.                     $this->getDoctrine()->getManager(),
  6791.                     $request->request->get('start_date'),
  6792.                     $request->request->get('end_date'),
  6793.                     array_sum($request->request->get('drAmount')),
  6794.                     $request->request->get('description'),
  6795.                     (empty($request->request->get('voucherNumber')) ? Generic::simpleRandString() : $request->request->get('voucherNumber')),
  6796.                     $request->request->get('type_hash'),
  6797.                     $request->request->get('prefix_hash'),
  6798.                     $request->request->get('assoc_hash'),
  6799.                     $request->request->get('number_hash'),
  6800.                     $check_allowed,
  6801.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6802.                     $this->getLoggedUserCompanyId($request)
  6803.                 );
  6804.                 for ($i 0$i count($ledgerHeads); $i++) {
  6805.                     if (!empty($drAmount[$i]) && $drAmount[$i] != 0) {
  6806.                         Accounts::CreateNewBudgetDetails(
  6807.                             $this->getDoctrine()->getManager(),
  6808.                             $request->request->get('start_date'),
  6809.                             $request->request->get('end_date'),
  6810.                             $BudgetId,
  6811.                             Generic::CurrToInt($drAmount[$i]),
  6812.                             $ledgerHeads[$i],
  6813.                             //                            $notes[$i],
  6814.                             AccountsConstant::DEBIT,
  6815.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  6816.                             [],
  6817.                             [],
  6818.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6819.                         );
  6820.                     }
  6821.                     if (!empty($crAmount[$i]) && $crAmount[$i] != 0) {
  6822.                         Accounts::CreateNewBudgetDetails(
  6823.                             $this->getDoctrine()->getManager(),
  6824.                             $request->request->get('start_date'),
  6825.                             $request->request->get('end_date'),
  6826.                             $BudgetId,
  6827.                             Generic::CurrToInt($crAmount[$i]),
  6828.                             $ledgerHeads[$i],
  6829.                             //                            $notes[$i],
  6830.                             AccountsConstant::CREDIT,
  6831.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  6832.                             [],
  6833.                             [],
  6834.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  6835.                         );
  6836.                     }
  6837.                 }
  6838.                 //now add Approval info
  6839.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6840.                 $approveRole $request->request->get('approvalRole');
  6841.                 $options = array(
  6842.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6843.                     'notification_server' => $this->container->getParameter('notification_server'),
  6844.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6845.                     'url' => $this->generateUrl(
  6846.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['FinancialBudget']]['entity_view_route_path_name']
  6847.                     )
  6848.                 );
  6849.                 System::setApprovalInfo(
  6850.                     $this->getDoctrine()->getManager(),
  6851.                     $options,
  6852.                     array_flip(GeneralConstant::$Entity_list)['FinancialBudget'],
  6853.                     $BudgetId,
  6854.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)   //journal voucher
  6855.                 );
  6856.                 System::createEditSignatureHash(
  6857.                     $this->getDoctrine()->getManager(),
  6858.                     array_flip(GeneralConstant::$Entity_list)['FinancialBudget'],
  6859.                     $BudgetId,
  6860.                     $loginId,
  6861.                     $approveRole,
  6862.                     $request->request->get('approvalHash')
  6863.                 );
  6864.                 $trans_here $this->getDoctrine()
  6865.                     ->getRepository('ApplicationBundle\\Entity\\FinancialBudget')
  6866.                     ->findOneBy(
  6867.                         array(
  6868.                             'budgetId' => $BudgetId
  6869.                         )
  6870.                     );
  6871.                 //notify
  6872.                 $this->addFlash(
  6873.                     'success',
  6874.                     'New Budget Added.'
  6875.                 );
  6876.                 $url $this->generateUrl(
  6877.                     'view_financial_budget'
  6878.                 );
  6879.                 System::AddNewNotification(
  6880.                     $this->container->getParameter('notification_enabled'),
  6881.                     $this->container->getParameter('notification_server'),
  6882.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  6883.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  6884.                     "Financial Budget : " $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
  6885.                     'pos',
  6886.                     System::getPositionIdsByDepartment($emGeneralConstant::ACCOUNTS_DEPARTMENT),
  6887.                     'success',
  6888.                     $url "/" $BudgetId,
  6889.                     "Journal"
  6890.                 );
  6891.                 // return $this->redirect($url."/".$BudgetId);
  6892.             }
  6893.         }
  6894.         //for edits
  6895.         $extBudgetData = [];
  6896.         $extBudgetDetailsData = [];
  6897.         if ($id == 0) {
  6898.         } else {
  6899.             $extTrans $em->getRepository('ApplicationBundle\\Entity\\FinancialBudget')->findOneBy(
  6900.                 array(
  6901.                     'budgetId' => $id///material
  6902.                 )
  6903.             );
  6904.             //now if its not editable, redirect to view
  6905.             if ($extTrans) {
  6906.                 if ($extTrans->getEditFlag() != 1) {
  6907.                     $url $this->generateUrl(
  6908.                         'view_financial_budget'
  6909.                     );
  6910.                     return $this->redirect($url "/" $id);
  6911.                 } else {
  6912.                     $extBudgetData $extTrans;
  6913.                     $extBudgetDetailsData Accounts::GetBudgetDataForEdit($em$id);
  6914.                 }
  6915.             } else {
  6916.             }
  6917.         }
  6918.         return $this->render(
  6919.             '@Accounts/pages/input_forms/financial_budget.html.twig',
  6920.             array(
  6921.                 'page_title' => 'Create Financial Budget',
  6922.                 'transaction' => [],
  6923.                 'currBudgetList' => $em->getRepository('ApplicationBundle\\Entity\\FinancialBudget')->findBy(
  6924.                     array(
  6925.                         //                        'budgetId'=>$id, ///material
  6926.                         'CompanyId' => $this->getLoggedUserCompanyId($request), ///material
  6927.                     )
  6928.                 ),
  6929.                 'headListForBudget' => Accounts::HeadListFullPathExtended($em'>'$this->getLoggedUserCompanyId($request)),
  6930.                 'extBudgetData' => $extBudgetData,
  6931.                 'extBudgetDetailsData' => $extBudgetDetailsData
  6932.             )
  6933.         );
  6934.     }
  6935.     public function CreateJournalVoucher(Request $request$id 0)
  6936.     {
  6937.         $em $this->getDoctrine()->getManager();
  6938.         $voucherId $id;
  6939.         if ($request->isMethod('POST')) {
  6940.             //            Generic::debugMessage($_POST);
  6941.             $em $this->getDoctrine()->getManager();
  6942.             MiscActions::RemoveExpiredDocs($em);
  6943.             $entity_id array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
  6944.             $dochash $request->request->get('voucherNumber'); //change
  6945.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6946.             $approveRole $request->request->get('approvalRole');
  6947.             $approveHash $request->request->get('approvalHash');
  6948.             if (!DocValidation::isInsertable(
  6949.                 $em,
  6950.                 $entity_id,
  6951.                 $dochash,
  6952.                 $loginId,
  6953.                 $approveRole,
  6954.                 $approveHash,
  6955.                 $id
  6956.             )) {
  6957.                 $this->addFlash(
  6958.                     'error',
  6959.                     'Sorry Could not insert Data.'
  6960.                 );
  6961.             } else {
  6962.                 // ── Ledger-integrity pre-flight: refuse an unbalanced voucher BEFORE any write ──
  6963.                 // The Dr==Cr check used to be JavaScript-only, so a bypassed submit persisted a
  6964.                 // corrupt voucher. ApprovalFunction's backstop fires only at approval — by then the
  6965.                 // header + legs are already committed (each leg commits separately), so the user got
  6966.                 // a 500 and the imbalance stayed in the books. This MUST stay above DeleteDocument:
  6967.                 // refusing after it would destroy the user's existing voucher on an edit.
  6968.                 $balanceCheck VoucherBalanceGuard::check(
  6969.                     $request->request->get('drAmount'),
  6970.                     $request->request->get('crAmount'),
  6971.                     $request->request->get('currencyMultiplyRate')
  6972.                 );
  6973.                 if (!$balanceCheck['balanced']) {
  6974.                     if ($request->request->has('returnJson')) {
  6975.                         return new JsonResponse(array(
  6976.                             'success' => false,
  6977.                             'error' => $balanceCheck['message'],
  6978.                         ));
  6979.                     }
  6980.                     $this->addFlash('error'$balanceCheck['message']);
  6981.                     return $this->redirect($this->generateUrl('create_journal_voucher', array('id' => $voucherId)));
  6982.                 }
  6983.                 // ── Dimension-allocation pre-flight (audit #3) ────────────────────────────────
  6984.                 // The allocation UI has always posted allocations[row][split][...], but this
  6985.                 // action never read it and never passed CreateNewTransactionDetails' 20th
  6986.                 // $allocations arg — so every leg silently got the 'unallocated' fallback and no
  6987.                 // transaction was EVER tagged, which is why the ledger dimension filter always
  6988.                 // came back empty. Validate up-front for the same reason the balance guard does:
  6989.                 // AccountingAllocationService throws when a tag group != the leg amount, and the
  6990.                 // header is written before the legs, so a throw mid-loop would leave a half-written
  6991.                 // voucher. Refuse the whole save with a message instead — never persist a partial,
  6992.                 // never silently drop the tag.
  6993.                 // NOTE: $ledgerHeads/$drAmount/$crAmount were only assigned AFTER this block (~line
  6994.                 // 8056), so the foreach hit an undefined $ledgerHeads and 500'd. Read them now
  6995.                 // (re-read below for the write); default to [] so an absent/empty post can't crash.
  6996.                 $ledgerHeads $request->request->get('ledgerHeads') ?: array();
  6997.                 $drAmount    $request->request->get('drAmount') ?: array();
  6998.                 $crAmount    $request->request->get('crAmount') ?: array();
  6999.                 $postedAllocations $request->request->get('allocations');
  7000.                 $legAmountsByRow = array();
  7001.                 foreach ($ledgerHeads as $rowIdx => $_head) {
  7002.                     if (!empty($drAmount[$rowIdx]) && $drAmount[$rowIdx] != 0) {
  7003.                         $legAmountsByRow[$rowIdx] = $drAmount[$rowIdx];
  7004.                     } elseif (!empty($crAmount[$rowIdx]) && $crAmount[$rowIdx] != 0) {
  7005.                         $legAmountsByRow[$rowIdx] = $crAmount[$rowIdx];
  7006.                     }
  7007.                 }
  7008.                 $allocCheck VoucherAllocationInput::check($postedAllocations$legAmountsByRow);
  7009.                 if (!$allocCheck['ok']) {
  7010.                     if ($request->request->has('returnJson')) {
  7011.                         return new JsonResponse(array(
  7012.                             'success' => false,
  7013.                             'error' => $allocCheck['message'],
  7014.                         ));
  7015.                     }
  7016.                     $this->addFlash('error'$allocCheck['message']);
  7017.                     return $this->redirect($this->generateUrl('create_journal_voucher', array('id' => $voucherId)));
  7018.                 }
  7019.                 $funcname 'AccTransactions';
  7020.                 $doc_id $voucherId;
  7021.                 DeleteDocument::$funcname($em$doc_id0);
  7022.                 $ledgerHeads $request->request->get('ledgerHeads');
  7023.                 $notes $request->request->get('trNote');
  7024.                 $costCenters $request->request->get('costCenters');
  7025.                 $drAmount $request->request->get('drAmount');
  7026.                 $crAmount $request->request->get('crAmount');
  7027.                 $check_allowed 0;
  7028.                 if ($request->request->has('check_allowed'))
  7029.                     $check_allowed 1;
  7030.                 $em_goc $this->getDoctrine()->getManager('company_group');
  7031.                 $post_data $request->request;
  7032.                 $TransID Accounts::CreateNewTransaction(
  7033.                     $voucherId,
  7034.                     $this->getDoctrine()->getManager(),
  7035.                     $request->request->get('date'),
  7036.                     array_sum($request->request->get('drAmount')),
  7037.                     AccountsConstant::VOUCHER_JOURNAL,
  7038.                     $request->request->get('description'),
  7039.                     (empty($request->request->get('voucherNumber')) ? Generic::simpleRandString() : $request->request->get('voucherNumber')),
  7040.                     $request->request->get('type_hash'),
  7041.                     $request->request->get('prefix_hash'),
  7042.                     $request->request->get('assoc_hash'),
  7043.                     $request->request->get('number_hash'),
  7044.                     $check_allowed,
  7045.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7046.                     $this->getLoggedUserCompanyId($request)
  7047.                 );
  7048.                 $file_path_list = [];
  7049.                 if ($TransID != 0)
  7050.                     if (!empty($request->files)) {
  7051.                         MiscActions::RemoveFilesForEntityDoc($em_goc'AccTransactions'$TransID);
  7052.                         $storePath 'uploads/Voucher/';
  7053.                         $path "";
  7054.                         $file_path "";
  7055.                         $session $request->getSession();
  7056.                         MiscActions::RemoveExpiredFiles($em_goc);
  7057.                         foreach ($request->files as $uploadedFileGG) {
  7058.                             //            if($uploadedFile->getImage())
  7059.                             //                var_dump($uploadedFile->getFile());
  7060.                             //                var_dump($uploadedFile);
  7061.                             $tempD $uploadedFileGG;
  7062.                             if (!is_array($uploadedFileGG)) {
  7063.                                 $uploadedFileGG = array();
  7064.                                 $uploadedFileGG[] = $tempD;
  7065.                             }
  7066.                             foreach ($uploadedFileGG as $uploadedFile) {
  7067.                                 if ($uploadedFile != null) {
  7068.                                     $extension $uploadedFile->guessExtension();
  7069.                                     $size $uploadedFile->getSize();
  7070.                                     $fileName 'TRANS_' $TransID '_' . (md5(uniqid())) . '.' $uploadedFile->guessExtension();
  7071.                                     $path $fileName;
  7072.                                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  7073.                                     if (!file_exists($upl_dir)) {
  7074.                                         mkdir($upl_dir0777true);
  7075.                                     }
  7076.                                     if (file_exists($upl_dir '' $path)) {
  7077.                                         chmod($upl_dir '' $path0755);
  7078.                                         unlink($upl_dir '' $path);
  7079.                                     }
  7080.                                     $file $uploadedFile->move($upl_dir$path);
  7081.                                     $expireNever 1;
  7082.                                     $expireTs 0;
  7083.                                     $EntityFile = new EntityFile();
  7084.                                     $EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path);
  7085.                                     $EntityFile->setName($path);
  7086.                                     $EntityFile->setMarker('_GEN_');
  7087.                                     $EntityFile->setExtension($extension);
  7088.                                     $EntityFile->setExpireTs($expireTs);
  7089.                                     $EntityFile->setSize($size);
  7090.                                     $EntityFile->setRelativePath($storePath $path);
  7091.                                     $EntityFile->setEntityName('AccTransactions');
  7092.                                     $EntityFile->setEntityBundle('ApplicationBundle');
  7093.                                     $EntityFile->setEntityId($TransID);
  7094.                                     $EntityFile->setEntityIdField('transactionId');
  7095.                                     $EntityFile->setModifyFieldSetter('setFiles');
  7096.                                     $EntityFile->setDocIdForApplicant(0);
  7097.                                     $EntityFile->setUserId($session->get(UserConstants::USER_ID0));
  7098.                                     $EntityFile->setAppId($session->get(UserConstants::USER_APP_ID0));
  7099.                                     $EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID0));
  7100.                                     $EntityFile->setUserType($session->get(UserConstants::USER_TYPE0));
  7101.                                     $em_goc->persist($EntityFile);
  7102.                                     $em_goc->flush();
  7103.                                     $EntityFileId $EntityFile->getId();
  7104.                                 }
  7105.                                 if ($path != "")
  7106.                                     $file_path_list[] = ($storePath $path);
  7107.                             }
  7108.                         }
  7109.                         $g_path $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path;
  7110.                         $v $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  7111.                             'transactionId' => $TransID,
  7112.                         ));
  7113.                         if ($v) {
  7114.                             $v->setFiles(implode(','$file_path_list));
  7115.                             $em->flush();
  7116.                         } else {
  7117.                         }
  7118.                     }
  7119.                 for ($i 0$i count($ledgerHeads); $i++) {
  7120.                     if (!empty($drAmount[$i]) && $drAmount[$i] != 0) {
  7121.                         Accounts::CreateNewTransactionDetails(
  7122.                             $this->getDoctrine()->getManager(),
  7123.                             $request->request->get('date'),
  7124.                             $TransID,
  7125.                             Generic::CurrToInt($drAmount[$i]),
  7126.                             $ledgerHeads[$i],
  7127.                             $notes[$i],
  7128.                             AccountsConstant::DEBIT,
  7129.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  7130.                             [],
  7131.                             [],
  7132.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7133.                             0,
  7134.                             0,
  7135.                             '_UNSET_',
  7136.                             $request->request->get('currency')[$i],
  7137.                             1,
  7138.                             $request->request->get('currencyMultiplyRate')[$i],
  7139.                             0,
  7140.                             0,
  7141.                             VoucherAllocationInput::forRow($postedAllocations$i)
  7142.                         );
  7143.                     }
  7144.                     if (!empty($crAmount[$i]) && $crAmount[$i] != 0) {
  7145.                         Accounts::CreateNewTransactionDetails(
  7146.                             $this->getDoctrine()->getManager(),
  7147.                             $request->request->get('date'),
  7148.                             $TransID,
  7149.                             Generic::CurrToInt($crAmount[$i]),
  7150.                             $ledgerHeads[$i],
  7151.                             $notes[$i],
  7152.                             AccountsConstant::CREDIT,
  7153.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  7154.                             [],
  7155.                             [],
  7156.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7157.                             0,
  7158.                             0,
  7159.                             '_UNSET_',
  7160.                             $request->request->get('currency')[$i],
  7161.                             1,
  7162.                             $request->request->get('currencyMultiplyRate')[$i],
  7163.                             0,
  7164.                             0,
  7165.                             VoucherAllocationInput::forRow($postedAllocations$i)
  7166.                         );
  7167.                     }
  7168.                 }
  7169.                 //now add Approval info
  7170.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7171.                 $approveRole $request->request->get('approvalRole');
  7172.                 $options = array(
  7173.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  7174.                     'notification_server' => $this->container->getParameter('notification_server'),
  7175.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  7176.                     'url' => $this->generateUrl(
  7177.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AccTransactions']]['entity_view_route_path_name']
  7178.                     )
  7179.                 );
  7180.                 System::setApprovalInfo(
  7181.                     $this->getDoctrine()->getManager(),
  7182.                     $options,
  7183.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  7184.                     $TransID,
  7185.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7186.                     3    //journal voucher
  7187.                 );
  7188.                 System::createEditSignatureHash(
  7189.                     $this->getDoctrine()->getManager(),
  7190.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  7191.                     $TransID,
  7192.                     $loginId,
  7193.                     $approveRole,
  7194.                     $request->request->get('approvalHash')
  7195.                 );
  7196.                 $trans_here $this->getDoctrine()
  7197.                     ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  7198.                     ->findOneBy(
  7199.                         array(
  7200.                             'transactionId' => $TransID
  7201.                         )
  7202.                     );
  7203.                 //notify
  7204.                 $url $this->generateUrl(
  7205.                     'view_voucher'
  7206.                 );
  7207.                 System::AddNewNotification(
  7208.                     $this->container->getParameter('notification_enabled'),
  7209.                     $this->container->getParameter('notification_server'),
  7210.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  7211.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  7212.                     "Journal Voucher : " $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
  7213.                     'pos',
  7214.                     System::getPositionIdsByDepartment($emGeneralConstant::ACCOUNTS_DEPARTMENT),
  7215.                     'success',
  7216.                     //                    $url . "/" . $TransID,
  7217.                     $url "/" $TransID,
  7218.                     "Journal"
  7219.                 );
  7220.                 if ($request->request->has('returnJson')) {
  7221.                     $doc $trans_here;
  7222.                     return new JsonResponse(array(
  7223.                         'success' => true,
  7224.                         'documentHash' => $trans_here->getDocumentHash(),
  7225.                         'documentId' => $TransID,
  7226.                         'documentIdPadded' => str_pad($TransID8'0'STR_PAD_LEFT),
  7227.                         'documentDate' => $trans_here->getTransactionDate()->format('Y-m-d'),
  7228.                         'documentAmount' => $trans_here->getTransactionAmount(),
  7229.                         'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
  7230.                         'viewUrl' => $url "/" $TransID,
  7231.                         'docPrintMainUrl' => $this->generateUrl('print_voucher'),
  7232.                     ));
  7233.                 } else {
  7234.                     $this->addFlash(
  7235.                         'success',
  7236.                         'New Document Created'
  7237.                     );
  7238.                     return $this->redirect($url "/" $TransID);
  7239.                 }
  7240.             }
  7241.         }
  7242.         //for edits
  7243.         $extVoucherData = [];
  7244.         $extVoucherDetailsData = [];
  7245.         if ($voucherId == 0) {
  7246.         } else {
  7247.             $extTrans $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(
  7248.                 array(
  7249.                     'transactionId' => $voucherId///material
  7250.                 )
  7251.             );
  7252.             //now if its not editable, redirect to view
  7253.             if ($extTrans) {
  7254.                 if ($extTrans->getEditFlag() != 1) {
  7255.                     $url $this->generateUrl(
  7256.                         'view_voucher'
  7257.                     );
  7258.                     return $this->redirect($url "/" $voucherId);
  7259.                 } else {
  7260.                     $extVoucherData $extTrans;
  7261.                     $extVoucherDetailsData Accounts::GetVoucherDataForEdit($em$voucherId);
  7262.                 }
  7263.             } else {
  7264.             }
  7265.         }
  7266.         return $this->render(
  7267.             '@Accounts/pages/input_forms/journal_voucher.html.twig',
  7268.             array(
  7269.                 'page_title' => 'Create Journal Voucher',
  7270.                 'transaction' => [],
  7271.                 'extVoucherData' => $extVoucherData,
  7272.                 'extVoucherDetailsData' => $extVoucherDetailsData
  7273.             )
  7274.         );
  7275.     }
  7276.     public function CreateContraVoucher(Request $request$id 0)
  7277.     {
  7278.         $em $this->getDoctrine()->getManager();
  7279.         $voucherId $id;
  7280.         $details_ids = [];
  7281.         if ($request->isMethod('POST')) {
  7282.             //            Generic::debugMessage($_POST);
  7283.             $em $this->getDoctrine()->getManager();
  7284.             MiscActions::RemoveExpiredDocs($em);
  7285.             $entity_id array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
  7286.             $dochash $request->request->get('voucherNumber'); //change
  7287.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7288.             $approveRole $request->request->get('approvalRole');
  7289.             $approveHash $request->request->get('approvalHash');
  7290.             if (!DocValidation::isInsertable(
  7291.                 $em,
  7292.                 $entity_id,
  7293.                 $dochash,
  7294.                 $loginId,
  7295.                 $approveRole,
  7296.                 $approveHash,
  7297.                 $id
  7298.             )) {
  7299.                 $this->addFlash(
  7300.                     'error',
  7301.                     'Sorry Could not insert Data.'
  7302.                 );
  7303.             } else {
  7304.                 // ── Ledger-integrity pre-flight (same defect as the journal-voucher path) ──
  7305.                 // Reproduced on dev: an unbalanced contra posted txn 4621 (auto_created=0) with
  7306.                 // Dr 2,000 vs Cr 5,000. Its legs come purely from the posted rows — verified: exactly
  7307.                 // two CreateNewTransactionDetails calls in this action, no auto-added bank leg — so the
  7308.                 // shared guard applies unchanged. MUST stay above DeleteDocument (a refused edit would
  7309.                 // otherwise destroy the user's voucher).
  7310.                 $balanceCheck VoucherBalanceGuard::check(
  7311.                     $request->request->get('drAmount'),
  7312.                     $request->request->get('crAmount'),
  7313.                     $request->request->get('currencyMultiplyRate')
  7314.                 );
  7315.                 if (!$balanceCheck['balanced']) {
  7316.                     if ($request->request->has('returnJson')) {
  7317.                         return new JsonResponse(array(
  7318.                             'success' => false,
  7319.                             'error' => $balanceCheck['message'],
  7320.                         ));
  7321.                     }
  7322.                     $this->addFlash('error'$balanceCheck['message']);
  7323.                     return $this->redirect($this->generateUrl('create_contra_voucher', array('id' => $voucherId)));
  7324.                 }
  7325.                 // Dimension-allocation pre-flight — see the identical block in
  7326.                 // CreateJournalVoucher (audit #3). Validate before any write: the service throws
  7327.                 // when a tag group != the leg amount, and the header lands before the legs, so a
  7328.                 // mid-loop throw would leave a half-written voucher.
  7329.                 // NOTE: unlike the JV path, here $ledgerHeads/$drAmount/$crAmount were only assigned
  7330.                 // AFTER this block, so the foreach hit an undefined $ledgerHeads and 500'd. Read them
  7331.                 // now (re-read below for the write); default to [] so an absent/empty post can't crash.
  7332.                 $ledgerHeads $request->request->get('ledgerHeads') ?: array();
  7333.                 $drAmount    $request->request->get('drAmount') ?: array();
  7334.                 $crAmount    $request->request->get('crAmount') ?: array();
  7335.                 $postedAllocations $request->request->get('allocations');
  7336.                 $legAmountsByRow = array();
  7337.                 foreach ($ledgerHeads as $rowIdx => $_head) {
  7338.                     if (!empty($drAmount[$rowIdx]) && $drAmount[$rowIdx] != 0) {
  7339.                         $legAmountsByRow[$rowIdx] = $drAmount[$rowIdx];
  7340.                     } elseif (!empty($crAmount[$rowIdx]) && $crAmount[$rowIdx] != 0) {
  7341.                         $legAmountsByRow[$rowIdx] = $crAmount[$rowIdx];
  7342.                     }
  7343.                 }
  7344.                 $allocCheck VoucherAllocationInput::check($postedAllocations$legAmountsByRow);
  7345.                 if (!$allocCheck['ok']) {
  7346.                     if ($request->request->has('returnJson')) {
  7347.                         return new JsonResponse(array(
  7348.                             'success' => false,
  7349.                             'error' => $allocCheck['message'],
  7350.                         ));
  7351.                     }
  7352.                     $this->addFlash('error'$allocCheck['message']);
  7353.                     return $this->redirect($this->generateUrl('create_contra_voucher', array('id' => $voucherId)));
  7354.                 }
  7355.                 $funcname 'AccTransactions';
  7356.                 $doc_id $voucherId;
  7357.                 DeleteDocument::$funcname($em$doc_id0);
  7358.                 $ledgerHeads $request->request->get('ledgerHeads');
  7359.                 $notes $request->request->get('trNote');
  7360.                 $costCenters $request->request->get('costCenters');
  7361.                 $drAmount $request->request->get('drAmount');
  7362.                 $crAmount $request->request->get('crAmount');
  7363.                 $currencies $request->request->get('currency', []);
  7364.                 $currencyMultiplyRates $request->request->get('currencyMultiplyRate', []);
  7365.                 $em $this->getDoctrine()->getManager();
  7366.                 $check_allowed 0;
  7367.                 $provisional 0;
  7368.                 if ($request->request->has('check_allowed'))
  7369.                     $check_allowed 1;
  7370.                 if ($request->request->has('provisional'))
  7371.                     $provisional 1;
  7372.                 $em_goc $this->getDoctrine()->getManager('company_group');
  7373.                 $post_data $request->request;
  7374.                 $TransID Accounts::CreateNewTransaction(
  7375.                     $voucherId,
  7376.                     $this->getDoctrine()->getManager(),
  7377.                     $request->request->get('date'),
  7378.                     array_sum($request->request->get('drAmount')),
  7379.                     AccountsConstant::VOUCHER_CONTRA,
  7380.                     $request->request->get('description'),
  7381.                     (empty($request->request->get('voucherNumber')) ? Generic::simpleRandString() : $request->request->get('voucherNumber')),
  7382.                     $request->request->get('type_hash'),
  7383.                     $request->request->get('prefix_hash'),
  7384.                     $request->request->get('assoc_hash'),
  7385.                     $request->request->get('number_hash'),
  7386.                     $check_allowed,
  7387.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7388.                     $this->getLoggedUserCompanyId($request),
  7389.                     '',
  7390.                     $provisional,
  7391.                     0,
  7392.                     $request->request->has('checkAssignType') ? $request->request->get('checkAssignType') : 1,
  7393.                     $request->request->has('prReference') ? $request->request->get('prReference') : '',
  7394.                     0,
  7395.                     '_UNSET_',
  7396.                     '_UNSET_',
  7397.                     0,
  7398.                     '',
  7399.                     '',
  7400.                     isset($currencies[0]) ? $currencies[0] : 0,
  7401.                     1,
  7402.                     isset($currencyMultiplyRates[0]) ? $currencyMultiplyRates[0] : 1
  7403.                 );
  7404.                 $file_path_list = [];
  7405.                 if ($TransID != 0)
  7406.                     if (!empty($request->files)) {
  7407.                         MiscActions::RemoveFilesForEntityDoc($em_goc'AccTransactions'$TransID);
  7408.                         $storePath 'uploads/Voucher/';
  7409.                         $path "";
  7410.                         $file_path "";
  7411.                         $session $request->getSession();
  7412.                         MiscActions::RemoveExpiredFiles($em_goc);
  7413.                         foreach ($request->files as $uploadedFileGG) {
  7414.                             //            if($uploadedFile->getImage())
  7415.                             //                var_dump($uploadedFile->getFile());
  7416.                             //                var_dump($uploadedFile);
  7417.                             $tempD $uploadedFileGG;
  7418.                             if (!is_array($uploadedFileGG)) {
  7419.                                 $uploadedFileGG = array();
  7420.                                 $uploadedFileGG[] = $tempD;
  7421.                             }
  7422.                             foreach ($uploadedFileGG as $uploadedFile) {
  7423.                                 if ($uploadedFile != null) {
  7424.                                     $extension $uploadedFile->guessExtension();
  7425.                                     $size $uploadedFile->getSize();
  7426.                                     $fileName 'TRANS_' $TransID '_' . (md5(uniqid())) . '.' $uploadedFile->guessExtension();
  7427.                                     $path $fileName;
  7428.                                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  7429.                                     if (!file_exists($upl_dir)) {
  7430.                                         mkdir($upl_dir0777true);
  7431.                                     }
  7432.                                     if (file_exists($upl_dir '' $path)) {
  7433.                                         chmod($upl_dir '' $path0755);
  7434.                                         unlink($upl_dir '' $path);
  7435.                                     }
  7436.                                     $file $uploadedFile->move($upl_dir$path);
  7437.                                     $expireNever 1;
  7438.                                     $expireTs 0;
  7439.                                     $EntityFile = new EntityFile();
  7440.                                     $EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path);
  7441.                                     $EntityFile->setName($path);
  7442.                                     $EntityFile->setMarker('_GEN_');
  7443.                                     $EntityFile->setExtension($extension);
  7444.                                     $EntityFile->setExpireTs($expireTs);
  7445.                                     $EntityFile->setSize($size);
  7446.                                     $EntityFile->setRelativePath($storePath $path);
  7447.                                     $EntityFile->setEntityName('AccTransactions');
  7448.                                     $EntityFile->setEntityBundle('ApplicationBundle');
  7449.                                     $EntityFile->setEntityId($TransID);
  7450.                                     $EntityFile->setEntityIdField('transactionId');
  7451.                                     $EntityFile->setModifyFieldSetter('setFiles');
  7452.                                     $EntityFile->setDocIdForApplicant(0);
  7453.                                     $EntityFile->setUserId($session->get(UserConstants::USER_ID0));
  7454.                                     $EntityFile->setAppId($session->get(UserConstants::USER_APP_ID0));
  7455.                                     $EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID0));
  7456.                                     $EntityFile->setUserType($session->get(UserConstants::USER_TYPE0));
  7457.                                     $em_goc->persist($EntityFile);
  7458.                                     $em_goc->flush();
  7459.                                     $EntityFileId $EntityFile->getId();
  7460.                                 }
  7461.                                 if ($path != "")
  7462.                                     $file_path_list[] = ($storePath $path);
  7463.                             }
  7464.                         }
  7465.                         $g_path $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path;
  7466.                         $v $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  7467.                             'transactionId' => $TransID,
  7468.                         ));
  7469.                         if ($v) {
  7470.                             $v->setFiles(implode(','$file_path_list));
  7471.                             $em->flush();
  7472.                         } else {
  7473.                         }
  7474.                     }
  7475.                 $check_here = [];
  7476.                 $id_list_for_check = [];
  7477.                 $details_ids = [];
  7478.                 for ($i 0$i count($ledgerHeads); $i++) {
  7479.                     if (!empty($drAmount[$i]) && $drAmount[$i] != 0) {
  7480.                         $id_list_for_check[$ledgerHeads[$i]] = $ledgerHeads[$i];
  7481.                         Accounts::CreateNewTransactionDetails(
  7482.                             $this->getDoctrine()->getManager(),
  7483.                             $request->request->get('date'),
  7484.                             $TransID,
  7485.                             Generic::CurrToInt($drAmount[$i]),
  7486.                             $ledgerHeads[$i],
  7487.                             $notes[$i],
  7488.                             AccountsConstant::DEBIT,
  7489.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  7490.                             [],
  7491.                             [],
  7492.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7493.                             0,
  7494.                             0,
  7495.                             '_UNSET_',
  7496.                             isset($currencies[$i]) ? $currencies[$i] : 0,
  7497.                             1,
  7498.                             isset($currencyMultiplyRates[$i]) ? $currencyMultiplyRates[$i] : 1,
  7499.                             0,
  7500.                             0,
  7501.                             VoucherAllocationInput::forRow($postedAllocations$i)
  7502.                         );
  7503.                     }
  7504.                     if (!empty($crAmount[$i]) && $crAmount[$i] != 0) {
  7505.                         Accounts::CreateNewTransactionDetails(
  7506.                             $this->getDoctrine()->getManager(),
  7507.                             $request->request->get('date'),
  7508.                             $TransID,
  7509.                             Generic::CurrToInt($crAmount[$i]),
  7510.                             $ledgerHeads[$i],
  7511.                             $notes[$i],
  7512.                             AccountsConstant::CREDIT,
  7513.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  7514.                             [],
  7515.                             [],
  7516.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7517.                             0,
  7518.                             0,
  7519.                             '_UNSET_',
  7520.                             isset($currencies[$i]) ? $currencies[$i] : 0,
  7521.                             1,
  7522.                             isset($currencyMultiplyRates[$i]) ? $currencyMultiplyRates[$i] : 1,
  7523.                             0,
  7524.                             0,
  7525.                             VoucherAllocationInput::forRow($postedAllocations$i)
  7526.                         );
  7527.                     }
  7528.                 }
  7529.                 if ($request->request->has('check_id')) {
  7530.                     $check_assign_type $request->request->get('checkAssignType');
  7531.                     foreach ($request->request->get('check_id') as $k => $value) {
  7532.                         $check_here $this->getDoctrine()
  7533.                             ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  7534.                             ->findOneBy(
  7535.                                 array(
  7536.                                     'CheckId' => $value
  7537.                                 )
  7538.                             );
  7539.                         if ($check_assign_type == 1) {
  7540.                             $ind_head_id json_decode($request->request->get('check_received_id')[$k], true)[0];
  7541.                             $check_here->setRecAccountsHeadId($id_list_for_check[$ind_head_id]);
  7542.                             $check_here->setRecAccountsHeadIdList(json_encode([$id_list_for_check[$ind_head_id]]));
  7543.                         }
  7544.                         if ($check_assign_type == 2) {
  7545.                             $ind_head_id_list json_decode($request->request->get('check_received_id')[$k], true);
  7546.                             $new_id_list = [];
  7547.                             foreach ($ind_head_id_list as $ind_head_id) {
  7548.                                 $new_id_list[] = $id_list_for_check[$ind_head_id];
  7549.                             }
  7550.                             $check_here->setRecAccountsHeadId(null);
  7551.                             $check_here->setRecAccountsHeadIdList(json_encode($new_id_list));
  7552.                         }
  7553.                         $check_here->setCheckNarration($request->request->get('check_narration')[$k]);
  7554.                         $check_here->setCheckAmount($request->request->get('check_assigned_amount')[$k]);
  7555.                         $check_here->setCheckDate(new \DateTime($request->request->get('checkDate')[$k]));
  7556.                         $check_here->setTransactionDate(new \DateTime($request->request->get('date')));
  7557.                         //                        $check_here->setCheckDate(new \DateTime($request->request->get('date')));
  7558.                         $check_here->setAssigned(1);
  7559.                         $check_here->setVoucherId($TransID);
  7560.                     }
  7561.                 }
  7562.                 //approval system
  7563.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7564.                 $approveRole $request->request->get('approvalRole');
  7565.                 //            Accounts::UpdatePurchasePayments($em,$pi_list,$po_list,$details_ids, $request->request->get('date'));
  7566.                 $options = array(
  7567.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  7568.                     'notification_server' => $this->container->getParameter('notification_server'),
  7569.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  7570.                     'url' => $this->generateUrl(
  7571.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AccTransactions']]['entity_view_route_path_name']
  7572.                     )
  7573.                 );
  7574.                 System::setApprovalInfo(
  7575.                     $this->getDoctrine()->getManager(),
  7576.                     $options,
  7577.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  7578.                     $TransID,
  7579.                     $loginId,
  7580.                     4    //contra voucher
  7581.                 );
  7582.                 System::createEditSignatureHash(
  7583.                     $em,
  7584.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  7585.                     $TransID,
  7586.                     $loginId,
  7587.                     $approveRole,
  7588.                     $request->request->get('approvalHash')
  7589.                 );
  7590.                 $url $this->generateUrl(
  7591.                     'view_voucher'
  7592.                 );
  7593.                 $trans_here $this->getDoctrine()
  7594.                     ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  7595.                     ->findOneBy(
  7596.                         array(
  7597.                             'transactionId' => $TransID
  7598.                         )
  7599.                     );
  7600.                 System::AddNewNotification(
  7601.                     $this->container->getParameter('notification_enabled'),
  7602.                     $this->container->getParameter('notification_server'),
  7603.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  7604.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  7605.                     "Contra Voucher : " $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
  7606.                     'pos',
  7607.                     System::getPositionIdsByDepartment($emGeneralConstant::ACCOUNTS_DEPARTMENT),
  7608.                     'success',
  7609.                     $url "/" $TransID,
  7610.                     "Contra Voucher"
  7611.                 );
  7612.                 if ($request->request->has('returnJson')) {
  7613.                     $doc $trans_here;
  7614.                     return new JsonResponse(array(
  7615.                         'success' => true,
  7616.                         'documentHash' => $trans_here->getDocumentHash(),
  7617.                         'documentId' => $TransID,
  7618.                         'documentIdPadded' => str_pad($TransID8'0'STR_PAD_LEFT),
  7619.                         'documentDate' => $trans_here->getTransactionDate()->format('Y-m-d'),
  7620.                         'documentAmount' => $trans_here->getTransactionAmount(),
  7621.                         'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
  7622.                         'viewUrl' => $url "/" $TransID,
  7623.                         'docPrintMainUrl' => $this->generateUrl('print_voucher'),
  7624.                     ));
  7625.                 } else {
  7626.                     $this->addFlash(
  7627.                         'success',
  7628.                         'New Document Created'
  7629.                     );
  7630.                     return $this->redirect($url "/" $TransID);
  7631.                 }
  7632.             }
  7633.         }
  7634.         $extVoucherData = [];
  7635.         $extVoucherDetailsData = [];
  7636.         if ($voucherId == 0) {
  7637.         } else {
  7638.             $extTrans $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(
  7639.                 array(
  7640.                     'transactionId' => $voucherId///material
  7641.                 )
  7642.             );
  7643.             //now if its not editable, redirect to view
  7644.             if ($extTrans) {
  7645.                 if ($extTrans->getEditFlag() != 1) {
  7646.                     $url $this->generateUrl(
  7647.                         'view_voucher'
  7648.                     );
  7649.                     return $this->redirect($url "/" $voucherId);
  7650.                 } else {
  7651.                     $extVoucherData $extTrans;
  7652.                     $extVoucherDetailsData Accounts::GetVoucherDataForEdit($em$voucherId);
  7653.                 }
  7654.             } else {
  7655.             }
  7656.         }
  7657.         return $this->render(
  7658.             '@Accounts/pages/input_forms/contra_voucher.html.twig',
  7659.             array(
  7660.                 'page_title' => 'Create Contra Voucher',
  7661.                 'test' => $details_ids,
  7662.                 'extVoucherData' => $extVoucherData,
  7663.                 'extVoucherDetailsData' => $extVoucherDetailsData,
  7664.                 'supplier_list' => Accounts::SupplierListForPv($this->getDoctrine()->getManager()),
  7665.                 'supplier_list_by_ac_head' => Accounts::SupplierListByAcHead($this->getDoctrine()->getManager()),
  7666.                 'supplier_list_by_advance_head' => Accounts::SupplierListByAdvanceHead($this->getDoctrine()->getManager())
  7667.             )
  7668.         );
  7669.     }
  7670.     public function CreatePaymentVoucher(Request $request$id 0)
  7671.     {
  7672.         $details_ids = [];
  7673.         $voucherId $id;
  7674.         $em $this->getDoctrine()->getManager();
  7675.         $FundRequisitionDetails $em->getRepository(FundRequisition::class)->findAll();
  7676.         $prePopulateData = [];
  7677.         $skipInvoiceBalancing $request->get('skipInvoiceBalancing'0);
  7678.         if ($request->request->get('payslip_ids''') != '') {
  7679.             $payslip_ids_array explode(','$request->request->get('payslip_ids'''));
  7680.             $payslips $em->getRepository('ApplicationBundle\\Entity\\Payslip')->findBy(
  7681.                 array(
  7682.                     'payslipId' => $payslip_ids_array///material
  7683.                 )
  7684.             );
  7685.             foreach ($payslips as $payslip) {
  7686.                 $employee $em->getRepository('ApplicationBundle\\Entity\\Employee')->findOneBy(array(
  7687.                         'employeeId' => $payslip->getSysId())
  7688.                 );
  7689.                 $dtHead 0;
  7690.                 if ($employee)
  7691.                     $dtHead $employee->getAccountsHeadId();
  7692.                 if ($dtHead != '' && $dtHead != && $dtHead != null)
  7693.                     $prePopulateData[] = array(
  7694.                         'accountsHeadId' => $dtHead,
  7695.                         'position' => 'dr',
  7696.                         'payslipId' => $payslip->getPayslipId(),
  7697.                         'payslipPaymentType' => $request->request->get('disburse_type''bank'),
  7698.                         'amount' => $request->request->get('disburse_type''bank') == 'bank' $payslip->getBankTransfer() : $payslip->getHandCash(),
  7699.                         'note' => $employee->getName(),
  7700.                     );
  7701.             }
  7702.         } else if ($request->isMethod('POST')) {
  7703.             //            Generic::debugMessage($_POST);
  7704.             $em $this->getDoctrine()->getManager();
  7705.             MiscActions::RemoveExpiredDocs($em);
  7706.             $entity_id array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
  7707.             $dochash $request->request->get('voucherNumber'); //change
  7708.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7709.             $approveRole $request->request->get('approvalRole');
  7710.             $approveHash $request->request->get('approvalHash');
  7711.             if (!DocValidation::isInsertable(
  7712.                 $em,
  7713.                 $entity_id,
  7714.                 $dochash,
  7715.                 $loginId,
  7716.                 $approveRole,
  7717.                 $approveHash,
  7718.                 $id
  7719.             )) {
  7720.                 if ($request->request->has('returnJson')) {
  7721.                     return new JsonResponse(array(
  7722.                         'success' => false,
  7723.                         'documentHash' => 0,
  7724.                         'documentId' => 0,
  7725.                     ));
  7726.                 } else
  7727.                     $this->addFlash(
  7728.                         'error',
  7729.                         'Sorry Could not insert Data.'
  7730.                     );
  7731.             } else {
  7732.                 // ── Ledger-integrity pre-flight (same defect as the journal/contra paths) ──
  7733.                 // Reproduced on dev: an unbalanced payment posted txn 4623 (auto_created=0) with
  7734.                 // Dr 2,000 vs Cr 5,000. Guarding on the POSTED rows is correct here even though this
  7735.                 // action writes MORE legs than it has rows: for a supplier head the debit is SPLIT into
  7736.                 // payable (pi/ei allocations) + advance (po allocations) + the remainder
  7737.                 // ($drAmount[$i] - $gt), which sums back to exactly $drAmount[$i]. Verified live — a
  7738.                 // 5,000 supplier payment carrying a 2,000 pi allocation wrote legs 2,000 + 3,000 = 5,000.
  7739.                 // The split REDISTRIBUTES the posted debit across heads; it never adds value, and there
  7740.                 // is no auto bank/cash counter-leg. So Sum(legs written) == Sum(posted rows) and this
  7741.                 // measures exactly what would be persisted. MUST stay above DeleteDocument.
  7742.                 $balanceCheck VoucherBalanceGuard::check(
  7743.                     $request->request->get('drAmount'),
  7744.                     $request->request->get('crAmount'),
  7745.                     $request->request->get('currencyMultiplyRate')
  7746.                 );
  7747.                 if (!$balanceCheck['balanced']) {
  7748.                     if ($request->request->has('returnJson')) {
  7749.                         return new JsonResponse(array(
  7750.                             'success' => false,
  7751.                             'error' => $balanceCheck['message'],
  7752.                         ));
  7753.                     }
  7754.                     $this->addFlash('error'$balanceCheck['message']);
  7755.                     return $this->redirect($this->generateUrl('create_payment_voucher', array('id' => $voucherId)));
  7756.                 }
  7757.                 $funcname 'AccTransactions';
  7758.                 $doc_id $voucherId;
  7759.                 DeleteDocument::$funcname($em$doc_id0);
  7760.                 $ledgerHeads $request->request->get('ledgerHeads');
  7761.                 $notes $request->request->get('trNote');
  7762.                 $costCenters $request->request->get('costCenters');
  7763.                 $drAmount $request->request->get('drAmount');
  7764.                 $crAmount $request->request->get('crAmount');
  7765.                 $em $this->getDoctrine()->getManager();
  7766.                 $pi_list = [];
  7767.                 $po_list = [];
  7768.                 $ei_list = [];
  7769.                 //1stly lets set the invoices po etc before we save the transaction normally
  7770.                 if ($request->request->has('ei_id'))
  7771.                     $ei_list = array(
  7772.                         'id' => $request->request->get('ei_id'),
  7773.                         'aa' => $request->request->get('ei_aa'),
  7774.                         'ei_head_id' => $request->request->get('ei_head_id')
  7775.                     );
  7776.                 if ($request->request->has('pi_id'))
  7777.                     $pi_list = array(
  7778.                         'id' => $request->request->get('pi_id'),
  7779.                         'aa' => $request->request->get('pi_aa')
  7780.                     );
  7781.                 if ($request->request->has('po_id'))
  7782.                     $po_list = array(
  7783.                         'id' => $request->request->get('po_id'),
  7784.                         'aa' => $request->request->get('po_aa')
  7785.                     );
  7786.                 $check_allowed 0;
  7787.                 $provisional 0;
  7788.                 if ($request->request->has('check_allowed'))
  7789.                     $check_allowed 1;
  7790.                 if ($request->request->has('provisional'))
  7791.                     $provisional 1;
  7792.                 $em_goc $this->getDoctrine()->getManager('company_group');
  7793.                 $post_data $request->request;
  7794.                 $TransID Accounts::CreateNewTransaction(
  7795.                     $voucherId,
  7796.                     $this->getDoctrine()->getManager(),
  7797.                     $request->request->get('date'),
  7798.                     array_sum($request->request->get('drAmount')),
  7799.                     AccountsConstant::VOUCHER_PAYMENT,
  7800.                     $request->request->get('description'),
  7801.                     (empty($request->request->get('voucherNumber')) ? Generic::simpleRandString() : $request->request->get('voucherNumber')),
  7802.                     $request->request->get('type_hash'),
  7803.                     $request->request->get('prefix_hash'),
  7804.                     $request->request->get('assoc_hash'),
  7805.                     $request->request->get('number_hash'),
  7806.                     $check_allowed,
  7807.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7808.                     $this->getLoggedUserCompanyId($request),
  7809.                     '',
  7810.                     $provisional,
  7811.                     0,
  7812.                     $request->request->has('checkAssignType') ? $request->request->get('checkAssignType') : 1,
  7813.                     $request->request->has('prReference') ? $request->request->get('prReference') : '',
  7814.                     0,
  7815.                     '_UNSET_',
  7816.                     '_UNSET_',
  7817.                     0,
  7818.                     '',
  7819.                     '',
  7820.                     $request->request->get('currency', [''])[0]
  7821.                 );
  7822.                 $check_here = [];
  7823.                 $id_list_for_check = [];
  7824.                 $file_path_list = [];
  7825.                 if ($TransID != 0)
  7826.                     if (!empty($request->files)) {
  7827.                         MiscActions::RemoveFilesForEntityDoc($em_goc'AccTransactions'$TransID);
  7828.                         $storePath 'uploads/Voucher/';
  7829.                         $path "";
  7830.                         $file_path "";
  7831.                         $session $request->getSession();
  7832.                         MiscActions::RemoveExpiredFiles($em_goc);
  7833.                         foreach ($request->files as $uploadedFileGG) {
  7834.                             //            if($uploadedFile->getImage())
  7835.                             //                var_dump($uploadedFile->getFile());
  7836.                             //                var_dump($uploadedFile);
  7837.                             $tempD $uploadedFileGG;
  7838.                             if (!is_array($uploadedFileGG)) {
  7839.                                 $uploadedFileGG = array();
  7840.                                 $uploadedFileGG[] = $tempD;
  7841.                             }
  7842.                             foreach ($uploadedFileGG as $uploadedFile) {
  7843.                                 if ($uploadedFile != null) {
  7844.                                     $extension $uploadedFile->guessExtension();
  7845.                                     $size $uploadedFile->getSize();
  7846.                                     $fileName 'TRANS_' $TransID '_' . (md5(uniqid())) . '.' $uploadedFile->guessExtension();
  7847.                                     $path $fileName;
  7848.                                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  7849.                                     if (!file_exists($upl_dir)) {
  7850.                                         mkdir($upl_dir0777true);
  7851.                                     }
  7852.                                     if (file_exists($upl_dir '' $path)) {
  7853.                                         chmod($upl_dir '' $path0755);
  7854.                                         unlink($upl_dir '' $path);
  7855.                                     }
  7856.                                     $file $uploadedFile->move($upl_dir$path);
  7857.                                     $expireNever 1;
  7858.                                     $expireTs 0;
  7859.                                     $EntityFile = new EntityFile();
  7860.                                     $EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path);
  7861.                                     $EntityFile->setMarker('_GEN_');
  7862.                                     $EntityFile->setName($path);
  7863.                                     $EntityFile->setExtension($extension);
  7864.                                     $EntityFile->setExpireTs($expireTs);
  7865.                                     $EntityFile->setSize($size);
  7866.                                     $EntityFile->setRelativePath($storePath $path);
  7867.                                     $EntityFile->setEntityName(GeneralConstant::$Entity_list[$entity_id]);
  7868.                                     $EntityFile->setEntityBundle('ApplicationBundle');
  7869.                                     $EntityFile->setEntityId($TransID);
  7870.                                     $EntityFile->setEntityIdField(GeneralConstant::$Entity_id_field_list[$entity_id]);
  7871.                                     $EntityFile->setModifyFieldSetter('setFiles');
  7872.                                     $EntityFile->setDocIdForApplicant(0);
  7873.                                     $EntityFile->setUserId($session->get(UserConstants::USER_ID0));
  7874.                                     $EntityFile->setAppId($session->get(UserConstants::USER_APP_ID0));
  7875.                                     $EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID0));
  7876.                                     $EntityFile->setUserType($session->get(UserConstants::USER_TYPE0));
  7877.                                     $em_goc->persist($EntityFile);
  7878.                                     $em_goc->flush();
  7879.                                     $EntityFileId $EntityFile->getId();
  7880.                                 }
  7881.                                 if ($path != "")
  7882.                                     $file_path_list[] = ($storePath $path);
  7883.                             }
  7884.                         }
  7885.                         $g_path $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path;
  7886.                         $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(
  7887.                             GeneralConstant::$Entity_id_field_list[$entity_id] => $TransID,
  7888.                         ));
  7889.                         if ($v) {
  7890.                             $v->setFiles(implode(','$file_path_list));
  7891.                             $em->flush();
  7892.                         } else {
  7893.                         }
  7894.                     }
  7895.                 $details_ids = [];
  7896.                 for ($i 0$i count($ledgerHeads); $i++) {
  7897.                     if (!empty($drAmount[$i]) && $drAmount[$i] != 0) {
  7898.                         $id_list_for_check[$ledgerHeads[$i]] = $ledgerHeads[$i]; //initially same all
  7899.                         //now lets see if any supplier exists and if yes , sprlit the value in advance and normal
  7900.                         $supplier_list Accounts::SupplierListThreeTypes($this->getDoctrine()->getManager());
  7901.                         $supplier_head_id_list = [];
  7902.                         $s_b_ac_h $supplier_list[1];
  7903.                         $s_b_advance_h $supplier_list[2];
  7904.                         //        $s_list=self::SupplierListForPv();
  7905.                         $head_index_calibrate = [];
  7906.                         $supplier_by_id '';
  7907.                         if (array_key_exists($ledgerHeads[$i], $s_b_ac_h)) {
  7908.                             $supplier_by_id $s_b_ac_h[$ledgerHeads[$i]];
  7909.                         }
  7910.                         if (array_key_exists($ledgerHeads[$i], $s_b_advance_h)) {
  7911.                             $supplier_by_id $s_b_advance_h[$ledgerHeads[$i]];
  7912.                         }
  7913.                         if ($supplier_by_id != '') {
  7914.                             $gt 0;
  7915.                             //use normal transaction
  7916.                             $tot 0;
  7917.                             if ($request->request->has('pi_id') || $request->request->has('ei_id')) {
  7918.                                 if ($request->request->has('pi_id'))
  7919.                                     foreach ($request->request->get('pi_id') as $k => $v) {
  7920.                                         if ($request->request->get('pi_head_id')[$k] == $ledgerHeads[$i])
  7921.                                             $tot += $request->request->get('pi_aa')[$k];
  7922.                                     }
  7923.                                 if ($request->request->has('ei_id'))
  7924.                                     foreach ($request->request->get('ei_id') as $k => $v) {
  7925.                                         if ($request->request->get('ei_head_id')[$k] == $ledgerHeads[$i])
  7926.                                             $tot += $request->request->get('ei_aa')[$k];
  7927.                                     }
  7928.                                 if ($tot 0) {
  7929.                                     $id_list_for_check[$ledgerHeads[$i]] = $supplier_by_id['supplier_head_id'];
  7930.                                     $details_ids[$supplier_by_id['supplier_head_id']] = Accounts::CreateNewTransactionDetails(
  7931.                                         $this->getDoctrine()->getManager(),
  7932.                                         $request->request->get('date'),
  7933.                                         $TransID,
  7934.                                         Generic::CurrToInt($tot),
  7935.                                         $supplier_by_id['supplier_head_id'],
  7936.                                         $notes[$i],
  7937.                                         AccountsConstant::DEBIT,
  7938.                                         isset($costCenters[$i]) ? $costCenters[$i] : 0,
  7939.                                         array($pi_list$po_list$ei_list),
  7940.                                         [],
  7941.                                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7942.                                         $provisional,
  7943.                                         0,
  7944.                                         '_UNSET_',
  7945.                                         $request->request->get('currency')[$i],
  7946.                                         1,
  7947.                                         $request->request->get('currencyMultiplyRate')[$i],
  7948.                                         isset($request->request->get('payslipId', [])[$i]) ? $request->request->get('payslipId', [])[$i] : 0,
  7949.                                         isset($request->request->get('payslipPaymentType', [])[$i]) ? $request->request->get('payslipPaymentType', [])[$i] : 0
  7950.                                     );
  7951.                                 }
  7952.                             }
  7953.                             $gt $gt $tot;
  7954.                             //now advance transaction
  7955.                             $tot 0;
  7956.                             if ($request->request->has('po_id')) {
  7957.                                 foreach ($request->request->get('po_id') as $k => $v) {
  7958.                                     if ($request->request->get('po_head_id')[$k] == $ledgerHeads[$i])
  7959.                                         $tot += $request->request->get('po_aa')[$k];
  7960.                                 }
  7961.                                 if ($tot 0) {
  7962.                                     $id_list_for_check[$ledgerHeads[$i]] = $supplier_by_id['supplier_advance_head_id'];
  7963.                                     $details_ids[$supplier_by_id['supplier_advance_head_id']] = Accounts::CreateNewTransactionDetails(
  7964.                                         $this->getDoctrine()->getManager(),
  7965.                                         $request->request->get('date'),
  7966.                                         $TransID,
  7967.                                         Generic::CurrToInt($tot),
  7968.                                         $supplier_by_id['supplier_advance_head_id'],
  7969.                                         $notes[$i],
  7970.                                         AccountsConstant::DEBIT,
  7971.                                         isset($costCenters[$i]) ? $costCenters[$i] : 0,
  7972.                                         array($pi_list$po_list$ei_list),
  7973.                                         [],
  7974.                                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7975.                                         $provisional,
  7976.                                         0,
  7977.                                         '_UNSET_',
  7978.                                         $request->request->get('currency')[$i],
  7979.                                         1,
  7980.                                         $request->request->get('currencyMultiplyRate')[$i],
  7981.                                         isset($request->request->get('payslipId', [])[$i]) ? $request->request->get('payslipId', [])[$i] : 0,
  7982.                                         isset($request->request->get('payslipPaymentType', [])[$i]) ? $request->request->get('payslipPaymentType', [])[$i] : 0
  7983.                                     );
  7984.                                 }
  7985.                             }
  7986.                             $gt $gt $tot;
  7987.                             //now assigning rest as normal trans
  7988.                             Accounts::CreateNewTransactionDetails(
  7989.                                 $this->getDoctrine()->getManager(),
  7990.                                 $request->request->get('date'),
  7991.                                 $TransID,
  7992.                                 Generic::CurrToInt($drAmount[$i] - $gt),
  7993.                                 $ledgerHeads[$i],
  7994.                                 $notes[$i],
  7995.                                 AccountsConstant::DEBIT,
  7996.                                 isset($costCenters[$i]) ? $costCenters[$i] : 0,
  7997.                                 array($pi_list$po_list$ei_list),
  7998.                                 [],
  7999.                                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  8000.                                 $provisional,
  8001.                                 0,
  8002.                                 '_UNSET_',
  8003.                                 $request->request->get('currency')[$i],
  8004.                                 1,
  8005.                                 $request->request->get('currencyMultiplyRate')[$i],
  8006.                                 isset($request->request->get('payslipId', [])[$i]) ? $request->request->get('payslipId', [])[$i] : 0,
  8007.                                 isset($request->request->get('payslipPaymentType', [])[$i]) ? $request->request->get('payslipPaymentType', [])[$i] : 0
  8008.                             );
  8009.                         } else
  8010.                             $details_ids[$ledgerHeads[$i]] = Accounts::CreateNewTransactionDetails(
  8011.                                 $this->getDoctrine()->getManager(),
  8012.                                 $request->request->get('date'),
  8013.                                 $TransID,
  8014.                                 Generic::CurrToInt($drAmount[$i]),
  8015.                                 $ledgerHeads[$i],
  8016.                                 $notes[$i],
  8017.                                 AccountsConstant::DEBIT,
  8018.                                 isset($costCenters[$i]) ? $costCenters[$i] : 0,
  8019.                                 array($pi_list$po_list$ei_list),
  8020.                                 [],
  8021.                                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  8022.                                 $provisional,
  8023.                                 0,
  8024.                                 '_UNSET_',
  8025.                                 $request->request->get('currency')[$i],
  8026.                                 1,
  8027.                                 $request->request->get('currencyMultiplyRate')[$i],
  8028.                                 isset($request->request->get('payslipId', [])[$i]) ? $request->request->get('payslipId', [])[$i] : 0,
  8029.                                 isset($request->request->get('payslipPaymentType', [])[$i]) ? $request->request->get('payslipPaymentType', [])[$i] : 0
  8030.                             );
  8031.                     }
  8032.                     if (!empty($crAmount[$i]) && $crAmount[$i] != 0) {
  8033.                         $details_ids[$ledgerHeads[$i]] = Accounts::CreateNewTransactionDetails(
  8034.                             $this->getDoctrine()->getManager(),
  8035.                             $request->request->get('date'),
  8036.                             $TransID,
  8037.                             Generic::CurrToInt($crAmount[$i]),
  8038.                             $ledgerHeads[$i],
  8039.                             $notes[$i],
  8040.                             AccountsConstant::CREDIT,
  8041.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  8042.                             array($pi_list$po_list$ei_list),
  8043.                             [],
  8044.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  8045.                             $provisional,
  8046.                             0,
  8047.                             '_UNSET_',
  8048.                             $request->request->get('currency')[$i],
  8049.                             1,
  8050.                             $request->request->get('currencyMultiplyRate')[$i],
  8051.                             isset($request->request->get('payslipId', [])[$i]) ? $request->request->get('payslipId', [])[$i] : 0,
  8052.                             isset($request->request->get('payslipPaymentType', [])[$i]) ? $request->request->get('payslipPaymentType', [])[$i] : 0
  8053.                         );
  8054.                     }
  8055.                 }
  8056.                 if ($request->request->has('check_id')) {
  8057.                     $check_assign_type $request->request->has('checkAssignType') ? $request->request->get('checkAssignType') : 1;
  8058.                     foreach ($request->request->get('check_id') as $k => $value) {
  8059.                         $check_here $this->getDoctrine()
  8060.                             ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  8061.                             ->findOneBy(
  8062.                                 array(
  8063.                                     'CheckId' => $value
  8064.                                 )
  8065.                             );
  8066.                         if ($check_assign_type == 1) {
  8067.                             $ind_head_id json_decode($request->request->get('check_received_id')[$k], true)[0];
  8068.                             $check_here->setRecAccountsHeadId($id_list_for_check[$ind_head_id]);
  8069.                             $check_here->setRecAccountsHeadIdList(json_encode([$id_list_for_check[$ind_head_id]]));
  8070.                         }
  8071.                         if ($check_assign_type == 2) {
  8072.                             $ind_head_id_list json_decode($request->request->get('check_received_id')[$k], true);
  8073.                             $new_id_list = [];
  8074.                             foreach ($ind_head_id_list as $ind_head_id) {
  8075.                                 $new_id_list[] = $id_list_for_check[$ind_head_id];
  8076.                             }
  8077.                             $check_here->setRecAccountsHeadId(null);
  8078.                             $check_here->setRecAccountsHeadIdList(json_encode($new_id_list));
  8079.                         }
  8080.                         $check_here->setCheckNarration($request->request->get('check_narration')[$k]);
  8081.                         $check_here->setCheckAmount($request->request->get('check_assigned_amount')[$k]);
  8082.                         $check_here->setCheckDate(new \DateTime($request->request->get('checkDate')[$k]));
  8083.                         $check_here->setTransactionDate(new \DateTime($request->request->get('date')));
  8084.                         //                        $check_here->setCheckDate(new \DateTime($request->request->get('date')));
  8085.                         $check_here->setAssigned(1);
  8086.                         $check_here->setVoucherId($TransID);
  8087.                     }
  8088.                 }
  8089.                 //approval system
  8090.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  8091.                 $approveRole $request->request->get('approvalRole');
  8092.                 Accounts::UpdatePurchasePayments($em$pi_list$po_list$details_ids$request->request->get('date'));
  8093.                 Accounts::UpdateExpensePayments($em$ei_list$details_ids$request->request->get('date'));
  8094.                 $options = array(
  8095.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  8096.                     'notification_server' => $this->container->getParameter('notification_server'),
  8097.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  8098.                     'url' => $this->generateUrl(
  8099.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AccTransactions']]['entity_view_route_path_name']
  8100.                     )
  8101.                 );
  8102.                 System::setApprovalInfo(
  8103.                     $this->getDoctrine()->getManager(),
  8104.                     $options,
  8105.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  8106.                     $TransID,
  8107.                     $loginId,
  8108.                     5    //payment voucher
  8109.                 );
  8110.                 System::createEditSignatureHash(
  8111.                     $em,
  8112.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  8113.                     $TransID,
  8114.                     $loginId,
  8115.                     $approveRole,
  8116.                     $request->request->get('approvalHash')
  8117.                 );
  8118.                 $url $this->generateUrl(
  8119.                     'view_voucher'
  8120.                 );
  8121.                 $trans_here $this->getDoctrine()
  8122.                     ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  8123.                     ->findOneBy(
  8124.                         array(
  8125.                             'transactionId' => $TransID
  8126.                         )
  8127.                     );
  8128.                 System::AddNewNotification(
  8129.                     $this->container->getParameter('notification_enabled'),
  8130.                     $this->container->getParameter('notification_server'),
  8131.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  8132.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  8133.                     "Debit Voucher : " $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
  8134.                     'pos',
  8135.                     System::getPositionIdsByDepartment($emGeneralConstant::ACCOUNTS_DEPARTMENT),
  8136.                     'success',
  8137.                     $url "/" $TransID,
  8138.                     "Debit Voucher"
  8139.                 );
  8140.                 if ($request->request->has('returnJson')) {
  8141.                     $doc $trans_here;
  8142.                     return new JsonResponse(array(
  8143.                         'success' => true,
  8144.                         'documentHash' => $trans_here->getDocumentHash(),
  8145.                         'documentId' => $TransID,
  8146.                         'documentIdPadded' => str_pad($TransID8'0'STR_PAD_LEFT),
  8147.                         'documentDate' => $trans_here->getTransactionDate()->format('Y-m-d'),
  8148.                         'documentAmount' => $trans_here->getTransactionAmount(),
  8149.                         'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
  8150.                         'viewUrl' => $url "/" $TransID,
  8151.                         'docPrintMainUrl' => $this->generateUrl('print_voucher'),
  8152.                     ));
  8153.                 } else {
  8154.                     $this->addFlash(
  8155.                         'success',
  8156.                         'New Document Created'
  8157.                     );
  8158.                     return $this->redirect($url "/" $TransID);
  8159.                 }
  8160.             }
  8161.         }
  8162.         //for edits
  8163.         $extVoucherData = [];
  8164.         $extVoucherDetailsData = [];
  8165.         if ($voucherId == 0) {
  8166.         } else {
  8167.             $extTrans $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(
  8168.                 array(
  8169.                     'transactionId' => $voucherId///material
  8170.                 )
  8171.             );
  8172.             //now if its not editable, redirect to view
  8173.             if ($extTrans) {
  8174.                 if ($extTrans->getEditFlag() != 1) {
  8175.                     $url $this->generateUrl(
  8176.                         'view_voucher'
  8177.                     );
  8178.                     return $this->redirect($url "/" $voucherId);
  8179.                 } else {
  8180.                     $extVoucherData $extTrans;
  8181.                     $extVoucherDetailsData Accounts::GetVoucherDataForEdit($em$voucherId);
  8182.                 }
  8183.             } else {
  8184.             }
  8185.         }
  8186.         return $this->render(
  8187.             '@Accounts/pages/input_forms/payment_voucher.html.twig',
  8188.             array(
  8189.                 'page_title' => 'Create Payment Voucher',
  8190.                 'test' => $details_ids,
  8191.                 'prePopulateData' => $prePopulateData,
  8192.                 'skipInvoiceBalancing' => $skipInvoiceBalancing,
  8193.                 'extVoucherData' => $extVoucherData,
  8194.                 'extVoucherDetailsData' => $extVoucherDetailsData,
  8195.                 'supplier_list' => Accounts::SupplierListForPv($this->getDoctrine()->getManager()),
  8196.                 'supplier_list_by_ac_head' => Accounts::SupplierListByAcHead($this->getDoctrine()->getManager()),
  8197.                 'supplier_list_by_advance_head' => Accounts::SupplierListByAdvanceHead($this->getDoctrine()->getManager()),
  8198.                 'fundRequisitionDetails' => $FundRequisitionDetails
  8199.             )
  8200.         );
  8201.     }
  8202.     public function CreateReceiptVoucher(Request $request$id 0)
  8203.     {
  8204.         $details_ids = [];
  8205.         $voucherId $id;
  8206.         $em $this->getDoctrine()->getManager();
  8207.         if ($request->isMethod('POST')) {
  8208.             //            Generic::debugMessage($_POST);
  8209.             $em $this->getDoctrine()->getManager();
  8210.             MiscActions::RemoveExpiredDocs($em);
  8211.             $entity_id array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
  8212.             $dochash $request->request->get('voucherNumber'); //change
  8213.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  8214.             $approveRole $request->request->get('approvalRole');
  8215.             $approveHash $request->request->get('approvalHash');
  8216.             if (!DocValidation::isInsertable(
  8217.                 $em,
  8218.                 $entity_id,
  8219.                 $dochash,
  8220.                 $loginId,
  8221.                 $approveRole,
  8222.                 $approveHash,
  8223.                 $id
  8224.             )) {
  8225.                 if ($request->request->has('returnJson')) {
  8226.                     return new JsonResponse(array(
  8227.                         'success' => false,
  8228.                         'documentHash' => 0,
  8229.                         'documentId' => 0,
  8230.                     ));
  8231.                 } else
  8232.                     $this->addFlash(
  8233.                         'error',
  8234.                         'Sorry Could not insert Data.'
  8235.                     );
  8236.             } else {
  8237.                 // ── Ledger-integrity pre-flight (the last of the four manual-voucher doors) ──
  8238.                 // Reproduced on dev: an unbalanced receipt posted txn 4641 (auto_created=0) with
  8239.                 // Dr 2,000 vs Cr 5,000. Receipt is the MIRROR of payment: it splits the CREDIT for a
  8240.                 // client head into receivable (allocations) + client advance + the remainder
  8241.                 // ($crAmount[$i] - $gt, ~line 9594), which sums back to exactly $crAmount[$i]; debits
  8242.                 // are the plain posted rows. Verified live — a 5,000 client receipt carrying a 2,000
  8243.                 // allocation wrote credit legs 2,000 + 3,000 = 5,000. The split REDISTRIBUTES the
  8244.                 // posted credit across heads; it never adds value and there is no extra counter-leg,
  8245.                 // so Sum(legs written) == Sum(posted rows). MUST stay above DeleteDocument.
  8246.                 $balanceCheck VoucherBalanceGuard::check(
  8247.                     $request->request->get('drAmount'),
  8248.                     $request->request->get('crAmount'),
  8249.                     $request->request->get('currencyMultiplyRate')
  8250.                 );
  8251.                 if (!$balanceCheck['balanced']) {
  8252.                     if ($request->request->has('returnJson')) {
  8253.                         return new JsonResponse(array(
  8254.                             'success' => false,
  8255.                             'error' => $balanceCheck['message'],
  8256.                         ));
  8257.                     }
  8258.                     $this->addFlash('error'$balanceCheck['message']);
  8259.                     return $this->redirect($this->generateUrl('create_receipt_voucher', array('id' => $voucherId)));
  8260.                 }
  8261.                 $funcname 'AccTransactions';
  8262.                 $doc_id $voucherId;
  8263.                 DeleteDocument::$funcname($em$doc_id0);
  8264.                 $ledgerHeads $request->request->get('ledgerHeads');
  8265.                 $notes $request->request->get('trNote');
  8266.                 $costCenters $request->request->get('costCenters');
  8267.                 $drAmount $request->request->get('drAmount');
  8268.                 $crAmount $request->request->get('crAmount');
  8269.                 $em $this->getDoctrine()->getManager();
  8270.                 $pi_list = [];
  8271.                 $po_list = [];
  8272.                 $ei_list = [];
  8273.                 //1stly lets set the invoices po etc before we save the transaction normally
  8274.                 if ($request->request->has('ei_id'))
  8275.                     $ei_list = array(
  8276.                         'id' => $request->request->get('ei_id'),
  8277.                         'aa' => $request->request->get('ei_aa'),
  8278.                         'ei_head_id' => $request->request->get('ei_head_id')
  8279.                     );
  8280.                 if ($request->request->has('pi_id'))
  8281.                     $pi_list = array(
  8282.                         'id' => $request->request->get('pi_id'),
  8283.                         'aa' => $request->request->get('pi_aa')
  8284.                     );
  8285.                 if ($request->request->has('po_id'))
  8286.                     $po_list = array(
  8287.                         'id' => $request->request->get('po_id'),
  8288.                         'aa' => $request->request->get('po_aa')
  8289.                     );
  8290.                 $check_allowed 0;
  8291.                 $provisional 0;
  8292.                 $pr_method 0;
  8293.                 $check_number '';
  8294.                 if ($request->request->has('check_allowed'))
  8295.                     $check_allowed 1;
  8296.                 if ($request->request->has('provisional'))
  8297.                     $provisional 1;
  8298.                 //            if($request->request->has('provisional'))
  8299.                 $pr_method $request->request->get('receipt_method');
  8300.                 //            $check_number=$request->request->get('receipt_method');
  8301.                 $em_goc $this->getDoctrine()->getManager('company_group');
  8302.                 $post_data $request->request;
  8303.                 $TransID Accounts::CreateNewTransaction(
  8304.                     $voucherId,
  8305.                     $this->getDoctrine()->getManager(),
  8306.                     $request->request->get('date'),
  8307.                     array_sum($request->request->get('drAmount')),
  8308.                     AccountsConstant::VOUCHER_RECEIPT,
  8309.                     $request->request->get('description'),
  8310.                     (empty($request->request->get('voucherNumber')) ? Generic::simpleRandString() : $request->request->get('voucherNumber')),
  8311.                     $request->request->get('type_hash'),
  8312.                     $request->request->get('prefix_hash'),
  8313.                     $request->request->get('assoc_hash'),
  8314.                     $request->request->get('number_hash'),
  8315.                     $check_allowed,
  8316.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  8317.                     $this->getLoggedUserCompanyId($request),
  8318.                     '',
  8319.                     $provisional,
  8320.                     0,
  8321.                     $pr_method
  8322.                 );
  8323.                 $file_path_list = [];
  8324.                 if ($TransID != 0)
  8325.                     if (!empty($request->files)) {
  8326.                         MiscActions::RemoveFilesForEntityDoc($em_goc'AccTransactions'$TransID);
  8327.                         $storePath 'uploads/Voucher/';
  8328.                         $path "";
  8329.                         $file_path "";
  8330.                         $session $request->getSession();
  8331.                         MiscActions::RemoveExpiredFiles($em_goc);
  8332.                         foreach ($request->files as $uploadedFileGG) {
  8333.                             //            if($uploadedFile->getImage())
  8334.                             //                var_dump($uploadedFile->getFile());
  8335.                             //                var_dump($uploadedFile);
  8336.                             $tempD $uploadedFileGG;
  8337.                             if (!is_array($uploadedFileGG)) {
  8338.                                 $uploadedFileGG = array();
  8339.                                 $uploadedFileGG[] = $tempD;
  8340.                             }
  8341.                             foreach ($uploadedFileGG as $uploadedFile) {
  8342.                                 if ($uploadedFile != null) {
  8343.                                     $extension $uploadedFile->guessExtension();
  8344.                                     $size $uploadedFile->getSize();
  8345.                                     $fileName 'TRANS_' $TransID '_' . (md5(uniqid())) . '.' $uploadedFile->guessExtension();
  8346.                                     $path $fileName;
  8347.                                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  8348.                                     if (!file_exists($upl_dir)) {
  8349.                                         mkdir($upl_dir0777true);
  8350.                                     }
  8351.                                     if (file_exists($upl_dir '' $path)) {
  8352.                                         chmod($upl_dir '' $path0755);
  8353.                                         unlink($upl_dir '' $path);
  8354.                                     }
  8355.                                     $file $uploadedFile->move($upl_dir$path);
  8356.                                     $expireNever 1;
  8357.                                     $expireTs 0;
  8358.                                     $EntityFile = new EntityFile();
  8359.                                     $EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path);
  8360.                                     $EntityFile->setMarker('_GEN_');
  8361.                                     $EntityFile->setName($path);
  8362.                                     $EntityFile->setExtension($extension);
  8363.                                     $EntityFile->setExpireTs($expireTs);
  8364.                                     $EntityFile->setSize($size);
  8365.                                     $EntityFile->setRelativePath($storePath $path);
  8366.                                     $EntityFile->setEntityName('AccTransactions');
  8367.                                     $EntityFile->setEntityBundle('ApplicationBundle');
  8368.                                     $EntityFile->setEntityId($TransID);
  8369.                                     $EntityFile->setEntityIdField('transactionId');
  8370.                                     $EntityFile->setModifyFieldSetter('setFiles');
  8371.                                     $EntityFile->setDocIdForApplicant(0);
  8372.                                     $EntityFile->setUserId($session->get(UserConstants::USER_ID0));
  8373.                                     $EntityFile->setAppId($session->get(UserConstants::USER_APP_ID0));
  8374.                                     $EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID0));
  8375.                                     $EntityFile->setUserType($session->get(UserConstants::USER_TYPE0));
  8376.                                     $em_goc->persist($EntityFile);
  8377.                                     $em_goc->flush();
  8378.                                     $EntityFileId $EntityFile->getId();
  8379.                                 }
  8380.                                 if ($path != "")
  8381.                                     $file_path_list[] = ($storePath $path);
  8382.                             }
  8383.                         }
  8384.                         $g_path $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path;
  8385.                         $v $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
  8386.                             'transactionId' => $TransID,
  8387.                         ));
  8388.                         if ($v) {
  8389.                             $v->setFiles(implode(','$file_path_list));
  8390.                             $em->flush();
  8391.                         } else {
  8392.                         }
  8393.                     }
  8394.                 $check_here = [];
  8395.                 $id_list_for_check = [];
  8396.                 $debit_head '';
  8397.                 $credit_head '';
  8398.                 $debit_amount '';
  8399.                 $details_ids = [];
  8400.                 for ($i 0$i count($ledgerHeads); $i++) {
  8401.                     //                if(!empty($drAmount[$i]) && $drAmount[$i]!=0){
  8402.                     if (!empty($crAmount[$i]) && $crAmount[$i] != 0) {
  8403.                         $id_list_for_check[$ledgerHeads[$i]] = $ledgerHeads[$i]; //initially same all
  8404.                         //now lets see if any supplier exists and if yes , sprlit the value in advance and normal
  8405.                         $supplier_list Accounts::ClientListThreeTypes($this->getDoctrine()->getManager());
  8406.                         $supplier_head_id_list = [];
  8407.                         $s_b_ac_h $supplier_list[1];
  8408.                         $s_b_advance_h $supplier_list[2];
  8409.                         //        $s_list=self::SupplierListForPv();
  8410.                         $head_index_calibrate = [];
  8411.                         $supplier_by_id '';
  8412.                         if (array_key_exists($ledgerHeads[$i], $s_b_ac_h)) {
  8413.                             $supplier_by_id $s_b_ac_h[$ledgerHeads[$i]];
  8414.                         }
  8415.                         if (array_key_exists($ledgerHeads[$i], $s_b_advance_h)) {
  8416.                             $supplier_by_id $s_b_advance_h[$ledgerHeads[$i]];
  8417.                         }
  8418.                         if ($supplier_by_id != '') {
  8419.                             $credit_head $supplier_by_id['client_head_id'];
  8420.                             $gt 0;
  8421.                             //use normal transaction
  8422.                             $tot 0;
  8423.                             if ($request->request->has('pi_id')) {
  8424.                                 foreach ($request->request->get('pi_id') as $k => $v) {
  8425.                                     if ($request->request->get('pi_head_id')[$k] == $ledgerHeads[$i])
  8426.                                         $tot += $request->request->get('pi_aa')[$k];
  8427.                                 }
  8428.                                 if ($tot 0) {
  8429.                                     $id_list_for_check[$ledgerHeads[$i]] = $supplier_by_id['client_head_id'];
  8430.                                     $details_ids[$supplier_by_id['client_head_id']] = Accounts::CreateNewTransactionDetails(
  8431.                                         $this->getDoctrine()->getManager(),
  8432.                                         $request->request->get('date'),
  8433.                                         $TransID,
  8434.                                         Generic::CurrToInt($tot),
  8435.                                         $supplier_by_id['client_head_id'],
  8436.                                         $notes[$i],
  8437.                                         AccountsConstant::CREDIT,
  8438.                                         isset($costCenters[$i]) ? $costCenters[$i] : 0,
  8439.                                         array($pi_list$po_list$ei_list),
  8440.                                         [],
  8441.                                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  8442.                                         $provisional
  8443.                                     );
  8444.                                 }
  8445.                             }
  8446.                             $gt $gt $tot;
  8447.                             //now advance transaction
  8448.                             $tot 0;
  8449.                             if ($request->request->has('po_id')) {
  8450.                                 foreach ($request->request->get('po_id') as $k => $v) {
  8451.                                     if ($request->request->get('po_head_id')[$k] == $ledgerHeads[$i])
  8452.                                         $tot += $request->request->get('po_aa')[$k];
  8453.                                 }
  8454.                                 if ($tot 0) {
  8455.                                     $id_list_for_check[$ledgerHeads[$i]] = $supplier_by_id['client_advance_head_id'];
  8456.                                     $details_ids[$supplier_by_id['client_advance_head_id']] = Accounts::CreateNewTransactionDetails(
  8457.                                         $this->getDoctrine()->getManager(),
  8458.                                         $request->request->get('date'),
  8459.                                         $TransID,
  8460.                                         Generic::CurrToInt($tot),
  8461.                                         $supplier_by_id['client_advance_head_id'],
  8462.                                         $notes[$i],
  8463.                                         AccountsConstant::CREDIT,
  8464.                                         isset($costCenters[$i]) ? $costCenters[$i] : 0,
  8465.                                         array($pi_list$po_list$ei_list),
  8466.                                         [],
  8467.                                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  8468.                                         $provisional
  8469.                                     );
  8470.                                 }
  8471.                             }
  8472.                             $gt $gt $tot;
  8473.                             Accounts::CreateNewTransactionDetails(
  8474.                                 $this->getDoctrine()->getManager(),
  8475.                                 $request->request->get('date'),
  8476.                                 $TransID,
  8477.                                 Generic::CurrToInt($crAmount[$i] - $gt),
  8478.                                 $ledgerHeads[$i],
  8479.                                 $notes[$i],
  8480.                                 AccountsConstant::CREDIT,
  8481.                                 isset($costCenters[$i]) ? $costCenters[$i] : 0,
  8482.                                 array($pi_list$po_list$ei_list),
  8483.                                 [],
  8484.                                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  8485.                                 $provisional,
  8486.                                 0,
  8487.                                 '_UNSET_',
  8488.                                 $request->request->get('currency')[$i],
  8489.                                 1,
  8490.                                 $request->request->get('currencyMultiplyRate')[$i]
  8491.                             );
  8492.                         } else {
  8493.                             $credit_head $ledgerHeads[$i];
  8494.                             $details_ids[$ledgerHeads[$i]] = Accounts::CreateNewTransactionDetails(
  8495.                                 $this->getDoctrine()->getManager(),
  8496.                                 $request->request->get('date'),
  8497.                                 $TransID,
  8498.                                 Generic::CurrToInt($crAmount[$i]),
  8499.                                 $ledgerHeads[$i],
  8500.                                 $notes[$i],
  8501.                                 AccountsConstant::CREDIT,
  8502.                                 isset($costCenters[$i]) ? $costCenters[$i] : 0,
  8503.                                 array($pi_list$po_list$ei_list),
  8504.                                 [],
  8505.                                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  8506.                                 $provisional,
  8507.                                 0,
  8508.                                 '_UNSET_',
  8509.                                 $request->request->get('currency')[$i],
  8510.                                 1,
  8511.                                 $request->request->get('currencyMultiplyRate')[$i]
  8512.                             );
  8513.                         }
  8514.                     }
  8515.                     //                if(!empty($crAmount[$i]) && $crAmount[$i]!=0){
  8516.                     if (!empty($drAmount[$i]) && $drAmount[$i] != 0) {
  8517.                         $debit_head $ledgerHeads[$i];
  8518.                         $debit_amount Generic::CurrToInt($drAmount[$i]);
  8519.                         $details_ids[$ledgerHeads[$i]] = Accounts::CreateNewTransactionDetails(
  8520.                             $this->getDoctrine()->getManager(),
  8521.                             $request->request->get('date'),
  8522.                             $TransID,
  8523.                             Generic::CurrToInt($drAmount[$i]),
  8524.                             $ledgerHeads[$i],
  8525.                             $notes[$i],
  8526.                             AccountsConstant::DEBIT,
  8527.                             isset($costCenters[$i]) ? $costCenters[$i] : 0,
  8528.                             array($pi_list$po_list$ei_list),
  8529.                             [],
  8530.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  8531.                             $provisional,
  8532.                             0,
  8533.                             '_UNSET_',
  8534.                             $request->request->get('currency')[$i],
  8535.                             1,
  8536.                             $request->request->get('currencyMultiplyRate')[$i]
  8537.                         );
  8538.                     }
  8539.                 }
  8540.                 if ($pr_method == 2) {
  8541.                     //                foreach($request->request->get('check_id') as $k=>$value)
  8542.                     //                {
  8543.                     $check_here = new AccCheck();
  8544.                     $check_here->setRecAccountsHeadId($debit_head);
  8545.                     $check_here->setRecAccountsHeadIdList(json_encode([$debit_head]));
  8546.                     $check_here->setAccountsHeadId($credit_head);
  8547.                     //                    $check_here->setCheckNarration($request->request->get('check_narration')[$k]);
  8548.                     $check_here->setCheckAmount($debit_amount);
  8549.                     $check_here->setCheckDate(new \DateTime($request->request->get('receiptCheckDate')));
  8550.                     $check_here->setTransactionDate(new \DateTime($request->request->get('date')));
  8551.                     //                    $check_here->setCheckDate(new \DateTime($request->request->get('date')));
  8552.                     $check_here->setAssigned(1);
  8553.                     $check_here->setActive(1);
  8554.                     $check_here->setDetails('');
  8555.                     $check_here->setCheckNumber($request->request->get('receiptCheckNo'));
  8556.                     $check_here->setStatus(3);
  8557.                     $check_here->setType(2); //receipt check
  8558.                     $check_here->setVoucherId($TransID);
  8559.                     //                }
  8560.                     $em->persist($check_here);
  8561.                     $em->flush();
  8562.                 }
  8563.                 //approval system
  8564.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  8565.                 $approveRole $request->request->get('approvalRole');
  8566.                 Accounts::UpdateSalesPayments($em$pi_list$po_list$details_ids$request->request->get('date'));
  8567.                 //            Accounts::UpdateExpensePayments($em,$ei_list,$details_ids, $request->request->get('date'));
  8568.                 $options = array(
  8569.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  8570.                     'notification_server' => $this->container->getParameter('notification_server'),
  8571.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  8572.                     'url' => $this->generateUrl(
  8573.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AccTransactions']]['entity_view_route_path_name']
  8574.                     )
  8575.                 );
  8576.                 System::setApprovalInfo(
  8577.                     $this->getDoctrine()->getManager(),
  8578.                     $options,
  8579.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  8580.                     $TransID,
  8581.                     $loginId,
  8582.                     AccountsConstant::VOUCHER_RECEIPT    //Receipt voucher
  8583.                 );
  8584.                 System::createEditSignatureHash(
  8585.                     $em,
  8586.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  8587.                     $TransID,
  8588.                     $loginId,
  8589.                     $approveRole,
  8590.                     $request->request->get('approvalHash')
  8591.                 );
  8592.                 $url $this->generateUrl(
  8593.                     'view_voucher'
  8594.                 );
  8595.                 $trans_here $this->getDoctrine()
  8596.                     ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  8597.                     ->findOneBy(
  8598.                         array(
  8599.                             'transactionId' => $TransID
  8600.                         )
  8601.                     );
  8602.                 System::AddNewNotification(
  8603.                     $this->container->getParameter('notification_enabled'),
  8604.                     $this->container->getParameter('notification_server'),
  8605.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  8606.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  8607.                     "Receipt Voucher : " $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
  8608.                     'pos',
  8609.                     System::getPositionIdsByDepartment($emGeneralConstant::ACCOUNTS_DEPARTMENT),
  8610.                     'success',
  8611.                     $url "/" $TransID,
  8612.                     "Receipt Voucher"
  8613.                 );
  8614.                 if ($request->request->has('returnJson')) {
  8615.                     $doc $trans_here;
  8616.                     return new JsonResponse(array(
  8617.                         'success' => true,
  8618.                         'documentHash' => $trans_here->getDocumentHash(),
  8619.                         'documentId' => $TransID,
  8620.                         'documentIdPadded' => str_pad($TransID8'0'STR_PAD_LEFT),
  8621.                         'documentDate' => $trans_here->getTransactionDate()->format('Y-m-d'),
  8622.                         'documentAmount' => $trans_here->getTransactionAmount(),
  8623.                         'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
  8624.                         'viewUrl' => $url "/" $TransID,
  8625.                         'docPrintMainUrl' => $this->generateUrl('print_voucher'),
  8626.                     ));
  8627.                 } else {
  8628.                     $this->addFlash(
  8629.                         'success',
  8630.                         'New Document Created'
  8631.                     );
  8632.                     return $this->redirect($url "/" $TransID);
  8633.                 }
  8634.             }
  8635.         }
  8636.         $extVoucherData = [];
  8637.         $extVoucherDetailsData = [];
  8638.         if ($voucherId == 0) {
  8639.         } else {
  8640.             $extTrans $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(
  8641.                 array(
  8642.                     'transactionId' => $voucherId///material
  8643.                 )
  8644.             );
  8645.             //now if its not editable, redirect to view
  8646.             if ($extTrans) {
  8647.                 if ($extTrans->getEditFlag() != 1) {
  8648.                     $url $this->generateUrl(
  8649.                         'view_voucher'
  8650.                     );
  8651.                     return $this->redirect($url "/" $voucherId);
  8652.                 } else {
  8653.                     $extVoucherData $extTrans;
  8654.                     $extVoucherDetailsData Accounts::GetVoucherDataForEdit($em$voucherId);
  8655.                 }
  8656.             } else {
  8657.             }
  8658.         }
  8659.         return $this->render(
  8660.             '@Accounts/pages/input_forms/receipt_voucher.html.twig',
  8661.             array(
  8662.                 'page_title' => 'Create Receipt Voucher',
  8663.                 'test' => $details_ids,
  8664.                 'extVoucherData' => $extVoucherData,
  8665.                 'extVoucherDetailsData' => $extVoucherDetailsData,
  8666.                 'client_list' => SalesOrderM::GetClientList($this->getDoctrine()->getManager()),
  8667.                 'client_list_by_ac_head' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  8668.                 'client_list_by_advance_head' => SalesOrderM::GetClientListByAdvanceHead($this->getDoctrine()->getManager())
  8669.             )
  8670.         );
  8671.     }
  8672.     public function CheckFormat(Request $request$id 0)
  8673.     {
  8674.         $data = array(
  8675.             'formatId' => '',
  8676.             'name' => '',
  8677.             'width' => 6,
  8678.             'height' => 2,
  8679.             'checkPayToLeft' => '130px',
  8680.             'checkPayToTop' => '58px',
  8681.             'checkAmountLeft' => '451px',
  8682.             'checkAmountTop' => '88px',
  8683.             'checkAiWLeft' => '131px',
  8684.             'checkAiWTop' => '82px',
  8685.             'checkDateLeft' => '487px',
  8686.             'checkDatePartLeft' => '459px',
  8687.             'checkDateD1Left' => '-49px',
  8688.             'checkDateD2Left' => '-28px',
  8689.             'checkDateM1Left' => '-10px',
  8690.             'checkDateM2Left' => '10px',
  8691.             'checkDateY1Left' => '27px',
  8692.             'checkDateY2Left' => '47px',
  8693.             'checkDateY3Left' => '64px',
  8694.             'checkDateY4Left' => '85px',
  8695.             'checkDateTop' => '34px',
  8696.             'checkDatePartTop' => '31px',
  8697.             'checkImage' => '',
  8698.             'dateDividerDisabled' => 1,
  8699.         );
  8700.         if ($request->isMethod('POST')) {
  8701.             $post $request->request;
  8702.             if ($request->request->get('formatId') != '') {
  8703.                 $query_here $this->getDoctrine()
  8704.                     ->getRepository('ApplicationBundle\\Entity\\CheckFormat')
  8705.                     ->findOneBy(
  8706.                         array(
  8707.                             'formatId' => $request->request->get('formatId')
  8708.                         )
  8709.                     );
  8710.                 if (!empty($query_here))
  8711.                     $new $query_here;
  8712.             } else
  8713.                 $new = new CheckFormat();
  8714.             $new->setName($request->request->get('name'));
  8715.             $new->setWidth($request->request->get('width'));
  8716.             $new->setHeight($request->request->get('height'));
  8717.             $new->setCheckPayToLeft($request->request->get('checkPayToLeft'));
  8718.             $new->setCheckPayToTop($request->request->get('checkPayToTop'));
  8719.             $new->setCheckAmountLeft($request->request->get('checkAmountLeft'));
  8720.             $new->setCheckAmountTop($request->request->get('checkAmountTop'));
  8721.             $new->setCheckAiWLeft($request->request->get('checkAiWLeft'));
  8722.             $new->setCheckAiWTop($request->request->get('checkAiWTop'));
  8723.             $new->setCheckDateLeft($request->request->get('checkDateLeft'));
  8724.             $new->setCheckDateTop($request->request->get('checkDateTop'));
  8725.             $new->setCheckDatePartLeft($request->request->get('checkDatePartLeft'));
  8726.             $new->setCheckDatePartTop($request->request->get('checkDatePartTop'));
  8727.             $new->setCheckDateD1Left($request->request->get('checkDateD1Left'));
  8728.             $new->setCheckDateD2Left($request->request->get('checkDateD2Left'));
  8729.             $new->setCheckDateM1Left($request->request->get('checkDateM1Left'));
  8730.             $new->setCheckDateM2Left($request->request->get('checkDateM2Left'));
  8731.             $new->setCheckDateY1Left($request->request->get('checkDateY1Left'));
  8732.             $new->setCheckDateY2Left($request->request->get('checkDateY2Left'));
  8733.             $new->setCheckDateY3Left($request->request->get('checkDateY3Left'));
  8734.             $new->setCheckDateY4Left($request->request->get('checkDateY4Left'));
  8735.             $new->setDateDividerDisabled($request->request->has('dateDividerDisabled') ? 0);
  8736.             $new->setCheckImage($request->request->get('checkImage'));
  8737.             $em $this->getDoctrine()->getManager();
  8738.             $em->persist($new);
  8739.             $em->flush();
  8740.         }
  8741.         if ($id != 0) {
  8742.             $query_here $this->getDoctrine()
  8743.                 ->getRepository('ApplicationBundle\\Entity\\CheckFormat')
  8744.                 ->findOneBy(
  8745.                     array(
  8746.                         'formatId' => $id
  8747.                     )
  8748.                 );
  8749.             if ($query_here)
  8750.                 $data $query_here;
  8751.         } else if ($request->query->has('formatId')) {
  8752.             $query_here $this->getDoctrine()
  8753.                 ->getRepository('ApplicationBundle\\Entity\\CheckFormat')
  8754.                 ->findOneBy(
  8755.                     array(
  8756.                         'formatId' => $request->query->get('formatId')
  8757.                     )
  8758.                 );
  8759.             if ($query_here)
  8760.                 $data $query_here;
  8761.         }
  8762.         return $this->render(
  8763.             '@Application/pages/accounts/settings/check_format.html.twig',
  8764.             array(
  8765.                 'page_title' => 'Cheque Format',
  8766.                 'data' => $data,
  8767.                 'formatList' => $this->getDoctrine()
  8768.                     ->getRepository('ApplicationBundle\\Entity\\CheckFormat')
  8769.                     ->findBy(
  8770.                         array( //                            'formatId' => $request->query->get('formatId')
  8771.                         )
  8772.                     )
  8773.                 //                'incomeLedgerHeads'=>Accounts::getChildLedgerHeads($this->getDoctrine()->getManager(),AccountsConstant::INCOME)
  8774.             )
  8775.         );
  8776.     }
  8777.     public function PrintCheck(Request $request$id)
  8778.     {
  8779.         $data = array(
  8780.             'formatId' => '',
  8781.             'name' => '',
  8782.             'width' => 6,
  8783.             'height' => 2,
  8784.             'checkPayToLeft' => '130px',
  8785.             'checkPayToTop' => '58px',
  8786.             'checkAmountLeft' => '451px',
  8787.             'checkAmountTop' => '88px',
  8788.             'checkAiWLeft' => '131px',
  8789.             'checkAiWTop' => '82px',
  8790.             'checkDateLeft' => '487px',
  8791.             'checkDatePartLeft' => '459px',
  8792.             'checkDateD1Left' => '-49px',
  8793.             'checkDateD2Left' => '-28px',
  8794.             'checkDateM1Left' => '-10px',
  8795.             'checkDateM2Left' => '10px',
  8796.             'checkDateY1Left' => '27px',
  8797.             'checkDateY2Left' => '47px',
  8798.             'checkDateY3Left' => '64px',
  8799.             'checkDateY4Left' => '85px',
  8800.             'checkDateTop' => '34px',
  8801.             'checkDatePartTop' => '31px',
  8802.             'checkImage' => '',
  8803.             'marginTopAdd' => '0',
  8804.             'dateDividerDisabled' => 1
  8805.         );
  8806.         $print_ac_payee_tag 0;
  8807.         if ($request->query->has('print_ac_payee_tag'))
  8808.             if ($request->query->get('print_ac_payee_tag') == 1)
  8809.                 $print_ac_payee_tag $request->query->get('print_ac_payee_tag');
  8810.         //first get check data
  8811.         $check_query $this->getDoctrine()
  8812.             ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  8813.             ->findOneBy(
  8814.                 array(
  8815.                     'CheckId' => $id
  8816.                 )
  8817.             );
  8818.         //now get the format data
  8819.         if (!empty($check_query))
  8820.             $query_here $this->getDoctrine()
  8821.                 ->getRepository('ApplicationBundle\\Entity\\CheckFormat')
  8822.                 ->findOneBy(
  8823.                     array(
  8824.                         'formatId' => $check_query->getFormatId()
  8825.                     )
  8826.                 );
  8827.         if (!empty($query_here))
  8828.             $data $query_here;
  8829.         $inv_parts explode('.'number_format($check_query->getCheckAmount(), 2'.'''));
  8830.         return $this->render(
  8831.             '@Accounts/pages/print/print_check.html.twig',
  8832.             array(
  8833.                 'page_title' => 'Print Check',
  8834.                 'red' => 0,
  8835.                 'data' => $data,
  8836.                 'print_ac_payee_tag' => $print_ac_payee_tag,
  8837.                 'check_data' => $check_query,
  8838.                 'amount_in_word_integer' => Accounts::ConvertNumberToWords($inv_parts[0]),
  8839.                 'amount_in_word_dec' => Accounts::ConvertNumberToWords((isset($inv_parts[1])) ? $inv_parts[1] * 0),
  8840.             )
  8841.         );
  8842.     }
  8843.     public function MarkCheckPrinted(Request $request$id)
  8844.     {
  8845.         //first get check data
  8846.         $check_query $this->getDoctrine()
  8847.             ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  8848.             ->findOneBy(
  8849.                 array(
  8850.                     'CheckId' => $id
  8851.                 )
  8852.             );
  8853.         $check_query->setPrinted(1);
  8854.         $em $this->getDoctrine()->getManager();
  8855.         $em->flush();
  8856.         return 1;
  8857.     }
  8858.     public function RemoveFile(Request $request)
  8859.     {
  8860.         $em_goc $this->getDoctrine()->getManager('company_group');
  8861.         $EntityFileId 0;
  8862.         $relId 0;
  8863.         MiscActions::RemoveExpiredFiles($em_goc);
  8864.         if ($request->isMethod('POST')) {
  8865.             $post $request->request;
  8866.             $relId $post->get('relId');
  8867.             $afterRemoveConfig $post->get('afterRemoveConfig', []);
  8868.             if ($post->get('path''') != '') {
  8869.                 MiscActions::RemoveFileByPath($em_goc$post->get('path'''), $afterRemoveConfig);
  8870.                 return new JsonResponse(array(
  8871.                     "success" => true,
  8872.                     "relId" => $relId,
  8873.                 ));
  8874.             } else if ($post->get('conditionOptions', []) != []) {
  8875.                 MiscActions::RemoveFileByCondition($em_goc$post->get('conditionOptions', []));
  8876.                 return new JsonResponse(array(
  8877.                     "success" => true,
  8878.                     "relId" => $relId,
  8879.                 ));
  8880.             } else if ($post->get('fileId'0) != 0) {
  8881.                 MiscActions::RemoveFileById($em_goc$post->get('fileId'0), $afterRemoveConfig);
  8882.                 return new JsonResponse(array(
  8883.                     "success" => true,
  8884.                     "relId" => $relId,
  8885.                 ));
  8886.             }
  8887.         }
  8888.         return new JsonResponse(array(
  8889.             "success" => false,
  8890.             "relId" => $relId,
  8891.         ));
  8892.     }
  8893.     public function FileUpload(Request $request)
  8894.     {
  8895.         $em_goc $this->getDoctrine()->getManager('company_group');
  8896.         $em $this->getDoctrine()->getManager();
  8897.         $EntityFileId 0;
  8898.         $file_path_list = [];
  8899.         $uploadErrorMessage '';
  8900.         if ($request->isMethod('POST')) {
  8901.             $post_data $request->request;
  8902.             if ($request->request->get('clearExistingFilesForThisDoc'0) == 1) {
  8903.                 MiscActions::RemoveFilesForEntityDoc($em_goc$request->request->get('entityName'''), $request->request->get('entityId'0));
  8904.             }
  8905.             if ($post_data->has('isBase64') || $post_data->has('imageBase64')) {
  8906.                 $imageBase64 $post_data->get('imageBase64');
  8907.                 $data base64_decode(preg_replace('#^data:image/\w+;base64,#i'''$imageBase64));
  8908.                 $fileName md5(uniqid()) . '.png';
  8909.                 if ($request->request->has('buddybee_profile_image_flag'))
  8910.                     $storePath 'uploads/applicants/';
  8911.                 if ($request->request->has('central_profile_image_flag'))
  8912.                     $storePath 'uploads/UserImage/';
  8913.                 if ($request->request->has('expense_invoice_attachment'))
  8914.                     $storePath 'uploads/ExpenseInvoice/';
  8915.                 if ($request->request->has('voucher_attachment'))
  8916.                     $storePath 'uploads/Voucher/';
  8917.                 if ($request->request->has('leave_attachment'))
  8918.                     $storePath 'uploads/LeaveDoc/';
  8919.                 if ($request->request->has('sales_invoice_attachment'))
  8920.                     $storePath 'uploads/SalesInvoice/';
  8921.                 if ($request->request->has('purchase_invoice_attachment'))
  8922.                     $storePath 'uploads/PurchaseInvoice/';
  8923.                 if ($request->request->has('po_attachment'))
  8924.                     $storePath 'uploads/PurchaseOrder/';
  8925.                 if ($request->request->has('so_attachment'))
  8926.                     $storePath 'uploads/SalesOrder/';
  8927.                 if ($request->request->has('product_mrp_attachment'))
  8928.                     $storePath 'uploads/PriceDoc/';
  8929.                 if ($request->request->has('pr_attachment'))
  8930.                     $storePath 'uploads/PurchaseRequisition/';
  8931.                 if ($request->request->has('so_amendment_attachment'))
  8932.                     $storePath 'uploads/SoAmendment/';
  8933.                 if ($request->request->has('fund_requisition_attachment'))
  8934.                     $storePath 'uploads/FundRequisition/';
  8935.                 if ($request->request->has('delivery_order_attachment'))
  8936.                     $storePath 'uploads/DeliveryOrder/';
  8937.                 if ($request->request->has('proforma_invoice_attachment'))
  8938.                     $storePath 'uploads/ProformaInvoice/';
  8939.                 if ($request->request->has('insurance_pay_request_attachment'))
  8940.                     $storePath 'uploads/InsurancePayRequest/';
  8941.                 if ($request->request->has('grn_attachment'))
  8942.                     $storePath 'uploads/Grn/';
  8943.                 if ($request->request->has('service_challan_attachment'))
  8944.                     $storePath 'uploads/ServiceChallan/';
  8945.                 if ($request->request->has('stock_requisition_attachment'))
  8946.                     $storePath 'uploads/StockRequisition/';
  8947.                 if ($request->request->has('store_requisition_attachment'))
  8948.                     $storePath 'uploads/StoreRequisition/';
  8949.                 if ($request->request->has('stock_transfer_attachment'))
  8950.                     $storePath 'uploads/StockTransfer/';
  8951.                 if ($request->request->has('stock_received_note_attachment'))
  8952.                     $storePath 'uploads/StockReceivedNote/';
  8953.                 if ($request->request->has('delivery_receipt_attachment'))
  8954.                     $storePath 'uploads/DeliveryReceipt/';
  8955.                 if ($request->request->has('item_received_and_replacement_attachment'))
  8956.                     $storePath 'uploads/ItemReceivedAndReplacement/';
  8957.                 if ($request->request->has('stock_consumption_note_attachment'))
  8958.                     $storePath 'uploads/StockConsumptionNote/';
  8959.                 if ($request->request->has('general_attachment'))
  8960.                     $storePath 'uploads/General/';
  8961.                 if ($request->request->has('product_datasheets_attachment'))
  8962.                     $storePath 'uploads/Product/Datasheets/';
  8963.                 if ($request->request->has('sales_proposal_cover_attachment'))
  8964.                     $storePath 'uploads/SalesProposal/';
  8965.                 $path "";
  8966.                 $file_path "";
  8967.                 $session $request->getSession();
  8968.                 MiscActions::RemoveExpiredFiles($em_goc);
  8969.                 $path $fileName;
  8970.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  8971.                 if (!file_exists($upl_dir)) {
  8972.                     mkdir($upl_dir0777true);
  8973.                 }
  8974.                 if (file_exists($upl_dir '' $path)) {
  8975.                     chmod($upl_dir '' $path0755);
  8976.                     unlink($upl_dir '' $path);
  8977.                 }
  8978.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ExpenseInvoice/' $path;
  8979.                 file_put_contents($upl_dir$data);
  8980.                 if ($path != "")
  8981.                     $file_path_list[] = ($storePath $path);
  8982.                 $g_path $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path;
  8983.             } else {
  8984.                 $storePath $request->request->get('storePath''uploads/FileUploads/');
  8985.                 if ($request->request->has('buddybee_profile_image_flag'))
  8986.                     $storePath 'uploads/applicants/';
  8987.                 if ($request->request->has('central_profile_image_flag'))
  8988.                     $storePath 'uploads/UserImage/';
  8989.                 if ($request->request->has('expense_invoice_attachment'))
  8990.                     $storePath 'uploads/ExpenseInvoice/';
  8991.                 if ($request->request->has('voucher_attachment'))
  8992.                     $storePath 'uploads/Voucher/';
  8993.                 if ($request->request->has('leave_attachment'))
  8994.                     $storePath 'uploads/LeaveDoc/';
  8995.                 if ($request->request->has('sales_invoice_attachment'))
  8996.                     $storePath 'uploads/SalesInvoice/';
  8997.                 if ($request->request->has('po_attachment'))
  8998.                     $storePath 'uploads/PurchaseOrder/';
  8999.                 if ($request->request->has('so_attachment'))
  9000.                     $storePath 'uploads/SalesOrder/';
  9001.                 if ($request->request->has('product_mrp_attachment'))
  9002.                     $storePath 'uploads/PriceDoc/';
  9003.                 if ($request->request->has('pr_attachment'))
  9004.                     $storePath 'uploads/PurchaseRequisition/';
  9005.                 if ($request->request->has('purchase_invoice_attachment'))
  9006.                     $storePath 'uploads/PurchaseInvoice/';
  9007.                 if ($request->request->has('so_amendment_attachment'))
  9008.                     $storePath 'uploads/SoAmendment/';
  9009.                 if ($request->request->has('fund_requisition_attachment'))
  9010.                     $storePath 'uploads/FundRequisition/';
  9011.                 if ($request->request->has('delivery_order_attachment'))
  9012.                     $storePath 'uploads/DeliveryOrder/';
  9013.                 if ($request->request->has('proforma_invoice_attachment'))
  9014.                     $storePath 'uploads/ProformaInvoice/';
  9015.                 if ($request->request->has('insurance_pay_request_attachment'))
  9016.                     $storePath 'uploads/InsurancePayRequest/';
  9017.                 if ($request->request->has('grn_attachment'))
  9018.                     $storePath 'uploads/Grn/';
  9019.                 if ($request->request->has('service_challan_attachment'))
  9020.                     $storePath 'uploads/ServiceChallan/';
  9021.                 if ($request->request->has('stock_requisition_attachment'))
  9022.                     $storePath 'uploads/StockRequisition/';
  9023.                 if ($request->request->has('store_requisition_attachment'))
  9024.                     $storePath 'uploads/StoreRequisition/';
  9025.                 if ($request->request->has('stock_transfer_attachment'))
  9026.                     $storePath 'uploads/StockTransfer/';
  9027.                 if ($request->request->has('stock_received_note_attachment'))
  9028.                     $storePath 'uploads/StockReceivedNote/';
  9029.                 if ($request->request->has('delivery_receipt_attachment'))
  9030.                     $storePath 'uploads/DeliveryReceipt/';
  9031.                 if ($request->request->has('item_received_and_replacement_attachment'))
  9032.                     $storePath 'uploads/ItemReceivedAndReplacement/';
  9033.                 if ($request->request->has('stock_consumption_note_attachment'))
  9034.                     $storePath 'uploads/StockConsumptionNote/';
  9035.                 if ($request->request->has('general_attachment'))
  9036.                     $storePath 'uploads/General/';
  9037.                 if ($request->request->has('product_datasheets_attachment'))
  9038.                     $storePath 'uploads/Product/Datasheets/';
  9039.                 if ($request->request->has('sales_proposal_cover_attachment'))
  9040.                     $storePath 'uploads/SalesProposal/';
  9041.                 $path "";
  9042.                 $file_path "";
  9043.                 $session $request->getSession();
  9044.                 MiscActions::RemoveExpiredFiles($em_goc);
  9045.                 foreach ($request->files as $uploadedFileGG) {
  9046.                     //            if($uploadedFile->getImage())
  9047.                     //                var_dump($uploadedFile->getFile());
  9048.                     //                var_dump($uploadedFile);
  9049.                     $tempD $uploadedFileGG;
  9050.                     if (!is_array($uploadedFileGG)) {
  9051.                         $uploadedFileGG = array();
  9052.                         $uploadedFileGG[] = $tempD;
  9053.                     }
  9054.                     foreach ($uploadedFileGG as $uploadedFile) {
  9055.                         // Skip files PHP rejected before they reached us (over
  9056.                         // upload_max_filesize, partial upload, no temp file). Such an
  9057.                         // UploadedFile is non-null but has an empty pathname, so guessExtension()
  9058.                         // / getMimeType() fatals with 'The "" file does not exist or is not
  9059.                         // readable.' Record the reason so the client gets an actionable message.
  9060.                         if ($uploadedFile != null && !$uploadedFile->isValid()) {
  9061.                             $errCode method_exists($uploadedFile'getError') ? $uploadedFile->getError() : UPLOAD_ERR_NO_FILE;
  9062.                             if ($errCode === UPLOAD_ERR_INI_SIZE || $errCode === UPLOAD_ERR_FORM_SIZE) {
  9063.                                 $uploadErrorMessage 'The file is too large to upload (server limit: ' ini_get('upload_max_filesize') . ').';
  9064.                             } else {
  9065.                                 $uploadErrorMessage 'The file could not be uploaded.';
  9066.                             }
  9067.                             continue;
  9068.                         }
  9069.                         if ($uploadedFile != null
  9070.                             && $uploadedFile->getPathname() !== ''
  9071.                             && is_file($uploadedFile->getPathname())) {
  9072.                             $extension $uploadedFile->guessExtension();
  9073.                             $size $uploadedFile->getSize();
  9074.                             $fileName md5(uniqid()) . '.' $uploadedFile->guessExtension();
  9075.                             $path $fileName;
  9076.                             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  9077.                             if (!file_exists($upl_dir)) {
  9078.                                 mkdir($upl_dir0777true);
  9079.                             }
  9080.                             if (file_exists($upl_dir '' $path)) {
  9081.                                 chmod($upl_dir '' $path0755);
  9082.                                 unlink($upl_dir '' $path);
  9083.                             }
  9084.                             $file $uploadedFile->move($upl_dir$path);
  9085.                             $expireTs $request->request->get('expireTs'0);
  9086.                             $expireNever $request->request->get('expireNever'0);
  9087.                             if ($expireNever == 1) {
  9088.                                 $expireTs 0;
  9089.                             } else {
  9090.                                 if ($expireTs == 0) {
  9091.                                     if ($request->request->get('expiryDays'0) != 0) {
  9092.                                         $currDate = new \DateTime();
  9093.                                         $currDate->modify('+' $request->request->get('expiryDays'0) . ' day');
  9094.                                         $expireTs $currDate->format('U');
  9095.                                     } else if ($request->request->get('expiryDate''') != '') {
  9096.                                         $currDate = new \DateTime($request->request->get('expiryDate'''));
  9097.                                         $currDate->modify('+14 day');
  9098.                                         $expireTs $currDate->format('U');
  9099.                                     } else {
  9100.                                         $currDate = new \DateTime();
  9101.                                         $currDate->modify('+720 day');
  9102.                                         $expireTs $currDate->format('U');
  9103.                                     }
  9104.                                 }
  9105.                             }
  9106.                             // Keep the filename the user actually uploaded, in the TENANT.
  9107.                             // The md5 rename above destroys it and neither the document's
  9108.                             // CSV column nor the central EntityFile row preserves it, so
  9109.                             // without this an annexure/attachment list can only show the
  9110.                             // md5. Additive metadata: never fatal to the upload itself.
  9111.                             try {
  9112.                                 $originalName trim((string) $uploadedFile->getClientOriginalName());
  9113.                                 if ($originalName !== '') {
  9114.                                     $attachMeta = new DocumentAttachmentMeta();
  9115.                                     $attachMeta->setRelativePath($storePath $path);
  9116.                                     $attachMeta->setOriginalName(mb_substr($originalName0255));
  9117.                                     $attachMeta->setEntityName($request->request->get('entityName'''));
  9118.                                     $attachMeta->setEntityId((int) $request->request->get('entityId'0));
  9119.                                     $attachMeta->setMarker($request->request->get('markerHash''_GEN_'));
  9120.                                     $attachMeta->setSizeBytes((int) $size);
  9121.                                     $attachMeta->setExtension($extension);
  9122.                                     $attachMeta->setUploadedByUserId((int) $request->getSession()->get(UserConstants::USER_ID0));
  9123.                                     $attachMeta->setUploadedTs(time());
  9124.                                     $attachMeta->setAppId((int) $request->getSession()->get(UserConstants::USER_APP_ID0));
  9125.                                     $em->persist($attachMeta);
  9126.                                     $em->flush();
  9127.                                 }
  9128.                             } catch (\Throwable $e) {
  9129.                                 // metadata is a nicety - an upload must still succeed
  9130.                             }
  9131.                             $EntityFile = new EntityFile();
  9132.                             $EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path);
  9133.                             $EntityFile->setMarker($request->request->get('markerHash''_GEN_'));
  9134.                             $EntityFile->setName($path);
  9135.                             $EntityFile->setExtension($extension);
  9136.                             $EntityFile->setExpireTs($expireTs);
  9137.                             $EntityFile->setSize($size);
  9138.                             $EntityFile->setRelativePath($storePath $path);
  9139.                             $EntityFile->setEntityName($request->request->get('entityName'''));
  9140.                             $EntityFile->setEntityBundle($request->request->get('entityBundle''CompanyGroupBundle'));
  9141.                             $EntityFile->setEntityId($request->request->get('entityId'0));
  9142.                             $EntityFile->setEntityIdField($request->request->get('entityIdField'''));
  9143.                             $EntityFile->setModifyFieldSetter($request->request->get('modifyFieldSetter'''));
  9144.                             $EntityFile->setDocIdForApplicant($request->request->get('docId'0));
  9145.                             $EntityFile->setUserId($session->get(UserConstants::USER_ID0));
  9146.                             $EntityFile->setAppId($session->get(UserConstants::USER_APP_ID0));
  9147.                             $EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID0));
  9148.                             $EntityFile->setUserType($session->get(UserConstants::USER_TYPE0));
  9149.                             $em_goc->persist($EntityFile);
  9150.                             $em_goc->flush();
  9151.                             $EntityFileId $EntityFile->getId();
  9152.                         }
  9153.                         if ($path != "")
  9154.                             $file_path_list[] = ($storePath $path);
  9155.                     }
  9156.                 }
  9157.                 $g_path $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path;
  9158.             }
  9159.             $baseUrl $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  9160.             //            $img_file = file_get_contents($g_path);
  9161.             //            $r = base64_encode($img_file);
  9162.             //            $url = url('dashboard');
  9163.             // Nothing stored but PHP flagged a rejected upload → report it as a failure so the
  9164.             // client can show why (e.g. file too large) instead of silently "succeeding" empty.
  9165.             if (empty($file_path_list) && $uploadErrorMessage !== '') {
  9166.                 return new JsonResponse(array(
  9167.                     "success" => false,
  9168.                     "file_path" => '',
  9169.                     "message" => $uploadErrorMessage,
  9170.                     "refId" => $request->request->get('refId'0),
  9171.                     "rowId" => $request->request->get('rowId'0),
  9172.                 ), 422);
  9173.             }
  9174.             return new JsonResponse(array(
  9175.                 "success" => true,
  9176.                 "file_path" => implode(','$file_path_list),
  9177.                 "file_url" => $baseUrl implode(',' $baseUrl$file_path_list),
  9178.                 "fileId" => $EntityFileId,
  9179.                 "refId" => $request->request->get('refId'0),
  9180.                 "rowId" => $request->request->get('rowId'0),
  9181.                 //                "r"=>$r,
  9182.                 //                "debug_data"=>System::encryptSignature($r)
  9183.             ));
  9184.         }
  9185.         return new JsonResponse(array(
  9186.             "success" => false,
  9187.             "file_path" => '',
  9188.             "refId" => $request->request->get('refId'0),
  9189.             "rowId" => $request->request->get('rowId'0),
  9190.         ));
  9191.     }
  9192.     public function BankReconExcelUpload(Request $request)
  9193.     {
  9194.         if ($request->isMethod('POST')) {
  9195.             $post $request->request;
  9196.             $path "";
  9197.             $file_path "";
  9198.             //            var_dump($request->files);
  9199.             //        var_dump($request->getFile());
  9200.             foreach ($request->files as $uploadedFile) {
  9201.                 //            if($uploadedFile->getImage())
  9202.                 //                var_dump($uploadedFile->getFile());
  9203.                 //                var_dump($uploadedFile);
  9204.                 if ($uploadedFile != null) {
  9205.                     $fileName md5(uniqid()) . '.' $uploadedFile->guessExtension();
  9206.                     $path $fileName;
  9207.                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/';
  9208.                     if (!file_exists($upl_dir)) {
  9209.                         mkdir($upl_dir0777true);
  9210.                     }
  9211.                     $file $uploadedFile->move($upl_dir$path);
  9212.                 }
  9213.             }
  9214.             //        print_r($file);
  9215.             if ($path != "")
  9216.                 $file_path 'uploads/FileUploads/' $path;
  9217.             $g_path $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' $path;
  9218.             //
  9219.             //            $img_file = file_get_contents($g_path);
  9220.             //            $r=base64_encode($img_file);
  9221.             $row 1;
  9222.             $csv_data = [];
  9223.             if (($handle fopen($g_path"r")) !== FALSE) {
  9224.                 while (($data fgetcsv($handle1000",")) !== FALSE) {
  9225.                     $num count($data);
  9226.                     $csv_data[$row] = $data;
  9227.                     //                    echo "<p> $num fields in line $row: <br /></p>\n";
  9228.                     $row++;
  9229.                     //                    for ($c=0; $c < $num; $c++) {
  9230.                     //                        echo $data[$c] . "<br />\n";
  9231.                     //                    }
  9232.                 }
  9233.                 fclose($handle);
  9234.             }
  9235.             //now getting the relevant checks
  9236.             $check_list = [];
  9237.             foreach ($csv_data as $data_row) {
  9238.                 $get_kids_sql "SELECT acc_check.*,
  9239.                   DATE_FORMAT(acc_transactions.transaction_date, '%b %d,%Y') trans_date,
  9240.                   DATE_FORMAT(acc_check.check_date, '%b %d,%Y') chk_date,
  9241.                   acc_transactions.document_hash FROM acc_check
  9242.                                 JOIN acc_transactions on acc_check.voucher_id= acc_transactions.transaction_id
  9243.                                 WHERE acc_check.check_number like '$data_row[0]' LIMIT 1";
  9244.                 //                $get_kids_sql .=' ORDER BY name ASC';
  9245.                 $stmt $this->getDoctrine()->getConnection()->fetchAllAssociative($get_kids_sql);
  9246.                 
  9247.                 $check_here $stmt;
  9248.                 if ($check_here) {
  9249.                     //                    $transdate = strtotime( $check_here['transaction_date'] );
  9250.                     //                    $checkdate = strtotime( $check_here['check_date'] );
  9251.                     $recondate strtotime($data_row[1]);
  9252.                     $recondatestr date('F d,Y'$recondate);
  9253.                     $new_check_data = array(
  9254.                         'checkId' => $check_here[0]['check_id'],
  9255.                         'checkNumber' => $check_here[0]['check_number'],
  9256.                         'voucherId' => $check_here[0]['voucher_id'],
  9257.                         'voucherNumber' => $check_here[0]['document_hash'],
  9258.                         'checkDate' => $check_here[0]['chk_date'],
  9259.                         'transactionDate' => $check_here[0]['trans_date'],
  9260.                         'reconDate' => $recondatestr,
  9261.                     );
  9262.                     $check_list[] = $new_check_data;
  9263.                 }
  9264.             }
  9265.             return new JsonResponse(array(
  9266.                 "success" => true,
  9267.                 "file_path" => $file_path,
  9268.                 "csv_data" => $csv_data,
  9269.                 "check_data" => $check_list,
  9270.                 //                "debug_data"=>System::encryptSignature($r)
  9271.             ));
  9272.         }
  9273.         return new JsonResponse(array(
  9274.             "success" => false,
  9275.             "file_path" => '',
  9276.         ));
  9277.     }
  9278.     public function AddExpense(Request $request)
  9279.     {
  9280.         $details_ids = [];
  9281.         $em $this->getDoctrine()->getManager();
  9282.         $em_goc $this->getDoctrine()->getManager('company_group');
  9283.         $expenseSubTypes GeneralConstant::$expenseSubTypes;
  9284.         if ($request->isMethod('POST')) {
  9285.             $em $this->getDoctrine()->getManager();
  9286.             $entity_id array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
  9287.             $dochash $request->request->get('voucherNumber'); //change
  9288.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  9289.             $approveRole $request->request->get('approvalRole');
  9290.             $approveHash $request->request->get('approvalHash');
  9291.             if (!DocValidation::isSignatureOk($em$loginId$approveHash)) {
  9292.                 //                $this->addFlash(
  9293.                 //                    'error',
  9294.                 //                    'Sorry Could Not insert Data.'
  9295.                 //                );
  9296.                 return new JsonResponse(array(
  9297.                     "success" => false,
  9298.                     'errorText' => 'Approval Hash Mismatch',
  9299.                     'errorStr' => 'Approval Hash Mismatch'
  9300.                 ));
  9301.             } else {
  9302.                 $new_ei = [];
  9303.                 $expenseDataList = array();
  9304.                 $primaryInvoiceId 0;
  9305.                 $hasChildInvoice 0;
  9306.                 $primaryInvoiceData = [];
  9307.                 $expense_data $request->request->get('expenseData', []);
  9308.                 $exp_distribution_poitemId $request->request->get('exp_distribution_poitemId', []);
  9309.                 $exp_distribution_amount $request->request->get('exp_distribution_amount', []);
  9310.                 $costDistributionData = [];
  9311.                 foreach ($exp_distribution_poitemId as $key => $value) {
  9312.                     $costDistributionData[$value] = array(
  9313.                         'poItemId' => $value,
  9314.                         'amount' => $exp_distribution_amount[$key],
  9315.                     );
  9316.                 }
  9317.                 $expense_type $request->request->get('expense_type'0);
  9318.                 if (is_string($expense_data)) $expense_data json_decode($expense_datatrue);
  9319.                 if (!empty($expense_data)) {
  9320.                     //multiple invoices so add childs and parent
  9321.                     if (count($expense_data) > 1$hasChildInvoice 1;
  9322.                     if ($hasChildInvoice == 1)
  9323.                         $expenseDataList[] = array(
  9324.                             "expenseType" => 4//primary
  9325.                             "expenseSubType" => 0,
  9326.                             "expenseId" => 0,
  9327.                             "ccId" => 0,
  9328.                             "currencyId" => 0,
  9329.                             "currencyMultiply" => 1,
  9330.                             "currencyMultiplyRate" => 1,
  9331.                             "docId" => 0,
  9332.                             "expenseToBePaidTo" => 0,
  9333.                             "expenseFrom" => 0,
  9334.                             "expenseFromNote" => '',
  9335.                             "expenseTo" => 0,
  9336.                             "expenseToNote" => 0,
  9337.                             "expenseAmount" => 0,
  9338.                             "previousAdvanceAmount" => 0,
  9339.                             "checkDate" => '',
  9340.                             "checkNumber" => '',
  9341.                             "checkNarration" => '',
  9342.                             "checkId" => 0,
  9343.                             "description" => '',
  9344.                             "expenseMarkerHash" => '',
  9345.                             "expenseDate" => $expense_data[0]['expenseDate'],
  9346.                             "invoiceBalancing" => 0,
  9347.                             "attachedFile" => [],
  9348.                             "uploadedFile" => '',
  9349.                             'expenseInvocationStrategyOnGrn' => null,
  9350.                             'expenseInvocationTypeOnItems' => null,
  9351.                             "isChildInvoice" => 0,
  9352.                             "costDistributionData" => $costDistributionData,
  9353.                         );
  9354.                     $currTime = new \DateTime();
  9355.                     $currTs $currTime->format('U');
  9356.                     foreach ($expense_data as $key => $expData) {
  9357.                         if (isset($expData['imageBase64'])) {
  9358.                             $imageBase64 $expData['imageBase64'];
  9359.                             $data base64_decode(preg_replace('#^data:image/\w+;base64,#i'''$imageBase64));
  9360.                             $fileName $currTs . (md5(uniqid())) . '.png';
  9361.                             $storePath 'uploads/ExpenseInvoice/';
  9362.                             $path "";
  9363.                             $file_path "";
  9364.                             $session $request->getSession();
  9365.                             MiscActions::RemoveExpiredFiles($em_goc);
  9366.                             $path $fileName;
  9367.                             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  9368.                             if (!file_exists($upl_dir)) {
  9369.                                 mkdir($upl_dir0777true);
  9370.                             }
  9371.                             if (file_exists($upl_dir '' $path)) {
  9372.                                 chmod($upl_dir '' $path0755);
  9373.                                 unlink($upl_dir '' $path);
  9374.                             }
  9375.                             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ExpenseInvoice/' $path;
  9376.                             file_put_contents($upl_dir$data);
  9377.                             if ($path != "")
  9378.                                 $file_path $storePath $path;
  9379.                             $expense_data[$key]['uploadedFile'] = $file_path;
  9380.                         }
  9381.                         if (!isset($expData['attachedFile'])) {
  9382.                             $expense_data[$key]['attachedFile'] = [];
  9383.                         }
  9384.                         $expense_data[$key]['isChildInvoice'] = $hasChildInvoice == 0;
  9385.                         $expenseDataList[] = $expense_data[$key];
  9386.                     }
  9387.                 } else {
  9388.                     $expense_type $request->request->get('expense_type'0);
  9389.                     $expenseDataList[] = array(
  9390.                         "expenseType" => $expense_type,
  9391.                         "currencyId" => $request->request->get('expense_currency_id'0),
  9392.                         "currencyMultiply" => $request->request->get('expense_currency_multiply'1),
  9393.                         "currencyMultiplyRate" => $request->request->get('expense_currency_multiply_rate'1),
  9394.                         "expenseSubType" => $request->request->get('expense_sub_type'0),
  9395.                         "expenseId" => $request->request->get('expense_id'0),
  9396.                         "ccId" => $request->request->get('ccId'0),
  9397.                         "docId" => $expense_type == $request->request->get('poId')
  9398.                             : ($expense_type == $request->request->get('soId')
  9399.                                 : ($expense_type == $request->request->get('opportunityId'$request->request->get('leadId'))
  9400.                                     : ($expense_type == $request->request->get('tour_id') : 0))),
  9401.                         "directProjectId" => $request->request->get('directProjectId'0),
  9402.                         "expenseToBePaidTo" => $request->request->get('expense_to_be_paid_to'0),
  9403.                         "expenseFrom" => $request->request->get('expense_from'0),
  9404.                         "checkDate" => $request->request->get('check_date'''),
  9405.                         "checkNumber" => $request->request->get('check_number'''),
  9406.                         "checkNarration" => $request->request->get('check_narration'''),
  9407.                         "checkId" => $request->request->get('check_id'0),
  9408.                         "expenseFromNote" => $request->request->get('expense_from_note'''),
  9409.                         "expenseTo" => $request->request->get('expense_to_' $expense_type0),
  9410.                         "expenseToNote" => $request->request->get('expense_to_note_' $expense_type''),
  9411.                         "expenseAmount" => $request->request->get('expense_amount'''),
  9412.                         "previousAdvanceAmount" => $request->request->get('prev_advance_amount'0),
  9413.                         "description" => $request->request->get('description'''),
  9414.                         "expenseMarkerHash" => $request->request->get('markerHash'''),
  9415.                         "expenseDate" => $request->request->get('expense_date'),
  9416.                         'expenseInvocationStrategyOnGrn' => $request->request->get('expenseInvocationStrategyOnGrn'null),
  9417.                         'expenseInvocationTypeOnItems' => $request->request->get('expenseInvocationTypeOnItems'null),
  9418.                         "invoiceBalancing" => $request->request->has('auto_balance' $expense_type) ? $request->request->get('auto_balance' $expense_type) : 0,
  9419.                         "attachedFile" => $request->files->get('file', []),
  9420.                         "expenseSubCategory" => $request->request->get('expense_sub_category'0),
  9421.                         "expenseSubCategoryOption" => $request->request->get('expense_sub_category_option'0),
  9422.                         "uploadedFile" => $request->request->get('uploadedFile'''),
  9423.                         "expenseDistributionOnProduct" => $request->request->get('exp_check_expense_distribution_on_product'0),
  9424.                         "isChildInvoice" => 0,
  9425.                         "costDistributionData" => $costDistributionData,
  9426.                     );
  9427.                 }
  9428.                 ///SIngle one
  9429.                 ///
  9430.                 //                 System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($expenseDataList),'test_mult_exp');
  9431.                 foreach ($expenseDataList as $expData) {
  9432.                     //            Generic::debugMessage($_POST);
  9433.                     $new_ei = [];
  9434.                     $em $this->getDoctrine()->getManager();
  9435.                     //            $to_assign=0;
  9436.                     if ($expData['expenseType'] == 4) {   ////// primary Invoice
  9437.                         $expBillType 4;
  9438.                         $data = array(
  9439.                             'doc_id' => $expData['docId'],
  9440.                             'expense_id' => $expData['expenseId'],
  9441.                             'party_id' => '',
  9442.                             'party_head_id' => $expData['expenseToBePaidTo'],
  9443.                             'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
  9444.                             'invoice_amount' => $expData['expenseAmount'],
  9445.                             'description' => $expData['description'],
  9446.                             'expense_to_note' => $expData['expenseToNote'],
  9447.                             'expense_from_note' => $expData['expenseFromNote'],
  9448.                             "currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
  9449.                             "currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
  9450.                             "currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
  9451.                             'date' => $expData['expenseDate'],
  9452.                             'file' => $expData['attachedFile'],
  9453.                             'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
  9454.                             'expense_from' => $expData['expenseFrom'],
  9455.                             'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
  9456.                             'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
  9457.                             'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
  9458.                             'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
  9459.                         );
  9460.                         if ($request->request->has('latitude')) {
  9461.                             $data['latitude'] = $request->request->get('latitude');
  9462.                             $data['longitude'] = $request->request->get('longitude');
  9463.                         }
  9464.                         $new_ei Accounts::CreateExpenseInvoiceFromAddExpense(
  9465.                             $this->getDoctrine()->getManager(),
  9466.                             $data,
  9467.                             '',
  9468.                             $expBillType,
  9469.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  9470.                             0,
  9471.                             0,
  9472.                             0,
  9473.                             $expData['ccId'],
  9474.                             $expData['isChildInvoice'],
  9475.                             $primaryInvoiceId,
  9476.                             1
  9477.                         );
  9478.                         //now add Approval info
  9479.                     }
  9480.                     if ($expData['expenseType'] == 0) {
  9481.                         $expBillType 0;
  9482.                         $data = array(
  9483.                             'doc_id' => $expData['docId'],
  9484.                             'expense_id' => $expData['expenseId'],
  9485.                             'party_id' => '',
  9486.                             'party_head_id' => $expData['expenseToBePaidTo'],
  9487.                             'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
  9488.                             'invoice_amount' => $expData['expenseAmount'],
  9489.                             'description' => $expData['description'],
  9490.                             'expense_to_note' => $expData['expenseToNote'],
  9491.                             'expense_from_note' => $expData['expenseFromNote'],
  9492.                             'date' => $expData['expenseDate'],
  9493.                             'file' => $expData['attachedFile'],
  9494.                             "currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
  9495.                             "currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
  9496.                             "currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
  9497.                             'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
  9498.                             'expense_from' => $expData['expenseFrom'],
  9499.                             'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
  9500.                             'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
  9501.                             'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
  9502.                             'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
  9503.                             'expenseMarkerHash' => isset($expData['markerHash']) ? $expData['markerHash'] : '',
  9504.                             'expenseSubCategory' => isset($expData['expense_sub_category']) ? $expData['expense_sub_category'] : 0,
  9505.                             'expenseSubCategoryOption' => isset($expData['expense_sub_category_option']) ? $expData['expense_sub_category_option'] : 0,
  9506.                         );
  9507.                         if ($request->request->has('latitude')) {
  9508.                             $data['latitude'] = $request->request->get('latitude');
  9509.                             $data['longitude'] = $request->request->get('longitude');
  9510.                         }
  9511.                         if ($expData['expenseMarkerHash'] != '') {
  9512.                             $get_kids_sql "SELECT accounts_head_id FROM acc_accounts_head where marker_hash like '%" $expData['expenseMarkerHash'] . "%'  limit 1";
  9513.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9514.                             
  9515.                             $query_output $stmt;
  9516.                             if (empty($query_output))
  9517.                                 return new JsonResponse(array("success" => false'errorText' => 'Could not find relevant Expense Head'));
  9518.                             else
  9519.                                 $data['expense_id'] = $query_output[0]['accounts_head_id'];
  9520.                         }
  9521.                         if ($expData['expenseToBePaidTo'] == '_OWN_' || $expData['expenseToBePaidTo'] == -1//own expense entry from app
  9522.                         {
  9523.                             $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";
  9524.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9525.                             
  9526.                             $query_output $stmt;
  9527.                             if (empty($query_output)) {
  9528.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  9529.                                 return new JsonResponse(array(
  9530.                                     "success" => false,
  9531.                                     'errorText' => 'You are not listed as Employee',
  9532.                                     'errorStr' => 'You are not listed as Employee',
  9533.                                 ));
  9534.                             } else if ($query_output[0]['accounts_head_id'] == || $query_output[0]['accounts_head_id'] == NULL)
  9535.                                 return new JsonResponse(array(
  9536.                                     "success" => false,
  9537.                                     'errorText' => 'Could not Find Employee Head',
  9538.                                     'errorStr' => 'Could not Find Employee Head',
  9539.                                 ));
  9540.                             else {
  9541.                                 $data['party_head_id'] = $query_output[0]['accounts_head_id'];
  9542.                                 $data['description'] = $expData['expenseToNote'];
  9543.                                 $data['personal_expense_flag'] = 1;
  9544.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  9545.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  9546.                             }
  9547.                         }
  9548.                         if ($expData['expenseToBePaidTo'] == '_OWN_ADVANCE_' || $expData['expenseToBePaidTo'] == -2//own expense entry from app
  9549.                         {
  9550.                             $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";
  9551.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9552.                             
  9553.                             $query_output $stmt;
  9554.                             if (empty($query_output)) {
  9555.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  9556.                                 return new JsonResponse(array(
  9557.                                     "success" => false,
  9558.                                     'errorText' => 'You are not listed as Employee',
  9559.                                     'errorStr' => 'You are not listed as Employee',
  9560.                                 ));
  9561.                             } else if ($query_output[0]['advance_head_id'] == || $query_output[0]['advance_head_id'] == NULL)
  9562.                                 return new JsonResponse(array(
  9563.                                     "success" => false,
  9564.                                     'errorText' => 'Could not Find Employee Advance Head',
  9565.                                     'errorStr' => 'Could not Find Employee Advance Head',
  9566.                                 ));
  9567.                             else {
  9568.                                 $data['party_head_id'] = $query_output[0]['advance_head_id'];
  9569.                                 $data['description'] = $expData['expenseToNote'];
  9570.                                 $data['personal_expense_flag'] = 1;
  9571.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  9572.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  9573.                             }
  9574.                         }
  9575.                         $new_ei Accounts::CreateExpenseInvoiceFromAddExpense(
  9576.                             $this->getDoctrine()->getManager(),
  9577.                             $data,
  9578.                             '',
  9579.                             $expBillType,
  9580.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  9581.                             0,
  9582.                             0,
  9583.                             0,
  9584.                             $expData['ccId'],
  9585.                             $expData['isChildInvoice'],
  9586.                             $primaryInvoiceId
  9587.                         );
  9588.                         //now add Approval info
  9589.                     }
  9590.                     //for purchase
  9591.                     if ($expData['expenseType'] == 1) {
  9592.                         $expBillType 1;
  9593.                         $po_data $this->getDoctrine()
  9594.                             ->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')
  9595.                             ->findOneBy(
  9596.                                 array(
  9597.                                     'purchaseOrderId' => $expData['docId']
  9598.                                 )
  9599.                             );
  9600.                         //                $balanceable_advance=$so_data->getBalanceableAdvanceAmount();
  9601.                         $data = array(
  9602.                             'doc_id' => $expData['docId'],
  9603.                             'expense_id' => $expData['expenseId'],
  9604.                             'party_id' => '',
  9605.                             'party_head_id' => $expData['expenseToBePaidTo'],
  9606.                             'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
  9607.                             'invoice_amount' => $expData['expenseAmount'],
  9608.                             'description' => $expData['description'],
  9609.                             'expense_to_note' => $expData['expenseToNote'],
  9610.                             'expense_from_note' => $expData['expenseFromNote'],
  9611.                             'expenseInvocationStrategyOnGrn' => $expData['expenseInvocationStrategyOnGrn'],
  9612.                             'expenseInvocationTypeOnItems' => $expData['expenseInvocationTypeOnItems'],
  9613.                             'date' => $expData['expenseDate'],
  9614.                             'file' => $expData['attachedFile'],
  9615.                             "currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
  9616.                             "currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
  9617.                             "currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
  9618.                             'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
  9619.                             'expense_from' => $expData['expenseFrom'],
  9620.                             'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
  9621.                             'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
  9622.                             'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
  9623.                             'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
  9624.                             'costDistributionData' => isset($expData['costDistributionData']) ? $expData['costDistributionData'] : 0,
  9625.                             'expenseDistributionOnProduct' => isset($expData['expenseDistributionOnProduct']) ? $expData['expenseDistributionOnProduct'] : 0,
  9626.                         );
  9627.                         if ($expData['expenseToBePaidTo'] == '_OWN_' || $expData['expenseToBePaidTo'] == -1//own expense entry from app
  9628.                         {
  9629.                             $get_kids_sql "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  limit 1";
  9630.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9631.                             
  9632.                             $query_output $stmt;
  9633.                             if (empty($query_output)) {
  9634.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  9635.                                 return new JsonResponse(array(
  9636.                                     "success" => false,
  9637.                                     'errorText' => 'You are not listed as Employee',
  9638.                                     'errorStr' => 'You are not listed as Employee',
  9639.                                 ));
  9640.                             } else if ($query_output[0]['accounts_head_id'] == || $query_output[0]['accounts_head_id'] == NULL)
  9641.                                 return new JsonResponse(array(
  9642.                                     "success" => false,
  9643.                                     'errorText' => 'Could not Find Employee Head',
  9644.                                     'errorStr' => 'Could not Find Employee Head',
  9645.                                 ));
  9646.                             else {
  9647.                                 $data['party_head_id'] = $query_output[0]['accounts_head_id'];
  9648.                                 $data['description'] = $expData['expenseToNote'];
  9649.                                 $data['personal_expense_flag'] = 1;
  9650.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  9651.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  9652.                             }
  9653.                         }
  9654.                         if ($expData['expenseToBePaidTo'] == '_OWN_ADVANCE_' || $expData['expenseToBePaidTo'] == -2//own expense entry from app
  9655.                         {
  9656.                             $get_kids_sql "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  limit 1";
  9657.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9658.                             
  9659.                             $query_output $stmt;
  9660.                             if (empty($query_output)) {
  9661.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  9662.                                 return new JsonResponse(array(
  9663.                                     "success" => false,
  9664.                                     'errorText' => 'You are not listed as Employee',
  9665.                                     'errorStr' => 'You are not listed as Employee',
  9666.                                 ));
  9667.                             } else if ($query_output[0]['advance_head_id'] == || $query_output[0]['advance_head_id'] == NULL)
  9668.                                 return new JsonResponse(array(
  9669.                                     "success" => false,
  9670.                                     'errorText' => 'Could not Find Employee Advance Head',
  9671.                                     'errorStr' => 'Could not Find Employee Advance Head',
  9672.                                 ));
  9673.                             else {
  9674.                                 $data['party_head_id'] = $query_output[0]['advance_head_id'];
  9675.                                 $data['description'] = $expData['expenseToNote'];
  9676.                                 $data['personal_expense_flag'] = 1;
  9677.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  9678.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  9679.                             }
  9680.                         }
  9681.                         $new_ei Accounts::CreateExpenseInvoiceFromAddExpense(
  9682.                             $this->getDoctrine()->getManager(),
  9683.                             $data,
  9684.                             '',
  9685.                             $expBillType,
  9686.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  9687.                             0,
  9688.                             $po_data->getProjectId(),
  9689.                             0,
  9690.                             $expData['ccId'],
  9691.                             $expData['isChildInvoice'],
  9692.                             $primaryInvoiceId
  9693.                         );
  9694.                         //now add Approval info
  9695.                     }
  9696.                     if ($expData['expenseType'] == 2) {
  9697.                         $data $request->request;
  9698.                         //                <option value="1">Against Purchase</option>
  9699.                         //                                                    <option value="2">Against Sales</option>
  9700.                         //                                                    <option value="3">Against Maintenance</option>
  9701.                         $expBillType 2;
  9702.                         $so_data $this->getDoctrine()
  9703.                             ->getRepository('ApplicationBundle\\Entity\\SalesOrder')
  9704.                             ->findOneBy(
  9705.                                 array(
  9706.                                     'salesOrderId' => $expData['docId']
  9707.                                 )
  9708.                             );
  9709.                         $supplier_data $this->getDoctrine()
  9710.                             ->getRepository('ApplicationBundle\\Entity\\AccSuppliers')
  9711.                             ->findOneBy(
  9712.                                 array(
  9713.                                     'accountsHeadId' => $expData['expenseToBePaidTo']
  9714.                                 )
  9715.                             );
  9716.                         //                $balanceable_advance=$so_data->getBalanceableAdvanceAmount();
  9717.                         $data = array(
  9718.                             'doc_id' => $expData['docId'],
  9719.                             'expense_id' => $expData['expenseId'],
  9720.                             'party_id' => $supplier_data $supplier_data->getSupplierId() : 0,
  9721.                             'party_head_id' => $expData['expenseToBePaidTo'],
  9722.                             'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
  9723.                             'invoice_amount' => $expData['expenseAmount'],
  9724.                             'description' => $expData['description'],
  9725.                             'expense_to_note' => $expData['expenseToNote'],
  9726.                             'expense_from_note' => $expData['expenseFromNote'],
  9727.                             "currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
  9728.                             "currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
  9729.                             "currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
  9730.                             'expenseInvocationStrategyOnGrn' => $expData['expenseInvocationStrategyOnGrn'],
  9731.                             'expenseInvocationTypeOnItems' => $expData['expenseInvocationTypeOnItems'],
  9732.                             'date' => $expData['expenseDate'],
  9733.                             'file' => $expData['attachedFile'],
  9734.                             'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
  9735.                             'expense_from' => $expData['expenseFrom'],
  9736.                             'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
  9737.                             'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
  9738.                             'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
  9739.                             'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
  9740.                         );
  9741.                         if ($expData['expenseToBePaidTo'] == '_OWN_' || $expData['expenseToBePaidTo'] == -1//own expense entry from app
  9742.                         {
  9743.                             $get_kids_sql "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  limit 1";
  9744.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9745.                             
  9746.                             $query_output $stmt;
  9747.                             if (empty($query_output)) {
  9748.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  9749.                                 return new JsonResponse(array(
  9750.                                     "success" => false,
  9751.                                     'errorText' => 'You are not listed as Employee',
  9752.                                     'errorStr' => 'You are not listed as Employee',
  9753.                                 ));
  9754.                             } else if ($query_output[0]['accounts_head_id'] == || $query_output[0]['accounts_head_id'] == NULL)
  9755.                                 return new JsonResponse(array(
  9756.                                     "success" => false,
  9757.                                     'errorText' => 'Could not Find Employee Head',
  9758.                                     'errorStr' => 'Could not Find Employee Head',
  9759.                                 ));
  9760.                             else {
  9761.                                 $data['party_head_id'] = $query_output[0]['accounts_head_id'];
  9762.                                 $data['description'] = $expData['expenseToNote'];
  9763.                                 $data['personal_expense_flag'] = 1;
  9764.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  9765.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  9766.                             }
  9767.                         }
  9768.                         if ($expData['expenseToBePaidTo'] == '_OWN_ADVANCE_' || $expData['expenseToBePaidTo'] == -2//own expense entry from app
  9769.                         {
  9770.                             $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";
  9771.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9772.                             
  9773.                             $query_output $stmt;
  9774.                             if (empty($query_output)) {
  9775.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  9776.                                 return new JsonResponse(array(
  9777.                                     "success" => false,
  9778.                                     'errorText' => 'You are not listed as Employee',
  9779.                                     'errorStr' => 'You are not listed as Employee',
  9780.                                 ));
  9781.                             } else if ($query_output[0]['advance_head_id'] == || $query_output[0]['advance_head_id'] == NULL)
  9782.                                 return new JsonResponse(array(
  9783.                                     "success" => false,
  9784.                                     'errorText' => 'Could not Find Employee Advance Head',
  9785.                                     'errorStr' => 'Could not Find Employee Advance Head',
  9786.                                 ));
  9787.                             else {
  9788.                                 $data['party_head_id'] = $query_output[0]['advance_head_id'];
  9789.                                 $data['description'] = $expData['expenseToNote'];
  9790.                                 $data['personal_expense_flag'] = 1;
  9791.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  9792.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  9793.                             }
  9794.                         }
  9795.                         $new_ei Accounts::CreateExpenseInvoiceFromAddExpense(
  9796.                             $this->getDoctrine()->getManager(),
  9797.                             $data,
  9798.                             '',
  9799.                             $expBillType,
  9800.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  9801.                             0,
  9802.                             ((int) ($expData['directProjectId'] ?? 0) > ? (int) $expData['directProjectId'] : ($so_data $so_data->getProjectId() : 0)),
  9803.                             0,
  9804.                             $expData['ccId'],
  9805.                             $expData['isChildInvoice'],
  9806.                             $primaryInvoiceId
  9807.                         );
  9808.                     }
  9809.                     if ($expData['expenseType'] == 3) {
  9810.                         $data $request->request;
  9811.                         $expBillType 3;
  9812.                         $so_data $this->getDoctrine()
  9813.                             ->getRepository('ApplicationBundle\\Entity\\Opportunity')
  9814.                             ->findOneBy(
  9815.                                 array(
  9816.                                     'opportunityId' => $expData['docId']
  9817.                                 )
  9818.                             );
  9819.                         $supplier_data $this->getDoctrine()
  9820.                             ->getRepository('ApplicationBundle\\Entity\\AccSuppliers')
  9821.                             ->findOneBy(
  9822.                                 array(
  9823.                                     'accountsHeadId' => $expData['expenseToBePaidTo']
  9824.                                 )
  9825.                             );
  9826.                         //                $balanceable_advance=$so_data->getBalanceableAdvanceAmount();
  9827.                         $data = array(
  9828.                             'doc_id' => $expData['docId'],
  9829.                             'expense_id' => $expData['expenseId'],
  9830.                             'party_id' => $supplier_data $supplier_data->getSupplierId() : 0,
  9831.                             'party_head_id' => $expData['expenseToBePaidTo'],
  9832.                             'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
  9833.                             'invoice_amount' => $expData['expenseAmount'],
  9834.                             'description' => $expData['description'],
  9835.                             'expense_to_note' => $expData['expenseToNote'],
  9836.                             'expense_from_note' => $expData['expenseFromNote'],
  9837.                             "currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
  9838.                             "currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
  9839.                             "currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
  9840.                             'expenseInvocationStrategyOnGrn' => $expData['expenseInvocationStrategyOnGrn'],
  9841.                             'expenseInvocationTypeOnItems' => $expData['expenseInvocationTypeOnItems'],
  9842.                             'date' => $expData['expenseDate'],
  9843.                             'file' => $expData['attachedFile'],
  9844.                             'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
  9845.                             'expense_from' => $expData['expenseFrom'],
  9846.                             'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
  9847.                             'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
  9848.                             'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
  9849.                             'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
  9850.                         );
  9851.                         if ($expData['expenseToBePaidTo'] == '_OWN_' || $expData['expenseToBePaidTo'] == -1//own expense entry from app
  9852.                         {
  9853.                             $get_kids_sql "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  limit 1";
  9854.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9855.                             
  9856.                             $query_output $stmt;
  9857.                             if (empty($query_output)) {
  9858.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  9859.                                 return new JsonResponse(array(
  9860.                                     "success" => false,
  9861.                                     'errorText' => 'You are not listed as Employee',
  9862.                                     'errorStr' => 'You are not listed as Employee',
  9863.                                 ));
  9864.                             } else if ($query_output[0]['accounts_head_id'] == || $query_output[0]['accounts_head_id'] == NULL)
  9865.                                 return new JsonResponse(array(
  9866.                                     "success" => false,
  9867.                                     'errorText' => 'Could not Find Employee Head',
  9868.                                     'errorStr' => 'Could not Find Employee Head',
  9869.                                 ));
  9870.                             else {
  9871.                                 $data['party_head_id'] = $query_output[0]['accounts_head_id'];
  9872.                                 $data['description'] = $expData['expenseToNote'];
  9873.                                 $data['personal_expense_flag'] = 1;
  9874.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  9875.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  9876.                             }
  9877.                         }
  9878.                         if ($expData['expenseToBePaidTo'] == '_OWN_ADVANCE_' || $expData['expenseToBePaidTo'] == -2//own expense entry from app
  9879.                         {
  9880.                             $get_kids_sql "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  limit 1";
  9881.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9882.                             
  9883.                             $query_output $stmt;
  9884.                             if (empty($query_output)) {
  9885.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  9886.                                 return new JsonResponse(array(
  9887.                                     "success" => false,
  9888.                                     'errorText' => 'You are not listed as Employee',
  9889.                                     'errorStr' => 'You are not listed as Employee',
  9890.                                 ));
  9891.                             } else if ($query_output[0]['advance_head_id'] == || $query_output[0]['advance_head_id'] == NULL)
  9892.                                 return new JsonResponse(array(
  9893.                                     "success" => false,
  9894.                                     'errorText' => 'Could not Find Employee Advance Head',
  9895.                                     'errorStr' => 'Could not Find Employee Advance Head',
  9896.                                 ));
  9897.                             else {
  9898.                                 $data['party_head_id'] = $query_output[0]['advance_head_id'];
  9899.                                 $data['description'] = $expData['expenseToNote'];
  9900.                                 $data['personal_expense_flag'] = 1;
  9901.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  9902.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  9903.                             }
  9904.                         }
  9905.                         $new_ei Accounts::CreateExpenseInvoiceFromAddExpense(
  9906.                             $this->getDoctrine()->getManager(),
  9907.                             $data,
  9908.                             '',
  9909.                             $expBillType,
  9910.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  9911.                             0,
  9912.                             ((int) ($expData['directProjectId'] ?? 0) > ? (int) $expData['directProjectId'] : ($so_data $so_data->getProjectId() : 0)),
  9913.                             0,
  9914.                             $expData['ccId'],
  9915.                             $expData['isChildInvoice'],
  9916.                             $primaryInvoiceId
  9917.                         );
  9918.                     }
  9919.                     if ($expData['expenseType'] == 5) {
  9920.                         $expBillType 0;
  9921.                         // Fetch the Tour data
  9922.                         $tour_data $this->getDoctrine()
  9923.                             ->getRepository('ApplicationBundle\\Entity\\PlanVisit')
  9924.                             ->findOneBy([
  9925.                                 'id' => $expData['docId']
  9926.                             ]);
  9927.                         $supplier_data $this->getDoctrine()
  9928.                             ->getRepository('ApplicationBundle\\Entity\\AccSuppliers')
  9929.                             ->findOneBy([
  9930.                                 'accountsHeadId' => $expData['expenseToBePaidTo']
  9931.                             ]);
  9932.                         $data = [
  9933.                             'doc_id' => $expData['docId'],
  9934.                             'expense_id' => $expData['expenseId'],
  9935.                             'party_id' => $supplier_data $supplier_data->getSupplierId() : '',
  9936.                             'party_head_id' => $expData['expenseToBePaidTo'],
  9937.                             'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
  9938.                             'invoice_amount' => $expData['expenseAmount'],
  9939.                             'description' => $expData['description'],
  9940.                             'expense_to_note' => $expData['expenseToNote'],
  9941.                             'expense_from_note' => $expData['expenseFromNote'],
  9942.                             'date' => $expData['expenseDate'],
  9943.                             'file' => $expData['attachedFile'],
  9944.                             'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
  9945.                             'expense_from' => $expData['expenseFrom'],
  9946.                             'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
  9947.                             'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
  9948.                             'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
  9949.                             'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
  9950.                             'expenseMarkerHash' => isset($expData['markerHash']) ? $expData['markerHash'] : '',
  9951.                             'expenseSubCategory' => isset($expData['expense_sub_category']) ? $expData['expense_sub_category'] : 0,
  9952.                             'expenseSubCategoryOption' => isset($expData['expense_sub_category_option']) ? $expData['expense_sub_category_option'] : 0,
  9953.                             'tour_title' => $tour_data $tour_data->getTitle() : '',
  9954.                             'tour_document_hash' => $tour_data $tour_data->getDocumentHash() : '',
  9955.                             'tour_id' => $tour_data $tour_data->getId() : ''
  9956.                         ];
  9957.                         if ($request->request->has('latitude')) {
  9958.                             $data['latitude'] = $request->request->get('latitude');
  9959.                             $data['longitude'] = $request->request->get('longitude');
  9960.                         }
  9961.                         // Handle personal expense if own head
  9962.                         if ($expData['expenseToBePaidTo'] == '_OWN_' || $expData['expenseToBePaidTo'] == -1) {
  9963.                             $get_kids_sql "SELECT accounts_head_id, advance_head_id, employee_id, user_id 
  9964.                          FROM employee 
  9965.                          WHERE user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  
  9966.                          LIMIT 1";
  9967.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9968.                             
  9969.                             $query_output $stmt;
  9970.                             if (empty($query_output)) {
  9971.                                 return new JsonResponse([
  9972.                                     "success" => false,
  9973.                                     'errorText' => 'You are not listed as Employee',
  9974.                                     'errorStr' => 'You are not listed as Employee',
  9975.                                 ]);
  9976.                             }
  9977.                             $data['party_head_id'] = $query_output[0]['accounts_head_id'];
  9978.                             $data['description'] = $expData['expenseToNote'];
  9979.                             $data['personal_expense_flag'] = 1;
  9980.                             $data['expense_of_user_id'] = $query_output[0]['user_id'];
  9981.                             $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  9982.                         }
  9983.                         // Handle own advance
  9984.                         if ($expData['expenseToBePaidTo'] == '_OWN_ADVANCE_' || $expData['expenseToBePaidTo'] == -2) {
  9985.                             $get_kids_sql "SELECT accounts_head_id, advance_head_id, employee_id, user_id 
  9986.                          FROM employee 
  9987.                          WHERE user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  
  9988.                          LIMIT 1";
  9989.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  9990.                             
  9991.                             $query_output $stmt;
  9992.                             if (empty($query_output)) {
  9993.                                 return new JsonResponse([
  9994.                                     "success" => false,
  9995.                                     'errorText' => 'You are not listed as Employee',
  9996.                                     'errorStr' => 'You are not listed as Employee',
  9997.                                 ]);
  9998.                             }
  9999.                             $data['party_head_id'] = $query_output[0]['advance_head_id'];
  10000.                             $data['description'] = $expData['expenseToNote'];
  10001.                             $data['personal_expense_flag'] = 1;
  10002.                             $data['expense_of_user_id'] = $query_output[0]['user_id'];
  10003.                             $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  10004.                         }
  10005.                         // Create Expense Invoice
  10006.                         $new_ei Accounts::CreateExpenseInvoiceFromAddExpense(
  10007.                             $this->getDoctrine()->getManager(),
  10008.                             $data,
  10009.                             '',
  10010.                             $expBillType,
  10011.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10012.                             0,
  10013.                             0,
  10014.                             0,
  10015.                             $expData['ccId'],
  10016.                             $expData['isChildInvoice'],
  10017.                             $primaryInvoiceId
  10018.                         );
  10019.                     }
  10020.                     if ($expData['isChildInvoice'] != && isset($new_ei['ei_id'])) {
  10021.                         $primaryInvoiceId $new_ei['ei_id'];
  10022.                     }
  10023.                 }
  10024.                 //single end
  10025.                 if ($primaryInvoiceId != 0) {
  10026.                     $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  10027.                     $approveRole $request->request->get('approvalRole');
  10028.                     $options = array(
  10029.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  10030.                         'notification_server' => $this->container->getParameter('notification_server'),
  10031.                         'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  10032.                         'url' => $this->generateUrl(
  10033.                             GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice']]['entity_view_route_path_name']
  10034.                         )
  10035.                     );
  10036.                     System::setApprovalInfo(
  10037.                         $this->getDoctrine()->getManager(),
  10038.                         $options,
  10039.                         array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
  10040.                         $primaryInvoiceId,
  10041.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  10042.                     );
  10043.                     System::createEditSignatureHash(
  10044.                         $this->getDoctrine()->getManager(),
  10045.                         array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
  10046.                         $primaryInvoiceId,
  10047.                         $loginId,
  10048.                         $approveRole,
  10049.                         $request->request->get('approvalHash')
  10050.                     );
  10051.                 }
  10052.                 return new JsonResponse(array(
  10053.                     "success" => true,
  10054.                     'docId' => isset($new_ei['ei_id']) ? $new_ei['ei_id'] : '',
  10055.                     'docHash' => isset($new_ei['ei_doc_hash']) ? $new_ei['ei_doc_hash'] : '',
  10056.                 ));
  10057.             }
  10058.         }
  10059.         return new JsonResponse(array(
  10060.             "success" => true,
  10061.             'docId' => isset($new_ei['ei_id']) ? $new_ei['ei_id'] : '',
  10062.             'docHash' => isset($new_ei['ei_doc_hash']) ? $new_ei['ei_doc_hash'] : '',
  10063.             'expenseSubTypes' => $expenseSubTypes
  10064.         ));
  10065.         //
  10066.         //        return $this->render('@Accounts/pages/input_forms/payment_voucher.html.twig',
  10067.         //            array(
  10068.         //                'page_title'=>'Create Payment Voucher',
  10069.         //                'test'=>$details_ids,
  10070.         //                'supplier_list'=>Accounts::SupplierListForPv($this->getDoctrine()->getManager()),
  10071.         //                'supplier_list_by_ac_head'=>Accounts::SupplierListByAcHead($this->getDoctrine()->getManager()),
  10072.         //                'supplier_list_by_advance_head'=>Accounts::SupplierListByAdvanceHead($this->getDoctrine()->getManager())
  10073.         //            )
  10074.         //        );
  10075.     }
  10076.     public function AddExpenseForApp(Request $request)
  10077.     {
  10078.         $details_ids = [];
  10079.         $em $this->getDoctrine()->getManager();
  10080.         $em_goc $this->getDoctrine()->getManager('company_group');
  10081.         $expenseSubTypes GeneralConstant::$expenseSubTypes;
  10082.         if ($request->isMethod('POST')) {
  10083.             $em $this->getDoctrine()->getManager();
  10084.             $entity_id array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
  10085.             $dochash $request->request->get('voucherNumber'); //change
  10086.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  10087.             $approveRole $request->request->get('approvalRole'1);
  10088.             $approveHash $request->request->get('approvalHash');
  10089.             if (!DocValidation::isSignatureOk($em$loginId$approveHash)) {
  10090.                 //                $this->addFlash(
  10091.                 //                    'error',
  10092.                 //                    'Sorry Could Not insert Data.'
  10093.                 //                );
  10094.                 return new JsonResponse(array(
  10095.                     "success" => false,
  10096.                     'errorText' => 'Approval Hash Mismatch',
  10097.                     'errorStr' => 'Approval Hash Mismatch'
  10098.                 ));
  10099.             } else {
  10100.                 $new_ei = [];
  10101.                 $expenseDataList = array();
  10102.                 $primaryInvoiceId 0;
  10103.                 $hasChildInvoice 0;
  10104.                 $primaryInvoiceData = [];
  10105.                 $expense_data $request->request->get('expenseData', []);
  10106.                 if (is_string($expense_data)) $expense_data json_decode($expense_datatrue);
  10107.                 if (!empty($expense_data)) {
  10108.                     //multiple invoices so add childs and parent
  10109.                     if (count($expense_data) > 1$hasChildInvoice 1;
  10110.                     if ($hasChildInvoice == 1)
  10111.                         $expenseDataList[] = array(
  10112.                             "expenseType" => 4//primary
  10113.                             "expenseSubType" => 0,
  10114.                             "expenseId" => 0,
  10115.                             "ccId" => 0,
  10116.                             "currencyId" => 0,
  10117.                             "currencyMultiply" => 1,
  10118.                             "currencyMultiplyRate" => 1,
  10119.                             "docId" => 0,
  10120.                             "expenseToBePaidTo" => 0,
  10121.                             "expenseFrom" => 0,
  10122.                             "expenseFromNote" => '',
  10123.                             "expenseTo" => 0,
  10124.                             "expenseToNote" => 0,
  10125.                             "expenseAmount" => 0,
  10126.                             "previousAdvanceAmount" => 0,
  10127.                             "checkDate" => '',
  10128.                             "checkNumber" => '',
  10129.                             "checkNarration" => '',
  10130.                             "checkId" => 0,
  10131.                             "description" => '',
  10132.                             "expenseMarkerHash" => '',
  10133.                             "expenseDate" => $expense_data[0]['expenseDate'],
  10134.                             "invoiceBalancing" => 0,
  10135.                             "attachedFile" => [],
  10136.                             "uploadedFile" => '',
  10137.                             'expenseInvocationStrategyOnGrn' => null,
  10138.                             'expenseInvocationTypeOnItems' => null,
  10139.                             "isChildInvoice" => 0,
  10140.                         );
  10141.                     $currTime = new \DateTime();
  10142.                     $currTs $currTime->format('U');
  10143.                     foreach ($expense_data as $key => $expData) {
  10144.                         if (isset($expData['imageBase64'])) {
  10145.                             $imageBase64 $expData['imageBase64'];
  10146.                             $data base64_decode(preg_replace('#^data:image/\w+;base64,#i'''$imageBase64));
  10147.                             $fileName $currTs . (md5(uniqid())) . '.png';
  10148.                             $storePath 'uploads/ExpenseInvoice/';
  10149.                             $path "";
  10150.                             $file_path "";
  10151.                             $session $request->getSession();
  10152.                             MiscActions::RemoveExpiredFiles($em_goc);
  10153.                             $path $fileName;
  10154.                             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  10155.                             if (!file_exists($upl_dir)) {
  10156.                                 mkdir($upl_dir0777true);
  10157.                             }
  10158.                             if (file_exists($upl_dir '' $path)) {
  10159.                                 chmod($upl_dir '' $path0755);
  10160.                                 unlink($upl_dir '' $path);
  10161.                             }
  10162.                             $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ExpenseInvoice/' $path;
  10163.                             file_put_contents($upl_dir$data);
  10164.                             if ($path != "")
  10165.                                 $file_path $storePath $path;
  10166.                             $expense_data[$key]['uploadedFile'] = $file_path;
  10167.                         }
  10168.                         if (!isset($expData['attachedFile'])) {
  10169.                             $expense_data[$key]['attachedFile'] = [];
  10170.                         }
  10171.                         $expense_data[$key]['isChildInvoice'] = $hasChildInvoice == 0;
  10172.                         $expenseDataList[] = $expense_data[$key];
  10173.                     }
  10174.                 } else {
  10175.                     $expense_type $request->request->get('expense_type'0);
  10176.                     $expenseDataList[] = array(
  10177.                         "expenseType" => $expense_type,
  10178.                         "currencyId" => $request->request->get('expense_currency_id'0),
  10179.                         "currencyMultiply" => $request->request->get('expense_currency_multiply'1),
  10180.                         "currencyMultiplyRate" => $request->request->get('expense_currency_multiply_rate'1),
  10181.                         "expenseSubType" => $request->request->get('expense_sub_type'0),
  10182.                         "expenseId" => $request->request->get('expense_id'0),
  10183.                         "ccId" => $request->request->get('ccId'0),
  10184.                         "docId" => $expense_type == $request->request->get('poId') : ($expense_type == $request->request->get('soId') : 0),
  10185.                         "expenseToBePaidTo" => $request->request->get('expense_to_be_paid_to'0),
  10186.                         "expenseFrom" => $request->request->get('expense_from'0),
  10187.                         "checkDate" => $request->request->get('check_date'''),
  10188.                         "checkNumber" => $request->request->get('check_number'''),
  10189.                         "checkNarration" => $request->request->get('check_narration'''),
  10190.                         "checkId" => $request->request->get('check_id'0),
  10191.                         "expenseFromNote" => $request->request->get('expense_from_note'''),
  10192.                         "expenseTo" => $request->request->get('expense_to_' $expense_type0),
  10193.                         "expenseToNote" => $request->request->get('expense_to_note_' $expense_type''),
  10194.                         "expenseAmount" => $request->request->get('expense_amount'''),
  10195.                         "previousAdvanceAmount" => $request->request->get('prev_advance_amount'0),
  10196.                         "description" => $request->request->get('description'''),
  10197.                         "expenseMarkerHash" => $request->request->get('markerHash'''),
  10198.                         "expenseDate" => $request->request->get('expense_date'),
  10199.                         'expenseInvocationStrategyOnGrn' => $request->request->get('expenseInvocationStrategyOnGrn'null),
  10200.                         'expenseInvocationTypeOnItems' => $request->request->get('expenseInvocationTypeOnItems'null),
  10201.                         "invoiceBalancing" => $request->request->has('auto_balance' $expense_type) ? $request->request->get('auto_balance' $expense_type) : 0,
  10202.                         "attachedFile" => $request->files->get('file', []),
  10203.                         "uploadedFile" => $request->request->get('uploadedFile'''),
  10204.                         "expenseSubCategory" => $request->request->get('expense_sub_category'0),
  10205.                         "expenseSubCategoryOption" => $request->request->get('expense_sub_category_option'0),
  10206.                         "isChildInvoice" => 0,
  10207.                     );
  10208.                 }
  10209.                 ///SIngle one
  10210.                 ///
  10211.                 //                 System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($expenseDataList),'test_mult_exp');
  10212.                 foreach ($expenseDataList as $expData) {
  10213.                     //            Generic::debugMessage($_POST);
  10214.                     $new_ei = [];
  10215.                     $em $this->getDoctrine()->getManager();
  10216.                     //            $to_assign=0;
  10217.                     if ($expData['expenseType'] == 4) {   ////// primary Invoice
  10218.                         $expBillType 4;
  10219.                         $data = array(
  10220.                             'doc_id' => $expData['docId'],
  10221.                             'expense_id' => $expData['expenseId'],
  10222.                             'party_id' => '',
  10223.                             'party_head_id' => $expData['expenseToBePaidTo'],
  10224.                             'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
  10225.                             'invoice_amount' => $expData['expenseAmount'],
  10226.                             'description' => $expData['description'],
  10227.                             'expense_to_note' => $expData['expenseToNote'],
  10228.                             'expense_from_note' => $expData['expenseFromNote'],
  10229.                             "currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
  10230.                             "currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
  10231.                             "currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
  10232.                             'date' => $expData['expenseDate'],
  10233.                             'file' => $expData['attachedFile'],
  10234.                             'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
  10235.                             'expense_from' => $expData['expenseFrom'],
  10236.                             'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
  10237.                             'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
  10238.                             'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
  10239.                             'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
  10240.                         );
  10241.                         if ($request->request->has('latitude')) {
  10242.                             $data['latitude'] = $request->request->get('latitude');
  10243.                             $data['longitude'] = $request->request->get('longitude');
  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.                             0,
  10253.                             0,
  10254.                             $expData['ccId'],
  10255.                             $expData['isChildInvoice'],
  10256.                             $primaryInvoiceId,
  10257.                             1
  10258.                         );
  10259.                         //now add Approval info
  10260.                     }
  10261.                     if ($expData['expenseType'] == 0) {
  10262.                         $expBillType 0;
  10263.                         $data = array(
  10264.                             'doc_id' => $expData['docId'],
  10265.                             'expense_id' => $expData['expenseId'],
  10266.                             'party_id' => '',
  10267.                             'party_head_id' => $expData['expenseToBePaidTo'],
  10268.                             'advance_amount_to_assign' => isset($expData['previousAdvanceAmount']) ? $expData['previousAdvanceAmount'] : '',
  10269.                             'invoice_amount' => $expData['expenseAmount'],
  10270.                             'description' => $expData['description'],
  10271.                             'expense_to_note' => isset($expData['expenseToNote']) ? $expData['expenseToNote'] : '',
  10272.                             'expense_from_note' => isset($expData['expenseFromNote']) ? $expData['expenseFromNote'] : '',
  10273.                             'date' => $expData['expenseDate'],
  10274.                             'file' => $expData['attachedFile'],
  10275.                             "currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
  10276.                             "currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
  10277.                             "currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
  10278.                             'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
  10279.                             'expense_from' => isset($expData['expenseFrom']) ? $expData['expenseFrom'] : '',
  10280.                             'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
  10281.                             'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
  10282.                             'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
  10283.                             'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
  10284.                             'markerHash' => isset($expData['expenseMarkerHash']) ? $expData['expenseMarkerHash'] : 0,
  10285.                             'expenseSubCategory' => isset($expData['expenseSubCategory']) ? $expData['expenseSubCategory'] : 0,
  10286.                             'expenseSubCategoryOption' => isset($expData['expenseSubCategoryOption']) ? $expData['expenseSubCategoryOption'] : 0,
  10287.                         );
  10288.                         if ($request->request->has('latitude')) {
  10289.                             $data['latitude'] = $request->request->get('latitude');
  10290.                             $data['longitude'] = $request->request->get('longitude');
  10291.                         }
  10292.                         if ($expData['expenseMarkerHash'] != '') {
  10293.                             $get_kids_sql "SELECT accounts_head_id FROM acc_accounts_head where marker_hash like '%" $expData['expenseMarkerHash'] . "%'  limit 1";
  10294.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  10295.                             
  10296.                             $query_output $stmt;
  10297.                             if (empty($query_output))
  10298.                                 return new JsonResponse(array("success" => false'errorText' => 'Could not find relevant Expense Head'));
  10299.                             else
  10300.                                 $data['expense_id'] = $query_output[0]['accounts_head_id'];
  10301.                         }
  10302.                         if ($expData['expenseToBePaidTo'] == '_OWN_' || $expData['expenseToBePaidTo'] == -1//own expense entry from app
  10303.                         {
  10304.                             $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";
  10305.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  10306.                             
  10307.                             $query_output $stmt;
  10308.                             if (empty($query_output)) {
  10309.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  10310.                                 return new JsonResponse(array(
  10311.                                     "success" => false,
  10312.                                     'errorText' => 'You are not listed as Employee',
  10313.                                     'errorStr' => 'You are not listed as Employee',
  10314.                                 ));
  10315.                             } else if ($query_output[0]['accounts_head_id'] == || $query_output[0]['accounts_head_id'] == NULL)
  10316.                                 return new JsonResponse(array(
  10317.                                     "success" => false,
  10318.                                     'errorText' => 'Could not Find Employee Head',
  10319.                                     'errorStr' => 'Could not Find Employee Head',
  10320.                                 ));
  10321.                             else {
  10322.                                 $data['party_head_id'] = $query_output[0]['accounts_head_id'];
  10323.                                 //                                $data['description'] = $expData['expenseToNote'];
  10324.                                 $data['description'] = $expData['description'];
  10325.                                 $data['personal_expense_flag'] = 1;
  10326.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  10327.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  10328.                             }
  10329.                         }
  10330.                         if ($expData['expenseToBePaidTo'] == '_OWN_ADVANCE_' || $expData['expenseToBePaidTo'] == -2//own expense entry from app
  10331.                         {
  10332.                             $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";
  10333.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  10334.                             
  10335.                             $query_output $stmt;
  10336.                             if (empty($query_output)) {
  10337.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  10338.                                 return new JsonResponse(array(
  10339.                                     "success" => false,
  10340.                                     'errorText' => 'You are not listed as Employee',
  10341.                                     'errorStr' => 'You are not listed as Employee',
  10342.                                 ));
  10343.                             } else if ($query_output[0]['advance_head_id'] == || $query_output[0]['advance_head_id'] == NULL)
  10344.                                 return new JsonResponse(array(
  10345.                                     "success" => false,
  10346.                                     'errorText' => 'Could not Find Employee Advance Head',
  10347.                                     'errorStr' => 'Could not Find Employee Advance Head',
  10348.                                 ));
  10349.                             else {
  10350.                                 $data['party_head_id'] = $query_output[0]['advance_head_id'];
  10351.                                 $data['description'] = $expData['expenseToNote'];
  10352.                                 $data['personal_expense_flag'] = 1;
  10353.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  10354.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  10355.                             }
  10356.                         }
  10357.                         $new_ei Accounts::CreateExpenseInvoiceFromAddExpense(
  10358.                             $this->getDoctrine()->getManager(),
  10359.                             $data,
  10360.                             '',
  10361.                             $expBillType,
  10362.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10363.                             0,
  10364.                             0,
  10365.                             0,
  10366.                             $expData['ccId'],
  10367.                             $expData['isChildInvoice'],
  10368.                             $primaryInvoiceId
  10369.                         );
  10370.                         //now add Approval info
  10371.                     }
  10372.                     //for purchase
  10373.                     if ($expData['expenseType'] == 1) {
  10374.                         $expBillType 1;
  10375.                         $po_data $this->getDoctrine()
  10376.                             ->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')
  10377.                             ->findOneBy(
  10378.                                 array(
  10379.                                     'purchaseOrderId' => $expData['docId']
  10380.                                 )
  10381.                             );
  10382.                         //                $balanceable_advance=$so_data->getBalanceableAdvanceAmount();
  10383.                         $data = array(
  10384.                             'doc_id' => $expData['docId'],
  10385.                             'expense_id' => $expData['expenseId'],
  10386.                             'party_id' => '',
  10387.                             'party_head_id' => $expData['expenseToBePaidTo'],
  10388.                             'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
  10389.                             'invoice_amount' => $expData['expenseAmount'],
  10390.                             'description' => $expData['description'],
  10391.                             'expense_to_note' => $expData['expenseToNote'],
  10392.                             'expense_from_note' => $expData['expenseFromNote'],
  10393.                             'expenseInvocationStrategyOnGrn' => $expData['expenseInvocationStrategyOnGrn'],
  10394.                             'expenseInvocationTypeOnItems' => $expData['expenseInvocationTypeOnItems'],
  10395.                             'date' => $expData['expenseDate'],
  10396.                             'file' => $expData['attachedFile'],
  10397.                             "currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
  10398.                             "currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
  10399.                             "currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
  10400.                             'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
  10401.                             'expense_from' => $expData['expenseFrom'],
  10402.                             'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
  10403.                             'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
  10404.                             'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
  10405.                             'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
  10406.                         );
  10407.                         if ($expData['expenseToBePaidTo'] == '_OWN_' || $expData['expenseToBePaidTo'] == -1//own expense entry from app
  10408.                         {
  10409.                             $get_kids_sql "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  limit 1";
  10410.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  10411.                             
  10412.                             $query_output $stmt;
  10413.                             if (empty($query_output)) {
  10414.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  10415.                                 return new JsonResponse(array(
  10416.                                     "success" => false,
  10417.                                     'errorText' => 'You are not listed as Employee',
  10418.                                     'errorStr' => 'You are not listed as Employee',
  10419.                                 ));
  10420.                             } else if ($query_output[0]['accounts_head_id'] == || $query_output[0]['accounts_head_id'] == NULL)
  10421.                                 return new JsonResponse(array(
  10422.                                     "success" => false,
  10423.                                     'errorText' => 'Could not Find Employee Head',
  10424.                                     'errorStr' => 'Could not Find Employee Head',
  10425.                                 ));
  10426.                             else {
  10427.                                 $data['party_head_id'] = $query_output[0]['accounts_head_id'];
  10428.                                 $data['description'] = $expData['expenseToNote'];
  10429.                                 $data['personal_expense_flag'] = 1;
  10430.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  10431.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  10432.                             }
  10433.                         }
  10434.                         if ($expData['expenseToBePaidTo'] == '_OWN_ADVANCE_' || $expData['expenseToBePaidTo'] == -2//own expense entry from app
  10435.                         {
  10436.                             $get_kids_sql "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  limit 1";
  10437.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  10438.                             
  10439.                             $query_output $stmt;
  10440.                             if (empty($query_output)) {
  10441.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  10442.                                 return new JsonResponse(array(
  10443.                                     "success" => false,
  10444.                                     'errorText' => 'You are not listed as Employee',
  10445.                                     'errorStr' => 'You are not listed as Employee',
  10446.                                 ));
  10447.                             } else if ($query_output[0]['advance_head_id'] == || $query_output[0]['advance_head_id'] == NULL)
  10448.                                 return new JsonResponse(array(
  10449.                                     "success" => false,
  10450.                                     'errorText' => 'Could not Find Employee Advance Head',
  10451.                                     'errorStr' => 'Could not Find Employee Advance Head',
  10452.                                 ));
  10453.                             else {
  10454.                                 $data['party_head_id'] = $query_output[0]['advance_head_id'];
  10455.                                 $data['description'] = $expData['expenseToNote'];
  10456.                                 $data['personal_expense_flag'] = 1;
  10457.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  10458.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  10459.                             }
  10460.                         }
  10461.                         $new_ei Accounts::CreateExpenseInvoiceFromAddExpense(
  10462.                             $this->getDoctrine()->getManager(),
  10463.                             $data,
  10464.                             '',
  10465.                             $expBillType,
  10466.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10467.                             0,
  10468.                             $po_data->getProjectId(),
  10469.                             0,
  10470.                             $expData['ccId'],
  10471.                             $expData['isChildInvoice'],
  10472.                             $primaryInvoiceId
  10473.                         );
  10474.                         //now add Approval info
  10475.                     }
  10476.                     if ($expData['expenseType'] == 2) {
  10477.                         $data $request->request;
  10478.                         //                <option value="1">Against Purchase</option>
  10479.                         //                                                    <option value="2">Against Sales</option>
  10480.                         //                                                    <option value="3">Against Maintenance</option>
  10481.                         $expBillType 2;
  10482.                         $so_data $this->getDoctrine()
  10483.                             ->getRepository('ApplicationBundle\\Entity\\SalesOrder')
  10484.                             ->findOneBy(
  10485.                                 array(
  10486.                                     'salesOrderId' => $expData['docId']
  10487.                                 )
  10488.                             );
  10489.                         $supplier_data $this->getDoctrine()
  10490.                             ->getRepository('ApplicationBundle\\Entity\\AccSuppliers')
  10491.                             ->findOneBy(
  10492.                                 array(
  10493.                                     'accountsHeadId' => $expData['expenseToBePaidTo']
  10494.                                 )
  10495.                             );
  10496.                         //                $balanceable_advance=$so_data->getBalanceableAdvanceAmount();
  10497.                         $data = array(
  10498.                             'doc_id' => $expData['docId'],
  10499.                             'expense_id' => $expData['expenseId'],
  10500.                             'party_id' => $supplier_data $supplier_data->getSupplierId() : 0,
  10501.                             'party_head_id' => $expData['expenseToBePaidTo'],
  10502.                             'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
  10503.                             'invoice_amount' => $expData['expenseAmount'],
  10504.                             'description' => $expData['description'],
  10505.                             'expense_to_note' => $expData['expenseToNote'],
  10506.                             'expense_from_note' => $expData['expenseFromNote'],
  10507.                             "currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
  10508.                             "currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
  10509.                             "currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
  10510.                             'expenseInvocationStrategyOnGrn' => $expData['expenseInvocationStrategyOnGrn'],
  10511.                             'expenseInvocationTypeOnItems' => $expData['expenseInvocationTypeOnItems'],
  10512.                             'date' => $expData['expenseDate'],
  10513.                             'file' => $expData['attachedFile'],
  10514.                             'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
  10515.                             'expense_from' => $expData['expenseFrom'],
  10516.                             'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
  10517.                             'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
  10518.                             'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
  10519.                             'markerHash' => isset($expData['expenseMarkerHash']) ? $expData['expenseMarkerHash'] : 0,
  10520.                             'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
  10521.                         );
  10522.                         if ($expData['expenseToBePaidTo'] == '_OWN_' || $expData['expenseToBePaidTo'] == -1//own expense entry from app
  10523.                         {
  10524.                             $get_kids_sql "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  limit 1";
  10525.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  10526.                             
  10527.                             $query_output $stmt;
  10528.                             if (empty($query_output)) {
  10529.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  10530.                                 return new JsonResponse(array(
  10531.                                     "success" => false,
  10532.                                     'errorText' => 'You are not listed as Employee',
  10533.                                     'errorStr' => 'You are not listed as Employee',
  10534.                                 ));
  10535.                             } else if ($query_output[0]['accounts_head_id'] == || $query_output[0]['accounts_head_id'] == NULL)
  10536.                                 return new JsonResponse(array(
  10537.                                     "success" => false,
  10538.                                     'errorText' => 'Could not Find Employee Head',
  10539.                                     'errorStr' => 'Could not Find Employee Head',
  10540.                                 ));
  10541.                             else {
  10542.                                 $data['party_head_id'] = $query_output[0]['accounts_head_id'];
  10543.                                 $data['description'] = $expData['expenseToNote'];
  10544.                                 $data['personal_expense_flag'] = 1;
  10545.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  10546.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  10547.                             }
  10548.                         }
  10549.                         if ($expData['expenseToBePaidTo'] == '_OWN_ADVANCE_' || $expData['expenseToBePaidTo'] == -2//own expense entry from app
  10550.                         {
  10551.                             $get_kids_sql "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " $request->getSession()->get(UserConstants::USER_ID) . "  limit 1";
  10552.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  10553.                             
  10554.                             $query_output $stmt;
  10555.                             if (empty($query_output)) {
  10556.                                 //                            $query_output[0] = $data['expense_id'];///// TEMP
  10557.                                 return new JsonResponse(array(
  10558.                                     "success" => false,
  10559.                                     'errorText' => 'You are not listed as Employee',
  10560.                                     'errorStr' => 'You are not listed as Employee',
  10561.                                 ));
  10562.                             } else if ($query_output[0]['advance_head_id'] == || $query_output[0]['advance_head_id'] == NULL)
  10563.                                 return new JsonResponse(array(
  10564.                                     "success" => false,
  10565.                                     'errorText' => 'Could not Find Employee Advance Head',
  10566.                                     'errorStr' => 'Could not Find Employee Advance Head',
  10567.                                 ));
  10568.                             else {
  10569.                                 $data['party_head_id'] = $query_output[0]['advance_head_id'];
  10570.                                 $data['description'] = $expData['expenseToNote'];
  10571.                                 $data['personal_expense_flag'] = 1;
  10572.                                 $data['expense_of_user_id'] = $query_output[0]['user_id'];
  10573.                                 $data['expense_of_employee_id'] = $query_output[0]['employee_id'];
  10574.                             }
  10575.                         }
  10576.                         if ($expData['expenseMarkerHash'] != '') {
  10577.                             $get_kids_sql "SELECT accounts_head_id FROM acc_accounts_head where marker_hash like '%" $expData['expenseMarkerHash'] . "%'  limit 1";
  10578.                             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  10579.                             
  10580.                             $query_output $stmt;
  10581.                             if (empty($query_output))
  10582.                                 return new JsonResponse(array("success" => false'errorText' => 'Could not find relevant Expense Head'));
  10583.                             else
  10584.                                 $data['expense_id'] = $query_output[0]['accounts_head_id'];
  10585.                         }
  10586.                         $new_ei Accounts::CreateExpenseInvoiceFromAddExpense(
  10587.                             $this->getDoctrine()->getManager(),
  10588.                             $data,
  10589.                             '',
  10590.                             $expBillType,
  10591.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10592.                             0,
  10593.                             ((int) ($expData['directProjectId'] ?? 0) > ? (int) $expData['directProjectId'] : ($so_data $so_data->getProjectId() : 0)),
  10594.                             0,
  10595.                             $expData['ccId'],
  10596.                             $expData['isChildInvoice'],
  10597.                             $primaryInvoiceId
  10598.                         );
  10599.                     }
  10600.                     if ($expData['isChildInvoice'] != && isset($new_ei['ei_id'])) {
  10601.                         $primaryInvoiceId $new_ei['ei_id'];
  10602.                     }
  10603.                 }
  10604.                 //single end
  10605.                 if ($primaryInvoiceId != 0) {
  10606.                     $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  10607.                     $approveRole $request->request->get('approvalRole');
  10608.                     $options = array(
  10609.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  10610.                         'notification_server' => $this->container->getParameter('notification_server'),
  10611.                         'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  10612.                         'url' => $this->generateUrl(
  10613.                             GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice']]['entity_view_route_path_name']
  10614.                         )
  10615.                     );
  10616.                     System::setApprovalInfo(
  10617.                         $this->getDoctrine()->getManager(),
  10618.                         $options,
  10619.                         array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
  10620.                         $primaryInvoiceId,
  10621.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  10622.                     );
  10623.                     System::createEditSignatureHash(
  10624.                         $this->getDoctrine()->getManager(),
  10625.                         array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
  10626.                         $primaryInvoiceId,
  10627.                         $loginId,
  10628.                         $request->request->get('approvalRole'1),
  10629.                         $request->request->get('approvalHash')
  10630.                     );
  10631.                 }
  10632.                 return new JsonResponse(array(
  10633.                     "success" => true,
  10634.                     'docId' => isset($new_ei['ei_id']) ? $new_ei['ei_id'] : '',
  10635.                     'docHash' => isset($new_ei['ei_doc_hash']) ? $new_ei['ei_doc_hash'] : '',
  10636.                 ));
  10637.             }
  10638.         }
  10639.         return new JsonResponse(array(
  10640.             "success" => true,
  10641.             'docId' => isset($new_ei['ei_id']) ? $new_ei['ei_id'] : '',
  10642.             'docHash' => isset($new_ei['ei_doc_hash']) ? $new_ei['ei_doc_hash'] : '',
  10643.             'expenseSubTypes' => $expenseSubTypes
  10644.         ));
  10645.         //
  10646.         //        return $this->render('@Accounts/pages/input_forms/payment_voucher.html.twig',
  10647.         //            array(
  10648.         //                'page_title'=>'Create Payment Voucher',
  10649.         //                'test'=>$details_ids,
  10650.         //                'supplier_list'=>Accounts::SupplierListForPv($this->getDoctrine()->getManager()),
  10651.         //                'supplier_list_by_ac_head'=>Accounts::SupplierListByAcHead($this->getDoctrine()->getManager()),
  10652.         //                'supplier_list_by_advance_head'=>Accounts::SupplierListByAdvanceHead($this->getDoctrine()->getManager())
  10653.         //            )
  10654.         //        );
  10655.     }
  10656.     public function GetSalesOrderDocument()
  10657.     {
  10658.         $em $this->getDoctrine()->getManager();
  10659.         $qb $em->createQueryBuilder();
  10660.         $qb->select('s.salesOrderId''s.documentHash''c.clientName')
  10661.             ->from('ApplicationBundle:SalesOrder''s')
  10662.             ->leftJoin('ApplicationBundle:AccClients''c''WITH''s.clientId = c.clientId')
  10663.             ->orderBy('s.salesOrderId''DESC');
  10664.         $results $qb->getQuery()->getArrayResult();
  10665.         return new JsonResponse([
  10666.             'success' => true,
  10667.             'data' => $results
  10668.         ]);
  10669.     }
  10670.     public function GetCostCenter()
  10671.     {
  10672.         $em $this->getDoctrine()->getManager();
  10673.         $qb $em->createQueryBuilder();
  10674.         $qb->select('c.costCentreId''c.name')
  10675.             ->from('ApplicationBundle:AccCostCentre''c');
  10676.         $results $qb->getQuery()->getArrayResult();
  10677.         return new JsonResponse([
  10678.             'success' => true,
  10679.             'data' => $results
  10680.         ]);
  10681.     }
  10682.     public function GetExpenseType()
  10683.     {
  10684.         $em $this->getDoctrine()->getManager();
  10685.         // Fetch Sales Orders
  10686.         $qb $em->createQueryBuilder();
  10687.         $qb->select(
  10688.             's.salesOrderId',
  10689.             's.documentHash',
  10690.             'c.clientName',
  10691.             'p.projectId',
  10692.             'p.projectName'
  10693.         )
  10694.             ->from('ApplicationBundle:SalesOrder''s')
  10695.             ->leftJoin('ApplicationBundle:AccClients''c''WITH''s.clientId = c.clientId')
  10696.             ->leftJoin('ApplicationBundle:Project''p''WITH''s.projectId = p.projectId')
  10697.             ->orderBy('s.salesOrderId''DESC');
  10698.         $salesOrders $qb->getQuery()->getArrayResult();
  10699.         // Fetch Cost Centres
  10700.         $qb2 $em->createQueryBuilder();
  10701.         $qb2->select('c.costCentreId''c.name')
  10702.             ->from('ApplicationBundle:AccCostCentre''c');
  10703.         $costCentres $qb2->getQuery()->getArrayResult();
  10704.         // Build Expense Types
  10705.         $types = [];
  10706.         foreach (GeneralConstant::$expenseType as $id => $name) {
  10707.             $types[] = [
  10708.                 'id' => $id,
  10709.                 'name' => $name,
  10710.                 'salesOrders' => $id === $salesOrders : [],
  10711.                 'costCentres' => $id === $costCentres : []
  10712.             ];
  10713.         }
  10714.         return new JsonResponse($types);
  10715.     }
  10716.     public function AddPayment(Request $request)
  10717.     {
  10718.         $details_ids = [];
  10719.         $em $this->getDoctrine()->getManager();
  10720.         if ($request->isMethod('POST')) {
  10721.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  10722.             $approveRole $request->request->get('approvalRole');
  10723.             $approveHash $request->request->get('approvalHash');
  10724.             if (!DocValidation::isSignatureOk($em$loginId$approveHash)) {
  10725.                 //                $this->addFlash(
  10726.                 //                    'error',
  10727.                 //                    'Sorry Could Not insert Data.'
  10728.                 //                );
  10729.                 return new JsonResponse(array(
  10730.                     "success" => false,
  10731.                     'errorText' => 'Approval Hash Mismatch',
  10732.                     'errorStr' => 'Approval Hash Mismatch'
  10733.                 ));
  10734.             } else {
  10735.                 //            Generic::debugMessage($_POST);
  10736.                 $payment_type $request->request->get('payment_type'); //1=supp, 2=employee 3=ac head
  10737.                 $payment_sub_type $request->request->get('payment_sub_type'); //1=gen, 2=adv 3=loan
  10738.                 $payment_to $request->request->get('payment_to_' $payment_type);
  10739.                 $payment_to_note $request->request->get('payment_to_note_' $payment_type);
  10740.                 $payment_from $request->request->get('payment_from');
  10741.                 $payment_from_note $request->request->get('payment_from_note');
  10742.                 $description $request->request->get('description');
  10743.                 $payment_amount $request->request->get('payment_amount');
  10744.                 $invoice_balancing $request->request->has('auto_balance' $payment_type) ? $request->request->get('auto_balance' $payment_type) : 0;
  10745.                 $em $this->getDoctrine()->getManager();
  10746.                 $pi_list = [];
  10747.                 $po_list = [];
  10748.                 $ei_list = [];
  10749.                 $assignable $payment_amount;
  10750.                 $general_amount 0;
  10751.                 $advance_amount 0;
  10752.                 $TransID 0;
  10753.                 $check_here = [];
  10754.                 $id_list_for_check = [];
  10755.                 $id_for_check '';
  10756.                 $details_ids = [];
  10757.                 $head_list Accounts::HeadList($em);
  10758.                 $balancing_data = [];
  10759.                 $purchase_invoices = [];
  10760.                 //            $to_assign=0;
  10761.                 //for supplier
  10762.                 if ($payment_type == 1) {
  10763.                     //                    $supplier_list = Accounts::SupplierListForPv($em);
  10764.                     $supp $em->getRepository('ApplicationBundle\\Entity\\AccSuppliers')->findOneBy(array(
  10765.                         'supplierId' => $payment_to,
  10766.                         'status' => GeneralConstant::ACTIVE
  10767.                     ));
  10768.                     $supplier_list = [];
  10769.                     $pa = array();
  10770.                     $pa['id'] = $supp->getSupplierId();
  10771.                     $pa['name'] = $supp->getSupplierName();
  10772.                     $pa['supplierShortCode'] = $supp->getSupplierShortCode();
  10773.                     $pa['supplier_head_id'] = $supp->getAccountsHeadId();
  10774.                     $pa['supplier_advance_head_id'] = $supp->getAdvanceHeadId();
  10775.                     $supplier_list[$supp->getSupplierId()] = $pa;
  10776.                     //                    $supplier_list = Accounts::SupplierListByAcHead($em, [$payment_to]);
  10777.                     $balancing_data Accounts::GetPurchaseInvoiceBalancingData($em, [], [$supplier_list[$payment_to]['supplier_head_id']]);
  10778.                     $id_for_check $supplier_list[$payment_to]['supplier_head_id'];
  10779.                     $purchase_invoices $balancing_data['purchase_invoices'];
  10780.                     if (!empty($purchase_invoices))
  10781.                         foreach ($purchase_invoices[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
  10782.                             $pi_list['id'][] = $entry['purchase_invoice_id'];
  10783.                             $pi_list['aa'][] = $assignable $entry['due_amount'] ? $entry['due_amount'] : $assignable;
  10784.                             $general_amount += ($assignable $entry['due_amount'] ? $entry['due_amount'] : $assignable);
  10785.                             $assignable $entry['due_amount'] ? ($assignable -= $entry['due_amount']) : ($assignable 0);
  10786.                         }
  10787.                     $expense_invoices $balancing_data['expense_invoices'];
  10788.                     if (!empty($expense_invoices))
  10789.                         foreach ($expense_invoices[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
  10790.                             $ei_list['id'][] = $entry['expense_invoice_id'];
  10791.                             $ei_list['ei_head_id'][] = $supplier_list[$payment_to]['supplier_head_id'];
  10792.                             $ei_list['aa'][] = $assignable $entry['due_amount'] ? $entry['due_amount'] : $assignable;
  10793.                             $general_amount += ($assignable $entry['due_amount'] ? $entry['due_amount'] : $assignable);
  10794.                             $assignable $entry['due_amount'] ? ($assignable -= $entry['due_amount']) : ($assignable 0);
  10795.                         }
  10796.                     $purchase_orders $balancing_data['purchase_orders'];
  10797.                     if (!empty($purchase_orders))
  10798.                         foreach ($purchase_orders[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
  10799.                             $po_list['id'][] = $entry['purchase_order_id'];
  10800.                             $po_list['aa'][] = $assignable $entry['po_amount'] ? $entry['po_amount'] : $assignable;
  10801.                             $advance_amount += ($assignable $entry['po_amount'] ? $entry['po_amount'] : $assignable);
  10802.                             $assignable $entry['po_amount'] ? ($assignable -= $entry['po_amount']) : ($assignable 0);
  10803.                         }
  10804.                     $ledgerHeads = [$supplier_list[$payment_to]['supplier_head_id'], $payment_to];
  10805.                     $notes = [$payment_from_note$payment_to_note];
  10806.                     $costCenters = [];
  10807.                     $drAmount $payment_amount;
  10808.                     $crAmount $payment_amount;
  10809.                     $notes $request->request->get('trNote');
  10810.                     $check_allowed 0;
  10811.                     //                $provisional=0;
  10812.                     if ($request->request->get('check_id') != '')
  10813.                         $check_allowed 1;
  10814.                     //                if($request->request->has('provisional'))
  10815.                     $provisional 1;
  10816.                     $TransID Accounts::CreateNewTransaction(
  10817.                         0,
  10818.                         $this->getDoctrine()->getManager(),
  10819.                         $request->request->get('payment_date'),
  10820.                         $payment_amount,
  10821.                         AccountsConstant::VOUCHER_PAYMENT,
  10822.                         $description,
  10823.                         'DV/GN/1/' Accounts::GetVNoHash($em'dv''gn'1),
  10824.                         'DV',
  10825.                         'GN',
  10826.                         1,
  10827.                         Accounts::GetVNoHash($em'dv''gn'1),
  10828.                         $check_allowed,
  10829.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10830.                         $this->getLoggedUserCompanyId($request),
  10831.                         '',
  10832.                         $provisional
  10833.                     );
  10834.                     $check_here = [];
  10835.                     //                $id_list_for_check=[];
  10836.                     //                $id_list_for_check[$supplier_list[$payment_to]['supplier_head_id']]=$supplier_list[$payment_to]['supplier_head_id'];
  10837.                     if ($general_amount 0) {
  10838.                         $details_ids[$supplier_list[$payment_to]['supplier_head_id']] = Accounts::CreateNewTransactionDetails(
  10839.                             $this->getDoctrine()->getManager(),
  10840.                             $request->request->get('payment_date'),
  10841.                             $TransID,
  10842.                             Generic::CurrToInt($general_amount),
  10843.                             $supplier_list[$payment_to]['supplier_head_id'],
  10844.                             $payment_to_note,
  10845.                             AccountsConstant::DEBIT,
  10846.                             0,
  10847.                             array($pi_list$po_list$ei_list),
  10848.                             [],
  10849.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10850.                             $provisional
  10851.                         );
  10852.                     }
  10853.                     if ($advance_amount 0) {
  10854.                         //                    $id_list_for_check[$supplier_list[$payment_to]['supplier_advance_head_id']]=$supplier_list[$payment_to]['supplier_head_id'];
  10855.                         $details_ids[$supplier_list[$payment_to]['supplier_advance_head_id']] = Accounts::CreateNewTransactionDetails(
  10856.                             $this->getDoctrine()->getManager(),
  10857.                             $request->request->get('payment_date'),
  10858.                             $TransID,
  10859.                             Generic::CurrToInt($advance_amount),
  10860.                             $supplier_list[$payment_to]['supplier_advance_head_id'],
  10861.                             $payment_to_note ' As Advance',
  10862.                             AccountsConstant::DEBIT,
  10863.                             0,
  10864.                             array($pi_list$po_list$ei_list),
  10865.                             [],
  10866.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10867.                             $provisional
  10868.                         );
  10869.                     }
  10870.                     $details_ids[$payment_from] = Accounts::CreateNewTransactionDetails(
  10871.                         $this->getDoctrine()->getManager(),
  10872.                         $request->request->get('payment_date'),
  10873.                         $TransID,
  10874.                         Generic::CurrToInt($payment_amount),
  10875.                         $payment_from,
  10876.                         $payment_from_note,
  10877.                         AccountsConstant::CREDIT,
  10878.                         0,
  10879.                         array($pi_list$po_list$ei_list),
  10880.                         [],
  10881.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10882.                         $provisional
  10883.                     );
  10884.                 }
  10885.                 if ($payment_type == 2) {
  10886.                     $id_for_check $payment_to;
  10887.                     //                    if(isset($supplier_list[$payment_to])) {
  10888.                     //                        $balancing_data = Accounts::GetPurchaseInvoiceBalancingData($em, [], [$supplier_list[$payment_to]['supplier_head_id']]);
  10889.                     //                        $id_for_check = $supplier_list[$payment_to]['supplier_head_id'];
  10890.                     //                        $purchase_invoices = $balancing_data['purchase_invoices'];
  10891.                     //
  10892.                     //                        if (!empty($purchase_invoices))
  10893.                     //                            foreach ($purchase_invoices[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
  10894.                     //                                $pi_list['id'][] = $entry['purchase_invoice_id'];
  10895.                     //                                $pi_list['aa'][] = $assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable;
  10896.                     //                                $general_amount += ($assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable);
  10897.                     //                                $assignable > $entry['due_amount'] ? ($assignable -= $entry['due_amount']) : ($assignable = 0);
  10898.                     //                            }
  10899.                     //                        $expense_invoices = $balancing_data['expense_invoices'];
  10900.                     //                        if (!empty($expense_invoices))
  10901.                     //                            foreach ($expense_invoices[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
  10902.                     //                                $ei_list['id'][] = $entry['expense_invoice_id'];
  10903.                     //                                $ei_list['ei_head_id'][] = $supplier_list[$payment_to]['supplier_head_id'];
  10904.                     //                                $ei_list['aa'][] = $assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable;
  10905.                     //                                $general_amount += ($assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable);
  10906.                     //                                $assignable > $entry['due_amount'] ? ($assignable -= $entry['due_amount']) : ($assignable = 0);
  10907.                     //                            }
  10908.                     //                        $purchase_orders = $balancing_data['purchase_orders'];
  10909.                     //                        if (!empty($purchase_orders))
  10910.                     //                            foreach ($purchase_orders[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
  10911.                     //                                $po_list['id'][] = $entry['purchase_order_id'];
  10912.                     //                                $po_list['aa'][] = $assignable > $entry['po_amount'] ? $entry['po_amount'] : $assignable;
  10913.                     //                                $advance_amount += ($assignable > $entry['po_amount'] ? $entry['po_amount'] : $assignable);
  10914.                     //                                $assignable > $entry['po_amount'] ? ($assignable -= $entry['po_amount']) : ($assignable = 0);
  10915.                     //                            }
  10916.                     //                    }
  10917.                     $check_allowed 0;
  10918.                     //                $provisional=0;
  10919.                     if ($request->request->get('check_id') != '')
  10920.                         $check_allowed 1;
  10921.                     //                if($request->request->has('provisional'))
  10922.                     $provisional 1;
  10923.                     $TransID Accounts::CreateNewTransaction(
  10924.                         0,
  10925.                         $this->getDoctrine()->getManager(),
  10926.                         $request->request->get('payment_date'),
  10927.                         $payment_amount,
  10928.                         AccountsConstant::VOUCHER_PAYMENT,
  10929.                         $description,
  10930.                         'DV/GN/1/' Accounts::GetVNoHash($em'dv''gn'1),
  10931.                         'DV',
  10932.                         'GN',
  10933.                         1,
  10934.                         Accounts::GetVNoHash($em'dv''gn'1),
  10935.                         $check_allowed,
  10936.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10937.                         $this->getLoggedUserCompanyId($request),
  10938.                         '',
  10939.                         $provisional
  10940.                     );
  10941.                     $check_here = [];
  10942.                     //                $id_list_for_check=[];
  10943.                     //                $id_list_for_check[$supplier_list[$payment_to]['supplier_head_id']]=$supplier_list[$payment_to]['supplier_head_id'];
  10944.                     $details_ids[$payment_to] = Accounts::CreateNewTransactionDetails(
  10945.                         $this->getDoctrine()->getManager(),
  10946.                         $request->request->get('payment_date'),
  10947.                         $TransID,
  10948.                         Generic::CurrToInt($payment_amount),
  10949.                         $payment_to,
  10950.                         $payment_to_note,
  10951.                         AccountsConstant::DEBIT,
  10952.                         0,
  10953.                         array($pi_list$po_list$ei_list),
  10954.                         [],
  10955.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10956.                         $provisional
  10957.                     );
  10958.                     $details_ids[$payment_from] = Accounts::CreateNewTransactionDetails(
  10959.                         $this->getDoctrine()->getManager(),
  10960.                         $request->request->get('payment_date'),
  10961.                         $TransID,
  10962.                         Generic::CurrToInt($payment_amount),
  10963.                         $payment_from,
  10964.                         $payment_from_note,
  10965.                         AccountsConstant::CREDIT,
  10966.                         0,
  10967.                         array($pi_list$po_list$ei_list),
  10968.                         [],
  10969.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10970.                         $provisional
  10971.                     );
  10972.                 }
  10973.                 if ($payment_type == 3) {
  10974.                     $id_for_check $payment_to;
  10975.                     $supplier_list Accounts::SupplierListForPv($em);
  10976.                     //                    if(isset($supplier_list[$payment_to])) {
  10977.                     //                        $balancing_data = Accounts::GetPurchaseInvoiceBalancingData($em, [], [$supplier_list[$payment_to]['supplier_head_id']]);
  10978.                     //                        $id_for_check = $supplier_list[$payment_to]['supplier_head_id'];
  10979.                     //                        $purchase_invoices = $balancing_data['purchase_invoices'];
  10980.                     //
  10981.                     //                        if (!empty($purchase_invoices))
  10982.                     //                            foreach ($purchase_invoices[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
  10983.                     //                                $pi_list['id'][] = $entry['purchase_invoice_id'];
  10984.                     //                                $pi_list['aa'][] = $assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable;
  10985.                     //                                $general_amount += ($assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable);
  10986.                     //                                $assignable > $entry['due_amount'] ? ($assignable -= $entry['due_amount']) : ($assignable = 0);
  10987.                     //                            }
  10988.                     //                        $expense_invoices = $balancing_data['expense_invoices'];
  10989.                     //                        if (!empty($expense_invoices))
  10990.                     //                            foreach ($expense_invoices[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
  10991.                     //                                $ei_list['id'][] = $entry['expense_invoice_id'];
  10992.                     //                                $ei_list['ei_head_id'][] = $supplier_list[$payment_to]['supplier_head_id'];
  10993.                     //                                $ei_list['aa'][] = $assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable;
  10994.                     //                                $general_amount += ($assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable);
  10995.                     //                                $assignable > $entry['due_amount'] ? ($assignable -= $entry['due_amount']) : ($assignable = 0);
  10996.                     //                            }
  10997.                     //                        $purchase_orders = $balancing_data['purchase_orders'];
  10998.                     //                        if (!empty($purchase_orders))
  10999.                     //                            foreach ($purchase_orders[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
  11000.                     //                                $po_list['id'][] = $entry['purchase_order_id'];
  11001.                     //                                $po_list['aa'][] = $assignable > $entry['po_amount'] ? $entry['po_amount'] : $assignable;
  11002.                     //                                $advance_amount += ($assignable > $entry['po_amount'] ? $entry['po_amount'] : $assignable);
  11003.                     //                                $assignable > $entry['po_amount'] ? ($assignable -= $entry['po_amount']) : ($assignable = 0);
  11004.                     //                            }
  11005.                     //                    }
  11006.                     $check_allowed 0;
  11007.                     //                $provisional=0;
  11008.                     if ($request->request->get('check_id') != '')
  11009.                         $check_allowed 1;
  11010.                     //                if($request->request->has('provisional'))
  11011.                     $provisional 1;
  11012.                     $TransID Accounts::CreateNewTransaction(
  11013.                         0,
  11014.                         $this->getDoctrine()->getManager(),
  11015.                         $request->request->get('payment_date'),
  11016.                         $payment_amount,
  11017.                         AccountsConstant::VOUCHER_PAYMENT,
  11018.                         $description,
  11019.                         'DV/GN/1/' Accounts::GetVNoHash($em'dv''gn'1),
  11020.                         'DV',
  11021.                         'GN',
  11022.                         1,
  11023.                         Accounts::GetVNoHash($em'dv''gn'1),
  11024.                         $check_allowed,
  11025.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  11026.                         $this->getLoggedUserCompanyId($request),
  11027.                         '',
  11028.                         $provisional
  11029.                     );
  11030.                     $check_here = [];
  11031.                     //                $id_list_for_check=[];
  11032.                     //                $id_list_for_check[$supplier_list[$payment_to]['supplier_head_id']]=$supplier_list[$payment_to]['supplier_head_id'];
  11033.                     $details_ids[$payment_to] = Accounts::CreateNewTransactionDetails(
  11034.                         $this->getDoctrine()->getManager(),
  11035.                         $request->request->get('payment_date'),
  11036.                         $TransID,
  11037.                         Generic::CurrToInt($payment_amount),
  11038.                         $payment_to,
  11039.                         $payment_to_note,
  11040.                         AccountsConstant::DEBIT,
  11041.                         0,
  11042.                         array($pi_list$po_list$ei_list),
  11043.                         [],
  11044.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  11045.                         $provisional
  11046.                     );
  11047.                     $details_ids[$payment_from] = Accounts::CreateNewTransactionDetails(
  11048.                         $this->getDoctrine()->getManager(),
  11049.                         $request->request->get('payment_date'),
  11050.                         $TransID,
  11051.                         Generic::CurrToInt($payment_amount),
  11052.                         $payment_from,
  11053.                         $payment_from_note,
  11054.                         AccountsConstant::CREDIT,
  11055.                         0,
  11056.                         array($pi_list$po_list$ei_list),
  11057.                         [],
  11058.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  11059.                         $provisional
  11060.                     );
  11061.                 }
  11062.                 if ($request->request->has('check_id')) {
  11063.                     $check_here $this->getDoctrine()
  11064.                         ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  11065.                         ->findOneBy(
  11066.                             array(
  11067.                                 'CheckId' => $request->request->get('check_id')
  11068.                             )
  11069.                         );
  11070.                     if ($check_here) {
  11071.                         $check_here->setRecAccountsHeadId($id_for_check);
  11072.                         $check_here->setRecAccountsHeadIdList(json_encode([$id_for_check]));
  11073.                         $check_here->setCheckNarration(empty($request->request->get('check_narration')) ? $head_list[$id_for_check]['name'] : $request->request->get('check_narration'));
  11074.                         $check_here->setCheckAmount($payment_amount);
  11075.                         $check_here->setCheckDate(new \DateTime($request->request->get('check_date')));
  11076.                         $check_here->setAssigned(1);
  11077.                         $check_here->setVoucherId($TransID);
  11078.                     }
  11079.                 }
  11080.                 //approval system
  11081.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  11082.                 $approveRole $request->request->get('approvalRole');
  11083.                 Accounts::UpdatePurchasePayments($em$pi_list$po_list$details_ids$request->request->get('payment_date'), $payment_to);
  11084.                 Accounts::UpdateExpensePayments($em$ei_list$details_ids$request->request->get('payment_date'));
  11085.                 System::setApprovalInfo(
  11086.                     $this->getDoctrine()->getManager(),
  11087.                     [],
  11088.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  11089.                     $TransID,
  11090.                     $loginId,
  11091.                     5    //payment voucher
  11092.                 );
  11093.                 System::createEditSignatureHash(
  11094.                     $em,
  11095.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  11096.                     $TransID,
  11097.                     $loginId,
  11098.                     $approveRole,
  11099.                     $request->request->get('approvalHash')
  11100.                 );
  11101.                 //                $this->addFlash(
  11102.                 //                    'success',
  11103.                 //                    'New Transaction Added.'
  11104.                 //                );
  11105.                 $url $this->generateUrl(
  11106.                     'view_voucher'
  11107.                 );
  11108.                 $trans_here $this->getDoctrine()
  11109.                     ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  11110.                     ->findOneBy(
  11111.                         array(
  11112.                             'transactionId' => $TransID
  11113.                         )
  11114.                     );
  11115.                 System::AddNewNotification(
  11116.                     $this->container->getParameter('notification_enabled'),
  11117.                     $this->container->getParameter('notification_server'),
  11118.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  11119.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  11120.                     "Debit Voucher : " $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
  11121.                     'pos',
  11122.                     System::getPositionIdsByDepartment($emGeneralConstant::ACCOUNTS_DEPARTMENT),
  11123.                     'success',
  11124.                     $url "/" $TransID,
  11125.                     "Debit Voucher"
  11126.                 );
  11127.                 return new JsonResponse(array(
  11128.                     "success" => true,
  11129.                     'docId' => $TransID,
  11130.                     'docHash' => $trans_here->getDocumentHash(),
  11131.                 ));
  11132.             }
  11133.         }
  11134.         return new JsonResponse(array("success" => true));
  11135.     }
  11136.     public function AddReceipt(Request $request)
  11137.     {
  11138.         $details_ids = [];
  11139.         $em $this->getDoctrine()->getManager();
  11140.         $docId 0;
  11141.         $docHash 0;
  11142.         $companyId $this->getLoggedUserCompanyId($request);
  11143.         if ($request->isMethod('POST')) {
  11144.             $balancing_data = [];
  11145.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  11146.             $approveRole $request->request->get('approvalRole');
  11147.             $approveHash $request->request->get('approvalHash');
  11148.             if (!DocValidation::isSignatureOk($em$loginId$approveHash)) {
  11149.                 //                $this->addFlash(
  11150.                 //                    'error',
  11151.                 //                    'Sorry Could Not insert Data.'
  11152.                 //                );
  11153.                 return new JsonResponse(array(
  11154.                     "success" => false,
  11155.                     'errorText' => 'Approval Hash Mismatch',
  11156.                     'errorStr' => 'Approval Hash Mismatch'
  11157.                 ));
  11158.             } else {
  11159.                 //            Generic::debugMessage($_POST);
  11160.                 //                $em->getRepository('ApplicationBundle\\Entity\\AccService')->findAll();
  11161.                 $receipt_type $request->request->get('receipt_type'); //1=client, 2=employee 3=ac head
  11162.                 $receipt_sub_type $request->request->get('receipt_sub_type'); //1=gen, 2=adv 3=loan
  11163.                 $receipt_from $request->request->get('receipt_from_' $receipt_type);
  11164.                 $receipt_from_note $request->request->get('receipt_from_note_' $receipt_type);
  11165.                 $receipt_to $request->request->get('receipt_to');
  11166.                 $receipt_to_note $request->request->get('receipt_to_note');
  11167.                 $description $request->request->get('description');
  11168.                 $receipt_amount $request->request->get('receipt_amount');
  11169.                 $receipt_charge_amount = ($request->request->get('receipt_charge_amount'));
  11170.                 $receipt_charge_head $request->request->get('receipt_charge_head');
  11171.                 $receipt_charge_note $request->request->get('receipt_charge_note');
  11172.                 $receipt_deposit_amount = ($request->request->get('receipt_deposit_amount'));
  11173.                 //                $em->getRepository('ApplicationBundle\\Entity\\AccService')->findAll();
  11174.                 //                $receipt_deposit_head = $request->request->get('receipt_deposit_head');
  11175.                 if ($receipt_charge_amount && $receipt_charge_head == '')
  11176.                     return new JsonResponse(array("success" => false));
  11177.                 if ($receipt_charge_amount $receipt_deposit_amount != $receipt_amount)
  11178.                     return new JsonResponse(array("success" => false));
  11179.                 $invoice_balancing $request->request->has('auto_balance' $receipt_type) ? $request->request->get('auto_balance' $receipt_type) : 0;
  11180.                 $em $this->getDoctrine()->getManager();
  11181.                 $si_list = [];
  11182.                 $so_list = [];
  11183.                 $ei_list = [];
  11184.                 $assignable $receipt_amount;
  11185.                 $general_amount 0;
  11186.                 $advance_amount 0;
  11187.                 $TransID 0;
  11188.                 $check_here = [];
  11189.                 $id_list_for_check = [];
  11190.                 $id_for_check '';
  11191.                 $details_ids = [];
  11192.                 $head_list Accounts::HeadList($em);
  11193.                 $client_list Client::GetExistingClientList($em$companyId);
  11194.                 //                $clnt = $client_list[$receipt_from];
  11195.                 //            $to_assign=0;
  11196.                 //for client
  11197.                 if ($receipt_type == 1) {
  11198.                     $clnt $client_list[$receipt_from];
  11199.                     //now check if special case like came form SO
  11200.                     $balancing_data Accounts::GetSalesInvoiceBalancingData(
  11201.                         $em,
  11202.                         [],
  11203.                         [$client_list[$receipt_from]['accHeadId']],
  11204.                         $request->request->get('AddReceiptModalSpecialType'),
  11205.                         [$request->request->get('AddReceiptModalSpecialTypeSoDocId')],
  11206.                         [$request->request->get('AddReceiptModalSpecialTypeSiDocId')]
  11207.                     );
  11208.                     $id_for_check $client_list[$receipt_from]['accHeadId'];
  11209.                     $sales_invoices $balancing_data['sales_invoices'];
  11210.                     if (!empty($sales_invoices))
  11211.                         foreach ($sales_invoices[$client_list[$receipt_from]['accHeadId']] as $entry) {
  11212.                             $si_list['id'][] = $entry['sales_invoice_id'];
  11213.                             $si_list['aa'][] = $assignable $entry['due_amount'] ? $entry['due_amount'] : $assignable;
  11214.                             $general_amount += ($assignable $entry['due_amount'] ? $entry['due_amount'] : $assignable);
  11215.                             $assignable $entry['due_amount'] ? ($assignable -= $entry['due_amount']) : ($assignable 0);
  11216.                         }
  11217.                     $expense_invoices $balancing_data['expense_invoices'];
  11218.                     if (!empty($expense_invoices))
  11219.                         foreach ($expense_invoices[$client_list[$receipt_from]['accHeadId']] as $entry) {
  11220.                             $ei_list['id'][] = $entry['expense_invoice_id'];
  11221.                             $ei_list['ei_head_id'][] = $client_list[$receipt_from]['accHeadId'];
  11222.                             $ei_list['aa'][] = $assignable $entry['due_amount'] ? $entry['due_amount'] : $assignable;
  11223.                             $general_amount += ($assignable $entry['due_amount'] ? $entry['due_amount'] : $assignable);
  11224.                             $assignable $entry['due_amount'] ? ($assignable -= $entry['due_amount']) : ($assignable 0);
  11225.                         }
  11226.                     $sales_orders $balancing_data['sales_orders'];
  11227.                     if (!empty($sales_orders))
  11228.                         foreach ($sales_orders[$client_list[$receipt_from]['accHeadId']] as $entry) {
  11229.                             $so_list['id'][] = $entry['sales_order_id'];
  11230.                             $so_list['aa'][] = $assignable $entry['so_amount'] ? $entry['so_amount'] : $assignable;
  11231.                             $advance_amount += ($assignable $entry['so_amount'] ? $entry['so_amount'] : $assignable);
  11232.                             $assignable $entry['so_amount'] ? ($assignable -= $entry['so_amount']) : ($assignable 0);
  11233.                         }
  11234.                     $ledgerHeads = [$client_list[$receipt_from]['accHeadId'], $receipt_from];
  11235.                     $notes = [$receipt_to_note$receipt_from_note];
  11236.                     $costCenters = [];
  11237.                     $drAmount $receipt_amount;
  11238.                     $crAmount $receipt_amount;
  11239.                     $notes $request->request->get('trNote');
  11240.                     $check_allowed 0;
  11241.                     //                $provisional=0;
  11242.                     if ($request->request->get('check_id') != '')
  11243.                         $check_allowed 1;
  11244.                     //                if($request->request->has('provisional'))
  11245.                     $provisional 1;
  11246.                     $TransID Accounts::CreateNewTransaction(
  11247.                         0,
  11248.                         $this->getDoctrine()->getManager(),
  11249.                         $request->request->get('receipt_date'),
  11250.                         $receipt_amount,
  11251.                         AccountsConstant::VOUCHER_RECEIPT,
  11252.                         $description,
  11253.                         'CV/GN/1/' Accounts::GetVNoHash($em'CV''GN'1),
  11254.                         'CV',
  11255.                         'GN',
  11256.                         1,
  11257.                         Accounts::GetVNoHash($em'CV''GN'1),
  11258.                         $check_allowed,
  11259.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  11260.                         $this->getLoggedUserCompanyId($request),
  11261.                         '',
  11262.                         $provisional,
  11263.                         0,
  11264.                         0,
  11265.                         '',
  11266.                         $request->request->get('branchId'0),
  11267.                         '_UNSET_',
  11268.                         '_UNSET_',
  11269.                         0,
  11270.                         '',
  11271.                         $request->request->get('uploaded_image_path''')
  11272.                     );
  11273.                     $check_here = [];
  11274.                     //                $id_list_for_check=[];
  11275.                     //                $id_list_for_check[$client_list[$receipt_from]['supplier_head_id']]=$client_list[$receipt_from]['supplier_head_id'];
  11276.                     if ($general_amount 0) {
  11277.                         $details_ids[$client_list[$receipt_from]['accHeadId']] = Accounts::CreateNewTransactionDetails(
  11278.                             $this->getDoctrine()->getManager(),
  11279.                             $request->request->get('receipt_date'),
  11280.                             $TransID,
  11281.                             Generic::CurrToInt($general_amount),
  11282.                             $client_list[$receipt_from]['accHeadId'],
  11283.                             $receipt_from_note,
  11284.                             AccountsConstant::CREDIT,
  11285.                             0,
  11286.                             array($si_list$so_list$ei_list),
  11287.                             [],
  11288.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  11289.                             $provisional
  11290.                         );
  11291.                     }
  11292.                     if ($advance_amount 0) {
  11293.                         //                    $id_list_for_check[$client_list[$receipt_from]['supplier_advance_head_id']]=$client_list[$receipt_from]['supplier_head_id'];
  11294.                         $details_ids[$client_list[$receipt_from]['advanceHeadId']] = Accounts::CreateNewTransactionDetails(
  11295.                             $this->getDoctrine()->getManager(),
  11296.                             $request->request->get('receipt_date'),
  11297.                             $TransID,
  11298.                             Generic::CurrToInt($advance_amount),
  11299.                             $client_list[$receipt_from]['advanceHeadId'],
  11300.                             $receipt_from_note ' As Advance',
  11301.                             AccountsConstant::CREDIT,
  11302.                             0,
  11303.                             array($si_list$so_list$ei_list),
  11304.                             [],
  11305.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  11306.                             $provisional
  11307.                         );
  11308.                     }
  11309.                     $details_ids[$receipt_to] = Accounts::CreateNewTransactionDetails(
  11310.                         $this->getDoctrine()->getManager(),
  11311.                         $request->request->get('receipt_date'),
  11312.                         $TransID,
  11313.                         Generic::CurrToInt($receipt_deposit_amount),
  11314.                         $receipt_to,
  11315.                         $receipt_to_note,
  11316.                         AccountsConstant::DEBIT,
  11317.                         0,
  11318.                         array($si_list$so_list$ei_list),
  11319.                         [],
  11320.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  11321.                         $provisional
  11322.                     );
  11323.                     if ($receipt_charge_amount != 0) {
  11324.                         $details_ids[$receipt_to] = Accounts::CreateNewTransactionDetails(
  11325.                             $this->getDoctrine()->getManager(),
  11326.                             $request->request->get('receipt_date'),
  11327.                             $TransID,
  11328.                             Generic::CurrToInt($receipt_charge_amount),
  11329.                             $receipt_charge_head,
  11330.                             $receipt_charge_note,
  11331.                             AccountsConstant::DEBIT,
  11332.                             0,
  11333.                             array($si_list$so_list$ei_list),
  11334.                             [],
  11335.                             $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  11336.                             $provisional
  11337.                         );
  11338.                     }
  11339.                 }
  11340.                 //now check if the head is bank head if so add a check entry
  11341.                 $bank_settings $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  11342.                     'name' => 'bank_parents'
  11343.                 ));
  11344.                 $under_bank 0;
  11345.                 $bank_id_list = [];
  11346.                 if ($bank_settings)
  11347.                     $bank_id_list json_decode($bank_settings->getData());
  11348.                 $the_head $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findOneBy(array('accountsHeadId' => $receipt_to));
  11349.                 if ($the_head) {
  11350.                     $path_tree_list explode('/'$the_head->getPathTree());
  11351.                     foreach ($path_tree_list as $pt) {
  11352.                         if (in_array($pt$bank_id_list)) {
  11353.                             $under_bank 1;
  11354.                         }
  11355.                     }
  11356.                 }
  11357.                 if ($under_bank == 1) {
  11358.                     //                foreach($request->request->get('check_id') as $k=>$value)
  11359.                     //                {
  11360.                     $check_here = new AccCheck();
  11361.                     $check_here->setRecAccountsHeadId($receipt_to);
  11362.                     $check_here->setRecAccountsHeadIdList(json_encode([$receipt_to]));
  11363.                     $check_here->setAccountsHeadId($client_list[$receipt_from]['accHeadId']);
  11364.                     //                    $check_here->setCheckNarration($request->request->get('check_narration')[$k]);
  11365.                     $check_here->setCheckAmount($receipt_amount);
  11366.                     $check_here->setCheckDate(new \DateTime($request->request->get('receipt_date')));
  11367.                     $check_here->setTransactionDate(new \DateTime($request->request->get('receipt_date')));
  11368.                     //                    $check_here->setCheckDate(new \DateTime($request->request->get('date')));
  11369.                     $check_here->setAssigned(1);
  11370.                     $check_here->setActive(1);
  11371.                     $check_here->setDetails('');
  11372.                     $check_here->setCheckNumber($request->request->get('receipt_check_number'));
  11373.                     $check_here->setStatus(3);
  11374.                     $check_here->setType(2); //receipt check
  11375.                     $check_here->setVoucherId($TransID);
  11376.                     //                }
  11377.                     $em->persist($check_here);
  11378.                     $em->flush();
  11379.                 }
  11380.                 //approval system
  11381.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  11382.                 $approveRole $request->request->get('approvalRole');
  11383.                 Accounts::UpdateSalesPayments($em$si_list$so_list$details_ids$request->request->get('receipt_date'), $receipt_from);
  11384.                 //            Accounts::UpdateExpenseReceipts($em,$ei_list,$details_ids,  $request->request->get('receipt_date'));
  11385.                 System::setApprovalInfo(
  11386.                     $this->getDoctrine()->getManager(),
  11387.                     [],
  11388.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  11389.                     $TransID,
  11390.                     $loginId,
  11391.                     6    //receipt voucher
  11392.                 );
  11393.                 System::createEditSignatureHash(
  11394.                     $em,
  11395.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  11396.                     $TransID,
  11397.                     $loginId,
  11398.                     $approveRole,
  11399.                     $request->request->get('approvalHash')
  11400.                 );
  11401.                 //                $this->addFlash(
  11402.                 //                    'success',
  11403.                 //                    'New Transaction Added.'
  11404.                 //                );
  11405.                 $url $this->generateUrl(
  11406.                     'view_voucher'
  11407.                 );
  11408.                 $trans_here $this->getDoctrine()
  11409.                     ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  11410.                     ->findOneBy(
  11411.                         array(
  11412.                             'transactionId' => $TransID
  11413.                         )
  11414.                     );
  11415.                 System::AddNewNotification(
  11416.                     $this->container->getParameter('notification_enabled'),
  11417.                     $this->container->getParameter('notification_server'),
  11418.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  11419.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  11420.                     "Debit Voucher : " $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
  11421.                     'pos',
  11422.                     System::getPositionIdsByDepartment($emGeneralConstant::ACCOUNTS_DEPARTMENT),
  11423.                     'success',
  11424.                     $url "/" $TransID,
  11425.                     "Debit Voucher"
  11426.                 );
  11427.                 return new JsonResponse(array(
  11428.                     'success' => true,
  11429.                     'transactionId' => $TransID,
  11430.                     'docId' => $TransID,
  11431.                     'docHash' => $trans_here->getDocumentHash(),
  11432.                     'balancing_data' => $balancing_data,
  11433.                     'clnt' => $clnt,
  11434.                     'general_amount' => $general_amount,
  11435.                     'advance_amount' => $advance_amount,
  11436.                     'assignable' => $assignable,
  11437.                 ));
  11438.             }
  11439.         }
  11440.         return new JsonResponse(array(
  11441.             'success' => false,
  11442.             'transactionId' => 0,
  11443.             'balancing_data' => [],
  11444.             'clnt' => 0,
  11445.             'general_amount' => 0,
  11446.             'advance_amount' => 0,
  11447.             'assignable' => 0,
  11448.         ));
  11449.     }
  11450.     public function GetChildHeadsByMarkerHash(Request $request$queryStr '')
  11451.     {
  11452.         $em $this->getDoctrine()->getManager();
  11453.         $dataList = [];
  11454.         $data_by_id = [];
  11455.         $lastChildrenOnly $request->request->has('lastChildrenOnly') ? $request->request->get('lastChildrenOnly') : 0;
  11456.         $renderTextFormat $request->request->has('renderTextFormat') ? $request->request->get('renderTextFormat') : '';
  11457.         $valueField $request->request->has('valueField') ? $request->request->get('valueField') : 'accounts_head_id';
  11458.         $textField $request->request->has('textField') ? $request->request->get('textField') : 'name';
  11459.         $parentOnly $request->request->has('parentOnly') ? $request->request->get('parentOnly') : 0;
  11460.         $queryText $request->request->get('query''_EMPTY_');
  11461.         $itemLimit $request->request->get('itemLimit'25);
  11462.         $offset $request->request->get('offset'0);
  11463.         $isMultiple $request->request->get('isMultiple'0);
  11464.         $selectorId $request->request->get('selectorId''');
  11465.         $dataId $request->request->get('dataId''');
  11466.         $joinTableData $request->request->has('joinTableData') ? $request->request->get('joinTableData') : [];
  11467.         if (is_string($joinTableData)) $joinTableData json_decode($joinTableDatatrue);
  11468.         $setValueArray = [];
  11469.         $setValue 0;
  11470.         $selectedId 0;
  11471.         $selectAll 0;
  11472.         $table 'acc_accounts_head';
  11473.         if (!(strpos($queryText'#setValue:') === false)) {
  11474.             $setValueArrayBeforeFilter explode(','str_replace('#setValue:'''$queryText));
  11475.             foreach ($setValueArrayBeforeFilter as $svf) {
  11476.                 if ($svf == '_ALL_') {
  11477.                     $selectAll 1;
  11478.                     $setValueArray = [];
  11479.                     continue;
  11480.                 }
  11481.                 if (is_numeric($svf)) {
  11482.                     $setValueArray[] = ($svf 1);
  11483.                     $setValue $svf 1;
  11484.                 }
  11485.             }
  11486.             $queryText '_EMPTY_';
  11487.             $marker_hash_list = ['_ALL_'];
  11488.         } else
  11489.             $marker_hash_list explode(','$request->request->get('marker_hash'''));
  11490.         if (!empty($marker_hash_list)) {
  11491.             $markerHashLikeStr '';
  11492.             $first_item 1;
  11493.             $skipMarkerHash 0;
  11494.             foreach ($marker_hash_list as $marker_hash) {
  11495.                 if ($first_item == 0$markerHashLikeStr .= " or ";
  11496.                 if ($marker_hash == '_ALL_') {
  11497.                     $skipMarkerHash 1;
  11498.                     continue;
  11499.                 } else
  11500.                     $markerHashLikeStr .= "acc_accounts_head.marker_hash like '%$marker_hash%' ";
  11501.                 $first_item 0;
  11502.             }
  11503.             $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 
  11504. cross join acc_accounts_head acc_accounts_head_0 on    `acc_accounts_head_0`.`accounts_head_id` = `acc_accounts_head`.`parent_id`
  11505. ";
  11506.             if ($skipMarkerHash == 1) {
  11507.                 $markerHashQuery "SELECT  acc_accounts_head.* , acc_accounts_head_0.name  parent_table_name FROM acc_accounts_head 
  11508. cross join acc_accounts_head acc_accounts_head_0 on    `acc_accounts_head_0`.`accounts_head_id` = `acc_accounts_head`.`parent_id` 
  11509.     
  11510.     ";
  11511.                 if ($lastChildrenOnly == 1) {
  11512.                     $markerHashQuery .= "WHERE acc_accounts_head.accounts_head_id not in (select distinct parent_id from acc_accounts_head) ";
  11513.                 } else if ($parentOnly == 1) {
  11514.                     $markerHashQuery .= "WHERE acc_accounts_head.accounts_head_id  in (select distinct parent_id from acc_accounts_head) ";
  11515.                 } else
  11516.                     $markerHashQuery .= "WHERE  1=1 ";
  11517.                 //                $markerHashQuery .= "WHERE acc_accounts_head.accounts_head_id not in (select distinct parent_id from acc_accounts_head) ";
  11518.                 if ($queryText != '_EMPTY_') {
  11519.                     $markerHashQuery .= " AND (";
  11520.                     if (is_numeric($queryText)) {
  11521.                         $markerHashQuery .= (" acc_accounts_head.accounts_head_id = " $queryText " ");
  11522.                     } else {
  11523.                         $queryTextArray explode(','$queryText);
  11524.                         $addOn '';
  11525.                         foreach ($queryTextArray as $dd) {
  11526.                             $markerHashQuery .= ($addOn " acc_accounts_head.name like '%" $dd "%' ");
  11527.                             $addOn ' or ';
  11528.                         }
  11529.                     }
  11530.                     $markerHashQuery .= " ) ";
  11531.                 }
  11532.                 if (!empty($setValueArray) || $selectAll == 1) {
  11533.                     if (!empty($setValueArray)) {
  11534.                         if ($markerHashQuery != '')
  11535.                             $markerHashQuery .= " and ";
  11536.                         $markerHashQuery .= " acc_accounts_head.accounts_head_id in (" implode(','$setValueArray) . ") ";
  11537.                     }
  11538.                 }
  11539.                 if ($itemLimit != '_ALL_')
  11540.                     $markerHashQuery .= "  limit $offset$itemLimit ";
  11541.                 else
  11542.                     $markerHashQuery .= "  limit $offset, 18446744073709551615 ";
  11543.                 $markerHashQuery .= " ;";
  11544.                 $stmt $em->getConnection()->fetchAllAssociative($markerHashQuery);
  11545.                 
  11546.                 $markerHashQueryResults $stmt;
  11547.                 foreach ($markerHashQueryResults as $markerHashQueryResult) {
  11548.                     $markerHashQueryResult['value'] = $markerHashQueryResult['accounts_head_id'];
  11549.                     $markerHashQueryResult['text'] = $markerHashQueryResult['name'];
  11550.                     $markerHashQueryResult['id_value'] = '# ' $markerHashQueryResult['accounts_head_id'] . ' ' $markerHashQueryResult['name'];
  11551.                     $renderedText $renderTextFormat;
  11552.                     $compare_array = [];
  11553.                     if ($renderTextFormat != '') {
  11554.                         $renderedText $renderTextFormat;
  11555.                         $compare_arrayFull = [];
  11556.                         $compare_array = [];
  11557.                         $toBeReplacedData = array( //                        'curr'=>'tobereplaced'
  11558.                         );
  11559.                         preg_match_all("/__\w+__/"$renderedText$compare_arrayFull);
  11560.                         if (isset($compare_arrayFull[0]))
  11561.                             $compare_array $compare_arrayFull[0];
  11562.                         //                   $compare_array= preg_split("/__\w+__/",$renderedText);
  11563.                         foreach ($compare_array as $cmpdt) {
  11564.                             $tbr str_replace("__"""$cmpdt);
  11565.                             if ($tbr != '') {
  11566.                                 if (isset($markerHashQueryResult[$tbr])) {
  11567.                                     if ($markerHashQueryResult[$tbr] == null)
  11568.                                         $renderedText str_replace($cmpdt''$renderedText);
  11569.                                     else
  11570.                                         $renderedText str_replace($cmpdt$markerHashQueryResult[$tbr], $renderedText);
  11571.                                 } else {
  11572.                                     $renderedText str_replace($cmpdt''$renderedText);
  11573.                                 }
  11574.                             }
  11575.                         }
  11576.                     }
  11577.                     $markerHashQueryResult['rendered_text'] = $renderedText;
  11578.                     $markerHashQueryResult['text'] = ($textField != '' $markerHashQueryResult[$textField] : '');
  11579.                     $dataList[] = $markerHashQueryResult;
  11580.                     if ($valueField != '') {
  11581.                         $data_by_id[$markerHashQueryResult[$valueField]] = $markerHashQueryResult;
  11582.                         $selectedId $markerHashQueryResult[$valueField];
  11583.                     }
  11584.                 }
  11585.             } else {
  11586.                 $markerHashQuery .= "WHERE ( $markerHashLikeStr );";
  11587.                 $stmt $em->getConnection()->fetchAllAssociative($markerHashQuery);
  11588.                 
  11589.                 $markerHashQueryResults $stmt;
  11590.                 $hids = [];
  11591.                 foreach ($markerHashQueryResults as $h) {
  11592.                     $hids[] = $h['accounts_head_id'];
  11593.                 }
  11594.                 $markerHashLikeStr '';
  11595.                 if (!empty($hids))
  11596.                     $markerHashLikeStr 'accounts_head_id in (' implode(','$hids) . ') ';
  11597.                 foreach ($markerHashQueryResults as $h) {
  11598.                     $markerHashLikeStr .= "OR path_tree LIKE '%/" $h['accounts_head_id'] . "/%'  ";
  11599.                 }
  11600.                 if ($markerHashLikeStr != '') {
  11601.                     $markerHashQuery "SELECT  acc_accounts_head.* FROM acc_accounts_head ";
  11602.                     //                    $markerHashQuery .= "WHERE acc_accounts_head.accounts_head_id not in (select distinct parent_id from acc_accounts_head) and ( $markerHashLikeStr )";
  11603.                     if ($lastChildrenOnly == 1) {
  11604.                         $markerHashQuery .= "WHERE acc_accounts_head.accounts_head_id not in (select distinct parent_id from acc_accounts_head) and ( $markerHashLikeStr )";
  11605.                     } else if ($parentOnly == 1) {
  11606.                         $markerHashQuery .= "WHERE acc_accounts_head.accounts_head_id  in (select distinct parent_id from acc_accounts_head) and ( $markerHashLikeStr )";
  11607.                     } else
  11608.                         $markerHashQuery .= "WHERE  ( $markerHashLikeStr )";
  11609.                     if ($queryText != '_EMPTY_') {
  11610.                         $markerHashQuery .= " AND (";
  11611.                         if (is_numeric($queryText)) {
  11612.                             $markerHashQuery .= (" acc_accounts_head.accounts_head_id = " $queryText " ");
  11613.                         } else {
  11614.                             $queryTextArray explode(','$queryText);
  11615.                             $addOn '';
  11616.                             foreach ($queryTextArray as $dd) {
  11617.                                 $markerHashQuery .= ($addOn " acc_accounts_head.name like '%" $dd "%' ");
  11618.                                 $addOn ' or ';
  11619.                             }
  11620.                         }
  11621.                         $markerHashQuery .= " ) ";
  11622.                     }
  11623.                     if ($itemLimit != '_ALL_')
  11624.                         $markerHashQuery .= "  limit $offset$itemLimit ";
  11625.                     else
  11626.                         $markerHashQuery .= "  limit $offset, 18446744073709551615 ";
  11627.                     $markerHashQuery .= " ;";
  11628.                     $stmt $em->getConnection()->fetchAllAssociative($markerHashQuery);
  11629.                     
  11630.                     $markerHashQueryResults $stmt;
  11631.                     foreach ($markerHashQueryResults as $markerHashQueryResult) {
  11632.                         $markerHashQueryResult['value'] = $markerHashQueryResult['accounts_head_id'];
  11633.                         $markerHashQueryResult['text'] = $markerHashQueryResult['name'];
  11634.                         $markerHashQueryResult['id_value'] = '# ' $markerHashQueryResult['accounts_head_id'] . ' ' $markerHashQueryResult['name'];
  11635.                         $renderedText $renderTextFormat;
  11636.                         $compare_array = [];
  11637.                         if ($renderTextFormat != '') {
  11638.                             $renderedText $renderTextFormat;
  11639.                             $compare_arrayFull = [];
  11640.                             $compare_array = [];
  11641.                             $toBeReplacedData = array( //                        'curr'=>'tobereplaced'
  11642.                             );
  11643.                             preg_match_all("/__\w+__/"$renderedText$compare_arrayFull);
  11644.                             if (isset($compare_arrayFull[0]))
  11645.                                 $compare_array $compare_arrayFull[0];
  11646.                             //                   $compare_array= preg_split("/__\w+__/",$renderedText);
  11647.                             foreach ($compare_array as $cmpdt) {
  11648.                                 $tbr str_replace("__"""$cmpdt);
  11649.                                 if ($tbr != '') {
  11650.                                     if (isset($markerHashQueryResult[$tbr])) {
  11651.                                         if ($markerHashQueryResult[$tbr] == null)
  11652.                                             $renderedText str_replace($cmpdt''$renderedText);
  11653.                                         else
  11654.                                             $renderedText str_replace($cmpdt$markerHashQueryResult[$tbr], $renderedText);
  11655.                                     } else {
  11656.                                         $renderedText str_replace($cmpdt''$renderedText);
  11657.                                     }
  11658.                                 }
  11659.                             }
  11660.                         }
  11661.                         $markerHashQueryResult['rendered_text'] = $renderedText;
  11662.                         $markerHashQueryResult['text'] = ($textField != '' $markerHashQueryResult[$textField] : '');
  11663.                         $dataList[] = $markerHashQueryResult;
  11664.                         if ($valueField != '') {
  11665.                             $data_by_id[$markerHashQueryResult[$valueField]] = $markerHashQueryResult;
  11666.                             $selectedId $markerHashQueryResult[$valueField];
  11667.                         }
  11668.                     }
  11669.                 }
  11670.             }
  11671.         }
  11672.         return new JsonResponse(array(
  11673.             'success' => empty($dataList) ? false true,
  11674.             'tableName' => $table,
  11675.             'setValue' => $setValue,
  11676.             'currentTs' => (new \Datetime())->format('U'),
  11677.             'dataList' => $dataList,
  11678.             'data' => $dataList,
  11679.             'dataById' => $data_by_id,
  11680.             'isMultiple' => $isMultiple,
  11681.             'selectorId' => $selectorId,
  11682.             'setValueArray' => $setValueArray,
  11683.             'queryStr' => $queryStr,
  11684.             //                    'andStr' => $andString,
  11685.             //                    'andOrStr' => $andOrString,
  11686.             'selectedId' => $selectedId,
  11687.             'dataId' => $dataId,
  11688.         ));
  11689.     }
  11690.     public function CreatePaymentRequisitionVoucher(Request $request)
  11691.     {
  11692.         $em $this->getDoctrine()->getManager();
  11693.         $new_cc $this->getDoctrine()
  11694.             ->getRepository('ApplicationBundle\\Entity\\SalesInvoice')
  11695.             ->findBy(
  11696.                 array(
  11697.                     'approved' => 1,
  11698.                     'voucherIds' => null
  11699.                 )
  11700.             );
  11701.         foreach ($new_cc as $d) {
  11702.             ApprovalFunction::SalesInvoice($em$d->getSalesInvoiceId());
  11703.         }
  11704.         return $this->render(
  11705.             '@Accounts/pages/input_forms/payment_requisition.html.twig',
  11706.             array(
  11707.                 'page_title' => 'Create Contra Voucher'
  11708.             )
  11709.         );
  11710.     }
  11711.     public function ViewBalanceSheet(Request $request)
  11712.     {
  11713.         $em $this->getDoctrine()->getManager();
  11714.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  11715.         $start_date = ($request->query->has('start_date')) ? $request->query->get('start_date') : "";
  11716.         $end_date = ($request->query->has('end_date')) ? $request->query->get('end_date') : "";
  11717.         //        $end_date="";
  11718.         $em $this->getDoctrine()->getManager();
  11719.         //        $child_list=Accounts::LedgerDetails($em,2,$start_date, $end_date);
  11720.         $bs_details Accounts::GetBsDetails($em$start_date$end_date);
  11721.         $grouped_heads Accounts::GroupedHeads($em);
  11722.         //        if($mis_start_date!=''&&$mis_start_date!=0)
  11723.         //            $start_date=$mis_start_date;
  11724.         //        if($mis_end_date!=''&&$mis_start_date!=0)
  11725.         //            $end_date=$mis_end_date;
  11726.         return $this->render(
  11727.             '@Accounts/pages/views/balance_sheet.html.twig',
  11728.             array(
  11729.                 'page_title' => 'Balance Sheet',
  11730.                 'company_name' => $company_data->getName(),
  11731.                 'company_data' => $company_data,
  11732.                 'details' => $bs_details
  11733.             )
  11734.         );
  11735.     }
  11736.     public function FiscalClosing(Request $request)
  11737.     {
  11738.         $em $this->getDoctrine()->getManager();
  11739.         if ($request->isMethod('POST')) {
  11740.             //now lets create new fiscal closing
  11741.             //            Accounts::FiscalClosing($em,$request->request->get('start_date'),$request->request->get('end_date'));
  11742.             $new = new FiscalClosing();
  11743.             $new->setClosingStartDate(new \DateTime($request->request->get('start_date')));
  11744.             $new->setClosingEndDate(new \DateTime($request->request->get('end_date')));
  11745.             $new->setClosingData(json_encode(array(
  11746.                 'heads' => $request->request->get('head_id'),
  11747.                 'balance' => $request->request->get('head_balance'),
  11748.                 'recon_balance' => $request->request->get('head_recon_balance')
  11749.             )));
  11750.             $new->setCompanyId($this->getLoggedUserCompanyId($request));
  11751.             $new->setLedgerHit(0);
  11752.             $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  11753.             $em->persist($new);
  11754.             $em->flush();
  11755.             Accounts::DoFiscalClosing($em$new->getClosingId());
  11756.             //            $new_cc = $this->getDoctrine()
  11757.             //                ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  11758.             //                ->findOneBy(
  11759.             //                    array(
  11760.             //                        'name' => 'accounting_year_start',
  11761.             //                    )
  11762.             //                );
  11763.             //            $new_cc->setData($request->request->get('end_date'));
  11764.             //            $em->flush();
  11765.         }
  11766.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  11767.         $new_cc $this->getDoctrine()
  11768.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  11769.             ->findOneBy(
  11770.                 array(
  11771.                     'name' => 'accounting_year_start',
  11772.                     //                    'CompanyId'=>$this->getLoggedUserCompanyId($request)
  11773.                 )
  11774.             );
  11775.         $today = new \DateTime();
  11776.         $start_date $new_cc $new_cc->getData() : "";
  11777.         //        $start_date=($request->query->has('start_date'))?$request->query->get('start_date'):"";
  11778.         $end_date = ($request->query->has('end_date')) ? $request->query->get('end_date') : $today->format('F d, Y');
  11779.         //        $end_date="";
  11780.         $em $this->getDoctrine()->getManager();
  11781.         $url $this->generateUrl('view_ledger_head', array(), true);
  11782.         //        $child_list=Accounts::LedgerDetails($em,2,$start_date, $end_date);
  11783.         $details Accounts::GetFiscalClosing($em1$start_date$end_date$url);
  11784.         $grouped_heads Accounts::GroupedHeads($em);
  11785.         //        if($mis_start_date!=''&&$mis_start_date!=0)
  11786.         //            $start_date=$mis_start_date;
  11787.         //        if($mis_end_date!=''&&$mis_start_date!=0)
  11788.         //            $end_date=$mis_end_date;
  11789.         return $this->render(
  11790.             '@Application/pages/accounts/settings/fiscal_closing.html.twig',
  11791.             array(
  11792.                 'page_title' => 'Fiscal Closing',
  11793.                 'company_name' => $company_data->getName(),
  11794.                 'company_data' => $company_data,
  11795.                 'start_date' => $start_date,
  11796.                 'end_date' => $end_date,
  11797.                 'details' => $details
  11798.             )
  11799.         );
  11800.     }
  11801.     public function ViewTrialBalance(Request $request)
  11802.     {
  11803.         $em $this->getDoctrine()->getManager();
  11804.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  11805.         $new_cc $this->getDoctrine()
  11806.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  11807.             ->findOneBy(
  11808.                 array(
  11809.                     'name' => 'accounting_year_start',
  11810.                 )
  11811.             );
  11812. //        $start_date = ($request->query->has('start_date')) ? $request->query->get('start_date') : ($new_cc ? $new_cc->getData() : "");
  11813.         $start_date = ($request->query->has('start_date')) ? trim((string)$request->query->get('start_date')) : "";
  11814.         if ($start_date === 'undefined' || $start_date === 'null') {
  11815.             $start_date "";
  11816.         }
  11817.         $skip_parent_head = ($request->query->has('skip_parent_head')) ? $request->query->get('skip_parent_head') : 0;
  11818.         $cur_level = ($request->query->has('level')) ? $request->query->get('level') : 1;
  11819.         $expand_level = ($request->query->has('expand_level')) ? $request->query->get('expand_level') : 1;
  11820.         $end_date = ($request->query->has('end_date')) ? trim((string)$request->query->get('end_date')) : (new \DateTime())->format('Y-m-d');
  11821.         if ($end_date === '' || $end_date === 'undefined' || $end_date === 'null') {
  11822.             $end_date = (new \DateTime())->format('Y-m-d');
  11823.         }
  11824.         $em $this->getDoctrine()->getManager();
  11825.         $url $this->generateUrl('view_ledger_head', array(), true);
  11826.         //        $child_list=Accounts::LedgerDetails($em,2,$start_date, $end_date);
  11827.         $bs_details = [];
  11828.         $get_kids_sql "SELECT max(head_level) max_level FROM acc_accounts_head where 1 ";
  11829.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  11830.         
  11831.         $query_output $stmt;
  11832.         $max_level = isset($query_output[0]['max_level']) ? $query_output[0]['max_level'] : 1;
  11833.         $budgetVarianceSettings = [];
  11834.         $budgetEnabled 0;
  11835.         $budgetEnabled 0;
  11836.         $budgetVarianceSettings = [];
  11837.         $allocationSupportData $this->getAllocationReportSupportData($em$request);
  11838.         $allocationFilters $allocationSupportData['allocation_filters'];
  11839.         if ($request->query->has('budget_variance_enabled')) {
  11840.             $budgetVarianceSettings['enabled'] = $request->query->get('budget_variance_enabled');
  11841.             $budgetEnabled $request->query->get('budget_variance_enabled');
  11842.             $budgetVarianceSettings['scale'] = ($request->query->has('scale_variance')) ? $request->query->get('scale_variance') : 1;
  11843.             $budgetVarianceSettings['budgetId'] = ($request->query->has('budgetId')) ? $request->query->get('budgetId') : 1;
  11844.         }
  11845.         $tb_details Accounts::GetTrialBalance($em$cur_level$start_date$end_date$url, [], $expand_level'view'$skip_parent_head$budgetVarianceSettings$request->get('forceShowTrans'0), $allocationFilters);
  11846.         //        $grouped_heads=Accounts::GroupedHeads($em);
  11847.         //        if($mis_start_date!=''&&$mis_start_date!=0)
  11848.         //            $start_date=$mis_start_date;
  11849.         //        if($mis_end_date!=''&&$mis_start_date!=0)
  11850.         //            $end_date=$mis_end_date
  11851.         return $this->render(
  11852.             '@Accounts/pages/views/trial_balance.html.twig',
  11853.             array(
  11854.                 'page_title' => 'Trial Balance',
  11855.                 'company_name' => $company_data->getName(),
  11856.                 'company_data' => $company_data,
  11857.                 'details' => $bs_details,
  11858.                 'tb_details' => $tb_details,
  11859.                 // UX audit #13 — this report can only total legs that belong to a head, so it must
  11860.                 // disclose any legs it had to drop instead of silently understating the imbalance.
  11861.                 'ledger_reconciliation' => Accounts::GetTrialBalanceLedgerReconciliation($em$start_date$end_date),
  11862.                 'skip_parent_head' => $skip_parent_head,
  11863.                 'start_date' => $start_date,
  11864.                 'end_date' => $end_date,
  11865.                 'max_level' => $max_level,
  11866.                 'budget_variance_enabled' => $budgetEnabled,
  11867.                 'currBudgetList' => $em->getRepository('ApplicationBundle\\Entity\\FinancialBudget')->findBy(
  11868.                     array(
  11869.                         //                        'budgetId'=>$id, ///material
  11870.                         'CompanyId' => $this->getLoggedUserCompanyId($request), ///material
  11871.                     )
  11872.                 ),
  11873.                 'scale_variance' => ($request->query->has('scale_variance')) ? $request->query->get('scale_variance') : 0,
  11874.                 'budgetId' => ($request->query->has('budgetId')) ? $request->query->get('budgetId') : 0,
  11875.                 'expand_level' => $expand_level,
  11876.                 'cur_level' => $cur_level,
  11877.                 'allocation_filters' => $allocationFilters,
  11878.                 'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
  11879.                 'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
  11880.                 'project_list' => $allocationSupportData['project_list'],
  11881.                 'branch_list' => $allocationSupportData['branch_list'],
  11882.                 'cost_centers' => $allocationSupportData['cost_centers'],
  11883.                 //                'end_date'=>new \DateTime(),
  11884.             )
  11885.         );
  11886.     }
  11887.     public function ViewTrialBalanceForApp(Request $request)
  11888.     {
  11889.         $em $this->getDoctrine()->getManager();
  11890.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  11891.         $new_cc $this->getDoctrine()
  11892.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  11893.             ->findOneBy(
  11894.                 array(
  11895.                     'name' => 'accounting_year_start',
  11896.                 )
  11897.             );
  11898. //        $start_date = ($request->query->has('start_date')) ? $request->query->get('start_date') : ($new_cc ? $new_cc->getData() : "");
  11899.         $start_date = ($request->query->has('start_date')) ? $request->query->get('start_date') : "";
  11900.         $skip_parent_head = ($request->query->has('skip_parent_head')) ? $request->query->get('skip_parent_head') : 0;
  11901.         $cur_level = ($request->query->has('level')) ? $request->query->get('level') : 1;
  11902.         $expand_level = ($request->query->has('expand_level')) ? $request->query->get('expand_level') : 1;
  11903.         $end_date = ($request->query->has('end_date')) ? $request->query->get('end_date') : (new \DateTime())->format('Y-m-d');
  11904.         $em $this->getDoctrine()->getManager();
  11905.         $url $this->generateUrl('view_ledger_head', array(), true);
  11906.         //        $child_list=Accounts::LedgerDetails($em,2,$start_date, $end_date);
  11907.         $bs_details = [];
  11908.         $get_kids_sql "SELECT max(head_level) max_level FROM acc_accounts_head where 1 ";
  11909.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  11910.         
  11911.         $query_output $stmt;
  11912.         $max_level = isset($query_output[0]['max_level']) ? $query_output[0]['max_level'] : 1;
  11913.         $budgetVarianceSettings = [];
  11914.         $budgetEnabled 0;
  11915.         $budgetEnabled 0;
  11916.         $budgetVarianceSettings = [];
  11917.         if ($request->query->has('budget_variance_enabled')) {
  11918.             $budgetVarianceSettings['enabled'] = $request->query->get('budget_variance_enabled');
  11919.             $budgetEnabled $request->query->get('budget_variance_enabled');
  11920.             $budgetVarianceSettings['scale'] = ($request->query->has('scale_variance')) ? $request->query->get('scale_variance') : 1;
  11921.             $budgetVarianceSettings['budgetId'] = ($request->query->has('budgetId')) ? $request->query->get('budgetId') : 1;
  11922.         }
  11923.         $tb_details Accounts::GetTrialBalance($em$cur_level$start_date$end_date$url, [], $expand_level'view'$skip_parent_head$budgetVarianceSettings);
  11924.         //        $grouped_heads=Accounts::GroupedHeads($em);
  11925.         //        if($mis_start_date!=''&&$mis_start_date!=0)
  11926.         //            $start_date=$mis_start_date;
  11927.         //        if($mis_end_date!=''&&$mis_start_date!=0)
  11928.         //            $end_date=$mis_end_date
  11929.         $heads_0 = isset($tb_details['heads'][0]) ? $tb_details['heads'][0] : [];
  11930.         $calculated_values = [];
  11931.         foreach ($heads_0 as $item) {
  11932.             $name $item['name'] ?? 'Unknown';
  11933.             $head_balance $item['head_data']['head_balance'] ?? 0;
  11934.             $head_debit $item['head_data']['head_debit'] ?? 0;
  11935.             $head_credit $item['head_data']['head_credit'] ?? 0;
  11936.             $value abs($head_debit $head_credit);
  11937.             $calculated_values[] = [
  11938.                 'tag' => $name,
  11939.                 'debit_credit' => round($value2),
  11940.                 'budget_variance' => 0
  11941.             ];
  11942.         }
  11943.         return new JsonResponse([
  11944.             'page_title' => 'Trial Balance',
  11945.             'calculated_values' => $calculated_values
  11946.         ]);
  11947.     }
  11948.     public function ViewFinancialReport(Request $request)
  11949.     {
  11950.         $em $this->getDoctrine()->getManager();
  11951.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  11952.         $new_cc $this->getDoctrine()
  11953.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  11954.             ->findOneBy(
  11955.                 array(
  11956.                     'name' => 'accounting_year_start',
  11957.                 )
  11958.             );
  11959.         $start_date $new_cc $new_cc->getData() : "";
  11960.         $start_date = ($request->query->has('start_date')) ? $request->query->get('start_date') : ($new_cc $new_cc->getData() : "");
  11961.         $cur_level = ($request->query->has('level')) ? $request->query->get('level') : 1;
  11962.         $expand_level = ($request->query->has('expand_level')) ? $request->query->get('expand_level') : 3;
  11963.         $end_date = ($request->query->has('end_date')) ? $request->query->get('end_date') : (new \DateTime())->format('F d, Y');
  11964.         $em $this->getDoctrine()->getManager();
  11965.         $url $this->generateUrl('view_ledger_head', array(), true);
  11966.         //        $child_list=Accounts::LedgerDetails($em,2,$start_date, $end_date);
  11967.         $bs_details = [];
  11968.         $get_kids_sql "SELECT max(head_level) max_level FROM acc_accounts_head where 1 ";
  11969.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  11970.         
  11971.         $query_output $stmt;
  11972.         $max_level = isset($query_output[0]['max_level']) ? $query_output[0]['max_level'] : 1;
  11973.         //*************Data generation start here
  11974.         $report_cats = [1234];
  11975.         $periodic 0;
  11976.         $last_entries_count 1;
  11977. //        if ($request->query->has('print_all')) {
  11978. //            if ($request->query->get('print_all') == 1)
  11979. //                $report_cats = [1, 2, 3, 4];
  11980. //        } else {
  11981. //            if ($request->query->has('statement'))
  11982. //                $report_cats = $request->query->get('statement');
  11983. //        }
  11984.         if ($request->query->has('periodic'))
  11985.             if ($request->query->get('periodic') == 1)
  11986.                 $periodic 1;
  11987.         if ($request->query->has('last_entries'))
  11988.             $last_entries_count $request->query->get('last_entries');
  11989.         //lets get prev fiscal closing data
  11990.         $new_cc_list $this->getDoctrine()
  11991.             ->getRepository('ApplicationBundle\\Entity\\FiscalClosing')
  11992.             ->findBy(
  11993.                 array(),
  11994.                 array(
  11995.                     'closingId' => 'DESC'
  11996.                 ),
  11997.                 $last_entries_count
  11998.             );
  11999.         $prev_data_list = array();
  12000.         $prev_data_amounts = array();
  12001.         $prev_data_amounts_for_is = array();
  12002.         $prev_data_amounts_for_cf = array();
  12003.         if (!empty($new_cc_list)) {
  12004.             $prev_data = array();
  12005.             foreach ($new_cc_list as $new_cc) {
  12006.                 $prev_data['closing_start_date'] = $new_cc->getClosingStartDate();
  12007.                 $prev_data['closing_end_date'] = $new_cc->getClosingEndDate();
  12008.                 $prev_data['closing_data'] = array();
  12009.                 $last_f_c_data json_decode($new_cc->getClosingData(), true);
  12010.                 //                foreach ($last_f_c_data['heads'] as $key => $entry) {
  12011.                 //                    $add_data = array(
  12012.                 //                        'head_id' => $entry,
  12013.                 //                        'balance' => $last_f_c_data['balance'][$key],
  12014.                 //                        'recon_balance' => $last_f_c_data['recon_balance'][$key]
  12015.                 //                    );
  12016.                 //                    $prev_data['closing_data'][$entry] = $add_data;
  12017.                 //                    $prev_data_amounts[$entry][]= $last_f_c_data['balance'][$key];
  12018.                 //                }
  12019.                 foreach ($last_f_c_data as $key => $entry) {
  12020.                     $add_data = array(
  12021.                         'head_id' => $key,
  12022.                         'balance' => $entry,
  12023.                         'recon_balance' => $entry
  12024.                     );
  12025.                     $prev_data['closing_data'][$key] = $add_data;
  12026.                     $prev_data_amounts[$key][] = $entry;
  12027.                 }
  12028.                 $prev_data_list[] = $prev_data;
  12029.             }
  12030.         }
  12031.         if (!empty($new_cc_list)) {
  12032.             $prev_data = array();
  12033.             foreach ($new_cc_list as $new_cc) {
  12034.                 $prev_data['closing_start_date'] = $new_cc->getClosingStartDate();
  12035.                 $prev_data['closing_end_date'] = $new_cc->getClosingEndDate();
  12036.                 $prev_data['closing_data'] = array();
  12037.                 $last_f_c_data json_decode($new_cc->getBeforeClosingData(), true);
  12038.                 if ($last_f_c_data == null$last_f_c_data = [];
  12039.                 //                foreach ($last_f_c_data['heads'] as $key => $entry) {
  12040.                 //                    $add_data = array(
  12041.                 //                        'head_id' => $entry,
  12042.                 //                        'balance' => $last_f_c_data['balance'][$key],
  12043.                 //                        'recon_balance' => $last_f_c_data['recon_balance'][$key]
  12044.                 //                    );
  12045.                 //                    $prev_data['closing_data'][$entry] = $add_data;
  12046.                 //                    $prev_data_amounts[$entry][]= $last_f_c_data['balance'][$key];
  12047.                 //                }
  12048.                 foreach ($last_f_c_data as $key => $entry) {
  12049.                     $add_data = array(
  12050.                         'head_id' => $key,
  12051.                         'balance' => $entry,
  12052.                         'recon_balance' => $entry
  12053.                     );
  12054.                     $prev_data['closing_data'][$key] = $add_data;
  12055.                     $prev_data_amounts_for_is[$key][] = $entry;
  12056.                 }
  12057.                 //                $prev_data_list[]=$prev_data;
  12058.             }
  12059.         }
  12060.         $balance_sheet_data = [];
  12061.         $is_data = [];
  12062.         $cf_data = [];
  12063.         $oe_data = [];
  12064.         $wacc_data = [];
  12065.         $allocationSupportData $this->getAllocationReportSupportData($em$request);
  12066.         $allocationFilters $allocationSupportData['allocation_filters'];
  12067.         //now get balance sheet if needed
  12068.         if (in_array(1$report_cats)) {
  12069.             $balance_sheet_data Accounts::GetBalanceSheet($em$cur_level$start_date$end_date$url, [], $expand_level'view'$periodic$prev_data_amounts$allocationFilters);
  12070.         }
  12071.         $CurrentRoute $request->attributes->get('_route');
  12072.         if ($CurrentRoute == 'app_get_financial_report') {
  12073.             if (in_array(1$report_cats)) {
  12074.                 $balance_sheet_data Accounts::GetBalanceSheetForApp($em$cur_level$start_date$end_date$url, [], $expand_level'view'$periodic$prev_data_amounts$allocationFilters);
  12075.             }
  12076.             return new JsonResponse([
  12077.                 'success' => true,
  12078.                 'message' => "Financial Report data fetch",
  12079.                 'data' => $balance_sheet_data
  12080.             ]);
  12081.         }
  12082.         //now the income statement
  12083. //        if (in_array(2, $report_cats)) {
  12084. //            $is_data = Accounts::GetIncomeStatement($em, $cur_level, $start_date, $end_date, $url, [], $expand_level, 'print', $periodic, $prev_data_amounts_for_is);
  12085. //        }
  12086.         if (in_array(2$report_cats)) {
  12087.             $markerHashes array_column(AccountsConstant::$incomeConfigData'markerHash');
  12088.             $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);
  12089.             $is_data['tree'] = "";
  12090.             $incomeConfigData AccountsConstant::$incomeConfigData;
  12091.             $currBal 0;
  12092.             $currBalByClosingDate = array();
  12093.             $totalBalByClosingDate = array();
  12094.             $totalBal 0;
  12095. //            dump($cf_data[AccountsConstant::INTEREST_RECEIVABLE_PARENT]);
  12096.             foreach ($is_data['fiscal_years'] as $fiscal_year) {
  12097.                 $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12098.                 $totalBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12099.             }
  12100.             foreach ($incomeConfigData as $config) {
  12101.                 $row "<tr style='" . ($config['bold'] == false "" "font-weight:bold;") . "'>
  12102.                     <td style='" . ($config['paddingMultiplier'] == "" : ("padding-left:" . (20 $config['paddingMultiplier']) . "px;")) . "'>" $config['title'] . "</td>";
  12103.                 if ($config['markerHash'] == '_TITLE_ONLY_') {
  12104.                     $row .= "<td ></td>";
  12105.                     foreach ($is_data['fiscal_years'] as $fiscal_year) {
  12106.                         $row .= "<td style='text-align: right' ></td>";
  12107.                     }
  12108.                 } else if ($config['markerHash'] == '_CURRENT_BALANCE_') {
  12109.                     //                    $row.="<td >pika$currBal</td>";
  12110.                     if ($currBal >= 0)
  12111.                         $row .= "<td style='text-align: right'>" number_format($currBal2'.'',') . "</td>";
  12112.                     else
  12113.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currBal2'.'',') . ")</td>";
  12114.                     foreach ($is_data['fiscal_years'] as $fiscal_year) {
  12115.                         $currValByFiscalYear $currBalByClosingDate[$fiscal_year['closing_end_date']];
  12116.                         if ($currValByFiscalYear >= 0)
  12117.                             $row .= "<td style='text-align: right' >" number_format($currValByFiscalYear2'.'',') . "</td>";
  12118.                         else
  12119.                             $row .= "<td style='text-align: right' >(" number_format((-1) * $currValByFiscalYear2'.'',') . ")</td>";
  12120.                     }
  12121.                 } else {
  12122.                     $currVal 0;
  12123.                     $currentMarkerData null;
  12124.                     if (isset($is_data[$config['markerHash']])) {
  12125.                         $currentMarkerData $is_data[$config['markerHash']];
  12126.                         $currVal $currentMarkerData['transCr'] - $currentMarkerData['transDr'];
  12127.                     }
  12128.                     if ($currVal >= 0)
  12129.                         $row .= "<td style='text-align: right' >" number_format($currVal2'.'',') . "</td>";
  12130.                     else
  12131.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currVal2'.'',') . ")</td>";
  12132.                     foreach ($is_data['fiscal_years'] as $fiscal_year) {
  12133.                         if ($currentMarkerData) {
  12134.                             $currFiscalTransVal $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transCr'] - $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transDr'];
  12135.                             if ($currVal >= 0)
  12136.                                 $row .= "<td style='text-align: right' >" number_format($currFiscalTransVal2'.'',') . "</td>";
  12137.                             else
  12138.                                 $row .= "<td style='text-align: right' >(" number_format((-1) * $currFiscalTransVal2'.'',') . ")</td>";
  12139.                             $currBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  12140.                             $totalBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  12141.                         } else {
  12142.                             $row .= "<td style='text-align: right' ></td>";
  12143.                         }
  12144.                     }
  12145.                     $totalBal += $currVal;
  12146.                     $currBal += $currVal;
  12147.                 }
  12148.                 $row .= "</tr>";
  12149.                 if (isset($config['resetCurrentBal'])) {
  12150.                     if ($config['resetCurrentBal'] == true)
  12151.                         $currBal 0;
  12152.                     foreach ($is_data['fiscal_years'] as $fiscal_year) {
  12153.                         $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12154.                     }
  12155.                 }
  12156.                 $is_data['tree'] .= $row;
  12157.                 $is_data['grandTotal'] = $totalBal;
  12158.                 $is_data['grandTotal'] = $totalBal;
  12159.                 $is_data['grandTotalByClosingDate'] = $totalBalByClosingDate;
  12160.             }
  12161.             //For Profit loss
  12162.             $finalProfit $currBal;
  12163.             $oe_data['_IS_PROFIT_'] = [
  12164.                 'transDr' => 0,
  12165.                 'transCr' => $finalProfit,
  12166.                 'dataByFiscalClosing' => []
  12167.             ];
  12168.         }
  12169.         if ($CurrentRoute == 'app_get_financial_report_by_marker_hash') {
  12170.             $markerHashes array_column(AccountsConstant::$incomeConfigData'markerHash');
  12171.             $is_data Accounts::GetBalanceOnDateByMarkerHash($em$end_date, [], [
  12172.                 AccountsConstant::OPERATING_REVENUE_PARENT,
  12173.                 AccountsConstant::COGS_PARENT,
  12174.                 AccountsConstant::NONOPERATING_REVENUE_PARENT,
  12175.                 AccountsConstant::ADMIN_EXPENSE_PARENT,
  12176.                 AccountsConstant::SELLING_EXPENSE_PARENT,
  12177.                 AccountsConstant::MARKETING_EXPENSE_PARENT,
  12178.                 AccountsConstant::ADVERTISEMENT_EXPENSE_PARENT,
  12179.                 AccountsConstant::FINANCIAL_EXPENSE_PARENT,
  12180.                 AccountsConstant::TAX_EXPENSE_PARENT,
  12181.                 AccountsConstant::OCI_RECLASSIFIABLE_PARENT,
  12182.                 AccountsConstant::OCI_NONRECLASSIFIABLE_PARENT
  12183.             ], 1);
  12184.             $incomeConfigData AccountsConstant::$incomeConfigData;
  12185.             $currBal 0;
  12186.             $currBalByClosingDate = [];
  12187.             $totalBalByClosingDate = [];
  12188.             $totalBal 0;
  12189.             foreach ($is_data['fiscal_years'] as $fiscal_year) {
  12190.                 $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12191.                 $totalBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12192.             }
  12193.             $treeArray = [];
  12194.             foreach ($incomeConfigData as $config) {
  12195.                 $node = [
  12196.                     'title' => $config['title'],
  12197.                     'bold' => $config['bold'],
  12198.                     'paddingMultiplier' => $config['paddingMultiplier'],
  12199.                     'currentValue' => null,
  12200.                     'yearlyValues' => [],
  12201.                 ];
  12202.                 if ($config['markerHash'] == '_TITLE_ONLY_') {
  12203.                     $node['currentValue'] = null;
  12204.                     foreach ($is_data['fiscal_years'] as $fiscal_year) {
  12205.                         $node['yearlyValues'][$fiscal_year['closing_end_date']] = null;
  12206.                     }
  12207.                 } else if ($config['markerHash'] == '_CURRENT_BALANCE_') {
  12208.                     $node['currentValue'] = $currBal;
  12209.                     foreach ($is_data['fiscal_years'] as $fiscal_year) {
  12210.                         $node['yearlyValues'][$fiscal_year['closing_end_date']] = $currBalByClosingDate[$fiscal_year['closing_end_date']];
  12211.                     }
  12212.                 } else {
  12213.                     $currVal 0;
  12214.                     $currentMarkerData null;
  12215.                     if (isset($is_data[$config['markerHash']])) {
  12216.                         $currentMarkerData $is_data[$config['markerHash']];
  12217.                         $currVal $currentMarkerData['transCr'] - $currentMarkerData['transDr'];
  12218.                     }
  12219.                     $node['currentValue'] = $currVal;
  12220.                     foreach ($is_data['fiscal_years'] as $fiscal_year) {
  12221.                         if ($currentMarkerData) {
  12222.                             $fiscalDate $fiscal_year['closing_end_date'];
  12223.                             $currFiscalTransVal $currentMarkerData['dataByFiscalClosing'][$fiscalDate]['transCr'] - $currentMarkerData['dataByFiscalClosing'][$fiscalDate]['transDr'];
  12224.                             $node['yearlyValues'][$fiscalDate] = $currFiscalTransVal;
  12225.                             $currBalByClosingDate[$fiscalDate] += $currFiscalTransVal;
  12226.                             $totalBalByClosingDate[$fiscalDate] += $currFiscalTransVal;
  12227.                         } else {
  12228.                             $node['yearlyValues'][$fiscal_year['closing_end_date']] = null;
  12229.                         }
  12230.                     }
  12231.                     $totalBal += $currVal;
  12232.                     $currBal += $currVal;
  12233.                 }
  12234.                 if (isset($config['resetCurrentBal']) && $config['resetCurrentBal'] === true) {
  12235.                     $currBal 0;
  12236.                     foreach ($is_data['fiscal_years'] as $fiscal_year) {
  12237.                         $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12238.                     }
  12239.                 }
  12240.                 $treeArray[] = $node;
  12241.             }
  12242.             // Helper function to build nested tree by paddingMultiplier
  12243.             function buildNestedTree(array $flatList)
  12244.             {
  12245.                 $stack = [];
  12246.                 $tree = [];
  12247.                 foreach ($flatList as &$node) {
  12248.                     unset($node['children']); // clear any existing children
  12249.                     // Pop stack while top has equal or greater paddingMultiplier
  12250.                     while (!empty($stack) && end($stack)['paddingMultiplier'] >= $node['paddingMultiplier']) {
  12251.                         array_pop($stack);
  12252.                     }
  12253.                     if (empty($stack)) {
  12254.                         // Root node
  12255.                         $tree[] = &$node;
  12256.                     } else {
  12257.                         // Add as child to last node in stack
  12258.                         $parent = &$stack[count($stack) - 1];
  12259.                         if (!isset($parent['children'])) {
  12260.                             $parent['children'] = [];
  12261.                         }
  12262.                         $parent['children'][] = &$node;
  12263.                     }
  12264.                     $stack[] = &$node;
  12265.                 }
  12266.                 return $tree;
  12267.             }
  12268.             $nestedTree buildNestedTree($treeArray);
  12269.             $response = [
  12270.                 'tree' => $nestedTree,
  12271.                 'grandTotal' => $totalBal,
  12272.                 'grandTotalByClosingDate' => $totalBalByClosingDate,
  12273.                 'fiscalYears' => $is_data['fiscal_years'],
  12274.             ];
  12275.             $finalProfit $currBal;
  12276.             $oe_data['_IS_PROFIT_'] = [
  12277.                 'transDr' => 0,
  12278.                 'transCr' => $finalProfit,
  12279.                 'dataByFiscalClosing' => []
  12280.             ];
  12281.             return new JsonResponse($response);
  12282.         }
  12283.         //now get cash flow
  12284.         if (in_array(3$report_cats)) {
  12285.             $markerHashes array_column(AccountsConstant::$cashFlowConfigData'markerHash');
  12286.             $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::TAX_EXPENSE_PARENTAccountsConstant::FIXED_ASSET_PARENTAccountsConstant::ASSET_SALE_PARENTAccountsConstant::INVESTMENT_PARENTAccountsConstant::LOAN_RECEIVED_PARENTAccountsConstant::LOAN_REPAYMENT_PARENTAccountsConstant::DIVIDEND_PAYMENT_PARENT], 1, [AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT], $allocationFilters);
  12287.             $cf_data[AccountsConstant::INTEREST_PAID_CASH] = Accounts::GetInterestPaidCashFlowMarkerData(
  12288.                 $em,
  12289.                 $start_date,
  12290.                 $end_date,
  12291.                 isset($cf_data['fiscal_years']) ? $cf_data['fiscal_years'] : array(),
  12292.                 $allocationFilters
  12293.             );
  12294.             $cf_data[AccountsConstant::DIVIDEND_RECEIVED_CASH] = Accounts::GetDividendReceivedCashFlowMarkerData(
  12295.                 $em,
  12296.                 $start_date,
  12297.                 $end_date,
  12298.                 isset($cf_data['fiscal_years']) ? $cf_data['fiscal_years'] : array(),
  12299.                 $allocationFilters
  12300.             );
  12301.             $openingData Accounts::GetBalanceOnDateByMarkerHash(
  12302.                 $em,
  12303.                 $start_date,
  12304.                 [],
  12305.                 [AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT],
  12306.                 1,
  12307.                 [],
  12308.                 $allocationFilters
  12309.             );
  12310.             $closingData Accounts::GetBalanceOnDateByMarkerHash(
  12311.                 $em,
  12312.                 $end_date,
  12313.                 [],
  12314.                 [AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT],
  12315.                 1,
  12316.                 [],
  12317.                 $allocationFilters
  12318.             );
  12319.             $openingCashBalance = isset($openingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT])
  12320.                 ? $openingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['transCr'] - $openingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['transDr']
  12321.                 : 0;
  12322.             $closingCashBalance = isset($closingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT])
  12323.                 ? $closingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['transCr'] - $closingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['transDr']
  12324.                 : 0;
  12325.             $cf_data['_CASH_OPENING_'] = [
  12326.                 'transDr' => 0,
  12327.                 'transCr' => $openingCashBalance,
  12328.                 'dataByFiscalClosing' => []
  12329.             ];
  12330.             $cf_data['_CASH_CLOSING_'] = [
  12331.                 'transDr' => 0,
  12332.                 'transCr' => $closingCashBalance,
  12333.                 'dataByFiscalClosing' => []
  12334.             ];
  12335.             $cf_data['tree'] = "";
  12336.             $cashFlowConfigData AccountsConstant::$cashFlowConfigData;
  12337.             $currBal 0;
  12338.             $currBalByClosingDate = array();
  12339.             $totalBalByClosingDate = array();
  12340.             $totalBal 0;
  12341. //            dump($cf_data[AccountsConstant::INTEREST_RECEIVABLE_PARENT]);
  12342.             foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  12343.                 $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12344.                 $totalBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12345.             }
  12346.             foreach ($cashFlowConfigData as $config) {
  12347.                 $row "<tr style='" . ($config['bold'] == false "" "font-weight:bold;") . "'>
  12348.                     <td style='" . ($config['paddingMultiplier'] == "" : ("padding-left:" . (20 $config['paddingMultiplier']) . "px;")) . "'>" $config['title'] . "</td>";
  12349.                 if ($config['markerHash'] == '_TITLE_ONLY_') {
  12350.                     $row .= "<td ></td>";
  12351.                     foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  12352.                         $row .= "<td style='text-align: right' ></td>";
  12353.                     }
  12354.                 } else if ($config['markerHash'] == '_CURRENT_BALANCE_') {
  12355.                     //                    $row.="<td >pika$currBal</td>";
  12356.                     if ($currBal >= 0)
  12357.                         $row .= "<td style='text-align: right'>" number_format($currBal2'.'',') . "</td>";
  12358.                     else
  12359.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currBal2'.'',') . ")</td>";
  12360.                     foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  12361.                         $currValByFiscalYear $currBalByClosingDate[$fiscal_year['closing_end_date']];
  12362.                         if ($currValByFiscalYear >= 0)
  12363.                             $row .= "<td style='text-align: right' >" number_format($currValByFiscalYear2'.'',') . "</td>";
  12364.                         else
  12365.                             $row .= "<td style='text-align: right' >(" number_format((-1) * $currValByFiscalYear2'.'',') . ")</td>";
  12366.                     }
  12367.                 } else {
  12368.                     $currVal 0;
  12369.                     $currentMarkerData null;
  12370.                     if (isset($cf_data[$config['markerHash']])) {
  12371.                         $currentMarkerData $cf_data[$config['markerHash']];
  12372.                         $currVal $currentMarkerData['transCr'] - $currentMarkerData['transDr'];
  12373.                     }
  12374.                     if ($currVal >= 0)
  12375.                         $row .= "<td style='text-align: right' >" number_format($currVal2'.'',') . "</td>";
  12376.                     else
  12377.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currVal2'.'',') . ")</td>";
  12378.                     foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  12379.                         if ($currentMarkerData) {
  12380.                             $currFiscalTransVal $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transCr'] - $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transDr'];
  12381.                             if ($currVal >= 0)
  12382.                                 $row .= "<td style='text-align: right' >" number_format($currFiscalTransVal2'.'',') . "</td>";
  12383.                             else
  12384.                                 $row .= "<td style='text-align: right' >(" number_format((-1) * $currFiscalTransVal2'.'',') . ")</td>";
  12385.                             $currBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  12386.                             $totalBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  12387.                         } else {
  12388.                             $row .= "<td style='text-align: right' ></td>";
  12389.                         }
  12390.                     }
  12391.                     $totalBal += $currVal;
  12392.                     $currBal += $currVal;
  12393.                 }
  12394.                 $row .= "</tr>";
  12395.                 if (isset($config['resetCurrentBal'])) {
  12396.                     if ($config['resetCurrentBal'] == true)
  12397.                         $currBal 0;
  12398.                     foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  12399.                         $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12400.                     }
  12401.                 }
  12402.                 $cf_data['tree'] .= $row;
  12403.                 $cf_data['grandTotal'] = $totalBal;
  12404.                 $cf_data['grandTotalByClosingDate'] = $totalBalByClosingDate;
  12405.             }
  12406.         }
  12407.         if (in_array(4$report_cats)) {
  12408.             $markerHashes array_column(AccountsConstant::$changesInEquityConfigData'markerHash');
  12409.             $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);
  12410.             if (isset($is_data['grandTotal'])) {
  12411.                 $finalProfit $is_data['grandTotal'];
  12412.             } else {
  12413.                 $finalProfit 0;
  12414.             }
  12415.             $oe_data['_IS_PROFIT_'] = [
  12416.                 'transDr' => 0,
  12417.                 'transCr' => $finalProfit,
  12418.                 'dataByFiscalClosing' => []
  12419.             ];
  12420.             $oe_data['tree'] = "";
  12421.             $changesInEquityConfigData AccountsConstant::$changesInEquityConfigData;
  12422.             $currBal 0;
  12423.             $currBalByClosingDate = array();
  12424.             $totalBalByClosingDate = array();
  12425.             $totalBal 0;
  12426. //            dump($cf_data[AccountsConstant::INTEREST_RECEIVABLE_PARENT]);
  12427.             foreach ($oe_data['fiscal_years'] as $fiscal_year) {
  12428.                 $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12429.                 $totalBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12430.             }
  12431.             foreach ($changesInEquityConfigData as $config) {
  12432.                 $row "<tr style='" . ($config['bold'] == false "" "font-weight:bold;") . "'>
  12433.                     <td style='" . ($config['paddingMultiplier'] == "" : ("padding-left:" . (20 $config['paddingMultiplier']) . "px;")) . "'>" $config['title'] . "</td>";
  12434.                 if ($config['markerHash'] == '_TITLE_ONLY_') {
  12435.                     $row .= "<td ></td>";
  12436.                     foreach ($oe_data['fiscal_years'] as $fiscal_year) {
  12437.                         $row .= "<td style='text-align: right' ></td>";
  12438.                     }
  12439.                 } else if ($config['markerHash'] == '_CURRENT_BALANCE_') {
  12440.                     //                    $row.="<td >pika$currBal</td>";
  12441.                     if ($currBal >= 0)
  12442.                         $row .= "<td style='text-align: right'>" number_format($currBal2'.'',') . "</td>";
  12443.                     else
  12444.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currBal2'.'',') . ")</td>";
  12445.                     foreach ($oe_data['fiscal_years'] as $fiscal_year) {
  12446.                         $currValByFiscalYear $currBalByClosingDate[$fiscal_year['closing_end_date']];
  12447.                         if ($currValByFiscalYear >= 0)
  12448.                             $row .= "<td style='text-align: right' >" number_format($currValByFiscalYear2'.'',') . "</td>";
  12449.                         else
  12450.                             $row .= "<td style='text-align: right' >(" number_format((-1) * $currValByFiscalYear2'.'',') . ")</td>";
  12451.                     }
  12452.                 } else {
  12453.                     $currVal 0;
  12454.                     $currentMarkerData null;
  12455.                     if (isset($oe_data[$config['markerHash']])) {
  12456.                         $currentMarkerData $oe_data[$config['markerHash']];
  12457.                         $currVal $currentMarkerData['transCr'] - $currentMarkerData['transDr'];
  12458.                     }
  12459.                     if ($currVal >= 0)
  12460.                         $row .= "<td style='text-align: right' >" number_format($currVal2'.'',') . "</td>";
  12461.                     else
  12462.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currVal2'.'',') . ")</td>";
  12463.                     foreach ($oe_data['fiscal_years'] as $fiscal_year) {
  12464.                         if ($currentMarkerData) {
  12465.                             $currFiscalTransVal $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transCr'] - $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transDr'];
  12466.                             if ($currVal >= 0)
  12467.                                 $row .= "<td style='text-align: right' >" number_format($currFiscalTransVal2'.'',') . "</td>";
  12468.                             else
  12469.                                 $row .= "<td style='text-align: right' >(" number_format((-1) * $currFiscalTransVal2'.'',') . ")</td>";
  12470.                             $currBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  12471.                             $totalBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  12472.                         } else {
  12473.                             $row .= "<td style='text-align: right' ></td>";
  12474.                         }
  12475.                     }
  12476.                     $totalBal += $currVal;
  12477.                     $currBal += $currVal;
  12478.                 }
  12479.                 $row .= "</tr>";
  12480.                 if (isset($config['resetCurrentBal'])) {
  12481.                     if ($config['resetCurrentBal'] == true)
  12482.                         $currBal 0;
  12483.                     foreach ($oe_data['fiscal_years'] as $fiscal_year) {
  12484.                         $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12485.                     }
  12486.                 }
  12487.                 $oe_data['tree'] .= $row;
  12488.                 $oe_data['grandTotal'] = $totalBal;
  12489.                 $oe_data['grandTotal'] = $totalBal;
  12490.                 $oe_data['grandTotalByClosingDate'] = $totalBalByClosingDate;
  12491.             }
  12492.         }
  12493.         if (in_array(5$report_cats)) {
  12494.             $wacc_data Accounts::GetWaccStatement($em$cur_level$start_date$end_date$url$periodic$prev_data_amounts_for_cf$expand_level);
  12495.         }
  12496.         //now get prev balance totals
  12497.         //*******Data generation Ends here
  12498.         $provisional_option 1//include
  12499.         if ($request->query->has('provisional')) {
  12500.             $provisional_option $request->query->get('provisional'); //include
  12501.         }
  12502.         // now lets get its tree for the description
  12503.         //        $id_list_for_ledger=[];
  12504.         //        if($request->query->has('id_list') )
  12505.         //            $id_list_for_ledger=explode(',',$request->query->get('id_list'));
  12506.         //        if($id=0&&empty($id_list))
  12507.         //            $id_list_for_ledger=[0];
  12508.         //        $ledger_det=[];
  12509.         //        $head_name_list=[];
  12510.         //        foreach($id_list_for_ledger as $ind_head_id) {
  12511.         //            $ledger_data = Accounts::LedgerDetails($em, $ind_head_id, $start_date, $end_date,$provisional_option);
  12512.         //            $ledger_det[$ind_head_id]=$ledger_data;
  12513.         //            $head_name_list[]=$ledger_data['basic_data']['name'];
  12514.         //        }
  12515.         //        $grouped_heads=Accounts::GroupedHeads($em);
  12516.         //        $grouped_heads=Accounts::GroupedHeads($em);
  12517.         //        if($mis_start_date!=''&&$mis_start_date!=0)
  12518.         //            $start_date=$mis_start_date;
  12519.         //        if($mis_end_date!=''&&$mis_start_date!=0)
  12520.         //            $end_date=$mis_end_date;
  12521. //        return new JsonResponse($oe_data);
  12522. //        dump(AccountsConstant::SHARE_CAPITAL_PARENT);
  12523.         return $this->render(
  12524.             '@Accounts/pages/report/view_financial_report.html.twig',
  12525.             array(
  12526.                 'page_title' => 'Financial Statement',
  12527.                 'company_name' => $company_data->getName(),
  12528.                 'company_data' => $company_data,
  12529.                 //                'details'=>$bs_details,
  12530.                 'bs_details' => $balance_sheet_data,
  12531.                 'is_details' => $is_data,
  12532.                 'cf_details' => $cf_data,
  12533.                 'oe_details' => $oe_data,
  12534.                 'prev_data_list' => $prev_data_list,
  12535.                 'report_cats' => $report_cats,
  12536.                 'start_date' => $start_date,
  12537.                 'end_date' => $end_date,
  12538.                 'max_level' => $max_level,
  12539.                 'expand_level' => $expand_level,
  12540.                 'cur_level' => $cur_level,
  12541.                 //                'ledger_data'=>$ledger_det,
  12542.                 'page_header' => 'Ledger',
  12543.                 'document_type' => 'Financial Statement',
  12544.                 'page_header_sub' => 'Add',
  12545.                 'head_list' => Accounts::HeadList($em),
  12546.                 'provisional' => $provisional_option,
  12547.                 //                'type_list'=>$type_list,
  12548.                 //            'child_list'=>$child_list,
  12549.                 //                'trans_data_by_closing'=>$trans_data_by_closing,
  12550.                 'item_data' => [],
  12551.                 'received' => 2,
  12552.                 'return' => 1,
  12553.                 'total_w_vat' => 1,
  12554.                 'total_vat' => 1,
  12555.                 'total_wo_vat' => 1,
  12556.                 'invoice_id' => 'abcd1234',
  12557.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12558.                 'created_by' => 'created by',
  12559.                 'created_at' => '',
  12560.                 'red' => 0,
  12561.                 'company_address' => $company_data->getAddress(),
  12562.                 'company_image' => $company_data->getImage(),
  12563.                 'allocation_filters' => $allocationFilters,
  12564.                 'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
  12565.                 'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
  12566.                 'project_list' => $allocationSupportData['project_list'],
  12567.                 'branch_list' => $allocationSupportData['branch_list'],
  12568.                 'cost_centers' => $allocationSupportData['cost_centers'],
  12569.                 //                'p'=>$p
  12570.             )
  12571.         );
  12572. //        return $this->render(
  12573. //            '@Accounts/pages/report/view_financial_report.html.twig',
  12574. //            array(
  12575. //                'page_title' => 'Financial Statements',
  12576. //                'company_name' => $company_data->getName(),
  12577. //                'company_data' => $company_data,
  12578. //                'details' => $bs_details,
  12579. //                'tb_details' => $tb_details,
  12580. //                'start_date' => $start_date,
  12581. //
  12582. //                'end_date' => $end_date,
  12583. //                'print_all' => $print_all,
  12584. //                'max_level' => $max_level,
  12585. //                'expand_level' => $expand_level,
  12586. //                'cur_level' => $cur_level,
  12587. //
  12588. //                //                'end_date'=>new \DateTime(),
  12589. //            )
  12590. //        );
  12591.     }
  12592.     public function TestController(Request $request)
  12593.     {
  12594.         $em $this->getDoctrine()->getManager();
  12595.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  12596.         $new_cc $this->getDoctrine()
  12597.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  12598.             ->findOneBy(
  12599.                 array(
  12600.                     'name' => 'accounting_year_start',
  12601.                 )
  12602.             );
  12603.         $start_date $new_cc $new_cc->getData() : "";
  12604.         $start_date = ($request->query->has('start_date')) ? $request->query->get('start_date') : ($new_cc $new_cc->getData() : "");
  12605.         $cur_level = ($request->query->has('level')) ? $request->query->get('level') : 1;
  12606.         $expand_level = ($request->query->has('expand_level')) ? $request->query->get('expand_level') : 3;
  12607.         $end_date = ($request->query->has('end_date')) ? $request->query->get('end_date') : (new \DateTime())->format('Y-m-d');
  12608.         $em $this->getDoctrine()->getManager();
  12609.         $url $this->generateUrl('view_ledger_head', array(), true);
  12610.         //        $child_list=Accounts::LedgerDetails($em,2,$start_date, $end_date);
  12611.         $bs_details = [];
  12612.         $get_kids_sql "SELECT max(head_level) max_level FROM acc_accounts_head where 1 ";
  12613.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  12614.         
  12615.         $query_output $stmt;
  12616.         $max_level = isset($query_output[0]['max_level']) ? $query_output[0]['max_level'] : 1;
  12617.         $report_cats = [1234];
  12618.         $periodic 0;
  12619.         $last_entries_count 1;
  12620.         if ($request->query->has('print_all')) {
  12621.             if ($request->query->get('print_all') == 1)
  12622.                 $report_cats = [1234];
  12623.         } else {
  12624.             if ($request->query->has('statement'))
  12625.                 $report_cats $request->query->get('statement');
  12626.         }
  12627.         if ($request->query->has('periodic'))
  12628.             if ($request->query->get('periodic') == 1)
  12629.                 $periodic 1;
  12630.         if ($request->query->has('last_entries'))
  12631.             $last_entries_count $request->query->get('last_entries');
  12632.         //lets get prev fiscal closing data
  12633.         $new_cc_list $this->getDoctrine()
  12634.             ->getRepository('ApplicationBundle\\Entity\\FiscalClosing')
  12635.             ->findBy(
  12636.                 array(),
  12637.                 array(
  12638.                     'closingId' => 'DESC'
  12639.                 ),
  12640.                 $last_entries_count
  12641.             );
  12642.         $prev_data_list = array();
  12643.         $prev_data_amounts = array();
  12644.         $prev_data_amounts_for_is = array();
  12645.         $prev_data_amounts_for_cf = array();
  12646.         if (!empty($new_cc_list)) {
  12647.             $prev_data = array();
  12648.             foreach ($new_cc_list as $new_cc) {
  12649.                 $prev_data['closing_start_date'] = $new_cc->getClosingStartDate();
  12650.                 $prev_data['closing_end_date'] = $new_cc->getClosingEndDate();
  12651.                 $prev_data['closing_data'] = array();
  12652.                 $last_f_c_data json_decode($new_cc->getClosingData(), true);
  12653.                 //                foreach ($last_f_c_data['heads'] as $key => $entry) {
  12654.                 //                    $add_data = array(
  12655.                 //                        'head_id' => $entry,
  12656.                 //                        'balance' => $last_f_c_data['balance'][$key],
  12657.                 //                        'recon_balance' => $last_f_c_data['recon_balance'][$key]
  12658.                 //                    );
  12659.                 //                    $prev_data['closing_data'][$entry] = $add_data;
  12660.                 //                    $prev_data_amounts[$entry][]= $last_f_c_data['balance'][$key];
  12661.                 //                }
  12662.                 foreach ($last_f_c_data as $key => $entry) {
  12663.                     $add_data = array(
  12664.                         'head_id' => $key,
  12665.                         'balance' => $entry,
  12666.                         'recon_balance' => $entry
  12667.                     );
  12668.                     $prev_data['closing_data'][$key] = $add_data;
  12669.                     $prev_data_amounts[$key][] = $entry;
  12670.                 }
  12671.                 $prev_data_list[] = $prev_data;
  12672.             }
  12673.         }
  12674.         if (!empty($new_cc_list)) {
  12675.             $prev_data = array();
  12676.             foreach ($new_cc_list as $new_cc) {
  12677.                 $prev_data['closing_start_date'] = $new_cc->getClosingStartDate();
  12678.                 $prev_data['closing_end_date'] = $new_cc->getClosingEndDate();
  12679.                 $prev_data['closing_data'] = array();
  12680.                 $last_f_c_data json_decode($new_cc->getBeforeClosingData(), true);
  12681.                 if ($last_f_c_data == null$last_f_c_data = [];
  12682.                 //                foreach ($last_f_c_data['heads'] as $key => $entry) {
  12683.                 //                    $add_data = array(
  12684.                 //                        'head_id' => $entry,
  12685.                 //                        'balance' => $last_f_c_data['balance'][$key],
  12686.                 //                        'recon_balance' => $last_f_c_data['recon_balance'][$key]
  12687.                 //                    );
  12688.                 //                    $prev_data['closing_data'][$entry] = $add_data;
  12689.                 //                    $prev_data_amounts[$entry][]= $last_f_c_data['balance'][$key];
  12690.                 //                }
  12691.                 foreach ($last_f_c_data as $key => $entry) {
  12692.                     $add_data = array(
  12693.                         'head_id' => $key,
  12694.                         'balance' => $entry,
  12695.                         'recon_balance' => $entry
  12696.                     );
  12697.                     $prev_data['closing_data'][$key] = $add_data;
  12698.                     $prev_data_amounts_for_is[$key][] = $entry;
  12699.                 }
  12700.                 //                $prev_data_list[]=$prev_data;
  12701.             }
  12702.         }
  12703.         $balance_sheet_data = [];
  12704.         $is_data = [];
  12705.         $cf_data = [];
  12706.         $oe_data = [];
  12707.         $wacc_data = [];
  12708.         $allocationSupportData $this->getAllocationReportSupportData($em$request);
  12709.         $allocationFilters $allocationSupportData['allocation_filters'];
  12710.         //now get balance sheet if needed
  12711.         if (in_array(1$report_cats)) {
  12712.             $balance_sheet_data Accounts::GetBalanceSheet($em$cur_level$start_date$end_date$url, [], $expand_level'print'$periodic$prev_data_amounts$allocationFilters);
  12713.         }
  12714.         //now the income statement
  12715.         if (in_array(2$report_cats)) {
  12716.             $is_data Accounts::GetIncomeStatement($em$cur_level$start_date$end_date$url, [], $expand_level'print'$periodic$prev_data_amounts_for_is);
  12717.         }
  12718.         //now get cash flow
  12719.         if (in_array(3$report_cats)) {
  12720.             $cf_data Accounts::GetBalanceOnDateByMarkerHash($em$end_date, [], [], 1, [AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENTAccountsConstant::SALES_REVENUE_PARENT], $allocationFilters);
  12721.             $cf_data['tree'] = "";
  12722.             $cashFlowConfigData AccountsConstant::$cashFlowConfigData;
  12723.             return new JsonResponse($cashFlowConfigData);
  12724.             $currBal 0;
  12725.             $currBalByClosingDate = array();
  12726.             $totalBalByClosingDate = array();
  12727.             $totalBal 0;
  12728.             foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  12729.                 $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12730.                 $totalBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12731.             }
  12732.             foreach ($cashFlowConfigData as $config) {
  12733.                 $row "<tr style='" . ($config['bold'] == false "" "font-weight:bold;") . "'>
  12734.                     <td style='" . ($config['paddingMultiplier'] == "" : ("padding-left:" . (20 $config['paddingMultiplier']) . "px;")) . "'>" $config['title'] . "</td>";
  12735.                 if ($config['markerHash'] == '_TITLE_ONLY_') {
  12736.                     $row .= "<td ></td>";
  12737.                     foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  12738.                         $row .= "<td style='text-align: right' ></td>";
  12739.                     }
  12740.                 } else if ($config['markerHash'] == '_CURRENT_BALANCE_') {
  12741.                     //                    $row.="<td >pika$currBal</td>";
  12742.                     if ($currBal >= 0)
  12743.                         $row .= "<td style='text-align: right'>" number_format($currBal2'.'',') . "</td>";
  12744.                     else
  12745.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currBal2'.'',') . ")</td>";
  12746.                     foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  12747.                         $currValByFiscalYear $currBalByClosingDate[$fiscal_year['closing_end_date']];
  12748.                         if ($currValByFiscalYear >= 0)
  12749.                             $row .= "<td style='text-align: right' >" number_format($currValByFiscalYear2'.'',') . "</td>";
  12750.                         else
  12751.                             $row .= "<td style='text-align: right' >(" number_format((-1) * $currValByFiscalYear2'.'',') . ")</td>";
  12752.                     }
  12753.                 } else {
  12754.                     $currVal 0;
  12755.                     $currentMarkerData null;
  12756.                     if (isset($cf_data[$config['markerHash']])) {
  12757.                         $currentMarkerData $cf_data[$config['markerHash']];
  12758.                         $currVal $currentMarkerData['transCr'] - $currentMarkerData['transDr'];
  12759.                     }
  12760.                     if ($currVal >= 0)
  12761.                         $row .= "<td style='text-align: right' >" number_format($currVal2'.'',') . "</td>";
  12762.                     else
  12763.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currVal2'.'',') . ")</td>";
  12764.                     foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  12765.                         if ($currentMarkerData) {
  12766.                             $currFiscalTransVal $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transCr'] - $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transDr'];
  12767.                             if ($currVal >= 0)
  12768.                                 $row .= "<td style='text-align: right' >" number_format($currFiscalTransVal2'.'',') . "</td>";
  12769.                             else
  12770.                                 $row .= "<td style='text-align: right' >(" number_format((-1) * $currFiscalTransVal2'.'',') . ")</td>";
  12771.                             $currBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  12772.                             $totalBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  12773.                         } else {
  12774.                             $row .= "<td style='text-align: right' ></td>";
  12775.                         }
  12776.                     }
  12777.                     $totalBal += $currVal;
  12778.                     $currBal += $currVal;
  12779.                 }
  12780.                 $row .= "</tr>";
  12781.                 if (isset($config['resetCurrentBal'])) {
  12782.                     if ($config['resetCurrentBal'] == true)
  12783.                         $currBal 0;
  12784.                     foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  12785.                         $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12786.                     }
  12787.                 }
  12788.                 $cf_data['tree'] .= $row;
  12789.                 $cf_data['grandTotal'] = $totalBal;
  12790.                 $cf_data['grandTotalByClosingDate'] = $totalBalByClosingDate;
  12791.             }
  12792.         }
  12793.         if (in_array(4$report_cats)) {
  12794.             $oe_data Accounts::GetCashFlowStatement($em$cur_level$start_date$end_date$url$periodic$prev_data_amounts_for_cf$expand_level$allocationFilters);
  12795.         }
  12796.         if (in_array(5$report_cats)) {
  12797.             $wacc_data Accounts::GetWaccStatement($em$cur_level$start_date$end_date$url$periodic$prev_data_amounts_for_cf$expand_level);
  12798.         }
  12799.     }
  12800.     public function PrintFinancialReport(Request $request)
  12801.     {
  12802.         $em $this->getDoctrine()->getManager();
  12803.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  12804.         $new_cc $this->getDoctrine()
  12805.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  12806.             ->findOneBy(
  12807.                 array(
  12808.                     'name' => 'accounting_year_start',
  12809.                 )
  12810.             );
  12811.         $start_date $new_cc $new_cc->getData() : "";
  12812.         $start_date = ($request->query->has('start_date')) ? $request->query->get('start_date') : ($new_cc $new_cc->getData() : "");
  12813.         $cur_level = ($request->query->has('level')) ? $request->query->get('level') : 1;
  12814.         $expand_level = ($request->query->has('expand_level')) ? $request->query->get('expand_level') : 3;
  12815.         $end_date = ($request->query->has('end_date')) ? $request->query->get('end_date') : (new \DateTime())->format('Y-m-d');
  12816.         $em $this->getDoctrine()->getManager();
  12817.         $url $this->generateUrl('view_ledger_head', array(), true);
  12818.         $allocationSupportData $this->getAllocationReportSupportData($em$request);
  12819.         $allocationFilters $allocationSupportData['allocation_filters'];
  12820.         //        $child_list=Accounts::LedgerDetails($em,2,$start_date, $end_date);
  12821.         $bs_details = [];
  12822.         $get_kids_sql "SELECT max(head_level) max_level FROM acc_accounts_head where 1 ";
  12823.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  12824.         
  12825.         $query_output $stmt;
  12826.         $max_level = isset($query_output[0]['max_level']) ? $query_output[0]['max_level'] : 1;
  12827.         //*************Data generation start here
  12828.         $report_cats = [1234];
  12829.         $periodic 0;
  12830.         $last_entries_count 1;
  12831.         if ($request->query->has('print_all')) {
  12832.             if ($request->query->get('print_all') == 1)
  12833.                 $report_cats = [1234];
  12834.         } else {
  12835.             if ($request->query->has('statement'))
  12836.                 $report_cats $request->query->get('statement');
  12837.         }
  12838.         if ($request->query->has('periodic'))
  12839.             if ($request->query->get('periodic') == 1)
  12840.                 $periodic 1;
  12841.         if ($request->query->has('last_entries'))
  12842.             $last_entries_count $request->query->get('last_entries');
  12843.         //lets get prev fiscal closing data
  12844.         $new_cc_list $this->getDoctrine()
  12845.             ->getRepository('ApplicationBundle\\Entity\\FiscalClosing')
  12846.             ->findBy(
  12847.                 array(),
  12848.                 array(
  12849.                     'closingId' => 'DESC'
  12850.                 ),
  12851.                 $last_entries_count
  12852.             );
  12853.         $prev_data_list = array();
  12854.         $prev_data_amounts = array();
  12855.         $prev_data_amounts_for_is = array();
  12856.         $prev_data_amounts_for_cf = array();
  12857.         if (!empty($new_cc_list)) {
  12858.             $prev_data = array();
  12859.             foreach ($new_cc_list as $new_cc) {
  12860.                 $prev_data['closing_start_date'] = $new_cc->getClosingStartDate();
  12861.                 $prev_data['closing_end_date'] = $new_cc->getClosingEndDate();
  12862.                 $prev_data['closing_data'] = array();
  12863.                 $last_f_c_data json_decode($new_cc->getClosingData(), true);
  12864.                 //                foreach ($last_f_c_data['heads'] as $key => $entry) {
  12865.                 //                    $add_data = array(
  12866.                 //                        'head_id' => $entry,
  12867.                 //                        'balance' => $last_f_c_data['balance'][$key],
  12868.                 //                        'recon_balance' => $last_f_c_data['recon_balance'][$key]
  12869.                 //                    );
  12870.                 //                    $prev_data['closing_data'][$entry] = $add_data;
  12871.                 //                    $prev_data_amounts[$entry][]= $last_f_c_data['balance'][$key];
  12872.                 //                }
  12873.                 foreach ($last_f_c_data as $key => $entry) {
  12874.                     $add_data = array(
  12875.                         'head_id' => $key,
  12876.                         'balance' => $entry,
  12877.                         'recon_balance' => $entry
  12878.                     );
  12879.                     $prev_data['closing_data'][$key] = $add_data;
  12880.                     $prev_data_amounts[$key][] = $entry;
  12881.                 }
  12882.                 $prev_data_list[] = $prev_data;
  12883.             }
  12884.         }
  12885.         if (!empty($new_cc_list)) {
  12886.             $prev_data = array();
  12887.             foreach ($new_cc_list as $new_cc) {
  12888.                 $prev_data['closing_start_date'] = $new_cc->getClosingStartDate();
  12889.                 $prev_data['closing_end_date'] = $new_cc->getClosingEndDate();
  12890.                 $prev_data['closing_data'] = array();
  12891.                 $last_f_c_data json_decode($new_cc->getBeforeClosingData(), true);
  12892.                 if ($last_f_c_data == null$last_f_c_data = [];
  12893.                 //                foreach ($last_f_c_data['heads'] as $key => $entry) {
  12894.                 //                    $add_data = array(
  12895.                 //                        'head_id' => $entry,
  12896.                 //                        'balance' => $last_f_c_data['balance'][$key],
  12897.                 //                        'recon_balance' => $last_f_c_data['recon_balance'][$key]
  12898.                 //                    );
  12899.                 //                    $prev_data['closing_data'][$entry] = $add_data;
  12900.                 //                    $prev_data_amounts[$entry][]= $last_f_c_data['balance'][$key];
  12901.                 //                }
  12902.                 foreach ($last_f_c_data as $key => $entry) {
  12903.                     $add_data = array(
  12904.                         'head_id' => $key,
  12905.                         'balance' => $entry,
  12906.                         'recon_balance' => $entry
  12907.                     );
  12908.                     $prev_data['closing_data'][$key] = $add_data;
  12909.                     $prev_data_amounts_for_is[$key][] = $entry;
  12910.                 }
  12911.                 //                $prev_data_list[]=$prev_data;
  12912.             }
  12913.         }
  12914.         $balance_sheet_data = [];
  12915.         $is_data = [];
  12916.         $cf_data = [];
  12917.         $oe_data = [];
  12918.         $wacc_data = [];
  12919.         //now get balance sheet if needed
  12920.         if (in_array(1$report_cats)) {
  12921.             $balance_sheet_data Accounts::GetBalanceSheet($em$cur_level$start_date$end_date$url, [], $expand_level'print'$periodic$prev_data_amounts$allocationFilters);
  12922.         }
  12923.         //now the income statement
  12924. //        if (in_array(2, $report_cats)) {
  12925. //            $is_data = Accounts::GetIncomeStatement($em, $cur_level, $start_date, $end_date, $url, [], $expand_level, 'print', $periodic, $prev_data_amounts_for_is);
  12926. //        }
  12927.         if (in_array(2$report_cats)) {
  12928.             $markerHashes array_column(AccountsConstant::$incomeConfigData'markerHash');
  12929.             $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);
  12930.             $is_data['tree'] = "";
  12931.             $incomeConfigData AccountsConstant::$incomeConfigData;
  12932.             $currBal 0;
  12933.             $currBalByClosingDate = array();
  12934.             $totalBalByClosingDate = array();
  12935.             $totalBal 0;
  12936. //            dump($cf_data[AccountsConstant::INTEREST_RECEIVABLE_PARENT]);
  12937.             foreach ($is_data['fiscal_years'] as $fiscal_year) {
  12938.                 $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12939.                 $totalBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12940.             }
  12941.             foreach ($incomeConfigData as $config) {
  12942.                 $row "<tr style='" . ($config['bold'] == false "" "font-weight:bold;") . "'>
  12943.                     <td style='" . ($config['paddingMultiplier'] == "" : ("padding-left:" . (20 $config['paddingMultiplier']) . "px;")) . "'>" $config['title'] . "</td>";
  12944.                 if ($config['markerHash'] == '_TITLE_ONLY_') {
  12945.                     $row .= "<td ></td>";
  12946.                     foreach ($is_data['fiscal_years'] as $fiscal_year) {
  12947.                         $row .= "<td style='text-align: right' ></td>";
  12948.                     }
  12949.                 } else if ($config['markerHash'] == '_CURRENT_BALANCE_') {
  12950.                     //                    $row.="<td >pika$currBal</td>";
  12951.                     if ($currBal >= 0)
  12952.                         $row .= "<td style='text-align: right'>" number_format($currBal2'.'',') . "</td>";
  12953.                     else
  12954.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currBal2'.'',') . ")</td>";
  12955.                     foreach ($is_data['fiscal_years'] as $fiscal_year) {
  12956.                         $currValByFiscalYear $currBalByClosingDate[$fiscal_year['closing_end_date']];
  12957.                         if ($currValByFiscalYear >= 0)
  12958.                             $row .= "<td style='text-align: right' >" number_format($currValByFiscalYear2'.'',') . "</td>";
  12959.                         else
  12960.                             $row .= "<td style='text-align: right' >(" number_format((-1) * $currValByFiscalYear2'.'',') . ")</td>";
  12961.                     }
  12962.                 } else {
  12963.                     $currVal 0;
  12964.                     $currentMarkerData null;
  12965.                     if (isset($is_data[$config['markerHash']])) {
  12966.                         $currentMarkerData $is_data[$config['markerHash']];
  12967.                         $currVal $currentMarkerData['transCr'] - $currentMarkerData['transDr'];
  12968.                     }
  12969.                     if ($currVal >= 0)
  12970.                         $row .= "<td style='text-align: right' >" number_format($currVal2'.'',') . "</td>";
  12971.                     else
  12972.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currVal2'.'',') . ")</td>";
  12973.                     foreach ($is_data['fiscal_years'] as $fiscal_year) {
  12974.                         if ($currentMarkerData) {
  12975.                             $currFiscalTransVal $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transCr'] - $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transDr'];
  12976.                             if ($currVal >= 0)
  12977.                                 $row .= "<td style='text-align: right' >" number_format($currFiscalTransVal2'.'',') . "</td>";
  12978.                             else
  12979.                                 $row .= "<td style='text-align: right' >(" number_format((-1) * $currFiscalTransVal2'.'',') . ")</td>";
  12980.                             $currBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  12981.                             $totalBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  12982.                         } else {
  12983.                             $row .= "<td style='text-align: right' ></td>";
  12984.                         }
  12985.                     }
  12986.                     $totalBal += $currVal;
  12987.                     $currBal += $currVal;
  12988.                 }
  12989.                 $row .= "</tr>";
  12990.                 if (isset($config['resetCurrentBal'])) {
  12991.                     if ($config['resetCurrentBal'] == true)
  12992.                         $currBal 0;
  12993.                     foreach ($is_data['fiscal_years'] as $fiscal_year) {
  12994.                         $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  12995.                     }
  12996.                 }
  12997.                 $is_data['tree'] .= $row;
  12998.                 $is_data['grandTotal'] = $totalBal;
  12999.                 $is_data['grandTotal'] = $totalBal;
  13000.                 $is_data['grandTotalByClosingDate'] = $totalBalByClosingDate;
  13001.             }
  13002.             //For Profit loss
  13003.             $finalProfit $currBal;
  13004.             $oe_data['_IS_PROFIT_'] = [
  13005.                 'transDr' => 0,
  13006.                 'transCr' => $finalProfit,
  13007.                 'dataByFiscalClosing' => []
  13008.             ];
  13009.         }
  13010.         //now get cash flow
  13011.         if (in_array(3$report_cats)) {
  13012.             $markerHashes array_column(AccountsConstant::$cashFlowConfigData'markerHash');
  13013.             $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::TAX_EXPENSE_PARENTAccountsConstant::FIXED_ASSET_PARENTAccountsConstant::ASSET_SALE_PARENTAccountsConstant::INVESTMENT_PARENTAccountsConstant::LOAN_RECEIVED_PARENTAccountsConstant::LOAN_REPAYMENT_PARENTAccountsConstant::DIVIDEND_PAYMENT_PARENT], 1, [AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT], $allocationFilters);
  13014.             $cf_data[AccountsConstant::INTEREST_PAID_CASH] = Accounts::GetInterestPaidCashFlowMarkerData(
  13015.                 $em,
  13016.                 $start_date,
  13017.                 $end_date,
  13018.                 isset($cf_data['fiscal_years']) ? $cf_data['fiscal_years'] : array(),
  13019.                 $allocationFilters
  13020.             );
  13021.             $cf_data[AccountsConstant::DIVIDEND_RECEIVED_CASH] = Accounts::GetDividendReceivedCashFlowMarkerData(
  13022.                 $em,
  13023.                 $start_date,
  13024.                 $end_date,
  13025.                 isset($cf_data['fiscal_years']) ? $cf_data['fiscal_years'] : array(),
  13026.                 $allocationFilters
  13027.             );
  13028.             $openingData Accounts::GetBalanceOnDateByMarkerHash(
  13029.                 $em,
  13030.                 $start_date,
  13031.                 [],
  13032.                 [AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT],
  13033.                 1,
  13034.                 [],
  13035.                 $allocationFilters
  13036.             );
  13037.             $closingData Accounts::GetBalanceOnDateByMarkerHash(
  13038.                 $em,
  13039.                 $end_date,
  13040.                 [],
  13041.                 [AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT],
  13042.                 1,
  13043.                 [],
  13044.                 $allocationFilters
  13045.             );
  13046.             $openingCashBalance = isset($openingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT])
  13047.                 ? $openingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['transCr'] - $openingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['transDr']
  13048.                 : 0;
  13049.             $closingCashBalance = isset($closingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT])
  13050.                 ? $closingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['transCr'] - $closingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['transDr']
  13051.                 : 0;
  13052.             $cf_data['_CASH_OPENING_'] = [
  13053.                 'transDr' => 0,
  13054.                 'transCr' => $openingCashBalance,
  13055.                 'dataByFiscalClosing' => []
  13056.             ];
  13057.             $cf_data['_CASH_CLOSING_'] = [
  13058.                 'transDr' => 0,
  13059.                 'transCr' => $closingCashBalance,
  13060.                 'dataByFiscalClosing' => []
  13061.             ];
  13062.             $cf_data['tree'] = "";
  13063.             $cashFlowConfigData AccountsConstant::$cashFlowConfigData;
  13064.             $currBal 0;
  13065.             $currBalByClosingDate = array();
  13066.             $totalBalByClosingDate = array();
  13067.             $totalBal 0;
  13068. //            dump($cf_data[AccountsConstant::INTEREST_RECEIVABLE_PARENT]);
  13069.             foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  13070.                 $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  13071.                 $totalBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  13072.             }
  13073.             foreach ($cashFlowConfigData as $config) {
  13074.                 $row "<tr style='" . ($config['bold'] == false "" "font-weight:bold;") . "'>
  13075.                     <td style='" . ($config['paddingMultiplier'] == "" : ("padding-left:" . (20 $config['paddingMultiplier']) . "px;")) . "'>" $config['title'] . "</td>";
  13076.                 if ($config['markerHash'] == '_TITLE_ONLY_') {
  13077.                     $row .= "<td ></td>";
  13078.                     foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  13079.                         $row .= "<td style='text-align: right' ></td>";
  13080.                     }
  13081.                 } else if ($config['markerHash'] == '_CURRENT_BALANCE_') {
  13082.                     //                    $row.="<td >pika$currBal</td>";
  13083.                     if ($currBal >= 0)
  13084.                         $row .= "<td style='text-align: right'>" number_format($currBal2'.'',') . "</td>";
  13085.                     else
  13086.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currBal2'.'',') . ")</td>";
  13087.                     foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  13088.                         $currValByFiscalYear $currBalByClosingDate[$fiscal_year['closing_end_date']];
  13089.                         if ($currValByFiscalYear >= 0)
  13090.                             $row .= "<td style='text-align: right' >" number_format($currValByFiscalYear2'.'',') . "</td>";
  13091.                         else
  13092.                             $row .= "<td style='text-align: right' >(" number_format((-1) * $currValByFiscalYear2'.'',') . ")</td>";
  13093.                     }
  13094.                 } else {
  13095.                     $currVal 0;
  13096.                     $currentMarkerData null;
  13097.                     if (isset($cf_data[$config['markerHash']])) {
  13098.                         $currentMarkerData $cf_data[$config['markerHash']];
  13099.                         $currVal $currentMarkerData['transCr'] - $currentMarkerData['transDr'];
  13100.                     }
  13101.                     if ($currVal >= 0)
  13102.                         $row .= "<td style='text-align: right' >" number_format($currVal2'.'',') . "</td>";
  13103.                     else
  13104.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currVal2'.'',') . ")</td>";
  13105.                     foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  13106.                         if ($currentMarkerData) {
  13107.                             $currFiscalTransVal $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transCr'] - $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transDr'];
  13108.                             if ($currVal >= 0)
  13109.                                 $row .= "<td style='text-align: right' >" number_format($currFiscalTransVal2'.'',') . "</td>";
  13110.                             else
  13111.                                 $row .= "<td style='text-align: right' >(" number_format((-1) * $currFiscalTransVal2'.'',') . ")</td>";
  13112.                             $currBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  13113.                             $totalBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  13114.                         } else {
  13115.                             $row .= "<td style='text-align: right' ></td>";
  13116.                         }
  13117.                     }
  13118.                     $totalBal += $currVal;
  13119.                     $currBal += $currVal;
  13120.                 }
  13121.                 $row .= "</tr>";
  13122.                 if (isset($config['resetCurrentBal'])) {
  13123.                     if ($config['resetCurrentBal'] == true)
  13124.                         $currBal 0;
  13125.                     foreach ($cf_data['fiscal_years'] as $fiscal_year) {
  13126.                         $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  13127.                     }
  13128.                 }
  13129.                 $cf_data['tree'] .= $row;
  13130.                 $cf_data['grandTotal'] = $totalBal;
  13131.                 $cf_data['grandTotalByClosingDate'] = $totalBalByClosingDate;
  13132.             }
  13133.         }
  13134.         if (in_array(4$report_cats)) {
  13135.             $markerHashes array_column(AccountsConstant::$changesInEquityConfigData'markerHash');
  13136.             $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);
  13137.             if (isset($is_data['grandTotal'])) {
  13138.                 $finalProfit $is_data['grandTotal'];
  13139.             } else {
  13140.                 $finalProfit 0;
  13141.             }
  13142.             $oe_data['_IS_PROFIT_'] = [
  13143.                 'transDr' => 0,
  13144.                 'transCr' => $finalProfit,
  13145.                 'dataByFiscalClosing' => []
  13146.             ];
  13147.             $oe_data['tree'] = "";
  13148.             $changesInEquityConfigData AccountsConstant::$changesInEquityConfigData;
  13149.             $currBal 0;
  13150.             $currBalByClosingDate = array();
  13151.             $totalBalByClosingDate = array();
  13152.             $totalBal 0;
  13153. //            dump($cf_data[AccountsConstant::INTEREST_RECEIVABLE_PARENT]);
  13154.             foreach ($oe_data['fiscal_years'] as $fiscal_year) {
  13155.                 $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  13156.                 $totalBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  13157.             }
  13158.             foreach ($changesInEquityConfigData as $config) {
  13159.                 $row "<tr style='" . ($config['bold'] == false "" "font-weight:bold;") . "'>
  13160.                     <td style='" . ($config['paddingMultiplier'] == "" : ("padding-left:" . (20 $config['paddingMultiplier']) . "px;")) . "'>" $config['title'] . "</td>";
  13161.                 if ($config['markerHash'] == '_TITLE_ONLY_') {
  13162.                     $row .= "<td ></td>";
  13163.                     foreach ($oe_data['fiscal_years'] as $fiscal_year) {
  13164.                         $row .= "<td style='text-align: right' ></td>";
  13165.                     }
  13166.                 } else if ($config['markerHash'] == '_CURRENT_BALANCE_') {
  13167.                     //                    $row.="<td >pika$currBal</td>";
  13168.                     if ($currBal >= 0)
  13169.                         $row .= "<td style='text-align: right'>" number_format($currBal2'.'',') . "</td>";
  13170.                     else
  13171.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currBal2'.'',') . ")</td>";
  13172.                     foreach ($oe_data['fiscal_years'] as $fiscal_year) {
  13173.                         $currValByFiscalYear $currBalByClosingDate[$fiscal_year['closing_end_date']];
  13174.                         if ($currValByFiscalYear >= 0)
  13175.                             $row .= "<td style='text-align: right' >" number_format($currValByFiscalYear2'.'',') . "</td>";
  13176.                         else
  13177.                             $row .= "<td style='text-align: right' >(" number_format((-1) * $currValByFiscalYear2'.'',') . ")</td>";
  13178.                     }
  13179.                 } else {
  13180.                     $currVal 0;
  13181.                     $currentMarkerData null;
  13182.                     if (isset($oe_data[$config['markerHash']])) {
  13183.                         $currentMarkerData $oe_data[$config['markerHash']];
  13184.                         $currVal $currentMarkerData['transCr'] - $currentMarkerData['transDr'];
  13185.                     }
  13186.                     if ($currVal >= 0)
  13187.                         $row .= "<td style='text-align: right' >" number_format($currVal2'.'',') . "</td>";
  13188.                     else
  13189.                         $row .= "<td style='text-align: right' >(" number_format((-1) * $currVal2'.'',') . ")</td>";
  13190.                     foreach ($oe_data['fiscal_years'] as $fiscal_year) {
  13191.                         if ($currentMarkerData) {
  13192.                             $currFiscalTransVal $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transCr'] - $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transDr'];
  13193.                             if ($currVal >= 0)
  13194.                                 $row .= "<td style='text-align: right' >" number_format($currFiscalTransVal2'.'',') . "</td>";
  13195.                             else
  13196.                                 $row .= "<td style='text-align: right' >(" number_format((-1) * $currFiscalTransVal2'.'',') . ")</td>";
  13197.                             $currBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  13198.                             $totalBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
  13199.                         } else {
  13200.                             $row .= "<td style='text-align: right' ></td>";
  13201.                         }
  13202.                     }
  13203.                     $totalBal += $currVal;
  13204.                     $currBal += $currVal;
  13205.                 }
  13206.                 $row .= "</tr>";
  13207.                 if (isset($config['resetCurrentBal'])) {
  13208.                     if ($config['resetCurrentBal'] == true)
  13209.                         $currBal 0;
  13210.                     foreach ($oe_data['fiscal_years'] as $fiscal_year) {
  13211.                         $currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
  13212.                     }
  13213.                 }
  13214.                 $oe_data['tree'] .= $row;
  13215.                 $oe_data['grandTotal'] = $totalBal;
  13216.                 $oe_data['grandTotal'] = $totalBal;
  13217.                 $oe_data['grandTotalByClosingDate'] = $totalBalByClosingDate;
  13218.             }
  13219.         }
  13220.         if (in_array(5$report_cats)) {
  13221.             $wacc_data Accounts::GetWaccStatement($em$cur_level$start_date$end_date$url$periodic$prev_data_amounts_for_cf$expand_level);
  13222.         }
  13223.         //now get prev balance totals
  13224.         //*******Data generation Ends here
  13225.         $provisional_option 1//include
  13226.         if ($request->query->has('provisional')) {
  13227.             $provisional_option $request->query->get('provisional'); //include
  13228.         }
  13229.         // now lets get its tree for the description
  13230.         //        $id_list_for_ledger=[];
  13231.         //        if($request->query->has('id_list') )
  13232.         //            $id_list_for_ledger=explode(',',$request->query->get('id_list'));
  13233.         //        if($id=0&&empty($id_list))
  13234.         //            $id_list_for_ledger=[0];
  13235.         //        $ledger_det=[];
  13236.         //        $head_name_list=[];
  13237.         //        foreach($id_list_for_ledger as $ind_head_id) {
  13238.         //            $ledger_data = Accounts::LedgerDetails($em, $ind_head_id, $start_date, $end_date,$provisional_option);
  13239.         //            $ledger_det[$ind_head_id]=$ledger_data;
  13240.         //            $head_name_list[]=$ledger_data['basic_data']['name'];
  13241.         //        }
  13242.         //        $grouped_heads=Accounts::GroupedHeads($em);
  13243.         $document_mark = array(
  13244.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13245.             'copy' => ''
  13246.         );
  13247.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  13248.             $html $this->renderView(
  13249.                 '@Accounts/pages/print/print_financial_report.html.twig',
  13250.                 array(
  13251.                     'pdf' => true,
  13252.                     'page_title' => 'Financial Statement',
  13253.                     'company_name' => $company_data->getName(),
  13254.                     'company_data' => $company_data,
  13255.                     //                'details'=>$bs_details,
  13256.                     'bs_details' => $balance_sheet_data,
  13257.                     'is_details' => $is_data,
  13258.                     'cf_details' => $cf_data,
  13259.                     'oe_details' => $oe_data,
  13260.                     'wacc_details' => $wacc_data,
  13261.                     'prev_data_list' => $prev_data_list,
  13262.                     'report_cats' => $report_cats,
  13263.                     'start_date' => $start_date,
  13264.                     'end_date' => $end_date,
  13265.                     'max_level' => $max_level,
  13266.                     'expand_level' => $expand_level,
  13267.                     'cur_level' => $cur_level,
  13268.                     //                'ledger_data'=>$ledger_det,
  13269.                     'page_header' => 'Ledger',
  13270.                     'document_type' => 'Financial Statement',
  13271.                     'document_mark_image' => $document_mark['original'],
  13272.                     'page_header_sub' => 'Add',
  13273.                     'head_list' => Accounts::HeadList($em),
  13274.                     'provisional' => $provisional_option,
  13275.                     //                'type_list'=>$type_list,
  13276.                     //            'child_list'=>$child_list,
  13277.                     //                'trans_data_by_closing'=>$trans_data_by_closing,
  13278.                     'item_data' => [],
  13279.                     'received' => 2,
  13280.                     'return' => 1,
  13281.                     'total_w_vat' => 1,
  13282.                     'total_vat' => 1,
  13283.                     'total_wo_vat' => 1,
  13284.                     'invoice_id' => 'abcd1234',
  13285.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  13286.                     'created_by' => 'created by',
  13287.                     'created_at' => '',
  13288.                     'red' => 0,
  13289.                     'company_address' => $company_data->getAddress(),
  13290.                     'company_image' => $company_data->getImage(),
  13291.                     'allocation_filters' => $allocationFilters,
  13292.                     'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
  13293.                     'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
  13294.                     'project_list' => $allocationSupportData['project_list'],
  13295.                     'branch_list' => $allocationSupportData['branch_list'],
  13296.                     'cost_centers' => $allocationSupportData['cost_centers'],
  13297.                 )
  13298.             );
  13299.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13300.                 //                'orientation' => 'landscape',
  13301.                 //                'enable-javascript' => false,
  13302.                 //                'javascript-delay' => 1000,
  13303.                 'no-stop-slow-scripts' => true,
  13304.                 'no-background' => false,
  13305.                 'lowquality' => false,
  13306.                 'encoding' => 'utf-8',
  13307.                 //            'images' => true,
  13308.                 //            'cookie' => array(),
  13309.                 'dpi' => 300,
  13310.                 'image-dpi' => 300,
  13311.                 //                'enable-external-links' => true,
  13312.                 //                'enable-internal-links' => true
  13313.             ));
  13314.             return new Response(
  13315.                 $pdf_response,
  13316.                 200,
  13317.                 array(
  13318.                     'Content-Type' => 'application/pdf',
  13319.                     'Content-Disposition' => 'attachment; filename="Financial_Report.pdf"'
  13320.                 )
  13321.             );
  13322.         }
  13323.         return $this->render(
  13324.             '@Accounts/pages/print/print_financial_report.html.twig',
  13325.             array(
  13326.                 'export' => 'all',
  13327.                 'page_title' => 'Financial Statement',
  13328.                 'company_name' => $company_data->getName(),
  13329.                 'company_data' => $company_data,
  13330.                 //                'details'=>$bs_details,
  13331.                 'bs_details' => $balance_sheet_data,
  13332.                 'is_details' => $is_data,
  13333.                 'cf_details' => $cf_data,
  13334.                 'oe_details' => $oe_data,
  13335.                 'prev_data_list' => $prev_data_list,
  13336.                 'report_cats' => $report_cats,
  13337.                 'start_date' => $start_date,
  13338.                 'end_date' => $end_date,
  13339.                 'max_level' => $max_level,
  13340.                 'expand_level' => $expand_level,
  13341.                 'cur_level' => $cur_level,
  13342.                 //                'ledger_data'=>$ledger_det,
  13343.                 'page_header' => 'Ledger',
  13344.                 'document_type' => 'Financial Statement',
  13345.                 'document_mark_image' => $document_mark['original'],
  13346.                 'page_header_sub' => 'Add',
  13347.                 'head_list' => Accounts::HeadList($em),
  13348.                 'provisional' => $provisional_option,
  13349.                 //                'type_list'=>$type_list,
  13350.                 //            'child_list'=>$child_list,
  13351.                 //                'trans_data_by_closing'=>$trans_data_by_closing,
  13352.                 'item_data' => [],
  13353.                 'received' => 2,
  13354.                 'return' => 1,
  13355.                 'total_w_vat' => 1,
  13356.                 'total_vat' => 1,
  13357.                 'total_wo_vat' => 1,
  13358.                 'invoice_id' => 'abcd1234',
  13359.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  13360.                 'created_by' => 'created by',
  13361.                 'created_at' => '',
  13362.                 'red' => 0,
  13363.                 'company_address' => $company_data->getAddress(),
  13364.                 'company_image' => $company_data->getImage(),
  13365.                 'allocation_filters' => $allocationFilters,
  13366.                 'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
  13367.                 'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
  13368.                 'project_list' => $allocationSupportData['project_list'],
  13369.                 'branch_list' => $allocationSupportData['branch_list'],
  13370.                 'cost_centers' => $allocationSupportData['cost_centers'],
  13371.                 //                'p'=>$p
  13372.             )
  13373.         );
  13374.     }
  13375.     public function PrintTrialBalance(Request $request)
  13376.     {
  13377.         $em $this->getDoctrine()->getManager();
  13378.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  13379.         $start_date = ($request->query->has('start_date')) ? trim((string)$request->query->get('start_date')) : "";
  13380.         if ($start_date === 'undefined' || $start_date === 'null') {
  13381.             $start_date "";
  13382.         }
  13383.         $skip_parent_head = ($request->query->has('skip_parent_head')) ? $request->query->get('skip_parent_head') : 0;
  13384.         $cur_level = ($request->query->has('level')) ? $request->query->get('level') : 1;
  13385.         $expand_level = ($request->query->has('expand_level')) ? $request->query->get('expand_level') : 1;
  13386.         $end_date = ($request->query->has('end_date')) ? trim((string)$request->query->get('end_date')) : (new \DateTime())->format('Y-m-d');
  13387.         if ($end_date === '' || $end_date === 'undefined' || $end_date === 'null') {
  13388.             $end_date = (new \DateTime())->format('Y-m-d');
  13389.         }
  13390.         $em $this->getDoctrine()->getManager();
  13391.         $url $this->generateUrl('view_ledger_head', array(), true);
  13392.         //        $child_list=Accounts::LedgerDetails($em,2,$start_date, $end_date);
  13393.         $bs_details = [];
  13394.         $get_kids_sql "SELECT max(head_level) max_level FROM acc_accounts_head where 1 ";
  13395.         $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  13396.         
  13397.         $query_output $stmt;
  13398.         $max_level = isset($query_output[0]['max_level']) ? $query_output[0]['max_level'] : 1;
  13399.         $budgetEnabled 0;
  13400.         $budgetVarianceSettings = [];
  13401.         $allocationSupportData $this->getAllocationReportSupportData($em$request);
  13402.         $allocationFilters $allocationSupportData['allocation_filters'];
  13403.         if ($request->query->has('budget_variance_enabled')) {
  13404.             $budgetVarianceSettings['enabled'] = $request->query->get('budget_variance_enabled');
  13405.             $budgetEnabled $request->query->get('budget_variance_enabled');
  13406.             $budgetVarianceSettings['scale'] = ($request->query->has('scale_variance')) ? $request->query->get('scale_variance') : 1;
  13407.             $budgetVarianceSettings['budgetId'] = ($request->query->has('budgetId')) ? $request->query->get('budgetId') : 1;
  13408.         }
  13409.         $tb_details Accounts::GetTrialBalance($em$cur_level$start_date$end_date$url, [], $expand_level'print'$skip_parent_head$budgetVarianceSettings0$allocationFilters);
  13410.         //        $tb_details=Accounts::GetTrialBalance($em,$cur_level,$start_date, $end_date,$url,[],$expand_level,'print',$skip_parent_head);
  13411.         //        $grouped_heads=Accounts::GroupedHeads($em);
  13412.         //        if($mis_start_date!=''&&$mis_start_date!=0)
  13413.         //            $start_date=$mis_start_date;
  13414.         //        if($mis_end_date!=''&&$mis_start_date!=0)
  13415.         //            $end_date=$mis_end_date;
  13416.         $provisional_option 1//include
  13417.         if ($request->query->has('provisional')) {
  13418.             $provisional_option $request->query->get('provisional'); //include
  13419.         }
  13420.         // now lets get its tree for the description
  13421.         //        $id_list_for_ledger=[];
  13422.         //        if($request->query->has('id_list') )
  13423.         //            $id_list_for_ledger=explode(',',$request->query->get('id_list'));
  13424.         //        if($id=0&&empty($id_list))
  13425.         //            $id_list_for_ledger=[0];
  13426.         //        $ledger_det=[];
  13427.         //        $head_name_list=[];
  13428.         //        foreach($id_list_for_ledger as $ind_head_id) {
  13429.         //            $ledger_data = Accounts::LedgerDetails($em, $ind_head_id, $start_date, $end_date,$provisional_option);
  13430.         //            $ledger_det[$ind_head_id]=$ledger_data;
  13431.         //            $head_name_list[]=$ledger_data['basic_data']['name'];
  13432.         //        }
  13433.         //        $grouped_heads=Accounts::GroupedHeads($em);
  13434.         $document_mark = array(
  13435.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13436.             'copy' => ''
  13437.         );
  13438.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  13439.             $html $this->renderView(
  13440.                 '@Accounts/pages/print/trial_balance_print.html.twig',
  13441.                 array(
  13442.                     //                    'pdf'=>true,
  13443.                     'page_title' => 'Trial Balance',
  13444.                     'company_name' => $company_data->getName(),
  13445.                     'company_data' => $company_data,
  13446.                     //                'details'=>$bs_details,
  13447.                     'tb_details' => $tb_details,
  13448.                     'start_date' => $start_date,
  13449.                     'end_date' => $end_date,
  13450.                     'max_level' => $max_level,
  13451.                     'expand_level' => $expand_level,
  13452.                     'cur_level' => $cur_level,
  13453.                     //                'ledger_data'=>$ledger_det,
  13454.                     'page_header' => 'Ledger',
  13455.                     'document_type' => 'Trial Balance',
  13456.                     'document_mark_image' => $document_mark['original'],
  13457.                     'page_header_sub' => 'Add',
  13458.                     'budget_variance_enabled' => $budgetEnabled,
  13459.                     'currBudgetList' => $em->getRepository('ApplicationBundle\\Entity\\FinancialBudget')->findBy(
  13460.                         array(
  13461.                             //                        'budgetId'=>$id, ///material
  13462.                             'CompanyId' => $this->getLoggedUserCompanyId($request), ///material
  13463.                         )
  13464.                     ),
  13465.                     'scale_variance' => ($request->query->has('scale_variance')) ? $request->query->get('scale_variance') : 0,
  13466.                     'budgetId' => ($request->query->has('budgetId')) ? $request->query->get('budgetId') : 0,
  13467.                     'head_list' => Accounts::HeadList($em),
  13468.                     'provisional' => $provisional_option,
  13469.                     //                'type_list'=>$type_list,
  13470.                     //            'child_list'=>$child_list,
  13471.                     //                'trans_data_by_closing'=>$trans_data_by_closing,
  13472.                     'item_data' => [],
  13473.                     'received' => 2,
  13474.                     'return' => 1,
  13475.                     'total_w_vat' => 1,
  13476.                     'total_vat' => 1,
  13477.                     'total_wo_vat' => 1,
  13478.                     'invoice_id' => 'abcd1234',
  13479.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  13480.                     'created_by' => 'created by',
  13481.                     'created_at' => '',
  13482.                     'red' => 0,
  13483.                     'company_address' => $company_data->getAddress(),
  13484.                     'company_image' => $company_data->getImage(),
  13485.                     'allocation_filters' => $allocationFilters,
  13486.                     'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
  13487.                     'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
  13488.                     'project_list' => $allocationSupportData['project_list'],
  13489.                     'branch_list' => $allocationSupportData['branch_list'],
  13490.                     'cost_centers' => $allocationSupportData['cost_centers'],
  13491.                 )
  13492.             );
  13493.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13494.                 //                'orientation' => 'landscape',
  13495.                 //                'enable-javascript' => false,
  13496.                 //                'javascript-delay' => 1000,
  13497.                 'no-stop-slow-scripts' => true,
  13498.                 'no-background' => false,
  13499.                 'lowquality' => false,
  13500.                 'encoding' => 'utf-8',
  13501.                 //            'images' => true,
  13502.                 //            'cookie' => array(),
  13503.                 'dpi' => 300,
  13504.                 'image-dpi' => 300,
  13505.                 //                'enable-external-links' => true,
  13506.                 //                'enable-internal-links' => true
  13507.             ));
  13508.             return new Response(
  13509.                 $pdf_response,
  13510.                 200,
  13511.                 array(
  13512.                     'Content-Type' => 'application/pdf',
  13513.                     'Content-Disposition' => 'attachment; filename="Trial Balance.pdf"'
  13514.                 )
  13515.             );
  13516.         }
  13517.         return $this->render(
  13518.             '@Accounts/pages/print/trial_balance_print.html.twig',
  13519.             array(
  13520.                 'page_title' => 'Trial Balance',
  13521.                 'export' => 'all',
  13522.                 'company_name' => $company_data->getName(),
  13523.                 'company_data' => $company_data,
  13524.                 //                'details'=>$bs_details,
  13525.                 'tb_details' => $tb_details,
  13526.                 'start_date' => $start_date,
  13527.                 'end_date' => $end_date,
  13528.                 'max_level' => $max_level,
  13529.                 'expand_level' => $expand_level,
  13530.                 'cur_level' => $cur_level,
  13531.                 //                'ledger_data'=>$ledger_det,
  13532.                 'page_header' => 'Ledger',
  13533.                 'document_type' => 'Trial Balance',
  13534.                 'document_mark_image' => $document_mark['original'],
  13535.                 'page_header_sub' => 'Add',
  13536.                 'budget_variance_enabled' => $budgetEnabled,
  13537.                 'currBudgetList' => $em->getRepository('ApplicationBundle\\Entity\\FinancialBudget')->findBy(
  13538.                     array(
  13539.                         //                        'budgetId'=>$id, ///material
  13540.                         'CompanyId' => $this->getLoggedUserCompanyId($request), ///material
  13541.                     )
  13542.                 ),
  13543.                 'scale_variance' => ($request->query->has('scale_variance')) ? $request->query->get('scale_variance') : 0,
  13544.                 'budgetId' => ($request->query->has('budgetId')) ? $request->query->get('budgetId') : 0,
  13545.                 'head_list' => Accounts::HeadList($em),
  13546.                 'provisional' => $provisional_option,
  13547.                 //                'type_list'=>$type_list,
  13548.                 //            'child_list'=>$child_list,
  13549.                 //                'trans_data_by_closing'=>$trans_data_by_closing,
  13550.                 'item_data' => [],
  13551.                 'received' => 2,
  13552.                 'return' => 1,
  13553.                 'total_w_vat' => 1,
  13554.                 'total_vat' => 1,
  13555.                 'total_wo_vat' => 1,
  13556.                 'invoice_id' => 'abcd1234',
  13557.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  13558.                 'created_by' => 'created by',
  13559.                 'created_at' => '',
  13560.                 'red' => 0,
  13561.                 'company_address' => $company_data->getAddress(),
  13562.                 'company_image' => $company_data->getImage(),
  13563.                 //                'p'=>$p
  13564.             )
  13565.         );
  13566.     }
  13567.     public function testSnappy(Request $request)
  13568.     {
  13569.         $em $this->getDoctrine()->getManager();
  13570.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  13571.         $document_mark = array(
  13572.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  13573.             'copy' => ''
  13574.         );
  13575.         $html $this->renderView(
  13576.             '@Accounts/pages/print/test.html.twig',
  13577.             array(
  13578.                 //                    'pdf'=>true,
  13579.                 'page_title' => 'Trial Balance',
  13580.                 'company_name' => $company_data->getName(),
  13581.                 'company_data' => $company_data,
  13582.                 //                'details'=>$bs_details,
  13583.                 //                'ledger_data'=>$ledger_det,
  13584.                 'page_header' => 'Ledger',
  13585.                 'document_type' => 'Trial Balance',
  13586.                 'document_mark_image' => $document_mark['original'],
  13587.                 'page_header_sub' => 'Add',
  13588.                 'company_address' => $company_data->getAddress(),
  13589.                 'company_image' => $company_data->getImage(),
  13590.                 'allocation_filters' => $allocationFilters,
  13591.                 'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
  13592.                 'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
  13593.                 'project_list' => $allocationSupportData['project_list'],
  13594.                 'branch_list' => $allocationSupportData['branch_list'],
  13595.                 'cost_centers' => $allocationSupportData['cost_centers'],
  13596.             )
  13597.         );
  13598.         $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  13599.             //                'orientation' => 'landscape',
  13600.             //                'enable-javascript' => false,
  13601.             //                'javascript-delay' => 1000,
  13602.             //                'no-stop-slow-scripts' => true,
  13603.             'no-background' => false,
  13604.             //                'lowquality' => false,
  13605.             'encoding' => 'utf-8',
  13606.             //            'images' => true,
  13607.             //            'cookie' => array(),
  13608.             'dpi' => 300,
  13609.             'image-dpi' => 300,
  13610.             //                'enable-external-links' => true,
  13611.             //                'enable-internal-links' => true
  13612.         ));
  13613.         return new Response(
  13614.             $pdf_response,
  13615.             200,
  13616.             array(
  13617.                 'Content-Type' => 'application/pdf',
  13618.                 'Content-Disposition' => 'attachment; filename="TestSnappy.pdf"'
  13619.             )
  13620.         );
  13621.     }
  13622.     public function CreateLedgerHead(Request $request)
  13623.     {
  13624.         $companyId $this->getLoggedUserCompanyId($request);
  13625.         if ($request->isMethod('POST')) {
  13626.             $em $this->getDoctrine()->getManager();
  13627.             $devAdmin $request->getSession()->get('devAdminMode'0) == 1;
  13628.             //first lets assume replication is not selected so lets get the parent and check if any head has this parents id as replication id
  13629.             $head_id Accounts::CreateNewHead(
  13630.                 $em,
  13631.                 GeneralConstant::OPENING_YEAR,
  13632.                 $request->request->get('parent_id'),
  13633.                 $request->request->get('name'),
  13634.                 $request->request->get('code'),
  13635.                 $request->request->get('opening_balance'),
  13636.                 $request->request->get('cc_enabled'),
  13637.                 $request->request->get('head_nature'),
  13638.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  13639.                 $request->request->get('replication_head_id'),
  13640.                 $request->request->has('checkAdvanceParent') ? 0,
  13641.                 "",
  13642.                 "",
  13643.                 $companyId,
  13644.                 $request->request->has('markerHash') ? $request->request->get('markerHash') : null,
  13645.                 $request->request->has('costCentreTypes') ? $request->request->get('costCentreTypes') : '',
  13646.                 $request->request->has('narrationOnCheck') ? $request->request->get('narrationOnCheck') : '',
  13647.                 $devAdmin && $request->request->has('flag_is_system')       ? (bool)$request->request->get('flag_is_system')       : false,
  13648.                 $devAdmin && $request->request->has('flag_is_editable')     ? (bool)$request->request->get('flag_is_editable')     : true,
  13649.                 $devAdmin && $request->request->has('flag_is_deletable')    ? (bool)$request->request->get('flag_is_deletable')    : true,
  13650.                 $devAdmin && $request->request->has('flag_is_child_allowed') ? (bool)$request->request->get('flag_is_child_allowed') : true
  13651.             ); //blahere
  13652.             // Optional: attach DATEV mapping if provided during creation
  13653.             if ($head_id && $request->request->has('datev_code') && $request->request->get('datev_code') != '') {
  13654.                 $newHead $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
  13655.                     ->findOneBy(['accountsHeadId' => $head_id]);
  13656.                 if ($newHead) {
  13657.                     AccountHeadExternalMappingService::setDatevMapping(
  13658.                         $em,
  13659.                         $newHead,
  13660.                         $companyId,
  13661.                         $request->request->get('datev_code'),
  13662.                         $request->request->has('datev_name') ? $request->request->get('datev_name') : null
  13663.                     );
  13664.                 }
  13665.             }
  13666.             if ($request->request->get('replication_head_id') == '') {
  13667.                 $replicate_data_qry $this->getDoctrine()
  13668.                     ->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
  13669.                     ->findBy(
  13670.                         array(
  13671.                             'replicationHeadId' => $request->request->get('parent_id'),
  13672.                             'replicate' => 1
  13673.                         )
  13674.                     );
  13675.                 //now create replicated heads for all of these
  13676.                 $p 0;
  13677.                 foreach ($replicate_data_qry as $entry) {
  13678.                     $p++;
  13679.                     $replicated_id Accounts::CreateNewHead(
  13680.                         $em,
  13681.                         GeneralConstant::OPENING_YEAR,
  13682.                         $entry->getAccountsHeadId(),
  13683.                         $request->request->get('name'),
  13684.                         $request->request->get('code') . $p,
  13685.                         $request->request->get('opening_balance'),
  13686.                         $request->request->get('cc_enabled'),
  13687.                         "",
  13688.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  13689.                         $head_id,
  13690.                         $entry->getAdvanceOf() == $request->request->get('parent_id') ? 0
  13691.                     );
  13692.                 }
  13693.             } else {
  13694.                 //                //creating the re
  13695.                 //                $head_id=Accounts::CreateNewHead(
  13696.                 //                    $em,
  13697.                 //                    GeneralConstant::OPENING_YEAR,
  13698.                 //                    $request->request->get('parent_id'),
  13699.                 //                    $request->request->get('name'),
  13700.                 //                    $request->request->get('code'),
  13701.                 //                    $request->request->get('opening_balance'),
  13702.                 //                    $request->request->get('cc_enabled'),
  13703.                 //                    $request->request->get('head_nature'),
  13704.                 //                    $request->getSession()->get(UserConstants::USER_LOGIN_ID,
  13705.                 //                        $request->request->get('replication_head_id'),
  13706.                 //                        $request->request->has('checkAdvanceParent')?1:0
  13707.                 //                    )
  13708.                 //                );
  13709.             }
  13710.             //            $url = $this->generateUrl(
  13711.             //                'edit_ledger_head'
  13712.             //            );
  13713.             //
  13714.             //            return $this->redirect($url . "/" . $head_id);
  13715.         }
  13716.         return $this->render(
  13717.             '@Accounts/pages/input_forms/add_ledger_heads.html.twig',
  13718.             array(
  13719.                 'page_title' => 'Create Ledger Head',
  13720.                 'headMarkers' => AccountsConstant::$HEAD_MARKER_ARRAY,
  13721.                 'costCentreTypesArray' => AccountsConstant::$costCentreTypesArray,
  13722.             )
  13723.         );
  13724.     }
  13725.     public function CreateLedgerHeadForApp(Request $request)
  13726.     {
  13727.         $companyId $this->getLoggedUserCompanyId($request);
  13728.         if ($request->isMethod('POST')) {
  13729.             $em $this->getDoctrine()->getManager();
  13730.             //first lets assume replication is not selected so lets get the parent and check if any head has this parents id as replication id
  13731.             $head_id Accounts::CreateNewHead(
  13732.                 $em,
  13733.                 GeneralConstant::OPENING_YEAR,
  13734.                 $request->request->get('parent_id'),
  13735.                 $request->request->get('name'),
  13736.                 $request->request->get('code'),
  13737.                 $request->request->get('opening_balance'),
  13738.                 $request->request->get('cc_enabled'),
  13739.                 $request->request->get('head_nature'),
  13740.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  13741.                 $request->request->get('replication_head_id'),
  13742.                 $request->request->has('checkAdvanceParent') ? 0,
  13743.                 "",
  13744.                 "",
  13745.                 $companyId,
  13746.                 $request->request->has('markerHash') ? $request->request->get('markerHash') : null,
  13747.                 $request->request->has('costCentreTypes') ? $request->request->get('costCentreTypes') : '',
  13748.                 $request->request->has('narrationOnCheck') ? $request->request->get('narrationOnCheck') : ''
  13749.             ); //blahere
  13750.             if ($request->request->get('replication_head_id') == '') {
  13751.                 $replicate_data_qry $this->getDoctrine()
  13752.                     ->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
  13753.                     ->findBy(
  13754.                         array(
  13755.                             'replicationHeadId' => $request->request->get('parent_id'),
  13756.                             'replicate' => 1
  13757.                         )
  13758.                     );
  13759.                 //now create replicated heads for all of these
  13760.                 $p 0;
  13761.                 foreach ($replicate_data_qry as $entry) {
  13762.                     $p++;
  13763.                     $replicated_id Accounts::CreateNewHead(
  13764.                         $em,
  13765.                         GeneralConstant::OPENING_YEAR,
  13766.                         $entry->getAccountsHeadId(),
  13767.                         $request->request->get('name'),
  13768.                         $request->request->get('code') . $p,
  13769.                         $request->request->get('opening_balance'),
  13770.                         $request->request->get('cc_enabled'),
  13771.                         "",
  13772.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  13773.                         $head_id,
  13774.                         $entry->getAdvanceOf() == $request->request->get('parent_id') ? 0
  13775.                     );
  13776.                 }
  13777.             } else {
  13778.                 //                //creating the re
  13779.                 //                $head_id=Accounts::CreateNewHead(
  13780.                 //                    $em,
  13781.                 //                    GeneralConstant::OPENING_YEAR,
  13782.                 //                    $request->request->get('parent_id'),
  13783.                 //                    $request->request->get('name'),
  13784.                 //                    $request->request->get('code'),
  13785.                 //                    $request->request->get('opening_balance'),
  13786.                 //                    $request->request->get('cc_enabled'),
  13787.                 //                    $request->request->get('head_nature'),
  13788.                 //                    $request->getSession()->get(UserConstants::USER_LOGIN_ID,
  13789.                 //                        $request->request->get('replication_head_id'),
  13790.                 //                        $request->request->has('checkAdvanceParent')?1:0
  13791.                 //                    )
  13792.                 //                );
  13793.             }
  13794.             //            $url = $this->generateUrl(
  13795.             //                'edit_ledger_head'
  13796.             //            );
  13797.             //
  13798.             //            return $this->redirect($url . "/" . $head_id);
  13799.         }
  13800.         return new JsonResponse([
  13801.             'success' => 'true',
  13802.         ]);
  13803. //        return $this->render(
  13804. //            '@Accounts/pages/input_forms/add_ledger_heads.html.twig',
  13805. //            array(
  13806. //                'page_title' => 'Create Ledger Head',
  13807. //                'headMarkers' => AccountsConstant::$HEAD_MARKER_ARRAY,
  13808. //                'costCentreTypesArray' => AccountsConstant::$costCentreTypesArray,
  13809. //            )
  13810. //        );
  13811.     }
  13812.     public function ChartOfAccounts(Request $request)
  13813.     {
  13814.         $em $this->getDoctrine()->getManager();
  13815.         $session $request->getSession();
  13816.         //        if($request->isMethod('POST')) {
  13817.         //
  13818.         //
  13819.         //
  13820.         //            //first lets assume replication is not selected so lets get the parent and check if any head has this parents id as replication id
  13821.         //
  13822.         //            $head_id=Accounts::CreateNewHead(
  13823.         //                $em,
  13824.         //                GeneralConstant::OPENING_YEAR,
  13825.         //                $request->request->get('parent_id'),
  13826.         //                $request->request->get('name'),
  13827.         //                $request->request->get('code'),
  13828.         //                $request->request->get('opening_balance'),
  13829.         //                $request->request->get('cc_enabled'),
  13830.         //                $request->request->get('head_nature'),
  13831.         //                $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  13832.         //                $request->request->get('replication_head_id'),
  13833.         //                $request->request->has('checkAdvanceParent')?1:0
  13834.         //
  13835.         //            ); //blahere
  13836.         //            if($request->request->get('replication_head_id')=='')
  13837.         //            {
  13838.         //                $replicate_data_qry= $this->getDoctrine()
  13839.         //                    ->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
  13840.         //                    ->findBy(
  13841.         //                        array(
  13842.         //                            'replicationHeadId' =>  $request->request->get('parent_id'),
  13843.         //                            'replicate'=>1
  13844.         //                        )
  13845.         //                    );
  13846.         //
  13847.         //                //now create replicated heads for all of these
  13848.         //                $p=0;
  13849.         //                foreach($replicate_data_qry as $entry)
  13850.         //                {
  13851.         //                    $p++;
  13852.         //
  13853.         //                    $replicated_id=Accounts::CreateNewHead(
  13854.         //                        $em,
  13855.         //                        GeneralConstant::OPENING_YEAR,
  13856.         //                        $entry->getAccountsHeadId(),
  13857.         //                        $request->request->get('name'),
  13858.         //                        $request->request->get('code').$p,
  13859.         //                        $request->request->get('opening_balance'),
  13860.         //                        $request->request->get('cc_enabled'),
  13861.         //                        "",
  13862.         //                        $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  13863.         //                        $head_id,
  13864.         //                        $entry->getAdvanceOf()==$request->request->get('parent_id')?1:0
  13865.         //
  13866.         //                    );
  13867.         //
  13868.         //                }
  13869.         //
  13870.         //            }
  13871.         //            else
  13872.         //            {
  13873.         ////                //creating the re
  13874.         ////                $head_id=Accounts::CreateNewHead(
  13875.         ////                    $em,
  13876.         ////                    GeneralConstant::OPENING_YEAR,
  13877.         ////                    $request->request->get('parent_id'),
  13878.         ////                    $request->request->get('name'),
  13879.         ////                    $request->request->get('code'),
  13880.         ////                    $request->request->get('opening_balance'),
  13881.         ////                    $request->request->get('cc_enabled'),
  13882.         ////                    $request->request->get('head_nature'),
  13883.         ////                    $request->getSession()->get(UserConstants::USER_LOGIN_ID,
  13884.         ////                        $request->request->get('replication_head_id'),
  13885.         ////                        $request->request->has('checkAdvanceParent')?1:0
  13886.         ////                    )
  13887.         ////                );
  13888.         //            }
  13889.         ////            $url = $this->generateUrl(
  13890.         ////                'edit_ledger_head'
  13891.         ////            );
  13892.         ////
  13893.         ////            return $this->redirect($url . "/" . $head_id);
  13894.         //
  13895.         //        }
  13896.         return $this->render(
  13897.             '@Accounts/pages/report/chart_of_accounts.html.twig',
  13898.             array(
  13899.                 'page_title' => 'Chart of Accounts',
  13900.                 //                'debug_data'=>  Company::getMonthlyDataForDashboard($em, $session->get(UserConstants::USER_COMPANY_ID, 1))
  13901.             )
  13902.         );
  13903.     }
  13904.     public function EditLedgerHead(Request $request$id)
  13905.     {
  13906.         $headExists 1;
  13907.         if ($request->isMethod('POST')) {
  13908.             $em $this->getDoctrine()->getManager();
  13909.             $head_data_qry $this->getDoctrine()
  13910.                 ->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
  13911.                 ->findOneBy(
  13912.                     array(
  13913.                         'accountsHeadId' => $id,
  13914.                         //                        'lockFlag'=>[0,null]
  13915.                     )
  13916.                 );
  13917.             $headExists 1;
  13918.             if ($request->request->has('transferTransactionsFlag')) {
  13919.                 $query "update acc_transaction_details set accounts_head_id =" $request->request->get('transferTransactionTo') . " where accounts_head_id =" $id ";";
  13920.                 //transfer any payment checks
  13921.                 $query .= "update acc_check set accounts_head_id =" $request->request->get('transferTransactionTo') . " where accounts_head_id =" $id ";";
  13922.                 $query .= "update acc_check set rec_accounts_head_id =" $request->request->get('transferTransactionTo') . " where rec_accounts_head_id =" $id ";";
  13923.                 $stmt $em->getConnection()->fetchAllAssociative($query);
  13924.                 
  13925.                 //now transfer any received checks
  13926.                 $query "SELECT *  from  acc_check where rec_accounts_head_id_list like '%\"" $id "\"%'  ;";
  13927.                 $stmt $em->getConnection()->fetchAllAssociative($query);
  13928.                 
  13929.                 $results $stmt;
  13930.                 foreach ($results as $result) {
  13931.                     $query 'update acc_check set rec_accounts_head_id_list=\''
  13932.                         str_replace("\"" $id "\"""\"" $request->request->get('transferTransactionTo') . "\""$result['rec_accounts_head_id_list']) . '\' '
  13933.                         'where check_id=' $result['check_id'];
  13934.                     $stmt $em->getConnection()->fetchAllAssociative($query);
  13935.                     
  13936.                 }
  13937.                 $this->addFlash(
  13938.                     'success',
  13939.                     'Transferred Transactions '
  13940.                 );
  13941.             }
  13942.             if ($request->request->has('deleteHeadFlag')) {
  13943.                 if (!AccountHeadPermissionService::canDelete($head_data_qry)) {
  13944.                     $this->addFlash('error''Could not Delete Head. This head is protected and cannot be deleted.');
  13945.                 } else {
  13946.                     $query "SELECT accounts_head_id  from  acc_accounts_head  where parent_id=" $id;
  13947.                     $stmt $em->getConnection()->fetchAllAssociative($query);
  13948.                     $results1 $stmt;
  13949.                     if (!empty($results1)) {
  13950.                         $this->addFlash(
  13951.                             'error',
  13952.                             'Could not Delete Head. Child Heads Found'
  13953.                         );
  13954.                     } else {
  13955.                         $query "SELECT * from acc_transaction_details where accounts_head_id =" $id;
  13956.                         $stmt $em->getConnection()->fetchAllAssociative($query);
  13957.                         $results2 $stmt;
  13958.                         if (!empty($results2)) {
  13959.                             $this->addFlash(
  13960.                                 'error',
  13961.                                 'Could not Delete Head. Transactions Entry Found'
  13962.                             );
  13963.                         } else {
  13964.                             $headExists 0;
  13965.                             if ($head_data_qry) {
  13966.                                 AccountHeadExternalMappingService::deleteMappingsForHead($em, (int)$id);
  13967.                                 $em->remove($head_data_qry);
  13968.                                 $em->flush();
  13969.                             }
  13970.                             $this->addFlash(
  13971.                                 'success',
  13972.                                 'Deleted Head'
  13973.                             );
  13974.                         }
  13975.                     }
  13976.                 }
  13977.             } else {
  13978.                 $devAdmin $request->getSession()->get('devAdminMode'0) == 1;
  13979.                 if (!$devAdmin && !AccountHeadPermissionService::canEdit($head_data_qry)) {
  13980.                     $this->addFlash('error''Could not Edit Head. This head is protected and cannot be modified.');
  13981.                 } else {
  13982.                     //            $change_in_opening= $request->request->get('opening_balance')-$head_data_qry->setOpeningBalance();
  13983.                     $head_data_qry->setParentId($request->request->get('parent_id'));
  13984.                     $head_data_qry->setName($request->request->get('name'));
  13985.                     if ($request->request->has('markerHash') && !$head_data_qry->getIsSystem())
  13986.                         $head_data_qry->setMarkerHash($request->request->get('markerHash'));
  13987.                     if ($request->request->has('costCentreTypes'))
  13988.                         $head_data_qry->setCostCentreTypes($request->request->get('costCentreTypes'));
  13989.                     if ($request->request->has('narrationOnCheck'))
  13990.                         $head_data_qry->setNarrationOnCheck($request->request->get('narrationOnCheck'));
  13991.                     $head_data_qry->setLedgerHeadCode($request->request->get('code'));
  13992.                     $head_data_qry->setOpeningBalance($request->request->get('opening_balance'));
  13993.                     $head_nature $request->request->get('head_nature');
  13994.                     $parentHead $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findOneBy(array(
  13995.                         "accountsHeadId" => $request->request->get('parent_id')
  13996.                     ));
  13997.                     //                if ($head_nature == '' || $head_nature == '0')
  13998.                     if (1// ovverride ,from now the nature will be asiigned by parent only
  13999.                     {
  14000.                         //            $accountsHead->setHeadnature(in_array($TheType, $credit_type) ? AccountsConstant::CREDIT : AccountsConstant::DEBIT);
  14001.                         $head_data_qry->setHeadnature($parentHead->getHeadNature());
  14002.                     } else
  14003.                         $head_data_qry->setHeadNature($head_nature);
  14004.                     $head_data_qry->setCcEnabled($request->request->get('cc_enabled'));
  14005.                     // Dev admin: allow overriding control flags directly from the form
  14006.                     if ($devAdmin) {
  14007.                         if ($request->request->has('flag_is_system'))
  14008.                             $head_data_qry->setIsSystem((bool)$request->request->get('flag_is_system'));
  14009.                         if ($request->request->has('flag_is_editable'))
  14010.                             $head_data_qry->setIsEditable((bool)$request->request->get('flag_is_editable'));
  14011.                         if ($request->request->has('flag_is_deletable'))
  14012.                             $head_data_qry->setIsDeletable((bool)$request->request->get('flag_is_deletable'));
  14013.                         if ($request->request->has('flag_is_child_allowed'))
  14014.                             $head_data_qry->setIsChildAllowed((bool)$request->request->get('flag_is_child_allowed'));
  14015.                     }
  14016.                     // Optional DATEV mapping update
  14017.                     if ($request->request->has('datev_code') && $request->request->get('datev_code') != '') {
  14018.                         AccountHeadExternalMappingService::setDatevMapping(
  14019.                             $em,
  14020.                             $head_data_qry,
  14021.                             $this->getLoggedUserCompanyId($request),
  14022.                             $request->request->get('datev_code'),
  14023.                             $request->request->has('datev_name') ? $request->request->get('datev_name') : null
  14024.                         );
  14025.                     }
  14026.                     //            if($head_data_qry->getLockFlag()!=1&&$change_in_opening!=0) {
  14027.                     //                $first_closing_date= $em->getRepository('ApplicationBundle\\Entity\\AccClosingBalance')->findOneBy(array(
  14028.                     ////                    'date' => new \DateTime($trans_date),
  14029.                     //                    'accountsHeadId'=>$id
  14030.                     //                ),array('date'=>'ASC'));
  14031.                     //                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);
  14032.                     //                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);
  14033.                     //                Accounts::HitLedger($em, $id, $change_in_opening, $head_data_qry->getHeadNature(), $change_in_opening);
  14034.                     //            }
  14035.                     Accounts::AddHeadPath($em$id);
  14036.                     $em->flush();
  14037.                 }
  14038.             }
  14039.         }
  14040.         $head_data = [];
  14041.         if ($id != '' && $id != && $headExists == 1) {
  14042.             $head_data_qry $this->getDoctrine()
  14043.                 ->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
  14044.                 ->findOneBy(
  14045.                     array(
  14046.                         'accountsHeadId' => $id,
  14047.                     )
  14048.                 );
  14049.             $head_data['id'] = $head_data_qry->getAccountsHeadId();
  14050.             $head_data['name'] = $head_data_qry->getName();
  14051.             $head_data['narrationOnCheck'] = $head_data_qry->getNarrationOnCheck();
  14052.             $head_data['parent_id'] = $head_data_qry->getParentId();
  14053.             $head_data['marker_hash'] = $head_data_qry->getMarkerHash();
  14054.             $head_data['cost_centre_types'] = $head_data_qry->getCostCentreTypes();
  14055.             $head_data['head_nature'] = $head_data_qry->getHeadNature();
  14056.             $head_data['cc_enabled'] = $head_data_qry->getCcEnabled();
  14057.             $head_data['ledger_head_code'] = $head_data_qry->getLedgerHeadCode();
  14058.             $head_data['opening_balance'] = $head_data_qry->getOpeningBalance();
  14059.             $head_data['is_system'] = $head_data_qry->getIsSystem() ? 0;
  14060.             $head_data['is_editable'] = $head_data_qry->getIsEditable() ? 0;
  14061.             $head_data['is_deletable'] = $head_data_qry->getIsDeletable() ? 0;
  14062.             $head_data['is_child_allowed'] = $head_data_qry->getIsChildAllowed() ? 0;
  14063.             return $this->render(
  14064.                 '@Accounts/pages/input_forms/edit_ledger_head.html.twig',
  14065.                 array(
  14066.                     'page_title' => 'Edit Ledger Head',
  14067.                     'head_data' => $head_data,
  14068.                     'headMarkers' => AccountsConstant::$HEAD_MARKER_ARRAY,
  14069.                     'costCentreTypesArray' => AccountsConstant::$costCentreTypesArray,
  14070.                 )
  14071.             );
  14072.         } else {
  14073.             return $this->render(
  14074.                 '@Accounts/pages/input_forms/add_ledger_heads.html.twig',
  14075.                 array(
  14076.                     'page_title' => 'Create Ledger Head',
  14077.                     'headMarkers' => AccountsConstant::$HEAD_MARKER_ARRAY,
  14078.                     'costCentreTypesArray' => AccountsConstant::$costCentreTypesArray,
  14079.                 )
  14080.             );
  14081.         }
  14082.     }
  14083.     public function GetCostCentres(Request $request$headId 0$costCentreTypesStr '')
  14084.     {
  14085.         $cc_id '';
  14086.         $cc_name '';
  14087.         $cc_type '';
  14088.         $cost_centre_types_array_this = [];
  14089.         $em $this->getDoctrine()->getManager();
  14090.         if ($headId != 0) {
  14091.             $queryStr "select * from acc_accounts_head where
  14092.             accounts_head_id=$headId  limit 1";
  14093.             $stmt $em->getConnection()->fetchAllAssociative($queryStr);
  14094.             
  14095.             $results $stmt;
  14096.             $parentIdList = [];
  14097.             if (!empty($results)) {
  14098.                 $headData $results[0];
  14099.                 $parentIdList array_filter(explode(","$headData['path_tree']));
  14100.                 $cost_centre_types_array_this array_filter(explode(","$headData['cost_centre_types']));
  14101.                 $costCentreTypesStr $headData['cost_centre_types'];
  14102.                 if ($costCentreTypesStr == "" || $costCentreTypesStr == null) {
  14103.                     $queryStr "select * from acc_accounts_head where
  14104.             accounts_head_id in ( " implode(','$parentIdList) . " )";
  14105.                     $stmt $em->getConnection()->fetchAllAssociative($queryStr);
  14106.                     
  14107.                     $results $stmt;
  14108.                     if (!empty($results)) {
  14109.                         foreach ($results as $result) {
  14110.                             $headData $result;
  14111.                             $cost_centre_types_array_this_only array_filter(explode(","$headData['cost_centre_types']));
  14112.                             $cost_centre_types_array_this array_merge($cost_centre_types_array_thisarray_diff($cost_centre_types_array_this$cost_centre_types_array_this_only));
  14113.                         }
  14114.                     }
  14115.                 }
  14116.             }
  14117.         }
  14118.         if (empty($cost_centre_types_array_this)) {
  14119.             if ($costCentreTypesStr == "" || $costCentreTypesStr == null) {
  14120.             } else {
  14121.                 $cost_centre_types_array_this array_filter(explode(","$costCentreTypesStr));
  14122.             }
  14123.         }
  14124.         $queryStr "select * from acc_cost_centre where
  14125.             company_id=" $this->getLoggedUserCompanyId($request);
  14126.         if (empty($cost_centre_types_array_this)) {
  14127.             foreach ($cost_centre_types_array_this as $typ)
  14128.                 $queryStr .= " and cost_centre_type like '%" $typ "%' ";
  14129.         }
  14130.         $stmt $em->getConnection()->fetchAllAssociative($queryStr);
  14131.         
  14132.         $cc_data $stmt;
  14133.         $cc_data_list = [];
  14134.         foreach ($cc_data as $value) {
  14135.             $cc_data_list[$value['cost_centre_id']]['id'] = $value['cost_centre_id'];
  14136.             $cc_data_list[$value['cost_centre_id']]['name'] = $value['name'];
  14137.             $cc_data_list[$value['cost_centre_id']]['type'] = $value['cost_centre_type'];
  14138.         }
  14139.         if (!empty($cc_data_list))
  14140.             return new JsonResponse(array(
  14141.                 'success' => true,
  14142.                 'data' => $cc_data_list
  14143.             ));
  14144.         else
  14145.             return new JsonResponse(array(
  14146.                 'success' => false,
  14147.                 'data' => $cc_data_list
  14148.             ));
  14149.     }
  14150.     public function CreateCostCentre(Request $request$id)
  14151.     {
  14152.         $em $this->getDoctrine()->getManager();
  14153.         $cc_id '';
  14154.         $cc_name '';
  14155.         $cc_type '';
  14156.         if ($request->isMethod('POST')) {
  14157.             $em $this->getDoctrine()->getManager();
  14158.             //            $submittedToken = $request->request->get('token');
  14159.             //
  14160.             //            // 'delete-item' is the same value used in the template to generate the token
  14161.             //            if ($this->isCsrfTokenValid('delete-item', $submittedToken)) {
  14162.             //                // ... do something, like deleting an object
  14163.             //            }
  14164.             //            return new Response(1);
  14165.             if ($request->request->get('cc_id') != '' && $request->request->get('cc_id') != 0) {
  14166.                 $em $this->getDoctrine()->getManager();
  14167.                 $new_cc $this->getDoctrine()
  14168.                     ->getRepository('ApplicationBundle\\Entity\\AccCostCentre')
  14169.                     ->findOneBy(
  14170.                         array(
  14171.                             'costCentreId' => $id,
  14172.                         )
  14173.                     );
  14174.                 $new_cc->setName($request->request->get('name'));
  14175.                 $new_cc->setCostCentreType($request->request->get('costCentreType'));
  14176.                 $new_cc->setCompanyId($this->getLoggedUserCompanyId($request));
  14177.                 $em->flush();
  14178.             } else {
  14179.                 $new_cc = new AccCostCentre();
  14180.                 $new_cc->setName($request->request->get('name'));
  14181.                 $new_cc->setCostCentreType($request->request->get('costCentreType'));
  14182.                 $new_cc->setCompanyId($this->getLoggedUserCompanyId($request));
  14183.                 $em->persist($new_cc);
  14184.                 $em->flush();
  14185.                 $new_cc->getCostCentreId();
  14186.             }
  14187.         }
  14188.         $cc_data $this->getDoctrine()
  14189.             ->getRepository('ApplicationBundle\\Entity\\AccCostCentre')
  14190.             ->findAll();
  14191.         $cc_data_list = [];
  14192.         foreach ($cc_data as $value) {
  14193.             $cc_data_list[$value->getCostCentreId()]['id'] = $value->getCostCentreId();
  14194.             $cc_data_list[$value->getCostCentreId()]['name'] = $value->getName();
  14195.             $cc_data_list[$value->getCostCentreId()]['type'] = $value->getCostCentreType();
  14196.             if ($value->getCostCentreId() == $id) {
  14197.                 $cc_id $value->getCostCentreId();
  14198.                 $cc_name $value->getName();
  14199.                 $cc_type $value->getCostCentreType();
  14200.             }
  14201.         }
  14202.         return $this->render(
  14203.             '@Accounts/pages/input_forms/add_cost_centre.html.twig',
  14204.             array(
  14205.                 'page_title' => 'Cost Centre',
  14206.                 'cc_data' => $cc_data_list,
  14207.                 'cc_id' => $cc_id,
  14208.                 'costCentreTypesArray' => AccountsConstant::$costCentreTypesArray,
  14209.                 'costCentreTypes' => AccountsConstant::$costCentreTypes,
  14210.                 'cc_name' => $cc_name,
  14211.                 'cc_type' => $cc_type
  14212.             )
  14213.         );
  14214.     }
  14215.     /**
  14216.      * Slug used as the split-allocation tag_type (e.g. "Sales Type" -> "sales_type").
  14217.      */
  14218.     private function slugifyDimensionCode($text)
  14219.     {
  14220.         $slug strtolower(trim((string) $text));
  14221.         $slug preg_replace('/[^a-z0-9]+/''_'$slug);
  14222.         $slug trim($slug'_');
  14223.         return $slug !== '' $slug 'dimension';
  14224.     }
  14225.     /**
  14226.      * Dimension Type Entry page — manage allocation dimensions (e.g. Sales Type)
  14227.      * and their values (Pump Sales / Solar Sales / Trade Sales). These feed the
  14228.      * split-allocation dropdowns on the vouchers.
  14229.      */
  14230.     public function DimensionEntry(Request $request$id)
  14231.     {
  14232.         $em $this->getDoctrine()->getManager();
  14233.         $dimensionRepo $em->getRepository('ApplicationBundle\\Entity\\Dimension');
  14234.         $valueRepo $em->getRepository('ApplicationBundle\\Entity\\DimensionValue');
  14235.         if ($request->isMethod('POST') && $request->request->has('dimension_submit')) {
  14236.             $dimId = (int) $request->request->get('dim_id'0);
  14237.             $name trim((string) $request->request->get('name'));
  14238.             $codeInput trim((string) $request->request->get('code'));
  14239.             $code $codeInput !== '' $this->slugifyDimensionCode($codeInput) : $this->slugifyDimensionCode($name);
  14240.             if ($name === '') {
  14241.                 $this->addFlash('error''Dimension name is required.');
  14242.                 return $this->redirectToRoute('dimension_entry', array('id' => $dimId));
  14243.             }
  14244.             // Enforce a unique code among live dimensions (other than the one being edited).
  14245.             $existingByCode $dimensionRepo->findOneActiveByCode($code);
  14246.             if ($existingByCode && (int) $existingByCode->getId() !== $dimId) {
  14247.                 $code $code '_' substr(md5($name microtime(true)), 04);
  14248.             }
  14249.             if ($dimId 0) {
  14250.                 $dimension $dimensionRepo->findOneBy(array('id' => $dimId));
  14251.                 if (!$dimension) {
  14252.                     $this->addFlash('error''Dimension not found.');
  14253.                     return $this->redirectToRoute('dimension_entry');
  14254.                 }
  14255.                 $dimension->setName($name);
  14256.                 $dimension->setCode($code);
  14257.                 $dimension->setDescription($request->request->get('description'));
  14258.                 $dimension->setSortOrder($request->request->get('sort_order') !== '' ? (int) $request->request->get('sort_order') : null);
  14259.                 $dimension->setActive($request->request->get('active') ? 0);
  14260.                 $dimension->setEditedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  14261.                 $em->flush();
  14262.                 $this->addFlash('success''Dimension updated.');
  14263.             } else {
  14264.                 $dimension = new \ApplicationBundle\Entity\Dimension();
  14265.                 $dimension->setName($name);
  14266.                 $dimension->setCode($code);
  14267.                 $dimension->setDescription($request->request->get('description'));
  14268.                 $dimension->setSortOrder($request->request->get('sort_order') !== '' ? (int) $request->request->get('sort_order') : null);
  14269.                 $dimension->setActive($request->request->get('active') ? 0);
  14270.                 $dimension->setDeleteFlag(0);
  14271.                 $dimension->setCompanyId($this->getLoggedUserCompanyId($request));
  14272.                 $dimension->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  14273.                 $em->persist($dimension);
  14274.                 $em->flush();
  14275.                 $this->addFlash('success''Dimension created. Now add its values below.');
  14276.                 $dimId $dimension->getId();
  14277.             }
  14278.             return $this->redirectToRoute('dimension_entry', array('id' => $dimId));
  14279.         }
  14280.         $id = (int) $id;
  14281.         $dimensions $dimensionRepo->findAllActive(true);
  14282.         $dimensionList = array();
  14283.         $editingDimension null;
  14284.         foreach ($dimensions as $dim) {
  14285.             $row = array(
  14286.                 'id' => $dim->getId(),
  14287.                 'name' => $dim->getName(),
  14288.                 'code' => $dim->getCode(),
  14289.                 'active' => (int) $dim->getActive(),
  14290.                 'valueCount' => $valueRepo->countByDimensionId($dim->getId()),
  14291.             );
  14292.             $dimensionList[] = $row;
  14293.             if ((int) $dim->getId() === $id) {
  14294.                 $editingDimension = array(
  14295.                     'id' => $dim->getId(),
  14296.                     'name' => $dim->getName(),
  14297.                     'code' => $dim->getCode(),
  14298.                     'description' => $dim->getDescription(),
  14299.                     'sortOrder' => $dim->getSortOrder(),
  14300.                     'active' => (int) $dim->getActive(),
  14301.                 );
  14302.             }
  14303.         }
  14304.         $valueList = array();
  14305.         if ($editingDimension) {
  14306.             foreach ($valueRepo->findByDimensionId($id) as $v) {
  14307.                 $valueList[] = array(
  14308.                     'id' => $v->getId(),
  14309.                     'name' => $v->getName(),
  14310.                     'code' => $v->getCode(),
  14311.                     'active' => (int) $v->getActive(),
  14312.                     'sortOrder' => $v->getSortOrder(),
  14313.                 );
  14314.             }
  14315.         }
  14316.         return $this->render(
  14317.             '@Accounts/pages/input_forms/dimension_entry.html.twig',
  14318.             array(
  14319.                 'page_title' => 'Dimension Entry',
  14320.                 'dimensionList' => $dimensionList,
  14321.                 'editingDimension' => $editingDimension,
  14322.                 'valueList' => $valueList,
  14323.             )
  14324.         );
  14325.     }
  14326.     public function DimensionValueSave(Request $request)
  14327.     {
  14328.         $em $this->getDoctrine()->getManager();
  14329.         $valueRepo $em->getRepository('ApplicationBundle\\Entity\\DimensionValue');
  14330.         $dimensionId = (int) $request->request->get('dimension_id'0);
  14331.         $valueId = (int) $request->request->get('value_id'0);
  14332.         $name trim((string) $request->request->get('name'));
  14333.         if ($dimensionId <= 0) {
  14334.             $this->addFlash('error''Missing dimension.');
  14335.             return $this->redirectToRoute('dimension_entry');
  14336.         }
  14337.         if ($name === '') {
  14338.             $this->addFlash('error''Value name is required.');
  14339.             return $this->redirectToRoute('dimension_entry', array('id' => $dimensionId));
  14340.         }
  14341.         if ($valueId 0) {
  14342.             $value $valueRepo->findOneBy(array('id' => $valueId));
  14343.             if (!$value) {
  14344.                 $this->addFlash('error''Value not found.');
  14345.                 return $this->redirectToRoute('dimension_entry', array('id' => $dimensionId));
  14346.             }
  14347.             $value->setName($name);
  14348.             $value->setCode($request->request->get('code'));
  14349.             $value->setSortOrder($request->request->get('sort_order') !== '' ? (int) $request->request->get('sort_order') : null);
  14350.             $value->setActive($request->request->get('active') ? 0);
  14351.             $value->setEditedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  14352.             $em->flush();
  14353.             $this->addFlash('success''Value updated.');
  14354.         } else {
  14355.             $value = new \ApplicationBundle\Entity\DimensionValue();
  14356.             $value->setDimensionId($dimensionId);
  14357.             $value->setName($name);
  14358.             $value->setCode($request->request->get('code'));
  14359.             $value->setSortOrder($request->request->get('sort_order') !== '' ? (int) $request->request->get('sort_order') : null);
  14360.             $value->setActive($request->request->get('active') ? 0);
  14361.             $value->setDeleteFlag(0);
  14362.             $value->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  14363.             $em->persist($value);
  14364.             $em->flush();
  14365.             $this->addFlash('success''Value added.');
  14366.         }
  14367.         return $this->redirectToRoute('dimension_entry', array('id' => $dimensionId));
  14368.     }
  14369.     public function DimensionDelete(Request $request$id)
  14370.     {
  14371.         $em $this->getDoctrine()->getManager();
  14372.         $dimensionRepo $em->getRepository('ApplicationBundle\\Entity\\Dimension');
  14373.         $valueRepo $em->getRepository('ApplicationBundle\\Entity\\DimensionValue');
  14374.         $dimension $dimensionRepo->findOneBy(array('id' => (int) $id));
  14375.         if ($dimension) {
  14376.             $dimension->setDeleteFlag(1);
  14377.             $dimension->setActive(0);
  14378.             $dimension->setEditedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  14379.             // soft-delete its values too
  14380.             foreach ($valueRepo->findByDimensionId((int) $id) as $v) {
  14381.                 $v->setDeleteFlag(1);
  14382.                 $v->setActive(0);
  14383.             }
  14384.             $em->flush();
  14385.             $this->addFlash('success''Dimension removed.');
  14386.         }
  14387.         return $this->redirectToRoute('dimension_entry');
  14388.     }
  14389.     public function DimensionValueDelete(Request $request$id)
  14390.     {
  14391.         $em $this->getDoctrine()->getManager();
  14392.         $valueRepo $em->getRepository('ApplicationBundle\\Entity\\DimensionValue');
  14393.         $value $valueRepo->findOneBy(array('id' => (int) $id));
  14394.         $dimensionId $value $value->getDimensionId() : 0;
  14395.         if ($value) {
  14396.             $value->setDeleteFlag(1);
  14397.             $value->setActive(0);
  14398.             $value->setEditedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  14399.             $em->flush();
  14400.             $this->addFlash('success''Value removed.');
  14401.         }
  14402.         return $this->redirectToRoute('dimension_entry', array('id' => $dimensionId));
  14403.     }
  14404.     public function index(Request $request)
  14405.     {
  14406.         return $this->render(
  14407.             '@Application/pages/dashboard/index.html.twig',
  14408.             array(
  14409.                 'page_title' => 'Dashboard'
  14410.             )
  14411.         );
  14412.     }
  14413.     public function TestPixInvent(Request $request)
  14414.     {
  14415.         $em $this->getDoctrine()->getManager();
  14416.         $allowed_ids = [];
  14417.         $companyId $this->getLoggedUserCompanyId($request);
  14418.         //        return $this->render('ApplicationBundle:pages/dashboard:test_pix_invent.html.twig',
  14419.         return $this->render(
  14420.             '@Application/pages/dashboard/codecovers_test.html.twig',
  14421.             array(
  14422.                 'page_title' => 'Client List',
  14423.                 'data' => SalesOrderM::GetClientList($em, [], $companyId),
  14424.                 'client_types' => Client::GetClientType($em$companyId),
  14425.                 'region_list' => Client::RegionList($em$companyId),
  14426.                 'geographical_region_list' => Client::GeographicalRegionList($em$companyId)
  14427.             )
  14428.         );
  14429.     }
  14430.     public function GetDocumentHash(Request $request$t$p$a)
  14431.     {
  14432.         $em $this->getDoctrine()->getManager();
  14433.         $companyId $this->getLoggedUserCompanyId($request);
  14434.         $timestamp $request->request->get('timeStampOfForm'$request->query->get('timeStampOfForm'''));
  14435.         $documentId $request->request->get('documentId'$request->query->get('documentId'0));
  14436.         if ($request->query->has('returnJson'))
  14437.             return new JsonResponse(array(
  14438.                 'success' => true,
  14439.                 'numberHash' => MiscActions::GetNumberHash($em$t$p$a$timestamp$documentId$companyId)
  14440.             ));
  14441.         else
  14442.             return new Response(MiscActions::GetNumberHash($em$t$p$a$timestamp$documentId$companyId));
  14443.     }
  14444.     public function CreatePrefix(Request $request)
  14445.     {
  14446.         if ($request->isMethod('POST')) {
  14447.             //            Generic::debugMessage($_POST);
  14448.             //
  14449.             $ledgerHeads = [];
  14450.             $costCenters = [];
  14451.             $prefix_name $request->request->get('pref_name');
  14452.             $prefix_usages $request->request->get('pref_usages');
  14453.             $prefix_entry_types $request->request->get('entryTypes');
  14454.             if ($prefix_name != 'GN' || $prefix_name != 'gn') {
  14455.                 $ledgerHeads $request->request->get('ledgerHeads');
  14456.                 $costCenters $request->request->get('costCenters');
  14457.                 $prefix_name $request->request->get('pref_name');
  14458.                 $prefix_usages $request->request->get('pref_usages');
  14459.                 $prefix_entry_types $request->request->get('entryTypes');
  14460.             }
  14461.             // Form arrays may be absent on a POST (e.g. a GN prefix with no ledger
  14462.             // heads) → coalesce to arrays so count()/indexing don't fatal (PHP 7.2+).
  14463.             $ledgerHeads is_array($ledgerHeads) ? $ledgerHeads : [];
  14464.             $costCenters is_array($costCenters) ? $costCenters : [];
  14465.             $prefix_usages is_array($prefix_usages) ? $prefix_usages : [];
  14466.             $prefix_entry_types is_array($prefix_entry_types) ? $prefix_entry_types : [];
  14467.             //            $crAmount=$request->request->get('crAmount');
  14468.             $prefix_details = array();
  14469.             for ($i 0$i count($ledgerHeads); $i++) {
  14470.                 array_push($prefix_details, array(
  14471.                     'head_id' => $ledgerHeads[$i],
  14472.                     'cost_centre' => isset($costCenters[$i]) ? $costCenters[$i] : 0,
  14473.                     'type' => $prefix_entry_types[$i],
  14474.                 ));
  14475.             }
  14476.             for ($i 0$i count($prefix_usages); $i++) {
  14477.                 Accounts::CreateNewPrefix(
  14478.                     $this->getDoctrine()->getManager(),
  14479.                     $prefix_usages[$i],
  14480.                     $prefix_name,
  14481.                     $prefix_details
  14482.                 );
  14483.             }
  14484.             $this->addFlash(
  14485.                 'success',
  14486.                 'New Prefix Added.'
  14487.             );
  14488.         }
  14489.         return $this->render(
  14490.             '@Accounts/pages/input_forms/add_prefix.html.twig',
  14491.             array(
  14492.                 'page_title' => 'Prefix'
  14493.             )
  14494.         );
  14495.     }
  14496.     public function BankRecon(Request $request$id 0)
  14497.     {
  14498.         $em $this->getDoctrine()->getManager();
  14499.         $bank_settings $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  14500.             'name' => 'bank_parents'
  14501.         ));
  14502.         $bank_id_list = [];
  14503.         if ($bank_settings)
  14504.             $bank_id_list json_decode($bank_settings->getData());
  14505.         $head_list Accounts::HeadListFullPath($em);
  14506.         $bank_head_list = [];
  14507.         foreach ($head_list as $k => $v) {
  14508.             foreach ($bank_id_list as $bid) {
  14509.                 $q_str '/' $bid '/';
  14510.                 $path_string $v['path'];
  14511.                 $debug_it[] = [$q_str$path_stringstrpos($path_string$q_str)];
  14512.                 if (strpos($path_string$q_str) !== false) {
  14513.                     $bank_head_list[$k] = $v;
  14514.                 } else {
  14515.                 }
  14516.             }
  14517.         }
  14518.         //        if($request->isMethod('POST')){
  14519.         //            //it will be used on the approval page start
  14520.         //                      //it will be used on the approval page start
  14521.         //        }
  14522.         if ($request->isMethod('POST')) {
  14523.             $em $this->getDoctrine()->getManager();
  14524.             $entity_id array_flip(GeneralConstant::$Entity_list)['Brs'];
  14525.             $typeHash "BRS-" $request->request->get('bank_head');
  14526.             $brsDate = new \DateTime($request->request->get('statement_date'));
  14527.             $prefixHash $brsDate->format('Y');
  14528.             $assocHash $brsDate->format('m');
  14529.             $numberHash $brsDate->format('d');
  14530.             //            $dochash=$request->request->get('docHash');
  14531.             $dochash $typeHash '/' $prefixHash '/' $assocHash '/' $numberHash;
  14532.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14533.             $approveRole $request->request->get('approvalRole') ? $request->request->get('approvalRole') : 1;
  14534.             $approveHash $request->request->has('approvalHash') ? $request->request->get('approvalHash') : '';
  14535.             $skipApprove 0;
  14536.             //            if($approveHash=='') {
  14537.             //                $skipApprove = 1;//temp
  14538.             //            }
  14539.             if (!DocValidation::isInsertable(
  14540.                 $em,
  14541.                 $entity_id,
  14542.                 $dochash,
  14543.                 $loginId,
  14544.                 $approveRole,
  14545.                 $approveHash,
  14546.                 $id,
  14547.                 $skipApprove
  14548.             )) {
  14549.                 $this->addFlash(
  14550.                     'error',
  14551.                     'Sorry Could not insert Data.'
  14552.                 );
  14553.             } else {
  14554.                 //construct the files
  14555.                 $post_data $request->request;
  14556.                 $brs $em
  14557.                     ->getRepository('ApplicationBundle\\Entity\\Brs')
  14558.                     ->findOneby(array(
  14559.                         'brsId' => $id
  14560.                     ));
  14561.                 if ($brs)
  14562.                     $new $brs;
  14563.                 else
  14564.                     $new = new Brs();
  14565.                 $LoginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14566.                 $companyId $this->getLoggedUserCompanyId($request);
  14567.                 $data = array();
  14568.                 $exception_key_list = [
  14569.                     'approvalRole',
  14570.                     'approvalHash',
  14571.                     'assocHash',
  14572.                     'numberHash',
  14573.                     'typeHash',
  14574.                     'prefixHash',
  14575.                     'pending_cn',
  14576.                     'pending_vn',
  14577.                     'cleared_cn',
  14578.                     'cleared_vn',
  14579.                     'pending_check_amount_old',
  14580.                     'pending_check_amount_add_old',
  14581.                     'nsf_cn',
  14582.                     'nsf_vn',
  14583.                 ];
  14584.                 $prTypeList = array(
  14585.                     => 'Document',
  14586.                     => 'Ind. Check',
  14587.                     => 'Cons. Check',
  14588.                     => 'Adv. Letter',
  14589.                     => 'O/L Trans',
  14590.                 );
  14591.                 //adding vn and cn
  14592.                 $pending_cn = [];
  14593.                 $pending_vn = [];
  14594.                 foreach (json_decode($post_data->get('pending_check_id'), true) as $v) {
  14595.                     $check $em
  14596.                         ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  14597.                         ->findOneby(array(
  14598.                             'CheckId' => $v
  14599.                         ));
  14600.                     if ($check) {
  14601.                         $pending_cn[] = $check->getCheckNumber();
  14602.                         $vchr $em
  14603.                             ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  14604.                             ->findOneby(array(
  14605.                                 'transactionId' => $check->getVoucherId()
  14606.                             ));
  14607.                         if ($vchr) {
  14608.                             $pending_vn[] = $vchr->getDocumentHash();
  14609.                         } else
  14610.                             $pending_vn[] = '';
  14611.                     } else {
  14612.                         $vid explode('_'explode('v'$v)[1])[0];
  14613.                         $vchr $em
  14614.                             ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  14615.                             ->findOneby(array(
  14616.                                 'transactionId' => $vid
  14617.                             ));
  14618.                         if ($vchr) {
  14619.                             $prRef $vchr->getPrReference();
  14620.                             if ($prRef == '0') {
  14621.                                 $prRef $prTypeList[$vchr->getPrMethod()] . " on " $vchr->getDocumentHash();
  14622.                             }
  14623.                             if ($vchr->getDocumentType() == 6) {
  14624.                                 $prRef "Cash Received on " $vchr->getDocumentHash();
  14625.                             }
  14626.                             $pending_cn[] = $prRef;
  14627.                             $pending_vn[] = $vchr->getDocumentHash();
  14628.                         }
  14629.                     }
  14630.                 }
  14631.                 $data['pending_cn'] = $pending_cn;
  14632.                 $data['pending_vn'] = $pending_vn;
  14633.                 $cleared_cn = [];
  14634.                 $cleared_vn = [];
  14635.                 foreach (json_decode($post_data->get('cleared_check_id'), true) as $v) {
  14636.                     $check $em
  14637.                         ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  14638.                         ->findOneby(array(
  14639.                             'CheckId' => $v
  14640.                         ));
  14641.                     if ($check) {
  14642.                         $cleared_cn[] = $check->getCheckNumber();
  14643.                         $vchr $em
  14644.                             ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  14645.                             ->findOneby(array(
  14646.                                 'transactionId' => $check->getVoucherId()
  14647.                             ));
  14648.                         if ($vchr) {
  14649.                             $cleared_vn[] = $vchr->getDocumentHash();
  14650.                         } else
  14651.                             $cleared_vn[] = '';
  14652.                     } else {
  14653.                         $vid explode('_'explode('v'$v)[1])[0];
  14654.                         $vchr $em
  14655.                             ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  14656.                             ->findOneby(array(
  14657.                                 'transactionId' => $vid
  14658.                             ));
  14659.                         if ($vchr) {
  14660.                             $prRef $vchr->getPrReference();
  14661.                             if ($prRef == '0') {
  14662.                                 $prRef $prTypeList[$vchr->getPrMethod()] . " on " $vchr->getDocumentHash();
  14663.                             }
  14664.                             if ($vchr->getDocumentType() == 6) {
  14665.                                 $prRef "Cash Received on " $vchr->getDocumentHash();
  14666.                             }
  14667.                             $cleared_cn[] = $prRef;
  14668.                             $cleared_vn[] = $vchr->getDocumentHash();
  14669.                         }
  14670.                     }
  14671.                 }
  14672.                 $data['cleared_cn'] = $cleared_cn;
  14673.                 $data['cleared_vn'] = $cleared_vn;
  14674.                 $nsf_cn = [];
  14675.                 $nsf_vn = [];
  14676.                 foreach (json_decode($post_data->get('nsf_check_id'), true) as $v) {
  14677.                     $check $em
  14678.                         ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  14679.                         ->findOneby(array(
  14680.                             'CheckId' => $v
  14681.                         ));
  14682.                     if ($check) {
  14683.                         $nsf_cn[] = $check->getCheckNumber();
  14684.                         $vchr $em
  14685.                             ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  14686.                             ->findOneby(array(
  14687.                                 'transactionId' => $check->getVoucherId()
  14688.                             ));
  14689.                         if ($vchr) {
  14690.                             $nsf_vn[] = $vchr->getDocumentHash();
  14691.                         } else
  14692.                             $nsf_vn[] = '';
  14693.                     } else {
  14694.                         $vid explode('_'explode('v'$v)[1])[0];
  14695.                         $vchr $em
  14696.                             ->getRepository('ApplicationBundle\\Entity\\AccTransactions')
  14697.                             ->findOneby(array(
  14698.                                 'transactionId' => $vid
  14699.                             ));
  14700.                         if ($vchr) {
  14701.                             $prRef $vchr->getPrReference();
  14702.                             if ($prRef == '0') {
  14703.                                 $prRef $prTypeList[$vchr->getPrMethod()] . " on " $vchr->getDocumentHash();
  14704.                             }
  14705.                             if ($vchr->getDocumentType() == 6) {
  14706.                                 $prRef "Cash Received on " $vchr->getDocumentHash();
  14707.                             }
  14708.                             $nsf_cn[] = $prRef;
  14709.                             $nsf_vn[] = $vchr->getDocumentHash();
  14710.                         }
  14711.                     }
  14712.                 }
  14713.                 $data['nsf_cn'] = $nsf_cn;
  14714.                 $data['nsf_vn'] = $nsf_vn;
  14715.                 foreach ($post_data->keys() as $req_key) {
  14716.                     if (!in_array($req_key$exception_key_list)) {
  14717.                         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'])) {
  14718.                             $data[$req_key] = json_decode($post_data->get($req_key), true);
  14719.                         } else
  14720.                             $data[$req_key] = $post_data->get($req_key);
  14721.                     }
  14722.                 }
  14723.                 $new->setBrsDate($brsDate);
  14724.                 $new->setDocumentHash($dochash);
  14725.                 $new->setTypeHash($typeHash);
  14726.                 $new->setPrefixHash($prefixHash);
  14727.                 $new->setNumberHash($numberHash);
  14728.                 $new->setAssocHash($assocHash);
  14729.                 $new->setAccountsHeadId($request->request->get('bank_head'));
  14730.                 $new->setCompanyId($companyId);
  14731.                 $new->setData(json_encode($data));
  14732.                 $new->setStatus(GeneralConstant::ACTIVE);
  14733.                 //                if($auto_created==1)
  14734.                 //                    $new->setApproved(GeneralConstant::APPROVED);
  14735.                 //                else
  14736.                 $new->setApproved(GeneralConstant::APPROVAL_STATUS_PENDING);
  14737.                 $new->setAutoCreated(0);
  14738.                 $new->setEditFlag(0);
  14739.                 $new->setDeleteFlag(0);
  14740.                 $new->setLockFlag(0);
  14741.                 $new->setDisabledFlag(0);
  14742.                 if (!$brs) {
  14743.                     $new->setCreatedLoginId($LoginId);
  14744.                 } else
  14745.                     $new->setEditedLoginId($LoginId);
  14746.                 $em->persist($new);
  14747.                 $em->flush();
  14748.                 $docId $new->getBrsId();
  14749.                 //now add Approval info
  14750.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  14751.                 $approveRole $request->request->get('approvalRole');  //created
  14752.                 System::setApprovalInfo(
  14753.                     $this->getDoctrine()->getManager(),
  14754.                     [],
  14755.                     array_flip(GeneralConstant::$Entity_list)['Brs'],
  14756.                     $docId,
  14757.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  14758.                 );
  14759.                 System::createEditSignatureHash(
  14760.                     $this->getDoctrine()->getManager(),
  14761.                     array_flip(GeneralConstant::$Entity_list)['Brs'],
  14762.                     $docId,
  14763.                     $loginId,
  14764.                     $approveRole,
  14765.                     $request->request->get('approvalHash')
  14766.                 );
  14767.                 $this->addFlash(
  14768.                     'success',
  14769.                     'Bank Reconciliation Created'
  14770.                 );
  14771.                 $url $this->generateUrl(
  14772.                     'view_brs'
  14773.                 );
  14774.                 System::AddNewNotification(
  14775.                     $this->container->getParameter('notification_enabled'),
  14776.                     $this->container->getParameter('notification_server'),
  14777.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  14778.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  14779.                     "Bank Reconciliation : " $dochash " Has Been Created And is Under Processing",
  14780.                     'pos',
  14781.                     System::getPositionIdsByDepartment($emGeneralConstant::SALES_DEPARTMENT),
  14782.                     'success',
  14783.                     $url "/" $docId,
  14784.                     "BRS"
  14785.                 );
  14786.                 return $this->redirect($url "/" $docId);
  14787.             }
  14788.         }
  14789.         $check_query $this->getDoctrine()
  14790.             ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  14791.             ->findBy(
  14792.                 array(
  14793.                     'assigned' => 1,
  14794.                     'status' => 3//pending
  14795.                     'active' => 1,
  14796.                     'destroyed' => [0null],
  14797.                     'securityCheck' => [0null],
  14798.                 ),
  14799.                 array(
  14800.                     'checkNumber' => 'ASC'
  14801.                 )
  14802.             );
  14803.         $check_data = [];
  14804.         $voucher_list Accounts::VoucherList($em);
  14805.         foreach ($check_query as $check_here) {
  14806.             $new_check_data = array(
  14807.                 'checkId' => $check_here->getCheckId(),
  14808.                 'checkNumber' => $check_here->getCheckNumber(),
  14809.                 'voucherId' => $check_here->getVoucherId(),
  14810.                 'voucherNumber' => isset($voucher_list[$check_here->getVoucherId()]) ? $voucher_list[$check_here->getVoucherId()]['doc_hash'] : '',
  14811.                 'checkDate' => $check_here->getCheckDate() ? $check_here->getCheckDate()->format('Y-m-d') : '',
  14812.                 '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') : ''),
  14813.                 //                'reconDate'=>$recondatestr,
  14814.             );
  14815.             $check_data[$check_here->getCheckId()] = $new_check_data;
  14816.         }
  14817.         return $this->render(
  14818.             '@Accounts/pages/input_forms/bank_recon.html.twig',
  14819.             array(
  14820.                 'page_title' => 'Bank ',
  14821.                 'check_list' => $check_data,
  14822.                 'bank_head_list' => $bank_head_list,
  14823.                 'bank_id_list' => $bank_id_list,
  14824.             )
  14825.         );
  14826.     }
  14827.     public function CheckRecon(Request $request)
  14828.     {
  14829.         $em $this->getDoctrine()->getManager();
  14830.         if ($request->isMethod('POST')) {
  14831.             $check_ids $request->request->get('check_id');
  14832.             $recon_dates $request->request->get('recon_date');
  14833.             if (!empty($check_ids)) {
  14834.                 foreach ($check_ids as $key => $c) {
  14835.                     $check $this->getDoctrine()
  14836.                         ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  14837.                         ->findOneBy(
  14838.                             array(
  14839.                                 'CheckId' => $c
  14840.                             )
  14841.                         );
  14842.                     if ($check) {
  14843.                         $check->setStatus(1); //transaction confirmed
  14844.                         $check->setReconDate(new \DateTime($recon_dates[$key]));
  14845.                         $em->flush();
  14846.                         Accounts::ActionAfterNonProvisionalVoucher($em$check->getVoucherId());
  14847.                     }
  14848.                 }
  14849.             }
  14850.         }
  14851.         $check_query $this->getDoctrine()
  14852.             ->getRepository('ApplicationBundle\\Entity\\AccCheck')
  14853.             ->findBy(
  14854.                 array(
  14855.                     'assigned' => 1,
  14856.                     'status' => 3//pending
  14857.                     'active' => 1
  14858.                 ),
  14859.                 array(
  14860.                     'checkNumber' => 'ASC'
  14861.                 )
  14862.             );
  14863.         $check_data = [];
  14864.         $voucher_list Accounts::VoucherList($em);
  14865.         foreach ($check_query as $check_here) {
  14866.             // A pending check whose voucher is not in VoucherList (voucherId 0, or a voucher since
  14867.             // deleted) used to fatal here with "Undefined offset: 0" — $voucher_list[...] was null
  14868.             // and ['doc_hash'] / ['date']->format() blew up, 500ing the whole reconciliation page.
  14869.             // Keep the check visible in the worklist (hiding it would hide recon work) but render
  14870.             // the missing voucher fields blank instead.
  14871.             $voucher = isset($voucher_list[$check_here->getVoucherId()]) ? $voucher_list[$check_here->getVoucherId()] : null;
  14872.             $checkDate $check_here->getCheckDate();
  14873.             $new_check_data = array(
  14874.                 'checkId' => $check_here->getCheckId(),
  14875.                 'checkNumber' => $check_here->getCheckNumber(),
  14876.                 'voucherId' => $check_here->getVoucherId(),
  14877.                 'voucherNumber' => $voucher $voucher['doc_hash'] : '',
  14878.                 'checkDate' => $checkDate $checkDate->format('Y-m-d') : '',
  14879.                 'transactionDate' => ($voucher && !empty($voucher['date'])) ? $voucher['date']->format('Y-m-d') : '',
  14880.                 //                'reconDate'=>$recondatestr,
  14881.             );
  14882.             $check_data[$check_here->getCheckId()] = $new_check_data;
  14883.         }
  14884.         return $this->render(
  14885.             '@Accounts/pages/input_forms/check_recon.html.twig',
  14886.             array(
  14887.                 'page_title' => 'Bank Reconciliation',
  14888.                 'check_list' => $check_data
  14889.             )
  14890.         );
  14891.     }
  14892.     public function ExcelTest(Request $request)
  14893.     {
  14894.         // ask the service for a Excel5
  14895.         $phpExcelObject $this->get('phpexcel')->createPHPExcelObject();
  14896.         $phpExcelObject->getProperties()->setCreator("liuggio")
  14897.             ->setLastModifiedBy("Giulio De Donato")
  14898.             ->setTitle("Office 2005 XLSX Test Document")
  14899.             ->setSubject("Office 2005 XLSX Test Document")
  14900.             ->setDescription("Test document for Office 2005 XLSX, generated using PHP classes.")
  14901.             ->setKeywords("office 2005 openxml php")
  14902.             ->setCategory("Test result file");
  14903.         $phpExcelObject->setActiveSheetIndex(0)
  14904.             ->setCellValue('A1''Hello')
  14905.             ->setCellValue('B2''world!');
  14906.         $phpExcelObject->getActiveSheet()->setTitle('Simple');
  14907.         // Set active sheet index to the first sheet, so Excel opens this as the first sheet
  14908.         $phpExcelObject->setActiveSheetIndex(0);
  14909.         // create the writer
  14910.         $writer $this->get('phpexcel')->createWriter($phpExcelObject'Excel5');
  14911.         // create the response
  14912.         $response $this->get('phpexcel')->createStreamedResponse($writer);
  14913.         // adding headers
  14914.         $dispositionHeader $response->headers->makeDisposition(
  14915.             ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  14916.             'stream-file.xls'
  14917.         );
  14918.         $response->headers->set('Content-Type''text/vnd.ms-excel; charset=utf-8');
  14919.         $response->headers->set('Pragma''public');
  14920.         $response->headers->set('Cache-Control''maxage=1');
  14921.         $response->headers->set('Content-Disposition'$dispositionHeader);
  14922.         return $response;
  14923.     }
  14924.     public function ImageUpload(Request $request)
  14925.     {
  14926.         $post_data $request->request;
  14927.         $file $post_data->get('file');
  14928.         $fileName "";
  14929.         if ($file) {
  14930.             if ($post_data->has('isBase64')) {
  14931.                 $data base64_decode(preg_replace('#^data:image/\w+;base64,#i'''$file));
  14932.                 $fileName md5(uniqid()) . '.png';
  14933.                 $path $fileName;
  14934.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ExpenseInvoice/';
  14935.                 if (!file_exists($upl_dir)) {
  14936.                     mkdir($upl_dir0777true);
  14937.                 }
  14938.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ExpenseInvoice/' $path;
  14939.                 file_put_contents($upl_dir$data);
  14940.             } else {
  14941.                 $fileName md5(uniqid()) . '.' $file->guessExtension();
  14942.                 $path $fileName;
  14943.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ExpenseInvoice/';
  14944.                 if (!file_exists($upl_dir)) {
  14945.                     mkdir($upl_dir0777true);
  14946.                 }
  14947.                 $file $file->move($upl_dir$path);
  14948.             }
  14949.         }
  14950.         return new JsonResponse(array('file_name' => $fileName));
  14951.     }
  14952.     public function ExportPagePdf(Request $request)
  14953.     {
  14954.         //        $l= $this->get('knp_snappy.pdf')->generateFromHtml($html
  14955.         //            ,
  14956.         //            $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/myfile.pdf'
  14957.         //        );
  14958.         //        $chk=$this->get('knp_snappy.pdf');
  14959.         if ($request->getMethod() == 'POST') {
  14960.             $data $request->request->has('exportable_data') ? $request->request->get('exportable_data') : '';
  14961.             $doc_title $request->request->has('doc_title') ? $request->request->get('doc_title') : 'Exported_data';
  14962.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($data, array(
  14963.                 //                'orientation' => 'landscape',
  14964.                 //                'enable-javascript' => true,
  14965.                 //                'javascript-delay' => 1000,
  14966.                 'no-stop-slow-scripts' => true,
  14967.                 'no-background' => false,
  14968.                 'lowquality' => false,
  14969.                 'encoding' => 'utf-8',
  14970.                 //            'images' => true,
  14971.                 //            'cookie' => array(),
  14972.                 'dpi' => 300,
  14973.                 'image-dpi' => 300,
  14974.                 //                'enable-external-links' => true,
  14975.                 //                'enable-internal-links' => true
  14976.             ));
  14977.             return new Response(
  14978.                 $pdf_response,
  14979.                 200,
  14980.                 array(
  14981.                     'Content-Type' => 'application/pdf',
  14982.                     'Content-Disposition' => 'attachment; filename="' $doc_title '.pdf"'
  14983.                 )
  14984.             );
  14985.         }
  14986.     }
  14987.     public function ExportTableDataExcel(Request $request)
  14988.     {
  14989.         // ask the service for a Excel5
  14990.         $em $this->getDoctrine()->getManager();
  14991.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  14992.         $company_name $company_data->getName();
  14993.         $company_address $company_data->getAddress();
  14994.         $company_invoice_footer $company_data->getInvoiceFooter();
  14995.         $replace_list = array(
  14996.             '%companyName%' => $company_name,
  14997.             '%companyAddress%' => $company_address,
  14998.         );
  14999.         if ($request->isMethod('POST')) {
  15000.             //            $phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
  15001.             //            $spreadsheet = new Spreadsheet();
  15002.             //
  15003.             //            $sheet = $spreadsheet->getActiveSheet();
  15004.             //            $sheet->setCellValue('A1', 'Hello World !');
  15005.             //
  15006.             //            $writer = new Xlsx($spreadsheet);
  15007.             //            $writer->save('hello world.xlsx');
  15008.             if (version_compare(PHP_VERSION'7.3.0''>=')) {
  15009.                 $phpExcelObject = new Spreadsheet();
  15010.             } else {
  15011.                 $phpExcelObject $this->get('phpexcel')->createPHPExcelObject();
  15012.             }
  15013.             $phpExcelObject->getProperties()->setCreator("HoneyBee IoT Ltd.")
  15014.                 ->setLastModifiedBy("Honeybee Ecosystem")
  15015.                 ->setTitle("Office 2005 XLSX Test Document")
  15016.                 ->setSubject("Office 2005 XLSX Test Document")
  15017.                 ->setDescription("Test document for Office 2005 XLSX, generated using PHP classes.")
  15018.                 ->setKeywords("office 2005 openxml php")
  15019.                 ->setCategory("Test result file");
  15020.             $data $request->request->has('exportable_data') ? json_decode($request->request->get('exportable_data'), true) : [];
  15021.             $sheet_title_data $request->request->has('sheet_title') ? json_decode($request->request->get('sheet_title'), true) : [];
  15022.             $doc_title $request->request->has('doc_title') ? $request->request->get('doc_title') : 'Exported_data';
  15023.             $sheet_id 0;
  15024.             foreach ($data as $list_index => $sheet) {
  15025.                 $phpExcelObject->createSheet($sheet_id);
  15026.                 $celldata = isset($sheet['data']) ? ($sheet['data']) : [];
  15027.                 $mergedata = isset($sheet['merge_data']) ? ($sheet['merge_data']) : [];
  15028.                 $styleArray = array(
  15029.                     'font' => array(
  15030.                         'bold' => false,
  15031.                         'color' => array('rgb' => '000000'),
  15032.                         'size' => 12,
  15033.                         'name' => 'Verdana',
  15034.                     ),
  15035.                     'alignment' => array(
  15036.                         'horizontal' => 'left',
  15037.                         'vertical' => 'middle',
  15038.                     )
  15039.                 );
  15040.                 $phpExcelObject->getDefaultStyle()
  15041.                     ->applyFromArray(
  15042.                         $styleArray
  15043.                     );
  15044.                 //
  15045.                 //                $phpExcelObject->getDefaultStyle()
  15046.                 //                    ->getAlignment()
  15047.                 //                    ->applyFromArray(
  15048.                 //                        array('horizontal' => 'left',));
  15049.                 foreach ($celldata as $cell_info) {
  15050.                     $cell_text = isset($replace_list[$cell_info['cell_data']]) ? $replace_list[$cell_info['cell_data']] : $cell_info['cell_data'];
  15051.                     $phpExcelObject->setActiveSheetIndex($sheet_id)->setCellValue($cell_info['cell_no'], $cell_text);
  15052.                     //                    $phpExcelObject->setActiveSheetIndex($sheet_id)->setCellValue($cell_info['cell_no'], json_encode($cell_info));
  15053.                     //                    $phpExcelObject->getActiveSheet()->getStyle($cell_info['cell_no'])->applyFromArray(array(           'alignment'=>['horizontal='=>$cell_info['align'] ]));
  15054.                     if (isset($cell_info['align']))
  15055.                         $phpExcelObject->getActiveSheet()->getStyle($cell_info['cell_no'])->getAlignment()->applyFromArray(
  15056.                             array('horizontal' => $cell_info['align'], 'vertical' => 'middle',)
  15057.                         );
  15058.                 }
  15059.                 foreach ($mergedata as $merge_info) {
  15060.                     if ($merge_info['enabled'] == 1)
  15061.                         $phpExcelObject->setActiveSheetIndex($sheet_id)->mergeCells($merge_info['merge_str']);
  15062.                 }
  15063.                 //now the sheet title
  15064.                 $sheet_name $sheet_title_data[$list_index];
  15065.                 $sheet_name str_ireplace('/'''$sheet_name);
  15066.                 $sheet_name str_ireplace(':'' '$sheet_name);
  15067.                 //                $sheet_name=str_ireplace('\n','',$sheet_name);
  15068.                 $sheet_name trim(preg_replace('/\s\s+/'' '$sheet_name));;
  15069.                 //                            System::log_it($this->container->getParameter('kernel.root_dir'),$sheet_name,'sheet_test');
  15070.                 if (strlen($sheet_name) > 31) {
  15071.                     //have to truncate
  15072.                     //first find if it has 'of and only take later part'
  15073.                     while (count(explode("of"$sheet_name)) > && strlen($sheet_name) > 31) {
  15074.                         $pieces explode("of"$sheet_name);
  15075.                         $sheet_name str_replace($pieces[0], ""$sheet_name);
  15076.                         $sheet_name str_replace($pieces[0], ""$sheet_name);
  15077.                     }
  15078.                     //now remove 1 word form start until length matches
  15079.                     //                    while(count(explode(" ", $sheet_name))>1&&strlen($sheet_name)>31) {
  15080.                     //                        $pieces = explode(" ", $sheet_name);
  15081.                     //                        if(count($pieces)<=1)
  15082.                     //                            break;
  15083.                     //                        $sheet_name=str_replace($pieces[0], "", $sheet_name);
  15084.                     ////                        str_replace()
  15085.                     ////                        $sheet_name = str_replace($pieces[0], "", $sheet_name);
  15086.                     //                    }
  15087.                     if (strlen($sheet_name) > 31//now just chop
  15088.                     {
  15089.                         $sheet_name substr($sheet_name030);
  15090.                     }
  15091.                 }
  15092.                 $phpExcelObject->getActiveSheet()->setTitle($sheet_name);
  15093.                 $sheet $phpExcelObject->getActiveSheet();
  15094.                 $cellIterator $sheet->getRowIterator()->current()->getCellIterator();
  15095.                 $cellIterator->setIterateOnlyExistingCells(true);
  15096.                 /** @var PHPExcel_Cell $cell */
  15097.                 foreach ($cellIterator as $cell) {
  15098.                     $sheet->getColumnDimension($cell->getColumn())->setAutoSize(true);
  15099.                 }
  15100.                 $sheet_id++;
  15101.             }
  15102.             // Auto size columns for each worksheet
  15103.             //            foreach ($phpExcelObject->getWorksheetIterator() as $worksheet) {
  15104.             //
  15105.             //                $phpExcelObject->setActiveSheetIndex($phpExcelObject->getIndex($worksheet));
  15106.             //
  15107.             //                $sheet = $phpExcelObject->getActiveSheet();
  15108.             //                $cellIterator = $sheet->getRowIterator()->current()->getCellIterator();
  15109.             //                $cellIterator->setIterateOnlyExistingCells(true);
  15110.             //                /** @var PHPExcel_Cell $cell */
  15111.             //                foreach ($cellIterator as $cell) {
  15112.             //                    $sheet->getColumnDimension($cell->getColumn())->setAutoSize(true);
  15113.             //                }
  15114.             //            }
  15115.             //
  15116.             // Set active sheet index to the first sheet, so Excel opens this as the first sheet
  15117.             if (version_compare(PHP_VERSION'7.3.0''>=')) {
  15118.                 $writer = new Xlsx($phpExcelObject);
  15119.                 $response = new StreamedResponse(
  15120.                     function () use ($writer) {
  15121.                         $writer->save('php://output');
  15122.                     }
  15123.                 );
  15124.             } else {
  15125.                 $writer $this->get('phpexcel')->createWriter($phpExcelObject'Excel5');
  15126.                 // create the response
  15127.                 $response $this->get('phpexcel')->createStreamedResponse($writer);
  15128.             }
  15129.             $phpExcelObject->setActiveSheetIndex(0);
  15130.             // adding headers
  15131.             //            $writer->save('hello world.xlsx');
  15132.             // create the writer
  15133.             //            $writer = $this->get('phpexcel')->createWriter($phpExcelObject, 'Excel5');
  15134.             // create the response
  15135.             //            $response = $this->get('phpexcel')->createStreamedResponse($writer);
  15136.             // adding headers
  15137.             $dispositionHeader $response->headers->makeDisposition(
  15138.                 ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  15139.                 $doc_title '.xls'
  15140.             );
  15141.             $response->headers->set('Content-Type''text/vnd.ms-excel; charset=utf-8');
  15142.             $response->headers->set('Pragma''public');
  15143.             $response->headers->set('Cache-Control''maxage=1');
  15144.             $response->headers->set('Content-Disposition'$dispositionHeader);
  15145.             return $response;
  15146.         } else {
  15147.             $phpExcelObject $this->get('phpexcel')->createPHPExcelObject();
  15148.             $phpExcelObject->getProperties()->setCreator("liuggio")
  15149.                 ->setLastModifiedBy("Giulio De Donato")
  15150.                 ->setTitle("Office 2005 XLSX Test Document")
  15151.                 ->setSubject("Office 2005 XLSX Test Document")
  15152.                 ->setDescription("Test document for Office 2005 XLSX, generated using PHP classes.")
  15153.                 ->setKeywords("office 2005 openxml php")
  15154.                 ->setCategory("Test result file");
  15155.             $phpExcelObject->createSheet(0);
  15156.             $phpExcelObject->setActiveSheetIndex(0);
  15157.             $phpExcelObject->setActiveSheetIndex(0)->setCellValue('A1''Hello');
  15158.             $phpExcelObject->setActiveSheetIndex(0)->setCellValue('B2''world!');
  15159.             $phpExcelObject->getActiveSheet()->setTitle('Simple');
  15160.             $phpExcelObject->createSheet(1);
  15161.             $phpExcelObject->setActiveSheetIndex(1)
  15162.                 ->setCellValue('A1''Hello')
  15163.                 ->setCellValue('B2''world!');
  15164.             $phpExcelObject->getActiveSheet()->setTitle('complex');
  15165.             // Set active sheet index to the first sheet, so Excel opens this as the first sheet
  15166.             $phpExcelObject->setActiveSheetIndex(0);
  15167.             // create the writer
  15168.             $writer $this->get('phpexcel')->createWriter($phpExcelObject'Excel5');
  15169.             // create the response
  15170.             $response $this->get('phpexcel')->createStreamedResponse($writer);
  15171.             // adding headers
  15172.             $dispositionHeader $response->headers->makeDisposition(
  15173.                 ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  15174.                 'stream-file.xls'
  15175.             );
  15176.             $response->headers->set('Content-Type''text/vnd.ms-excel; charset=utf-8');
  15177.             $response->headers->set('Pragma''public');
  15178.             $response->headers->set('Cache-Control''maxage=1');
  15179.             $response->headers->set('Content-Disposition'$dispositionHeader);
  15180.             return $response;
  15181.         }
  15182.     }
  15183.     public function AnalyzeTableDataExcel(Request $request)
  15184.     {
  15185.         // ask the service for a Excel5
  15186.         $em $this->getDoctrine()->getManager();
  15187.         $extractedData = array();
  15188.         if ($request->isMethod('POST')) {
  15189.             foreach ($request->files as $uploadedFileGG) {
  15190.                 //            if($uploadedFile->getImage())
  15191.                 //                var_dump($uploadedFile->getFile());
  15192.                 //                var_dump($uploadedFile);
  15193.                 $tempD $uploadedFileGG;
  15194.                 if (!is_array($uploadedFileGG)) {
  15195.                     $uploadedFileGG = array();
  15196.                     $uploadedFileGG[] = $tempD;
  15197.                 }
  15198.                 foreach ($uploadedFileGG as $uploadedFile) {
  15199.                     if ($uploadedFile != null) {
  15200.                         $extension $uploadedFile->guessExtension();
  15201.                         $size $uploadedFile->getSize();
  15202.                         $fileName 'TEMP_FILE_' . (md5(uniqid())) . '.' $uploadedFile->guessExtension();
  15203.                         $path $fileName;
  15204.                         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/temp';
  15205.                         if (!file_exists($upl_dir)) {
  15206.                             mkdir($upl_dir0777true);
  15207.                         }
  15208.                         if (file_exists($upl_dir '' $path)) {
  15209.                             chmod($upl_dir '' $path0755);
  15210.                             unlink($upl_dir '' $path);
  15211.                         }
  15212.                         $file $uploadedFile->move($upl_dir$path);
  15213.                         if (version_compare(PHP_VERSION'7.3.0''>=')) {
  15214.                             $phpExcelObject = new Spreadsheet($upl_dir '' $path);
  15215.                         } else {
  15216.                             $phpExcelObject $this->get('phpexcel')->createPHPExcelObject($upl_dir '' $path);
  15217.                         }
  15218.                         $extractedData $phpExcelObject;
  15219.                         if (file_exists($upl_dir '' $path)) {
  15220.                             chmod($upl_dir '' $path0755);
  15221.                             unlink($upl_dir '' $path);
  15222.                         }
  15223.                     }
  15224.                 }
  15225.             }
  15226.             //            $phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
  15227.             //            $spreadsheet = new Spreadsheet();
  15228.             //
  15229.             //            $sheet = $spreadsheet->getActiveSheet();
  15230.             //            $sheet->setCellValue('A1', 'Hello World !');
  15231.             //
  15232.             //            $writer = new Xlsx($spreadsheet);
  15233.             //            $writer->save('hello world.xlsx');
  15234.             if (version_compare(PHP_VERSION'7.3.0''>=')) {
  15235.                 $phpExcelObject = new Spreadsheet();
  15236.             } else {
  15237.                 $phpExcelObject $this->get('phpexcel')->createPHPExcelObject();
  15238.             }
  15239.         }
  15240.         return new JsonResponse($extractedData);
  15241.     }
  15242.     public function ViewVoucher(Request $request$id)
  15243.     {
  15244.         $voucher_id $id;
  15245.         $em $this->getDoctrine()->getManager();
  15246.         $dt Accounts::GetVoucherDetails($em$voucher_id);
  15247.         if ($request->get('returnJson')==1) {
  15248.             return new \Symfony\Component\HttpFoundation\JsonResponse([
  15249.                 'success' => true,
  15250.                 'data' => $dt
  15251.             ]);
  15252.         }
  15253.         return $this->render(
  15254. //            '@Accounts/pages/views/view_journal_voucher.html.twig',
  15255.             '@Accounts/pages/views/view_journal_voucher_demo.html.twig',
  15256.             array(
  15257.                 'page_title' => 'View',
  15258.                 'data' => $dt,
  15259.                 'auto_created' => $dt['auto_created'],
  15260.                 'approval_data' => System::checkIfApprovalExists(
  15261.                     $em,
  15262.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  15263.                     $voucher_id,
  15264.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  15265.                 ),
  15266.                 'document_log' => $dt['auto_created'] == System::getDocumentLog(
  15267.                     $this->getDoctrine()->getManager(),
  15268.                     array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
  15269.                     $voucher_id,
  15270.                     $dt['created_by'],
  15271.                     $dt['edited_by']
  15272.                 ) : []
  15273.             )
  15274.         );
  15275.     }
  15276.     public function ViewPurchaseInvoice(Request $request$id)
  15277.     {
  15278.         $em $this->getDoctrine()->getManager();
  15279.         $dt Accounts::GetInvoiceDetails($em$id);
  15280.         return $this->render(
  15281. //            '@Accounts/pages/views/view_purchase_invoice.html.twig',
  15282.             '@Accounts/pages/views/view_purchase_invoice_demo.html.twig',
  15283.             array(
  15284.                 'page_title' => 'View Purchase Invoice',
  15285.                 'data' => $dt,
  15286.                 'approval_data' => System::checkIfApprovalExists(
  15287.                     $em,
  15288.                     array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice'],
  15289.                     $id,
  15290.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  15291.                 ),
  15292.                 'document_log' => System::getDocumentLog(
  15293.                     $this->getDoctrine()->getManager(),
  15294.                     array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice'],
  15295.                     $id,
  15296.                     $dt['created_by'],
  15297.                     $dt['edited_by']
  15298.                 )
  15299.             )
  15300.         );
  15301.     }
  15302.     public function PrintPurchaseInvoice(Request $request$id)
  15303.     {
  15304.         $em $this->getDoctrine()->getManager();
  15305.         $invoice_id $id;
  15306.         $data Accounts::GetInvoiceDetails($em$invoice_id);
  15307.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  15308.         $document_mark = array(
  15309.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  15310.             'pending' => '/images/pending.jpg',
  15311.             'copy' => ''
  15312.         );
  15313.         $printTemplate CountryTemplateResolver::resolve(
  15314.             $this->get('twig'),
  15315.             $em,
  15316.             $this->getLoggedUserCompanyId($request),
  15317.             '@Accounts/pages/print/pi_print.html.twig'
  15318.         );
  15319.         $taxMarkers TaxMarkerLookup::forCompany($em$this->getLoggedUserCompanyId($request));
  15320.          if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  15321.             $html $this->renderView(
  15322.                  $printTemplate,
  15323.                 array(
  15324.                     //full array here
  15325.                 'pdf' => true,
  15326.                 'page_title' => 'Purchase Invoice',
  15327.                 'data' => $data,
  15328.                 'document_mark_image' => $document_mark['original'],
  15329.                 'company_name' => $company_data->getName(),
  15330.                 'company_data' => $company_data,
  15331.                 'company_address' => $company_data->getAddress(),
  15332.                 'company_image' => $company_data->getImage(),
  15333.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  15334.         
  15335.                 'export' => 'pdf,print',
  15336.                 'document_mark_image' => $document_mark['original'],
  15337.                 'company_name' => $company_data->getName(),
  15338.                 'company_data' => $company_data,
  15339.                 'company_address' => $company_data->getAddress(),
  15340.                 'company_image' => $company_data->getImage(),
  15341.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  15342.                 'page_header' => 'New Product',
  15343.                     'document_type' => 'Purchase Invoice',
  15344.                     'page_header_sub' => 'Add',
  15345.                     //                'type_list'=>$type_list,
  15346.                     //                'mis_data'=>$mis_data,
  15347.                     //                'mis_print'=>$mis_print,
  15348.                     'item_data' => [],
  15349.                     'received' => 2,
  15350.                     'return' => 1,
  15351.                     'total_w_vat' => 1,
  15352.                     'total_vat' => 1,
  15353.                     'total_wo_vat' => 1,
  15354.                     'invoice_id' => 'abcd1234',
  15355.                     'created_by' => 'created by',
  15356.                     'created_at' => '',
  15357.                     'red' => 0,
  15358.                     'taxMarkers' => $taxMarkers,
  15359.                 )
  15360.             );
  15361.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  15362.                 //                'orientation' => 'landscape',
  15363.                 //                'enable-javascript' => true,
  15364.                 //                'javascript-delay' => 1000,
  15365.                 'no-stop-slow-scripts' => false,
  15366.                 'no-background' => false,
  15367.                 'lowquality' => false,
  15368.                 'encoding' => 'utf-8',
  15369.                 //            'images' => true,
  15370.                 //            'cookie' => array(),
  15371.                 'dpi' => 300,
  15372.                 'image-dpi' => 300,
  15373.                 //                'enable-external-links' => true,
  15374.                 //                'enable-internal-links' => true
  15375.             ));
  15376.             return new Response(
  15377.                 $pdf_response,
  15378.                 200,
  15379.                 array(
  15380.                     'Content-Type' => 'application/pdf',
  15381.                     'Content-Disposition' => 'attachment; filename="sales_invoice_' $id '.pdf"'
  15382.                 )
  15383.             );
  15384.         }
  15385.         return $this->render(
  15386.             $printTemplate,
  15387.             array(
  15388.                 // 'page_title' => 'Purchase Invoice',
  15389.                 // 'data' => $data,
  15390.                 // 'document_mark_image' => $document_mark['original'],
  15391.                 // 'company_name' => $company_data->getName(),
  15392.                 // 'company_data' => $company_data,
  15393.                 // 'company_address' => $company_data->getAddress(),
  15394.                 // 'company_image' => $company_data->getImage(),
  15395.                 // 'invoice_footer' => $company_data->getInvoiceFooter(),
  15396.                 // 'red' => 0
  15397.                 'page_title' => 'Purchase Invoice',
  15398.                 'data' => $data,
  15399.                 'document_mark_image' => $document_mark['original'],
  15400.                 'company_name' => $company_data->getName(),
  15401.                 'company_data' => $company_data,
  15402.                 'company_address' => $company_data->getAddress(),
  15403.                 'company_image' => $company_data->getImage(),
  15404.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  15405.         
  15406.                 'export' => 'pdf,print',
  15407.                 'document_mark_image' => $document_mark['original'],
  15408.                 'company_name' => $company_data->getName(),
  15409.                 'company_data' => $company_data,
  15410.                 'company_address' => $company_data->getAddress(),
  15411.                 'company_image' => $company_data->getImage(),
  15412.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  15413.                 'page_header' => 'New Product',
  15414.                     'document_type' => 'Purchase Invoice',
  15415.                     'page_header_sub' => 'Add',
  15416.                     //                'type_list'=>$type_list,
  15417.                     //                'mis_data'=>$mis_data,
  15418.                     //                'mis_print'=>$mis_print,
  15419.                     'item_data' => [],
  15420.                     'received' => 2,
  15421.                     'return' => 1,
  15422.                     'total_w_vat' => 1,
  15423.                     'total_vat' => 1,
  15424.                     'total_wo_vat' => 1,
  15425.                     'invoice_id' => 'abcd1234',
  15426.                     'created_by' => 'created by',
  15427.                     'created_at' => '',
  15428.                     'red' => 0,
  15429.                     'taxMarkers' => $taxMarkers,
  15430.             )
  15431.         );
  15432.     }
  15433.     public function ExpenseInvoiceList(Request $request)
  15434.     {
  15435.         $q $this->getDoctrine()
  15436.             ->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')
  15437.             ->findBy(
  15438.                 array(
  15439.                     'status' => GeneralConstant::ACTIVE,
  15440.                 ),
  15441.                 array(
  15442.                     'expenseInvoiceDate' => 'DESC'
  15443.                 )
  15444.             );
  15445.         $stage_list = array(
  15446.             => 'Pending',
  15447.             => 'Complete',
  15448.             => 'Pending Payment',
  15449.         );
  15450.         $data = [];
  15451.         foreach ($q as $entry) {
  15452.             $data[] = array(
  15453.                 'doc_date' => $entry->getExpenseInvoiceDate(),
  15454.                 'id' => $entry->getExpenseInvoiceId(),
  15455.                 'doc_hash' => $entry->getDocumentHash(),
  15456.                 'invoice_amount' => $entry->getInvoiceAmount(),
  15457.                 'stage' => GeneralConstant::stageLabel($stage_list$entry->getStage())
  15458.             );
  15459.         }
  15460.         return $this->render(
  15461.             '@Accounts/pages/list/expense_invoices.html.twig',
  15462.             array(
  15463.                 'page_title' => 'Expense Invoices',
  15464.                 'data' => $data
  15465.             )
  15466.         );
  15467.     }
  15468.     public function ExpenseInvoiceApprovalQueue(Request $request)
  15469.     {
  15470.         $em $this->getDoctrine()->getManager();
  15471.         $expenseInvoiceEntityId array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'];
  15472.         if ($request->isMethod('POST')) {
  15473.             $selectedIds $request->request->all('selected_ids');
  15474.             if (!is_array($selectedIds)) {
  15475.                 $selectedIds = [];
  15476.             }
  15477.             $selectedIds array_values(array_filter(array_map('intval'$selectedIds)));
  15478.             $bulkAction $request->request->get('bulk_action''');
  15479.             if (empty($selectedIds)) {
  15480.                 $this->addFlash('error''Please select at least one expense invoice.');
  15481.             } elseif (!in_array($bulkAction, ['approve''decline'], true)) {
  15482.                 $this->addFlash('error''Please choose a valid bulk action.');
  15483.             } else {
  15484.                 $processed 0;
  15485.                 foreach ($selectedIds as $selectedId) {
  15486.                     if ($bulkAction === 'approve') {
  15487.                         System::takeFullApproveActions(
  15488.                             $em,
  15489.                             $expenseInvoiceEntityId,
  15490.                             $selectedId,
  15491.                             $this->get('mail_module')
  15492.                         );
  15493.                     } else {
  15494.                         System::takeFullDeclineActions(
  15495.                             $em,
  15496.                             $expenseInvoiceEntityId,
  15497.                             $selectedId,
  15498.                             $this->get('mail_module')
  15499.                         );
  15500.                     }
  15501.                     $processed++;
  15502.                 }
  15503.                 $this->addFlash(
  15504.                     'success',
  15505.                     sprintf(
  15506.                         '%d expense invoice%s %s successfully.',
  15507.                         $processed,
  15508.                         $processed === '' 's',
  15509.                         $bulkAction === 'approve' 'approved' 'declined'
  15510.                     )
  15511.                 );
  15512.             }
  15513.             $redirectParams array_filter([
  15514.                 'date_from' => $request->request->get('date_from'''),
  15515.                 'date_to' => $request->request->get('date_to'''),
  15516.                 'created_user_id' => $request->request->get('created_user_id'''),
  15517.                 'approved' => $request->request->get('approved'''),
  15518.                 'search' => $request->request->get('search'''),
  15519.             ], static function ($value) {
  15520.                 return $value !== '' && $value !== null;
  15521.             });
  15522.             return $this->redirectToRoute('expense_invoice_approval_queue'$redirectParams);
  15523.         }
  15524.         $dateFrom trim((string)$request->query->get('date_from'''));
  15525.         $dateTo trim((string)$request->query->get('date_to'''));
  15526.         $createdUserId trim((string)$request->query->get('created_user_id'''));
  15527.         $approved trim((string)$request->query->get('approved''3'));
  15528.         $search trim((string)$request->query->get('search'''));
  15529.         $qb $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')->createQueryBuilder('ei');
  15530.         $qb->where('ei.status = :status')
  15531.             ->setParameter('status'GeneralConstant::ACTIVE)
  15532.             ->orderBy('ei.expenseInvoiceDate''DESC')
  15533.             ->addOrderBy('ei.expenseInvoiceId''DESC');
  15534.         if ($dateFrom !== '') {
  15535.             $qb->andWhere('ei.expenseInvoiceDate >= :dateFrom')
  15536.                 ->setParameter('dateFrom', new \DateTime($dateFrom ' 00:00:00'));
  15537.         }
  15538.         if ($dateTo !== '') {
  15539.             $qb->andWhere('ei.expenseInvoiceDate <= :dateTo')
  15540.                 ->setParameter('dateTo', new \DateTime($dateTo ' 23:59:59'));
  15541.         }
  15542.         if ($createdUserId !== '') {
  15543.             $qb->andWhere(
  15544.                 $qb->expr()->orX(
  15545.                     'ei.createdUserId = :createdUserId',
  15546.                     'ei.createdUserId IS NULL AND ei.createdLoginId = :createdUserLoginId'
  15547.                 )
  15548.             )
  15549.                 ->setParameter('createdUserId', (int)$createdUserId)
  15550.                 ->setParameter('createdUserLoginId', (int)$createdUserId);
  15551.         }
  15552.         if ($approved !== '') {
  15553.             $qb->andWhere('ei.approved = :approved')
  15554.                 ->setParameter('approved', (int)$approved);
  15555.         }
  15556.         if ($search !== '') {
  15557.             $qb->andWhere(
  15558.                 $qb->expr()->orX(
  15559.                     $qb->expr()->like('ei.documentHash'':searchTerm'),
  15560.                     $qb->expr()->like('ei.description'':searchTerm')
  15561.                 )
  15562.             )->setParameter('searchTerm''%' $search '%');
  15563.         }
  15564.         $invoices $qb->getQuery()->getResult();
  15565.         $currencyList Inventory::CurrencyList($em);
  15566.         $approvalStatusMap = [
  15567.             => ['label' => 'Declined''class' => 'danger'],
  15568.             => ['label' => 'Approved''class' => 'success'],
  15569.             => ['label' => 'Reverted''class' => 'warning'],
  15570.             => ['label' => 'Pending''class' => 'warning'],
  15571.         ];
  15572.         $expenseInvoiceTypeList = [
  15573.             => 'General Expense',
  15574.             => 'Against Purchase',
  15575.             => 'Against Project/Sales',
  15576.             => 'Against Lead/Tender',
  15577.         ];
  15578.         $groupedInvoices = [];
  15579.         $userOptions = [];
  15580.         $userCache = [];
  15581.         $summary = [
  15582.             'count' => 0,
  15583.             'approved' => 0,
  15584.             'pending' => 0,
  15585.             'declined' => 0,
  15586.             'reverted' => 0,
  15587.             'amount_by_currency' => [],
  15588.         ];
  15589.         foreach ($invoices as $invoice) {
  15590.             $createdUserIdValue = (int)$invoice->getCreatedUserId();
  15591.             $loginId = (int)$invoice->getCreatedLoginId();
  15592.             $cacheKey $createdUserIdValue $createdUserIdValue $loginId;
  15593.             if (!isset($userCache[$cacheKey])) {
  15594.                 if ($createdUserIdValue 0) {
  15595.                     $userCache[$cacheKey] = Users::getUserInfoByUserId($em$createdUserIdValue);
  15596.                 } else {
  15597.                     $resolvedUser Users::getUserInfoByLoginId($em$loginId);
  15598.                     $userCache[$cacheKey] = $resolvedUser;
  15599.                     if (!empty($resolvedUser['id'])) {
  15600.                         $createdUserIdValue = (int)$resolvedUser['id'];
  15601.                         $cacheKey $createdUserIdValue;
  15602.                         $userCache[$cacheKey] = $resolvedUser;
  15603.                     }
  15604.                 }
  15605.             }
  15606.             $userInfo $userCache[$cacheKey] ?? [];
  15607.             $userId = (int)($userInfo['id'] ?? $createdUserIdValue);
  15608.             $userName $userInfo['name'] ?? ('User #' $userId);
  15609.             $invoiceDate $invoice->getExpenseInvoiceDate();
  15610.             $dateKey $invoiceDate $invoiceDate->format('Y-m-d') : 'unknown';
  15611.             $dateLabel $invoiceDate $invoiceDate->format('M d, Y') : 'Unknown date';
  15612.             $amount = (float)$invoice->getInvoiceAmount();
  15613.             $currencyId $invoice->getCurrency();
  15614.             $currencyName = isset($currencyList[$currencyId]) ? ($currencyList[$currencyId]['nameOnly'] ?? '') : '';
  15615.             $approvalState = (int)$invoice->getApproved();
  15616.             $approvalMeta $approvalStatusMap[$approvalState] ?? ['label' => 'Unknown''class' => 'default'];
  15617.             $summary['count']++;
  15618.             if ($approvalState === 1) {
  15619.                 $summary['approved']++;
  15620.             } elseif ($approvalState === 0) {
  15621.                 $summary['declined']++;
  15622.             } elseif ($approvalState === 2) {
  15623.                 $summary['reverted']++;
  15624.             } else {
  15625.                 $summary['pending']++;
  15626.             }
  15627.             if (!isset($summary['amount_by_currency'][$currencyId])) {
  15628.                 $summary['amount_by_currency'][$currencyId] = [
  15629.                     'currency' => $currencyName,
  15630.                     'amount' => 0,
  15631.                 ];
  15632.             }
  15633.             $summary['amount_by_currency'][$currencyId]['amount'] += $amount;
  15634.             $userOptions[$userId] = $userName;
  15635.             if (!isset($groupedInvoices[$userId])) {
  15636.                 $groupedInvoices[$userId] = [
  15637.                     'userId' => $userId,
  15638.                     'userName' => $userName,
  15639.                     'totalCount' => 0,
  15640.                     'totalAmount' => 0,
  15641.                     'amountByCurrency' => [],
  15642.                     'dates' => [],
  15643.                 ];
  15644.             }
  15645.             if (!isset($groupedInvoices[$userId]['amountByCurrency'][$currencyId])) {
  15646.                 $groupedInvoices[$userId]['amountByCurrency'][$currencyId] = [
  15647.                     'currency' => $currencyName,
  15648.                     'amount' => 0,
  15649.                 ];
  15650.             }
  15651.             $groupedInvoices[$userId]['amountByCurrency'][$currencyId]['amount'] += $amount;
  15652.             $groupedInvoices[$userId]['totalCount']++;
  15653.             $groupedInvoices[$userId]['totalAmount'] += $amount;
  15654.             if (!isset($groupedInvoices[$userId]['dates'][$dateKey])) {
  15655.                 $groupedInvoices[$userId]['dates'][$dateKey] = [
  15656.                     'key' => $dateKey,
  15657.                     'label' => $dateLabel,
  15658.                     'count' => 0,
  15659.                     'amount' => 0,
  15660.                     'rows' => [],
  15661.                 ];
  15662.             }
  15663.             $groupedInvoices[$userId]['dates'][$dateKey]['count']++;
  15664.             $groupedInvoices[$userId]['dates'][$dateKey]['amount'] += $amount;
  15665.             $groupedInvoices[$userId]['dates'][$dateKey]['rows'][] = [
  15666.                 'expenseInvoiceId' => $invoice->getExpenseInvoiceId(),
  15667.                 'documentHash' => $invoice->getDocumentHash(),
  15668.                 'expenseInvoiceDate' => $dateLabel,
  15669.                 'expenseInvoiceTypeId' => $invoice->getExpenseInvoiceTypeId(),
  15670.                 'expenseInvoiceTypeLabel' => $expenseInvoiceTypeList[$invoice->getExpenseInvoiceTypeId()] ?? 'N/A',
  15671.                 'invoiceAmount' => $amount,
  15672.                 'currencyId' => $currencyId,
  15673.                 'currencyName' => $currencyName,
  15674.                 'approved' => $approvalState,
  15675.                 'approvedLabel' => $approvalMeta['label'],
  15676.                 'approvedClass' => $approvalMeta['class'],
  15677.                 'description' => $invoice->getDescription(),
  15678.                 'partyHeadId' => $invoice->getPartyHeadId(),
  15679.                 'expenseTypeId' => $invoice->getExpenseTypeId(),
  15680.                 'createdUserId' => $userId,
  15681.                 'viewUrl' => $this->generateUrl('view_expense_invoice', ['id' => $invoice->getExpenseInvoiceId()]),
  15682.                 'printUrl' => $this->generateUrl('print_expense_invoice', ['id' => $invoice->getExpenseInvoiceId()]),
  15683.             ];
  15684.         }
  15685.         krsort($groupedInvoices);
  15686.         foreach ($groupedInvoices as &$group) {
  15687.             krsort($group['dates']);
  15688.         }
  15689.         unset($group);
  15690.         $amountBreakdown = [];
  15691.         foreach ($summary['amount_by_currency'] as $currencyData) {
  15692.             $amountBreakdown[] = trim(
  15693.                 ($currencyData['currency'] !== '' $currencyData['currency'] . ' ' '') .
  15694.                 number_format((float)$currencyData['amount'], 2'.'',')
  15695.             );
  15696.         }
  15697.         return $this->render(
  15698.             '@Accounts/pages/views/view_expense_invoice_approval_queue.html.twig',
  15699.             [
  15700.                 'page_title' => 'Expense Invoice Approval Queue',
  15701.                 'groupedInvoices' => $groupedInvoices,
  15702.                 'userOptions' => $userOptions,
  15703.                 'summary' => $summary,
  15704.                 'amountBreakdown' => $amountBreakdown,
  15705.                 'filters' => [
  15706.                     'date_from' => $dateFrom,
  15707.                     'date_to' => $dateTo,
  15708.                     'created_user_id' => $createdUserId,
  15709.                     'approved' => $approved,
  15710.                     'search' => $search,
  15711.                 ],
  15712.                 'approvalStatusMap' => $approvalStatusMap,
  15713.                 'expenseInvoiceTypeList' => $expenseInvoiceTypeList,
  15714.                 'currencyList' => $currencyList,
  15715.             ]
  15716.         );
  15717.     }
  15718.     public function BrsList(Request $request)
  15719.     {
  15720.         $q $this->getDoctrine()
  15721.             ->getRepository('ApplicationBundle\\Entity\\Brs')
  15722.             ->findBy(
  15723.                 array(
  15724.                     'status' => GeneralConstant::ACTIVE,
  15725.                 ),
  15726.                 array(
  15727.                     'brsDate' => 'DESC'
  15728.                 )
  15729.             );
  15730.         $stage_list = array(
  15731.             => 'Pending',
  15732.             => 'Complete',
  15733.             => 'Pending Payment',
  15734.         );
  15735.         $data = [];
  15736.         foreach ($q as $entry) {
  15737.             $data[] = array(
  15738.                 'doc_date' => $entry->getBrsDate(),
  15739.                 'id' => $entry->getBrsId(),
  15740.                 'doc_hash' => $entry->getDocumentHash(),
  15741.                 'accountsHeadId' => $entry->getAccountsHeadId(),
  15742.                 //                'stage'=>$stage_list[$entry->getStage()]
  15743.             );
  15744.         }
  15745.         return $this->render(
  15746.             '@Accounts/pages/list/brs_list.html.twig',
  15747.             array(
  15748.                 'page_title' => 'BRS Statements',
  15749.                 'data' => $data,
  15750.                 'head_list' => Accounts::HeadList($this->getDoctrine()->getManager())
  15751.             )
  15752.         );
  15753.     }
  15754.     public function FinancialBudgetList(Request $request)
  15755.     {
  15756.         $q $this->getDoctrine()
  15757.             ->getRepository('ApplicationBundle\\Entity\\FinancialBudget')
  15758.             ->findBy(
  15759.                 array( //                    'status' =>  GeneralConstant::ACTIVE,
  15760.                 ),
  15761.                 array( //                    'brsDate'=>'DESC'
  15762.                 )
  15763.             );
  15764.         $stage_list = array(
  15765.             => 'Pending',
  15766.             => 'Complete',
  15767.             => 'Pending Payment',
  15768.         );
  15769.         $data = [];
  15770.         foreach ($q as $entry) {
  15771.             $data[] = array(
  15772.                 'doc_start_date' => $entry->getBudgetStartDate(),
  15773.                 'doc_end_date' => $entry->getBudgetEndDate(),
  15774.                 'id' => $entry->getBudgetId(),
  15775.                 'doc_hash' => $entry->getBudgetTitle(),
  15776.                 //                'accountsHeadId'=>$entry->getAccountsHeadId(),
  15777.                 //                'stage'=>$stage_list[$entry->getStage()]
  15778.             );
  15779.         }
  15780.         return $this->render(
  15781.             '@Accounts/pages/list/financial_budget_list.html.twig',
  15782.             array(
  15783.                 'page_title' => 'Financial Budgets',
  15784.                 'data' => $data,
  15785.                 'head_list' => Accounts::HeadList($this->getDoctrine()->getManager())
  15786.             )
  15787.         );
  15788.     }
  15789.     public function ViewExpenseInvoice(Request $request$id)
  15790.     {
  15791.         $invoice_id $id;
  15792.         $em $this->getDoctrine()->getManager();
  15793.         $dt Accounts::GetExpenseInvoiceDetails($em$invoice_id);
  15794.         if ($request->get('returnJson')==1) {
  15795.             $ei $dt['ei_data'];
  15796.             return new \Symfony\Component\HttpFoundation\JsonResponse([
  15797.                 'success' => true,
  15798.                 'data' => [
  15799.                     'supplier_data' => $dt['supplier_data'] ? [
  15800.                         'supplierName'    => $dt['supplier_data']->getSupplierName(),
  15801.                         'supplierAddress' => $dt['supplier_data']->getSupplierAddress(),
  15802.                         'contactNumber'   => $dt['supplier_data']->getContactNumber(),
  15803.                     ] : null,
  15804.                     'party_head_data' => isset($dt['party_head_data']) && $dt['party_head_data'] ? [
  15805.                         'name' => $dt['party_head_data']->getName(),
  15806.                     ] : null,
  15807.                     'ei_data' => [
  15808.                         'expenseInvoiceId'      => $ei->getExpenseInvoiceId(),
  15809.                         'documentHash'          => $ei->getDocumentHash(),
  15810.                         'expenseInvoiceDate'    => $ei->getExpenseInvoiceDate()
  15811.                             ? $ei->getExpenseInvoiceDate()->format('Y-m-d') : null,
  15812.                         'invoiceAmount'         => $ei->getInvoiceAmount(),
  15813.                         'advanceAmount'         => $ei->getAdvanceAmount(),
  15814.                         'dueAmount'             => $ei->getDueAmount(),
  15815.                         'currency'              => $ei->getCurrency(),
  15816.                         'currencyMultiplyRate'  => $ei->getCurrencyMultiplyRate(),
  15817.                         'expenseInvoiceTypeId'  => $ei->getExpenseInvoiceTypeId(),
  15818.                         'expenseTypeId'         => $ei->getExpenseTypeId(),
  15819.                         'expenseFromNote'       => $ei->getExpenseFromNote(),
  15820.                         'expenseToNote'         => $ei->getExpenseToNote(),
  15821.                         'description'           => $ei->getDescription(),
  15822.                         'approved'              => $ei->getApproved(),
  15823.                         'editFlag'              => $ei->getEditFlag(),
  15824.                     ],
  15825.                     'supplier_data'             => $dt['supplier_data'] ? [
  15826.                         'supplierName'          => $dt['supplier_data']->getSupplierName(),
  15827.                         'supplierAddress'       => $dt['supplier_data']->getSupplierAddress(),
  15828.                         'contactNumber'         => $dt['supplier_data']->getContactNumber(),
  15829.                     ] : null,
  15830.                     'currency_list'             => $dt['currency_list'],
  15831.                     'head_list'                 => $dt['head_list'],
  15832.                     'expenseInvoiceTypeList'    => $dt['expenseInvoiceTypeList'] ?? [],
  15833.                     'voucher_data'              => $dt['voucher_data'],
  15834.                     'probable_transaction_data' => $dt['probable_transaction_data'] ?? [],
  15835.                 ]
  15836.             ]);
  15837.         }
  15838.         return $this->render(
  15839. //            '@Accounts/pages/views/view_expense_invoice.html.twig',
  15840.             '@Accounts/pages/views/view_expense_invoice_demo.html.twig',
  15841.             array(
  15842.                 'page_title' => 'View Expense Invoice',
  15843.                 'data' => $dt,
  15844.                 'auto_created' => $dt['ei_data']->getAutoCreated(),
  15845.                 'approval_data' => System::checkIfApprovalExists(
  15846.                     $em,
  15847.                     array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
  15848.                     $invoice_id,
  15849.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  15850.                 ),
  15851.                 'document_log' => System::getDocumentLog(
  15852.                     $this->getDoctrine()->getManager(),
  15853.                     array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
  15854.                     $invoice_id,
  15855.                     $dt['created_by'],
  15856.                     $dt['edited_by']
  15857.                 )
  15858.             )
  15859.         );
  15860.     }
  15861.     public function PrintExpenseInvoice(Request $request$id)
  15862.     {
  15863.         $em $this->getDoctrine()->getManager();
  15864.         $invoice_id $id;
  15865.         $data Accounts::GetExpenseInvoiceDetails($em$invoice_id);
  15866.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  15867.         $document_mark = array(
  15868.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  15869.             'copy' => ''
  15870.         );
  15871.         return $this->render(
  15872.             '@Accounts/pages/print/ei_print.html.twig',
  15873.             array(
  15874.                 'page_title' => 'Expense Invoice',
  15875.                 'data' => $data,
  15876.                 'export' => 'pdf,print,sendForward',
  15877.                 'document_mark_image' => $document_mark['original'],
  15878.                 'company_name' => $company_data->getName(),
  15879.                 'company_data' => $company_data,
  15880.                 'company_address' => $company_data->getAddress(),
  15881.                 'company_image' => $company_data->getImage(),
  15882.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  15883.                 'red' => 0
  15884.             )
  15885.         );
  15886.     }
  15887.     public function strtohex($x)
  15888.     {
  15889.         $s '';
  15890.         foreach (str_split($x) as $c$s .= sprintf("%02X"ord($c));
  15891.         return ($s);
  15892.     }
  15893.     public function PrintVoucher(Request $request$id$mis_start_date ''$mis_end_date '')
  15894.     {
  15895.         $voucher_id $id;
  15896.         $p '';
  15897. //        if ($this->container->has('profiler')) {
  15898. //            $this->container->get('profiler')->disable();
  15899. //        }
  15900.         $mis_print 0;
  15901.         if ($request->query->has('mis_print'))
  15902.             $mis_print $request->query->get('mis_print');
  15903.         $em $this->getDoctrine()->getManager();
  15904.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  15905.         $start_date "";
  15906.         $end_date "";
  15907.         $em $this->getDoctrine()->getManager();
  15908.         if ($mis_start_date != '' && $mis_start_date != 0)
  15909.             $start_date $mis_start_date;
  15910.         if ($mis_end_date != '' && $mis_start_date != 0)
  15911.             $end_date $mis_end_date;
  15912.         $document_mark = array(
  15913.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  15914.             'pending' => '/images/pending.jpg',
  15915.             'copy' => ''
  15916.         );
  15917.         $data Accounts::GetVoucherDetails($em$voucher_id);
  15918.         if (!empty($data))
  15919.             $mis_data Accounts::GetVoucherMisDetails($em$data['head_id_list'], $start_date$end_date);
  15920.         $templates = [
  15921.             '3' => '@Accounts/pages/print/voucher_print.html.twig',
  15922.             '4' => '@Accounts/pages/print/contra_voucher_print.html.twig',
  15923.             '5' => '@Accounts/pages/print/payment_voucher_print.html.twig',
  15924.             '6' => '@Accounts/pages/print/receipt_voucher_print.html.twig',
  15925.         ];
  15926.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  15927.             $html $this->renderView(
  15928.                 $templates[$data['type_id']],
  15929.                 array(
  15930.                     //full array here
  15931.                     'pdf' => true,
  15932.                     'page_title' => 'Voucher ' $data['doc_hash'],
  15933.                     'data' => $data,
  15934.                     'page_header' => 'New Product',
  15935.                     'document_type' => 'Journal voucher',
  15936.                     'document_mark_image' => $document_mark['original'],
  15937.                     'page_header_sub' => 'Add',
  15938.                     //                'type_list'=>$type_list,
  15939.                     'mis_data' => $mis_data,
  15940.                     'mis_print' => $mis_print,
  15941.                     'item_data' => [],
  15942.                     'received' => 2,
  15943.                     'return' => 1,
  15944.                     'total_w_vat' => 1,
  15945.                     'total_vat' => 1,
  15946.                     'total_wo_vat' => 1,
  15947.                     'invoice_id' => 'abcd1234',
  15948.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  15949.                     'created_by' => 'created by',
  15950.                     'created_at' => '',
  15951.                     'red' => 0,
  15952.                     'company_name' => $company_data->getName(),
  15953.                     'company_data' => $company_data,
  15954.                     'company_address' => $company_data->getAddress(),
  15955.                     'company_image' => $company_data->getImage(),
  15956.                     'p' => $p
  15957.                 )
  15958.             );
  15959.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  15960.                 //                'orientation' => 'landscape',
  15961.                 //                'enable-javascript' => true,
  15962.                 //                'javascript-delay' => 1000,
  15963.                 'no-stop-slow-scripts' => false,
  15964.                 'no-background' => false,
  15965.                 'lowquality' => false,
  15966.                 'encoding' => 'utf-8',
  15967.                 //            'images' => true,
  15968.                 //            'cookie' => array(),
  15969.                 'dpi' => 300,
  15970.                 'image-dpi' => 300,
  15971.                 //                'enable-external-links' => true,
  15972.                 //                'enable-internal-links' => true
  15973.             ));
  15974.             return new Response(
  15975.                 $pdf_response,
  15976.                 200,
  15977.                 array(
  15978.                     'Content-Type' => 'application/pdf',
  15979.                     'Content-Disposition' => 'attachment; filename="' $data['doc_hash'] . '.pdf"'
  15980.                 )
  15981.             );
  15982.         }
  15983.         return $this->render(
  15984.             $templates[$data['type_id']],
  15985.             array(
  15986.                 'page_title' => 'Voucher ' $data['doc_hash'],
  15987.                 'export' => 'pdf,print',
  15988.                 'data' => $data,
  15989.                 'page_header' => 'New Product',
  15990.                 'document_type' => 'Journal voucher',
  15991.                 'document_mark_image' => $document_mark['original'],
  15992.                 'page_header_sub' => 'Add',
  15993.                 //                'type_list'=>$type_list,
  15994.                 'mis_data' => $mis_data,
  15995.                 'mis_print' => $mis_print,
  15996.                 'item_data' => [],
  15997.                 'received' => 2,
  15998.                 'return' => 1,
  15999.                 'total_w_vat' => 1,
  16000.                 'total_vat' => 1,
  16001.                 'total_wo_vat' => 1,
  16002.                 'invoice_id' => 'abcd1234',
  16003.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  16004.                 'created_by' => 'created by',
  16005.                 'created_at' => '',
  16006.                 'red' => 0,
  16007.                 'company_name' => $company_data->getName(),
  16008.                 'company_data' => $company_data,
  16009.                 'company_address' => $company_data->getAddress(),
  16010.                 'company_image' => $company_data->getImage(),
  16011.                 'p' => $p
  16012.             )
  16013.         );
  16014.     }
  16015.     public function PrintVoucherPdf(Request $request$voucher_id$mis_start_date ''$mis_end_date '')
  16016.     {
  16017.         if ($this->container->has('profiler')) {
  16018.             $this->container->get('profiler')->disable();
  16019.         }
  16020.         $p '';
  16021.         $mis_print 0;
  16022.         if ($request->query->has('mis_print'))
  16023.             $mis_print $request->query->get('mis_print');
  16024.         $em $this->getDoctrine()->getManager();
  16025.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  16026.         $start_date "";
  16027.         $end_date "";
  16028.         $em $this->getDoctrine()->getManager();
  16029.         if ($mis_start_date != '' && $mis_start_date != 0)
  16030.             $start_date $mis_start_date;
  16031.         if ($mis_end_date != '' && $mis_start_date != 0)
  16032.             $end_date $mis_end_date;
  16033.         $document_mark = array(
  16034.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  16035.             'pending' => '/images/pending.jpg',
  16036.             'copy' => ''
  16037.         );
  16038.         $data Accounts::GetVoucherDetails($em$voucher_id);
  16039.         if (!empty($data))
  16040.             $mis_data Accounts::GetVoucherMisDetails($em$data['head_id_list'], $start_date$end_date);
  16041.         $format $request->get('_format');
  16042.         $this->get('knp_snappy.pdf');
  16043.         //        $format = 'pdf';
  16044.         //        $response = $this->render(sprintf('ApplicationBundle:pages/accounts/pdf:helloAction.%s.twig', $format), array(
  16045.         //            'name' => 'Ecobeco',
  16046.         //        ));
  16047.         ////        $response->headers->set('Content-Type', 'application/pdf');
  16048.         //
  16049.         //        return $response;
  16050.         $templates = [
  16051.             '3' => '@Accounts/pages/print/voucher_print.html.twig',
  16052.             '4' => '@Accounts/pages/print/contra_voucher_print.html.twig',
  16053.             '5' => '@Accounts/pages/print/payment_voucher_print.html.twig',
  16054.         ];
  16055.         //        return $this->render($templates[$data['type_id']],
  16056.         $html $this->renderView(
  16057.             $templates[$data['type_id']],
  16058.             array(
  16059.                 'page_title' => 'Voucher ' $data['doc_hash'],
  16060.                 'data' => $data,
  16061.                 'page_header' => 'New Product',
  16062.                 'document_type' => 'Journal voucher',
  16063.                 'document_mark_image' => $document_mark['original'],
  16064.                 'page_header_sub' => 'Add',
  16065.                 //                'type_list'=>$type_list,
  16066.                 'mis_data' => $mis_data,
  16067.                 'mis_print' => $mis_print,
  16068.                 'item_data' => [],
  16069.                 'received' => 2,
  16070.                 'return' => 1,
  16071.                 'total_w_vat' => 1,
  16072.                 'total_vat' => 1,
  16073.                 'total_wo_vat' => 1,
  16074.                 'invoice_id' => 'abcd1234',
  16075.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  16076.                 'created_by' => 'created by',
  16077.                 'created_at' => '',
  16078.                 'red' => 0,
  16079.                 'company_name' => $company_data->getName(),
  16080.                 'company_data' => $company_data,
  16081.                 'company_address' => $company_data->getAddress(),
  16082.                 'company_image' => $company_data->getImage(),
  16083.                 'p' => $p
  16084.             )
  16085.         );
  16086.         $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  16087.             //                'orientation' => 'landscape',
  16088.             //                'enable-javascript' => true,
  16089.             //                'javascript-delay' => 1000,
  16090.             'no-stop-slow-scripts' => true,
  16091.             'no-background' => false,
  16092.             'lowquality' => false,
  16093.             'encoding' => 'utf-8',
  16094.             //            'images' => true,
  16095.             //            'cookie' => array(),
  16096.             'dpi' => 300,
  16097.             'image-dpi' => 300,
  16098.             //                'enable-external-links' => true,
  16099.             //                'enable-internal-links' => true
  16100.         ));
  16101.         return new Response(
  16102.             $pdf_response,
  16103.             200,
  16104.             array(
  16105.                 'Content-Type' => 'application/pdf',
  16106.                 //                'Content-Disposition'   => 'attachment; filename="file.pdf"'
  16107.             )
  16108.         );
  16109.     }
  16110.     public function VoucherList(Request $request)
  16111.     {
  16112.         $em $this->getDoctrine()->getManager();
  16113.         //        $Transaction = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findAllOrderedByName();
  16114.         $voucherListData Accounts::GetVoucherList($em$request->isMethod('POST') ? 'POST' 'GET'$request->request);
  16115.         if ($request->isMethod('POST')) {
  16116.             if ($request->query->has('dataTableQry')) {
  16117.                 return new JsonResponse(
  16118.                     $voucherListData
  16119.                 );
  16120.             }
  16121.         }
  16122.         return $this->render(
  16123.             '@Accounts/pages/list/voucher_list.html.twig',
  16124.             array(
  16125.                 'page_title' => 'Transactions',
  16126.                 'data' => $voucherListData['data']
  16127.             )
  16128.         );
  16129.     }
  16130.     /**
  16131.      * @Pdf()
  16132.      */
  16133.     public function TestPdf(Request $request$slug)
  16134.     {
  16135.         $format $request->get('_format');
  16136.         //        $format = 'pdf';
  16137.         $response $this->render(sprintf('@Application/pages/accounts/pdf/helloAction.%s.twig'$format), array(
  16138.             'name' => 'Ecobeco',
  16139.         ));
  16140.         //        $response->headers->set('Content-Type', 'application/pdf');
  16141.         return $response;
  16142.     }
  16143.     public function ViewLedger(Request $request$id)
  16144.     {
  16145.         //        $format = $request->get('_format');
  16146.         //        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);
  16147.         $start_date "";
  16148.         $end_date "";
  16149.         $em $this->getDoctrine()->getManager();
  16150.         if ($request->query->has('start_date'))
  16151.             $start_date $request->query->get('start_date');
  16152.         if ($request->query->has('end_date'))
  16153.             $end_date $request->query->get('end_date');
  16154.         $balance_view_method 0;
  16155.         $bal_set $em
  16156.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  16157.             ->findOneBy(
  16158.                 array(
  16159.                     'name' => 'ledger_balance_display_method',
  16160.                 )
  16161.             );
  16162.         if ($bal_set) {
  16163.             $balance_view_method $bal_set->getdata();
  16164.         }
  16165.         // now lets get its tree for the description
  16166.         $id_list_for_ledger = [];
  16167.         $parent_id_list_for_ledger = [];
  16168.         if ($request->query->has('HeadId'))
  16169.             $id_list_for_ledger $request->query->get('HeadId');
  16170.         if ($request->query->has('parentHeadId'))
  16171.             $parent_id_list_for_ledger $request->query->get('parentHeadId');
  16172.         $provisional_option 1//include
  16173.         if ($request->query->has('provisional')) {
  16174.             $provisional_option $request->query->get('provisional'); //include
  16175.         }
  16176.         $allocationSupportData $this->getAllocationReportSupportData($em$request);
  16177.         $allocationFilters $allocationSupportData['allocation_filters'];
  16178.         if (empty($id_list_for_ledger))
  16179.             if ($id != 0)
  16180.                 $id_list_for_ledger = [$id];
  16181.         $ledger_det = [];
  16182.         foreach ($id_list_for_ledger as $ind_head_id) {
  16183.             //            $ledger_data = Accounts::LedgerDetails($em, $ind_head_id, $start_date, $end_date,$provisional_option);
  16184.             $ledger_data Accounts::LedgerDetailsTransMethod($em$ind_head_id$start_date$end_date$provisional_option$allocationFilters);
  16185.             $ledger_det[$ind_head_id] = $ledger_data;
  16186.         }
  16187.         $grouped_heads Accounts::getLedgerHeadsWithParents($em);
  16188.         return $this->render(
  16189.             '@Accounts/pages/views/view_head_ledger.html.twig',
  16190.             array(
  16191.                 'page_title' => 'Ledger',
  16192.                 'id_list' => $id_list_for_ledger,
  16193.                 'parent_id_list' => $parent_id_list_for_ledger,
  16194.                 //                'products'=>Inventory::ProductList($this->getDoctrine()->getManager()),
  16195.                 //                'categories'=>Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  16196.                 //                'itemgroup'=>Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  16197.                 //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager())
  16198.                 'products' => [],
  16199.                 'provisional' => $provisional_option,
  16200.                 'ledger_data' => $ledger_det,
  16201.                 'balance_view_method' => $balance_view_method,
  16202.                 'categories' => [],
  16203.                 'heads' => $grouped_heads,
  16204.                 'itemgroup' => [],
  16205.                 'data' => [],
  16206.                 'start_date' => $start_date,
  16207.                 'end_date' => $end_date,
  16208.                 'allocation_filters' => $allocationFilters,
  16209.                 'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
  16210.                 'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
  16211.                 'project_list' => $allocationSupportData['project_list'],
  16212.                 'branch_list' => $allocationSupportData['branch_list'],
  16213.                 'cost_centers' => $allocationSupportData['cost_centers'],
  16214.                 //                'desc_head_list'=>$desc_tree_list,
  16215.             )
  16216.         );
  16217.     }
  16218.     public function ViewLedgerForApp(Request $request$id 0)
  16219.     {
  16220.         $start_date "";
  16221.         $end_date "";
  16222.         $em $this->getDoctrine()->getManager();
  16223.         if ($request->query->has('start_date'))
  16224.             $start_date $request->query->get('start_date');
  16225.         if ($request->query->has('end_date'))
  16226.             $end_date $request->query->get('end_date');
  16227.         $balance_view_method 0;
  16228.         $bal_set $em
  16229.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  16230.             ->findOneBy(['name' => 'ledger_balance_display_method']);
  16231.         if ($bal_set) {
  16232.             $balance_view_method $bal_set->getdata();
  16233.         }
  16234.         $id_list_for_ledger = [];
  16235.         if ($request->query->has('acc_heads_id')) {
  16236.             $raw_head_id $request->query->get('acc_heads_id');
  16237.             if (is_array($raw_head_id)) {
  16238.                 $id_list_for_ledger $raw_head_id;
  16239.             } elseif (is_string($raw_head_id)) {
  16240.                 $id_list_for_ledger array_filter(explode(','$raw_head_id));
  16241.             }
  16242.         }
  16243.         $parent_id_list_for_ledger = [];
  16244.         if ($request->query->has('acc_parent_head_id')) {
  16245.             $parent_id_list_for_ledger $request->query->get('acc_parent_head_id');
  16246.         }
  16247.         $provisional_option $request->query->get('provisional'1);
  16248.         $allocationFilters $this->getAllocationReportFilters($request);
  16249.         // ✅ Fallback if HeadId not passed
  16250.         if (empty($id_list_for_ledger) && $id != 0) {
  16251.             $id_list_for_ledger = [$id];
  16252.         }
  16253.         $ledger_det = [];
  16254.         foreach ($id_list_for_ledger as $ind_head_id) {
  16255.             $ledger_data Accounts::LedgerDetailsTransMethodForApp(
  16256.                 $em,
  16257.                 $ind_head_id,
  16258.                 $start_date,
  16259.                 $end_date,
  16260.                 $provisional_option,
  16261.                 23232323,
  16262.                 0,
  16263.                 'DATE_RANGE',
  16264.                 $allocationFilters
  16265.             );
  16266.             if (isset($ledger_data['error']) && $ledger_data['error'] === true) {
  16267.                 continue;
  16268.             }
  16269.             $head $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findOneBy(['accountsHeadId' => $ind_head_id]);
  16270.             $head_name $head $head->getName() : 'Unknown_' $ind_head_id;
  16271.             $ledger_det[$head_name] = Accounts::formatLedgerSummary($ledger_data);
  16272.         }
  16273.         $grouped_heads Accounts::getLedgerHeadsWithParents($em);
  16274.         return new JsonResponse([
  16275.             'success' => true,
  16276.             'response' => $ledger_det,
  16277.         ]);
  16278.     }
  16279.     public function ListOfProvisional()
  16280.     {
  16281.         return new JsonResponse([
  16282.             ['id' => 0'label' => "Don't Include Provisional Transaction"],
  16283.             ['id' => 1'label' => 'Include Provisional Transaction'],
  16284.             ['id' => 2'label' => 'Only Provisional Transaction'],
  16285.         ]);
  16286.     }
  16287.     // public function dashboardCashFlow(Request $request, $id)
  16288.     // {
  16289.     //     $em = $this->getDoctrine()->getManager();
  16290.     //     $end_date = new \DateTime();
  16291.     //     $end_date = $end_date->format('Y-m-d'); 
  16292.     //     $start_date = new \DateTime();
  16293.     //     $start_date->modify('-1 month');
  16294.     //     $start_date = $start_date->format('Y-m-d'); 
  16295.     //     // Get the date for the last 7 days
  16296.     //     $seven_days_ago = new \DateTime();
  16297.     //     $seven_days_ago->modify('-7 days');
  16298.     //     $seven_days_ago = $seven_days_ago->format('Y-m-d'); 
  16299.     //     $balance_view_method = 0;
  16300.     //     $bal_set = $em
  16301.     //         ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  16302.     //         ->findOneBy(array(
  16303.     //             'name' => 'ledger_balance_display_method',
  16304.     //         ));
  16305.     //     if ($bal_set) {
  16306.     //         $balance_view_method = $bal_set->getdata();
  16307.     //     }
  16308.     //     // Now lets get its tree for the description
  16309.     //     $id_list_for_ledger = [];
  16310.     //     $parent_id_list_for_ledger = [];
  16311.     //     $candceq = $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  16312.     //         'name' => 'cash_and_cash_equivalent_parents'
  16313.     //     ));
  16314.     //     if ($candceq)
  16315.     //         $id_list_for_ledger = json_decode($candceq->getData(), true);
  16316.     //     $provisional_option = 1; //include
  16317.     //     if ($request->query->has('provisional')) {
  16318.     //         $provisional_option = $request->query->get('provisional'); //include
  16319.     //     }
  16320.     //     if (empty($id_list_for_ledger))
  16321.     //         if ($id != 0)
  16322.     //             $id_list_for_ledger = [$id];
  16323.     //     $ledger_det = [];
  16324.     //     foreach ($id_list_for_ledger as $ind_head_id) {
  16325.     //         $ledger_data = Accounts::LedgerDetailsTransMethod($em, $ind_head_id, $start_date, $end_date, $provisional_option);
  16326.     //         $ledger_det[$ind_head_id] = $ledger_data;
  16327.     //     }
  16328.     //     $last_7_days_ledger_det = [];
  16329.     //     foreach ($id_list_for_ledger as $ind_head_id) {
  16330.     //         $ledger_data_7_days = Accounts::LedgerDetailsTransMethod($em, $ind_head_id, $seven_days_ago, $end_date, $provisional_option);
  16331.     //         $last_7_days_ledger_det[$ind_head_id] = $ledger_data_7_days;
  16332.     //     }
  16333.     //     $grouped_heads = Accounts::getLedgerHeadsWithParents($em);
  16334.     //     $debitCreditData = [];
  16335.     //     foreach ($ledger_det as $key => $entry) {
  16336.     //         if (isset($entry['imidiate_child']) && is_array($entry['imidiate_child'])) {
  16337.     //             foreach ($entry['imidiate_child'] as $child) {
  16338.     //                 $debitCreditData[] = [
  16339.     //                     'debit'  => $child['debit'] ?? 0,
  16340.     //                     'credit' => $child['credit'] ?? 0,
  16341.     //                     'balance' => $child['balance'] ?? 0
  16342.     //                 ];
  16343.     //             }
  16344.     //         }
  16345.     //     }
  16346.     //     $total = [
  16347.     //         'debit' => 0,
  16348.     //         'credit' => 0,
  16349.     //         'balance' => 0,
  16350.     //         'closing_balance_last_7_days' => 0, 
  16351.     //     ];
  16352.     //     foreach ($debitCreditData as $entry) {
  16353.     //         $total['debit'] += $entry['debit'];
  16354.     //         $total['credit'] += $entry['credit'];
  16355.     //         $total['balance'] += $entry['balance'];
  16356.     //     }
  16357.     //     $closing_balance_details_last_7_days = [];
  16358.     //     foreach ($last_7_days_ledger_det as $key => $entry) {
  16359.     //         if (isset($entry['closing_data']) && is_array($entry['closing_data'])) {
  16360.     //             foreach ($entry['closing_data'] as $closing_entry) {
  16361.     //                 $closing_balance_details_last_7_days[] = [
  16362.     //                     'date' => $closing_entry['date'] ?? null,
  16363.     //                     //'opening' => $closing_entry['opening'] ?? 0,
  16364.     //                     //'balance' => $closing_entry['balance'] ?? 0,
  16365.     //                     'difference' => ($closing_entry['balance'] ?? 0) - ($closing_entry['opening'] ?? 0) // Calculate balance - opening
  16366.     //                 ];
  16367.     //             }
  16368.     //         }
  16369.     //     }
  16370.     //     // Add to total response
  16371.     //     $total['closing_balance_details_last_7_days'] = $closing_balance_details_last_7_days;
  16372.     //     return new JsonResponse($total);
  16373.     // }
  16374.     // public function dashboardCashFlow(Request $request, $id)
  16375.     // {
  16376.     //     $em = $this->getDoctrine()->getManager();
  16377.     //     $end_date = new \DateTime();
  16378.     //     $end_date = $end_date->format('Y-m-d');
  16379.     //     $start_date = new \DateTime();
  16380.     //     $start_date->modify('-1 month');
  16381.     //     $start_date = $start_date->format('Y-m-d');
  16382.     //     $seven_days_ago = new \DateTime();
  16383.     //     $seven_days_ago->modify('-7 days');
  16384.     //     $seven_days_ago = $seven_days_ago->format('Y-m-d');
  16385.     //     $balance_view_method = 0;
  16386.     //     $bal_set = $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(['name' => 'ledger_balance_display_method']);
  16387.     //     if ($bal_set) {
  16388.     //         $balance_view_method = $bal_set->getdata();
  16389.     //     }
  16390.     //     $id_list_for_ledger = [];
  16391.     //     $candceq = $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(['name' => 'cash_and_cash_equivalent_parents']);
  16392.     //     if ($candceq) {
  16393.     //         $id_list_for_ledger = json_decode($candceq->getData(), true);
  16394.     //     }
  16395.     //     $provisional_option = $request->query->get('provisional', 1);
  16396.     //     if (empty($id_list_for_ledger) && $id != 0) {
  16397.     //         $id_list_for_ledger = [$id];
  16398.     //     }
  16399.     //     $ledger_det = [];
  16400.     //     foreach ($id_list_for_ledger as $ind_head_id) {
  16401.     //         $ledger_det[$ind_head_id] = Accounts::LedgerDetailsTransMethod($em, $ind_head_id, $start_date, $end_date, $provisional_option);
  16402.     //     }
  16403.     //     $last_7_days_ledger_det = [];
  16404.     //     foreach ($id_list_for_ledger as $ind_head_id) {
  16405.     //         $last_7_days_ledger_det[$ind_head_id] = Accounts::LedgerDetailsTransMethod($em, $ind_head_id, $seven_days_ago, $end_date, $provisional_option);
  16406.     //     }
  16407.     //     $total = ['debit' => 0, 'credit' => 0, 'balance' => 0, 'past_week' => 0, 'vs_past_period' => 0];
  16408.     //     $first_day_opening_7_days = 0;
  16409.     //     $first_day_opening_30_days = 0;
  16410.     //     $first_day_set_7_days = false;
  16411.     //     $first_day_set_30_days = false;
  16412.     //     foreach ($ledger_det as $entry) {
  16413.     //         if (isset($entry['closing_data']) && is_array($entry['closing_data'])) {
  16414.     //             foreach ($entry['closing_data'] as $closing_entry) {
  16415.     //                 if (!$first_day_set_30_days) {
  16416.     //                     $first_day_opening_30_days = $closing_entry['opening'] ?? 0;
  16417.     //                     $first_day_set_30_days = true;
  16418.     //                 }
  16419.     //             }
  16420.     //         }
  16421.     //     }
  16422.     //     foreach ($last_7_days_ledger_det as $entry) {
  16423.     //         if (isset($entry['closing_data']) && is_array($entry['closing_data'])) {
  16424.     //             foreach ($entry['closing_data'] as $closing_entry) {
  16425.     //                 if (!$first_day_set_7_days) {
  16426.     //                     $first_day_opening_7_days = $closing_entry['opening'] ?? 0;
  16427.     //                     $first_day_set_7_days = true;
  16428.     //                 }
  16429.     //             }
  16430.     //         }
  16431.     //     }
  16432.     //     foreach ($ledger_det as $entry) {
  16433.     //         if (isset($entry['imidiate_child']) && is_array($entry['imidiate_child'])) {
  16434.     //             foreach ($entry['imidiate_child'] as $child) {
  16435.     //                 $total['debit'] += $child['debit'] ?? 0;
  16436.     //                 $total['credit'] += $child['credit'] ?? 0;
  16437.     //                 $total['balance'] += $child['balance'] ?? 0;
  16438.     //             }
  16439.     //         }
  16440.     //     }
  16441.     //     $closing_balance_details_last_7_days = [];
  16442.     //     foreach ($last_7_days_ledger_det as $key => $entry) {
  16443.     //         if (isset($entry['closing_data']) && is_array($entry['closing_data'])) {
  16444.     //             foreach ($entry['closing_data'] as $closing_entry) {
  16445.     //                 $closing_balance_details_last_7_days[] = [
  16446.     //                     'date' => $closing_entry['date'] ?? null,
  16447.     //                     //'opening' => $closing_entry['opening'] ?? 0,
  16448.     //                     //'balance' => $closing_entry['balance'] ?? 0,
  16449.     //                     'difference' => ($closing_entry['balance'] ?? 0) - ($closing_entry['opening'] ?? 0) // Calculate balance - opening
  16450.     //                 ];
  16451.     //             }
  16452.     //         }
  16453.     //     }
  16454.     //     $total['closing_balance_details_last_7_days'] = $closing_balance_details_last_7_days;
  16455.     //     $total['past_week'] = $total['balance'] - $first_day_opening_7_days;
  16456.     //     $total['past_period'] = $total['balance'] - $first_day_opening_30_days;
  16457.     //     $total['vs_past_period'] = ($total['balance'] - $total['past_period'])/100;
  16458.     //     return new JsonResponse($total);
  16459.     // } 
  16460.     public function dashboardCashFlow(Request $request$id)
  16461.     {
  16462.         $em $this->getDoctrine()->getManager();
  16463.         $end_date = new \DateTime();
  16464.         $end_date $end_date->format('Y-m-d');
  16465.         $start_date = new \DateTime();
  16466.         $start_date->modify('-1 month');
  16467.         $start_date $start_date->format('Y-m-d');
  16468.         $seven_days_ago = new \DateTime();
  16469.         $seven_days_ago->modify('-7 days');
  16470.         $seven_days_ago $seven_days_ago->format('Y-m-d');
  16471.         $balance_view_method 0;
  16472.         $bal_set $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(['name' => 'ledger_balance_display_method']);
  16473.         if ($bal_set) {
  16474.             $balance_view_method $bal_set->getdata();
  16475.         }
  16476.         $id_list_for_ledger = [];
  16477.         $candceq $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(['name' => 'cash_and_cash_equivalent_parents']);
  16478.         if ($candceq) {
  16479.             $id_list_for_ledger json_decode($candceq->getData(), true);
  16480.         }
  16481.         $provisional_option $request->query->get('provisional'1);
  16482.         if (empty($id_list_for_ledger) && $id != 0) {
  16483.             $id_list_for_ledger = [$id];
  16484.         }
  16485.         $ledger_det = [];
  16486.         foreach ($id_list_for_ledger as $ind_head_id) {
  16487.             $ledger_det[$ind_head_id] = Accounts::LedgerDetailsTransMethod($em$ind_head_id$start_date$end_date$provisional_option);
  16488.         }
  16489.         $last_7_days_ledger_det = [];
  16490.         foreach ($id_list_for_ledger as $ind_head_id) {
  16491.             $last_7_days_ledger_det[$ind_head_id] = Accounts::LedgerDetailsTransMethod($em$ind_head_id$seven_days_ago$end_date$provisional_option);
  16492.         }
  16493.         $total = ['debit' => 0'credit' => 0'balance' => 0'closing_balance_last_7_days' => 0'past_week' => 0'vs_past_period' => 0];
  16494.         $first_day_opening_7_days 0;
  16495.         $first_day_opening_30_days 0;
  16496.         $first_day_set_7_days false;
  16497.         $first_day_set_30_days false;
  16498.         foreach ($ledger_det as $entry) {
  16499.             if (isset($entry['closing_data']) && is_array($entry['closing_data'])) {
  16500.                 foreach ($entry['closing_data'] as $closing_entry) {
  16501.                     if (!$first_day_set_30_days) {
  16502.                         $first_day_opening_30_days $closing_entry['opening'] ?? 0;
  16503.                         $first_day_set_30_days true;
  16504.                     }
  16505.                 }
  16506.             }
  16507.         }
  16508.         foreach ($last_7_days_ledger_det as $entry) {
  16509.             if (isset($entry['closing_data']) && is_array($entry['closing_data'])) {
  16510.                 foreach ($entry['closing_data'] as $closing_entry) {
  16511.                     if (!$first_day_set_7_days) {
  16512.                         $first_day_opening_7_days $closing_entry['opening'] ?? 0;
  16513.                         $first_day_set_7_days true;
  16514.                     }
  16515.                 }
  16516.             }
  16517.         }
  16518.         foreach ($ledger_det as $entry) {
  16519.             if (isset($entry['imidiate_child']) && is_array($entry['imidiate_child'])) {
  16520.                 foreach ($entry['imidiate_child'] as $child) {
  16521.                     $total['debit'] += $child['debit'] ?? 0;
  16522.                     $total['credit'] += $child['credit'] ?? 0;
  16523.                     $total['balance'] += $child['balance'] ?? 0;
  16524.                 }
  16525.             }
  16526.         }
  16527.         $closing_balance_details_last_7_days = [];
  16528.         $closing_balance_last_7_days_total 0;
  16529.         foreach ($last_7_days_ledger_det as $key => $entry) {
  16530.             if (isset($entry['closing_data']) && is_array($entry['closing_data'])) {
  16531.                 foreach ($entry['closing_data'] as $closing_entry) {
  16532.                     $difference = ($closing_entry['balance'] ?? 0) - ($closing_entry['opening'] ?? 0);
  16533.                     $closing_balance_details_last_7_days[] = [
  16534.                         'date' => $closing_entry['date'] ?? null,
  16535.                         'difference' => $difference
  16536.                     ];
  16537.                     $closing_balance_last_7_days_total += $difference;
  16538.                 }
  16539.             }
  16540.         }
  16541.         $total['closing_balance_details_last_7_days'] = $closing_balance_details_last_7_days;
  16542.         $total['closing_balance_last_7_days'] = $closing_balance_last_7_days_total;
  16543.         $total['past_week'] = $total['balance'] - $first_day_opening_7_days;
  16544.         $total['past_period'] = $total['balance'] - $first_day_opening_30_days;
  16545.         $total['vs_past_period'] = ($total['balance'] - $total['past_period']) / 100;
  16546.         return new JsonResponse($total);
  16547.     }
  16548.     public function LedgerReportForApp(Request $request$id)
  16549.     {
  16550.         //        $format = $request->get('_format');
  16551.         //        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);
  16552.         $start_date "";
  16553.         $end_date "";
  16554.         $em $this->getDoctrine()->getManager();
  16555.         $start_date $request->request->get('start_date'$request->query->get('start_date'''));
  16556.         $end_date $request->request->get('end_date'$request->query->get('end_date'''));
  16557.         $limit $request->request->get('limit'$request->query->get('limit'2511165651));
  16558.         $offset $request->request->get('offset'$request->query->get('offset'0));
  16559.         $indexType $request->request->get('indexType'$request->query->get('indexType''DATE_RANGE'));
  16560.         $balance_view_method 0;
  16561.         $bal_set $em
  16562.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  16563.             ->findOneBy(
  16564.                 array(
  16565.                     'name' => 'ledger_balance_display_method',
  16566.                 )
  16567.             );
  16568.         if ($bal_set) {
  16569.             $balance_view_method $bal_set->getdata();
  16570.         }
  16571.         // now lets get its tree for the description
  16572.         $id_list_for_ledger = [];
  16573.         $parent_id_list_for_ledger = [];
  16574.         $id_list_for_ledger $request->request->get('HeadId'$request->query->get('HeadId', []));
  16575.         if (is_string($id_list_for_ledger))
  16576.             $id_list_for_ledger json_decode($id_list_for_ledgertrue);
  16577.         if ($id_list_for_ledger == null)
  16578.             $id_list_for_ledger = [];
  16579.         $parent_id_list_for_ledger $request->request->get('parentHeadId'$request->query->get('parentHeadId', []));
  16580.         $provisional_option 1//include
  16581.         $provisional_option $request->request->get('provisional'$request->query->get('provisional'1));
  16582.         $allocationSupportData $this->getAllocationReportSupportData($em$request);
  16583.         $allocationFilters $allocationSupportData['allocation_filters'];
  16584.         if (empty($id_list_for_ledger))
  16585.             if ($id != 0)
  16586.                 $id_list_for_ledger = [$id];
  16587.         $ledger_det = [];
  16588.         foreach ($id_list_for_ledger as $ind_head_id) {
  16589.             //            $ledger_data = Accounts::LedgerDetails($em, $ind_head_id, $start_date, $end_date,$provisional_option);
  16590.             $ledger_data Accounts::LedgerDetailsTransMethodForApp($em$ind_head_id$start_date$end_date$provisional_option$limit$offset$indexType$allocationFilters);
  16591.             //            $ledger_det[$ind_head_id] = $ledger_data;
  16592.             $ledger_det $ledger_data;
  16593.         }
  16594.         $grouped_heads Accounts::getLedgerHeadsWithParents($em);
  16595.         if (!empty($ledger_det)) {
  16596.             return new JsonResponse(
  16597.                 array(
  16598.                     'success' => true,
  16599.                     //                'id_list' => $id_list_for_ledger,
  16600.                     //                'parent_id_list' => $parent_id_list_for_ledger,
  16601.                     //                'products' => [],
  16602.                     //                'provisional' => $provisional_option,
  16603.                     'ledger_data' => $ledger_det,
  16604.                     //                'balance_view_method' => $balance_view_method,
  16605.                     //                'categories' => [],
  16606.                     //                'heads' => $grouped_heads,
  16607.                     'itemgroup' => [],
  16608.                     'data' => [],
  16609.                     'start_date' => $start_date,
  16610.                     'end_date' => $end_date,
  16611.                 )
  16612.             );
  16613.         } else {
  16614.             return new JsonResponse(
  16615.                 array(
  16616.                     'message' => "data not found"
  16617.                 )
  16618.             );
  16619.         }
  16620.     }
  16621.     public function PrintLedger(Request $request$id)
  16622.     {
  16623.         $start_date "";
  16624.         $end_date "";
  16625.         $em $this->getDoctrine()->getManager();
  16626.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  16627.         if ($request->query->has('start_date'))
  16628.             $start_date $request->query->get('start_date');
  16629.         if ($request->query->has('end_date'))
  16630.             $end_date $request->query->get('end_date');
  16631.         $provisional_option 1//include
  16632.         if ($request->query->has('provisional')) {
  16633.             $provisional_option $request->query->get('provisional'); //include
  16634.         }
  16635.         $balance_view_method 0;
  16636.         $bal_set $em
  16637.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  16638.             ->findOneBy(
  16639.                 array(
  16640.                     'name' => 'ledger_balance_display_method',
  16641.                 )
  16642.             );
  16643.         if ($bal_set) {
  16644.             $balance_view_method $bal_set->getdata();
  16645.         }
  16646.         // now lets get its tree for the description
  16647.         $id_list_for_ledger = [];
  16648.         if ($request->query->has('id_list'))
  16649.             $id_list_for_ledger explode(','$request->query->get('id_list'));
  16650.         if ($id && empty($id_list))
  16651.             $id_list_for_ledger = [0];
  16652.         $ledger_det = [];
  16653.         $head_name_list = [];
  16654.         // Build the allocation filters (tag/project/branch/cost-center) from the request — same as the
  16655.         // ledger view; the print URL carries these query params and LedgerDetailsTransMethod requires them.
  16656.         $allocationSupportData $this->getAllocationReportSupportData($em$request);
  16657.         $allocationFilters $allocationSupportData['allocation_filters'];
  16658.         foreach ($id_list_for_ledger as $ind_head_id) {
  16659.             $ledger_data Accounts::LedgerDetailsTransMethod($em$ind_head_id$start_date$end_date$provisional_option$allocationFilters);
  16660.             $ledger_det[$ind_head_id] = $ledger_data;
  16661.             $head_name_list[] = $ledger_data['basic_data']['name'];
  16662.         }
  16663.         $grouped_heads Accounts::GroupedHeads($em);
  16664.         $document_mark = array(
  16665.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  16666.             'copy' => ''
  16667.         );
  16668.         $html "";
  16669.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  16670.             $html $this->renderView(
  16671.                 '@Accounts/pages/print/ledger_print.html.twig',
  16672.                 array(
  16673.                     'pdf' => true,
  16674.                     'page_title' => 'Ledger ',
  16675.                     'ledger_data' => $ledger_det,
  16676.                     'balance_view_method' => $balance_view_method,
  16677.                     'page_header' => 'Ledger',
  16678.                     'document_type' => implode(', '$head_name_list),
  16679.                     'document_mark_image' => $document_mark['original'],
  16680.                     'page_header_sub' => 'Add',
  16681.                     'start_date' => $start_date,
  16682.                     'end_date' => $end_date,
  16683.                     'head_list' => Accounts::HeadListFullPath($em),
  16684.                     'provisional' => $provisional_option,
  16685.                     //                'type_list'=>$type_list,
  16686.                     //            'child_list'=>$child_list,
  16687.                     //                'trans_data_by_closing'=>$trans_data_by_closing,
  16688.                     'item_data' => [],
  16689.                     'received' => 2,
  16690.                     'return' => 1,
  16691.                     'total_w_vat' => 1,
  16692.                     'total_vat' => 1,
  16693.                     'total_wo_vat' => 1,
  16694.                     'invoice_id' => 'abcd1234',
  16695.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  16696.                     'created_by' => 'created by',
  16697.                     'created_at' => '',
  16698.                     'red' => 0,
  16699.                     //                'desc_head_list'=>$desc_tree_list,
  16700.                     'company_name' => $company_data->getName(),
  16701.                     'company_data' => $company_data,
  16702.                     'company_address' => $company_data->getAddress(),
  16703.                     'company_image' => $company_data->getImage(),
  16704.                     //                'p'=>$p
  16705.                 )
  16706.             );
  16707.             if ($request->query->has('sendMail')) {
  16708.                 if ($request->query->get('sendMail') == 1) {
  16709.                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' 'ledger' '.pdf';
  16710.                     $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  16711.                         'no-stop-slow-scripts' => true,
  16712.                         'no-background' => false,
  16713.                         'lowquality' => false,
  16714.                         'encoding' => 'utf-8',
  16715.                         'dpi' => 300,
  16716.                         'image-dpi' => 300,
  16717.                     ));
  16718.                     $new_mail $this->get('mail_module');
  16719.                     $new_mail->sendMyMail(array(
  16720.                         'attachment' => $pdf_response
  16721.                     ));
  16722.                     return $this->render(
  16723.                         '@Accounts/pages/print/ledger_print.html.twig',
  16724.                         array(
  16725.                             'page_title' => 'Ledger ',
  16726.                             'ledger_data' => $ledger_det,
  16727.                             'page_header' => 'Ledger',
  16728.                             'document_type' => implode(', '$head_name_list),
  16729.                             'document_mark_image' => $document_mark['original'],
  16730.                             'page_header_sub' => 'Add',
  16731.                             'start_date' => $start_date,
  16732.                             'end_date' => $end_date,
  16733.                             'head_list' => Accounts::HeadListFullPath($em),
  16734.                             'provisional' => $provisional_option,
  16735.                             'balance_view_method' => $balance_view_method,
  16736.                             //                'type_list'=>$type_list,
  16737.                             //            'child_list'=>$child_list,
  16738.                             //                'trans_data_by_closing'=>$trans_data_by_closing,
  16739.                             'item_data' => [],
  16740.                             'received' => 2,
  16741.                             'return' => 1,
  16742.                             'total_w_vat' => 1,
  16743.                             'total_vat' => 1,
  16744.                             'total_wo_vat' => 1,
  16745.                             'invoice_id' => 'abcd1234',
  16746.                             'invoice_footer' => $company_data->getInvoiceFooter(),
  16747.                             'created_by' => 'created by',
  16748.                             'created_at' => '',
  16749.                             'red' => 0,
  16750.                             //                'desc_head_list'=>$desc_tree_list,
  16751.                             'company_name' => $company_data->getName(),
  16752.                             'company_data' => $company_data,
  16753.                             'company_address' => $company_data->getAddress(),
  16754.                             'company_image' => $company_data->getImage(),
  16755.                             'allocation_filters' => $allocationFilters,
  16756.                             'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
  16757.                             'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
  16758.                             'project_list' => $allocationSupportData['project_list'],
  16759.                             'branch_list' => $allocationSupportData['branch_list'],
  16760.                             'cost_centers' => $allocationSupportData['cost_centers'],
  16761.                             'export' => 'all'
  16762.                             //                'p'=>$p
  16763.                         )
  16764.                     );
  16765.                 }
  16766.             } else {
  16767.                 $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  16768.                     'no-stop-slow-scripts' => true,
  16769.                     'no-background' => false,
  16770.                     'lowquality' => false,
  16771.                     'encoding' => 'utf-8',
  16772.                     'dpi' => 300,
  16773.                     'image-dpi' => 300,
  16774.                 ));
  16775.                 return new Response(
  16776.                     $pdf_response,
  16777.                     200,
  16778.                     array(
  16779.                         'Content-Type' => 'application/pdf',
  16780.                         'Content-Disposition' => 'attachment; filename="Ledger.pdf"'
  16781.                     )
  16782.                 );
  16783.             }
  16784.         }
  16785.         return $this->render(
  16786.             '@Accounts/pages/print/ledger_print.html.twig',
  16787.             array(
  16788.                 'page_title' => 'Ledger ',
  16789.                 'ledger_data' => $ledger_det,
  16790.                 'page_header' => 'Ledger',
  16791.                 'document_type' => implode(', '$head_name_list),
  16792.                 'document_mark_image' => $document_mark['original'],
  16793.                 'page_header_sub' => 'Add',
  16794.                 'start_date' => $start_date,
  16795.                 'end_date' => $end_date,
  16796.                 'head_list' => Accounts::HeadListFullPath($em),
  16797.                 'provisional' => $provisional_option,
  16798.                 'balance_view_method' => $balance_view_method,
  16799.                 //                'type_list'=>$type_list,
  16800.                 //            'child_list'=>$child_list,
  16801.                 //                'trans_data_by_closing'=>$trans_data_by_closing,
  16802.                 'item_data' => [],
  16803.                 'received' => 2,
  16804.                 'return' => 1,
  16805.                 'total_w_vat' => 1,
  16806.                 'total_vat' => 1,
  16807.                 'total_wo_vat' => 1,
  16808.                 'invoice_id' => 'abcd1234',
  16809.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  16810.                 'created_by' => 'created by',
  16811.                 'created_at' => '',
  16812.                 'red' => 0,
  16813.                 //                'desc_head_list'=>$desc_tree_list,
  16814.                 'company_name' => $company_data->getName(),
  16815.                 'company_data' => $company_data,
  16816.                 'company_address' => $company_data->getAddress(),
  16817.                 'company_image' => $company_data->getImage(),
  16818.                 'export' => 'all'
  16819.                 //                'p'=>$p
  16820.             )
  16821.         );
  16822.     }
  16823.     public function PrintLedgerPdf(Request $request$id)
  16824.     {
  16825.         $start_date "";
  16826.         $end_date "";
  16827.         if ($this->container->has('profiler')) {
  16828.             $this->container->get('profiler')->disable();
  16829.         }
  16830.         $em $this->getDoctrine()->getManager();
  16831.         $company_data Company::getCompanyData($em$this->getLoggedUserCompanyId($request));
  16832.         if ($request->query->has('start_date'))
  16833.             $start_date $request->query->get('start_date');
  16834.         if ($request->query->has('end_date'))
  16835.             $end_date $request->query->get('end_date');
  16836.         $provisional_option 1//include
  16837.         if ($request->query->has('provisional')) {
  16838.             $provisional_option $request->query->get('provisional'); //include
  16839.         }
  16840.         // now lets get its tree for the description
  16841.         $id_list_for_ledger = [];
  16842.         if ($request->query->has('id_list'))
  16843.             $id_list_for_ledger explode(','$request->query->get('id_list'));
  16844.         if ($id && empty($id_list))
  16845.             $id_list_for_ledger = [0];
  16846.         $ledger_det = [];
  16847.         $head_name_list = [];
  16848.         foreach ($id_list_for_ledger as $ind_head_id) {
  16849.             $ledger_data Accounts::LedgerDetailsTransMethod($em$ind_head_id$start_date$end_date$provisional_option);
  16850.             $ledger_det[$ind_head_id] = $ledger_data;
  16851.             $head_name_list[] = $ledger_data['basic_data']['name'];
  16852.         }
  16853.         $grouped_heads Accounts::GroupedHeads($em);
  16854.         $document_mark = array(
  16855.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  16856.             'copy' => ''
  16857.         );
  16858.         // now lets get its tree for the description
  16859.         //        $id_list=explode('/',$em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findOneBy(array(
  16860.         //            'accountsHeadId'=>$id
  16861.         //        ))->getPathTree());
  16862.         //        $desc_tree_list=$em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findBy(array(
  16863.         //            'accountsHeadId'=>$id_list
  16864.         //        ),
  16865.         //            array(
  16866.         //                'accountsHeadId'=>'ASC',
  16867.         //            ));
  16868.         //
  16869.         //        //now assigning transactions to closing_data_list
  16870.         //        $trans_data_by_closing=[];
  16871.         //
  16872.         //        foreach($child_list['transaction_list'] as $g=>$entry)
  16873.         //        {
  16874.         //            $my_time = strtotime($entry['transaction_date']);
  16875.         //            $tr_date = date("m/d/Y", $my_time);
  16876.         ////                if($entry['transaction_date'] instanceof \DateTime)
  16877.         //            $trans_data_by_closing[$tr_date][]=$entry;
  16878.         //        }
  16879.         $html $this->renderView(
  16880.             '@Accounts/pages/print/ledger_print.html.twig',
  16881.             array(
  16882.                 'page_title' => 'Ledger ',
  16883.                 'ledger_data' => $ledger_det,
  16884.                 'page_header' => 'Ledger',
  16885.                 'document_type' => implode(', '$head_name_list),
  16886.                 'document_mark_image' => $document_mark['original'],
  16887.                 'page_header_sub' => 'Add',
  16888.                 'start_date' => $start_date,
  16889.                 'end_date' => $end_date,
  16890.                 'provisional' => $provisional_option,
  16891.                 'head_list' => Accounts::HeadList($em),
  16892.                 //                'type_list'=>$type_list,
  16893.                 //            'child_list'=>$child_list,
  16894.                 //                'trans_data_by_closing'=>$trans_data_by_closing,
  16895.                 'item_data' => [],
  16896.                 'received' => 2,
  16897.                 'return' => 1,
  16898.                 'total_w_vat' => 1,
  16899.                 'total_vat' => 1,
  16900.                 'total_wo_vat' => 1,
  16901.                 'invoice_id' => 'abcd1234',
  16902.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  16903.                 'created_by' => 'created by',
  16904.                 'created_at' => '',
  16905.                 'red' => 0,
  16906.                 //                'desc_head_list'=>$desc_tree_list,
  16907.                 'company_name' => $company_data->getName(),
  16908.                 'company_data' => $company_data,
  16909.                 'company_address' => $company_data->getAddress(),
  16910.                 'company_image' => $company_data->getImage(),
  16911.                 'allocation_filters' => $allocationFilters,
  16912.                 'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
  16913.                 'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
  16914.                 'project_list' => $allocationSupportData['project_list'],
  16915.                 'branch_list' => $allocationSupportData['branch_list'],
  16916.                 'cost_centers' => $allocationSupportData['cost_centers'],
  16917.                 //                'p'=>$p
  16918.             )
  16919.         );
  16920.         //        $l= $this->get('knp_snappy.pdf')->generateFromHtml($html
  16921.         //            ,
  16922.         //            $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/myfile.pdf'
  16923.         //        );
  16924.         //        $chk=$this->get('knp_snappy.pdf');
  16925.         $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  16926.             //                'orientation' => 'landscape',
  16927.             'enable-javascript' => true,
  16928.             'javascript-delay' => 1000,
  16929.             'no-stop-slow-scripts' => true,
  16930.             'no-background' => false,
  16931.             //            'lowquality' => false,
  16932.             'encoding' => 'utf-8',
  16933.             'images' => true,
  16934.             'cookie' => array(),
  16935.             'dpi' => 300,
  16936.             'image-dpi' => 300,
  16937.             //            'page-height' =>  '29.7cm',
  16938.             //            'page-width' => '21cm'
  16939.             //                'enable-external-links' => true,
  16940.             //                'enable-internal-links' => true
  16941.         ));
  16942.         return new Response(
  16943.             $pdf_response,
  16944.             200,
  16945.             array(
  16946.                 'Content-Type' => 'application/pdf',
  16947.                 //                'Content-Disposition'   => 'attachment; filename="file.pdf"'
  16948.             )
  16949.         );
  16950.     }
  16951.     public function AccountsSettings(Request $request)
  16952.     {
  16953.         $id 0;
  16954.         $cc_id '';
  16955.         $cc_name '';
  16956.         $em $this->getDoctrine()->getManager();
  16957.         if ($request->isMethod('POST')) {
  16958.             // ADDITIVE by contract: this loop only UPSERTS the keys actually
  16959.             // posted by the form — rows for keys not on this page are never
  16960.             // touched and never deleted. Additionally, PROTECTED keys (agent
  16961.             // thresholds, AI allocations, platform/period-lock switches — see
  16962.             // AgentSettingsRegistry) are skipped outright, so this generic
  16963.             // writer can never clobber them even via a stray/injected field.
  16964.             foreach ($request->request->keys() as $req_key) {
  16965.                 if (\ApplicationBundle\Modules\AgentOS\Support\AgentSettingsRegistry::isProtectedKey($req_key)) {
  16966.                     continue;
  16967.                 }
  16968.                 //first check if it exists so we can update
  16969.                 $new_cc $this->getDoctrine()
  16970.                     ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  16971.                     ->findOneBy(
  16972.                         array(
  16973.                             'name' => $req_key,
  16974.                         )
  16975.                     );
  16976.                 if (empty($new_cc)) //doesnot exists  make new
  16977.                 {
  16978.                     $new = new AccSettings();
  16979.                     $new->setName($req_key);
  16980.                     if ($req_key == 'accounting_year_start' || $req_key == 'accounting_year_end')
  16981.                         $new->setData($request->request->get($req_key)); //might look as array so setting as string
  16982.                     else if (is_array($request->request->get($req_key)))
  16983.                         $new->setData(json_encode($request->request->get($req_key)));
  16984.                     else
  16985.                         $new->setData($request->request->get($req_key));
  16986.                     $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  16987.                     $em->persist($new);
  16988.                     $em->flush();
  16989.                 } else {
  16990.                     if ($req_key == 'accounting_year_start' || $req_key == 'accounting_year_end')
  16991.                         $new_cc->setData($request->request->get($req_key));
  16992.                     else if (is_array($request->request->get($req_key)))
  16993.                         $new_cc->setData(json_encode($request->request->get($req_key)));
  16994.                     else
  16995.                         $new_cc->setData($request->request->get($req_key));
  16996.                     $new_cc->setEditLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  16997.                 }
  16998.             }
  16999.             $em->flush();
  17000.         }
  17001.         $data $this->getDoctrine()
  17002.             ->getRepository('ApplicationBundle\\Entity\\AccSettings')
  17003.             ->findAll();
  17004.         $supplier_type_data $this->getDoctrine()
  17005.             ->getRepository('ApplicationBundle\\Entity\\SupplierType')
  17006.             ->findAll();
  17007.         $client_type_data $this->getDoctrine()
  17008.             ->getRepository('ApplicationBundle\\Entity\\ClientType')
  17009.             ->findAll();
  17010.         $action_type_data = [
  17011.             => 'general',
  17012.             => 'advance',
  17013.         ];
  17014.         $settings_list = [];
  17015.         $supplier_type_data_list = [];
  17016.         $client_type_data_list = [];
  17017.         foreach ($supplier_type_data as $value) {
  17018.             $supplier_type_data_list[$value->getSupplierTypeId()]['id'] = $value->getSupplierTypeId();
  17019.             $supplier_type_data_list[$value->getSupplierTypeId()]['name'] = $value->getName();
  17020.         }
  17021.         foreach ($client_type_data as $value) {
  17022.             $client_type_data_list[$value->getClientTypeId()]['id'] = $value->getClientTypeId();
  17023.             $client_type_data_list[$value->getClientTypeId()]['name'] = $value->getName();
  17024.         }
  17025.         foreach ($data as $value) {
  17026.             $settings_list[$value->getName()]['id'] = $value->getId();
  17027.             $settings_list[$value->getName()]['name'] = $value->getName();
  17028.             $settings_list[$value->getName()]['value'] = $value->getData();
  17029.             if ($value->getName() == 'accounting_year_start' || $value->getName() == 'accounting_year_end')
  17030.                 $settings_list[$value->getName()]['value'] = $value->getData();
  17031.             else if (is_array(json_decode($value->getData())))
  17032.                 $settings_list[$value->getName()]['value'] = json_decode($value->getData());
  17033.             else
  17034.                 $settings_list[$value->getName()]['value'] = $value->getData();
  17035.         }
  17036.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');
  17037.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  17038.         // ★ Cash-config discovery (2026-07-26). Same candidate list the MCP tool `search_cash_bank_ledger`
  17039.         // returns, surfaced on the page that actually sets it — so the browser path is not a guessing game
  17040.         // either. READ-ONLY: it only ever renders a hint; the human still picks from the multi-select.
  17041.         $cash_config_hint null;
  17042.         try {
  17043.             $cash_cfg = \ApplicationBundle\Modules\Accounts\Support\CashLedgerReader::loadConfig($em->getConnection());
  17044.             if (!$cash_cfg['configured'] || $cash_cfg['warning']) {
  17045.                 $cash_disc = \ApplicationBundle\Modules\Accounts\Support\CashLedgerReader::discover($em->getConnection(), 1);
  17046.                 $cash_config_hint = array(
  17047.                     'configured' => $cash_cfg['configured'],
  17048.                     'warning'    => $cash_cfg['warning'],
  17049.                     'canonical'  => $cash_cfg['canonical'],
  17050.                     'suggested'  => array_slice($cash_disc['candidates'], 05),
  17051.                     'how'        => $cash_disc['how_identified'],
  17052.                 );
  17053.             }
  17054.         } catch (\Throwable $e) { $cash_config_hint null; } // a hint must never break the settings page
  17055.         return $this->render(
  17056.             '@Application/pages/accounts/settings/acc_settings.html.twig',
  17057.             array(
  17058.                 'page_title' => 'Settings',
  17059.                 'cash_config_hint' => $cash_config_hint,
  17060.                 'settings_data' => $settings_list,
  17061.                 'client_type_list' => $client_type_data_list,
  17062.                 'sales_type_list' => array(=> 'Package'=> 'Project'=> 'Item/Spare'),
  17063.                 'sales_sub_type_list' => array(=> 'Cash Sales'=> 'Credit Sale'),
  17064.                 'supplier_type_list' => $supplier_type_data_list,
  17065.                 'payment_action_type_list' => $action_type_data,
  17066.                 'warehouse_action_list' => $warehouse_action_list,
  17067.                 'head_list' => Accounts::HeadListFullPath($em),
  17068.                 'expense_list' => InventoryConstant::$Expense_list_details,
  17069.                 'payroll_segregation_settings' => HumanResourceConstant::$segregationSettings
  17070.             )
  17071.         );
  17072.     }
  17073.     public function BankAccount(Request $request$id 0)
  17074.     {
  17075.         $em $this->getDoctrine()->getManager();
  17076.         $AccounDetails $em->getRepository(BankAccounts::class)->findAll();
  17077.         $childAccount Accounts::getChildLedgerHeads($em"""");
  17078.         $accountType AccountsConstant::$AccountType;
  17079.         $interestCategory AccountsConstant::$InterestCategory;
  17080.         $bankLists $em->getRepository(BankList::class)->findAll();
  17081.         $bankAccount $id $em->getRepository(BankAccounts::class)->find($id) : new BankAccounts();
  17082.         $availableHeads $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findAll();
  17083.         if ($id && !$bankAccount) {
  17084.             return new JsonResponse(['success' => false'message' => 'Bank account not found'], 404);
  17085.         }
  17086.         if ($request->isMethod('POST')) {
  17087.             $accountHolderName $request->request->get('account_holder_name');
  17088.             $accountNumber $request->request->get('account_number');
  17089.             $accountTypeVal $request->request->get('account_type');
  17090.             $interestRate $request->request->get('interest_rate');
  17091.             $bankName $request->request->get('bank_name');
  17092.             $branchName $request->request->get('branch_name');
  17093.             $swiftCode $request->request->get('swift_code');
  17094.             $routingNumber $request->request->get('routing_number');
  17095.             $numlength strlen((string)$accountNumber);
  17096.             if ($numlength || $accountNumber <= 0) {
  17097.                 return new JsonResponse(['message' => 'Account number must be at least 8 digits and positive!']);
  17098.             }
  17099.             if (!$accountHolderName || !$accountNumber || !$accountTypeVal || $interestRate <= 0) {
  17100.                 return new JsonResponse(['message' => 'Missing or invalid required fields.']);
  17101.             }
  17102.             // Save main bank
  17103.             $bank $em->getRepository(BankList::class)->findOneBy(['name' => $bankName'type' => 0]);
  17104.             if (!$bank) {
  17105.                 $bank = new BankList();
  17106.                 $bank->setName($bankName);
  17107.                 $bank->setType(0); // Type 0 for Bank
  17108.                 $bank->setSwiftCode($swiftCode);
  17109.                 $bank->setRoutingNumber($routingNumber);
  17110.                 $em->persist($bank);
  17111.                 $em->flush();
  17112.             }
  17113.             // Save or find branch under this bank
  17114.             $branch $em->getRepository(BankList::class)->findOneBy([
  17115.                 'name' => $branchName,
  17116.                 'type' => 2,
  17117.                 'parentId' => $bank->getBankId()
  17118.             ]);
  17119.             if (!$branch) {
  17120.                 $branch = new BankList();
  17121.                 $branch->setName($branchName);
  17122.                 $branch->setType(2);
  17123.                 $branch->setParentId($bank->getBankId());
  17124.                 $branch->setBank($bankName);
  17125.                 $branch->setSwiftCode($swiftCode);
  17126.                 $branch->setRoutingNumber($routingNumber);
  17127.                 $em->persist($branch);
  17128.                 $em->flush();
  17129.             }
  17130.             // Set BankAccount info
  17131.             $bankAccount->setAccountHolderName($accountHolderName);
  17132.             $bankAccount->setAccountNumber($accountNumber);
  17133.             $bankAccount->setAccountType($accountTypeVal);
  17134.             $bankAccount->setInterestRate($interestRate);
  17135.             $bankAccount->setInterestCategory($request->request->get('interest_category'));
  17136.             $bankAccount->setSwiftCode($swiftCode);
  17137.             $bankAccount->setRoutingNumber($routingNumber);
  17138.             $bankAccount->setBranchName($branchName);
  17139.             $accountsHeadId $request->request->get('accounts_head_id');
  17140.             if (!$accountsHeadId) {
  17141.                 $branchBankParentData $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(['name' => 'branch_bank_parent']);
  17142.                 if (!$branchBankParentData) {
  17143.                     return new JsonResponse(['success' => false'message' => 'Parent not found']);
  17144.                 }
  17145.                 $branchBankParent $branchBankParentData->getData();
  17146.                 $accHead Accounts::CreateNewHead(
  17147.                     $em,
  17148.                     GeneralConstant::OPENING_YEAR,
  17149.                     $branchBankParent,
  17150.                     $bankAccount->getAccountHolderName() . ' # ' $bankAccount->getAccountNumber(),
  17151.                     '',
  17152.                     0,
  17153.                     0,
  17154.                     'dr',
  17155.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  17156.                 );
  17157.                 $em->flush();
  17158.                 $bankAccount->setAccountsHeadId($accHead);
  17159.             } else {
  17160.                 $bankAccount->setAccountsHeadId($accountsHeadId);
  17161.             }
  17162.             $em->persist($bankAccount);
  17163.             $em->flush();
  17164.             return new JsonResponse(['success' => true]);
  17165.         }
  17166.         return $this->render('@Accounts/pages/input_forms/bank_account.html.twig', [
  17167.             'page_title' => $id 'Update Bank Account' 'Bank Account',
  17168.             'account_type' => $accountType,
  17169.             'childAccounts' => $childAccount,
  17170.             'interestCategory' => $interestCategory,
  17171.             'bankLists' => $bankLists,
  17172.             'bankaccount' => $bankAccount,
  17173.             'AccounDetails' => $AccounDetails,
  17174.             'available_heads' => $availableHeads,
  17175.             'id' => $id
  17176.         ]);
  17177.     }
  17178.     public function DeleteBankAccount(Request $request$id)
  17179.     {
  17180.         $em $this->getDoctrine()->getManager();
  17181.         $account $em->getRepository('ApplicationBundle\\Entity\\BankAccounts')->find($id);
  17182.         if (!$account) {
  17183.             return new JsonResponse(['success' => false'message' => 'Bank account not found'], 404);
  17184.         }
  17185.         $currentHeadId $account->getAccountsHeadId();
  17186.         $currentHead $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->find($currentHeadId);
  17187.         if ($request->isXmlHttpRequest() && $request->isMethod('POST')) {
  17188.             $newHeadId $request->request->get('new_head');
  17189.             if (!$newHeadId) {
  17190.                 return new JsonResponse(['success' => false'message' => 'Please select a new head before deletion'], 400);
  17191.             }
  17192.             $transactions $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')
  17193.                 ->findBy(['accountsHeadId' => $account->getAccountsHeadId()]);
  17194.             $newHead $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->find($newHeadId);
  17195.             if ($newHead) {
  17196.                 foreach ($transactions as $transaction) {
  17197.                     $transaction->setAccountsHead($newHead);
  17198.                     $em->persist($transaction);
  17199.                 }
  17200.                 $em->flush();
  17201.             }
  17202.             $accountId $account->getId();
  17203.             $em->remove($account);
  17204.             $em->flush();
  17205.             if ($currentHead) {
  17206.                 $em->remove($currentHead);
  17207.                 $em->flush();
  17208.             }
  17209.             return new JsonResponse([
  17210.                 'success' => true,
  17211.                 'message' => 'Bank account deleted successfully',
  17212.                 'accountId' => $accountId
  17213.             ]);
  17214.         }
  17215.         return new JsonResponse(['success' => false'message' => 'Invalid request'], 400);
  17216.     }
  17217.     public function BankAccountList()
  17218.     {
  17219.         $em $this->getDoctrine()->getManager();
  17220.         $AccounDetails $em->getRepository(BankAccounts::class)->findAll();
  17221.         $childAccount Accounts:: getChildLedgerHeads($em$doc_type ""$Type "");
  17222.         $accountType AccountsConstant::$AccountType;
  17223.         return $this->render('@Accounts/pages/list/bank_account_list.html.twig', array(
  17224.             'page_title' => 'Bank Account List',
  17225.             'AccounDetails' => $AccounDetails,
  17226.             'childAccounts' => $childAccount,
  17227.             'accountType' => $accountType,
  17228.         ));
  17229.     }
  17230.     public function createBank(Request $request)
  17231.     {
  17232.         $em $this->getDoctrine()->getManager();
  17233.         $BankList $em->getRepository('ApplicationBundle\\Entity\\BankList')->findAll();
  17234.         if ($request->isMethod('POST')) {
  17235.             $bank = new BankList();
  17236.             $name $request->request->get('name');
  17237.             $branchName $request->request->get('branch_name');
  17238.             $swiftCode $request->request->get('swift_code');
  17239.             $routingNumber $request->request->get('routing_number');
  17240.             $address $request->request->get('address');
  17241.             $mapPosition $request->request->get('map_position');
  17242.             $countryId $request->request->get('country_id');
  17243.             $type $request->request->get('type');
  17244.             $parentId $request->request->get('parent_id');
  17245.             $status $request->request->get('status');
  17246.             $createdLoginId $request->getSession()->get('user_login_id');
  17247.             $bank->setName($name);
  17248.             $bank->setBranchName($branchName);
  17249.             $bank->setSwiftCode($swiftCode);
  17250.             $bank->setRoutingNumber($routingNumber);
  17251.             $bank->setAddress($address);
  17252.             $bank->setMapPosition($mapPosition);
  17253.             $bank->setCountryId($countryId);
  17254.             $bank->setType($type);
  17255.             $bank->setParentId($parentId);
  17256.             $bank->setStatus($status);
  17257.             $bank->setCreatedLoginId($createdLoginId);
  17258.             $bank->setCreatedAt(new \DateTime());
  17259.             $em->persist($bank);
  17260.             $em->flush();
  17261. //            return new JsonResponse(['success' => true, 'message' => 'Bank created successfully']);
  17262.             return $this->redirectToRoute('create_bank_account');
  17263.         }
  17264.         return $this->render('@Accounts/pages/input_forms/create_bank.html.twig', [
  17265.             'page_title' => 'Create Bank Account',
  17266.             'bankList' => $BankList
  17267.         ]);
  17268.     }
  17269.     public function ViewAccountDetail($id)
  17270.     {
  17271.         $em $this->getDoctrine()->getManager();
  17272.         $AccounDetails $em->getRepository(BankAccounts::class)->find($id);
  17273.         $bankLists $em->getRepository(BankList::class)->findAll();
  17274.         $childAccount Accounts::getChildLedgerHeads($em$doc_type ""$Type "");
  17275.         $accountType AccountsConstant::$AccountType;
  17276.         $interestCategory AccountsConstant::$InterestCategory;
  17277.         return $this->render('@Accounts/pages/views/view_bank_account_details.html.twig', array(
  17278.             'page_title' => ' View Bank Account Details',
  17279.             'AccounDetails' => $AccounDetails,
  17280.             'childAccounts' => $childAccount,
  17281.             'account_Type' => $accountType,
  17282.             'bankLists' => $bankLists,
  17283.             'interestCategory' => $interestCategory,
  17284.             'id' => $id,
  17285.         ));
  17286.     }
  17287.     public function PrintBankAccount(Request $request$id)
  17288.     {
  17289.         $em $this->getDoctrine()->getManager();
  17290.         $company_data Company::getCompanyData($em1);
  17291.         $AccounDetails $em->getRepository(BankAccounts::class)->find($id);
  17292.         $bankLists $em->getRepository(BankList::class)->findAll();
  17293.         $childAccount Accounts::getChildLedgerHeads($em$doc_type ""$Type "");
  17294.         $accountType AccountsConstant::$AccountType;
  17295.         $interestCategory AccountsConstant::$InterestCategory;
  17296.         return $this->render('@Accounts/pages/print/bank_account_print.html.twig', array(
  17297.             'page_title' => ' Print Bank Account Details',
  17298.             'AccounDetails' => $AccounDetails,
  17299.             'company_name' => $company_data->getName(),
  17300.             'company_data' => $company_data,
  17301.             'company_address' => $company_data->getAddress(),
  17302.             'company_image' => $company_data->getImage(),
  17303.             'bankLists' => $bankLists,
  17304.             'childAccounts' => $childAccount,
  17305.             'account_Type' => $accountType,
  17306.             'interestCategory' => $interestCategory,
  17307.         ));
  17308.     }
  17309.     public function SingleBank($id)
  17310.     {
  17311.         $em $this->getDoctrine()->getManager();
  17312.         $bankLists $em->getRepository(BankList::class)->find($id);
  17313.         return new JsonResponse(
  17314.             array(
  17315.                 'success' => true,
  17316.                 'routing_code' => $bankLists->getRoutingNumber(),
  17317.                 'swift_code' => $bankLists->getSwiftCode(),
  17318.             )
  17319.         );
  17320.     }
  17321.     public function createTaxConfig(Request $request$id 0)
  17322.     {
  17323.         $em $this->getDoctrine()->getManager();
  17324.         $companyId $this->getLoggedUserCompanyId($request);
  17325.         $taxConfig null;
  17326.         if ($request->isMethod('POST')) {
  17327.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  17328.             if ($id != 0)
  17329.                 $taxConfig $em->getRepository(TaxConfig::class)->find($id);
  17330.             if (!$taxConfig)
  17331.                 $taxConfig = new TaxConfig();
  17332.             $taxConfig->setName($request->request->get('name'));
  17333.             $taxConfig->setAmount($request->request->get('amount'));
  17334.             $taxConfig->setAmountType($request->request->get('amountType'));
  17335.             $taxConfig->setInvocationType($request->request->get('invocationType'));
  17336.             $taxConfig->setMinimumAmountToinvoke($request->request->get('minimumInvokeAmount'));
  17337.             $taxConfig->setOutgoingHeadId($request->request->get('outgoingHeadId'));
  17338.             $taxConfig->setIncomingHeadId($request->request->get('incomingHeadId'));
  17339.             $taxConfig->setPayableHeadId($request->request->get('payableHeadId'));
  17340.             $taxConfig->setCurrency($request->request->get('currency'));
  17341.             $markerPost $request->request->get('marker'null);
  17342.             $markerNorm = ($markerPost === null) ? null trim((string) $markerPost);
  17343.             $taxConfig->setMarker(($markerNorm === '' || $markerNorm === null) ? null $markerNorm);
  17344.             $taxConfig->setStatus(1);
  17345.             $em->persist($taxConfig);
  17346.             $em->flush();
  17347.             $this->addFlash(
  17348.                 'success',
  17349.                 'Data added successfully'
  17350.             );
  17351.         }
  17352.         $taxConfigDetails $em->getRepository(TaxConfig::class)->findAll();
  17353.         $taxConfigData = [];
  17354.         if ($id != 0)
  17355.             $taxConfigData $em->getRepository(TaxConfig::class)->find($id);
  17356.         return $this->render('@Accounts/pages/input_forms/create_tax_config.html.twig', array(
  17357.             'page_title' => 'Tax Config ',
  17358.             'taxconfigDetails' => $taxConfigDetails,
  17359.             'data' => $taxConfigData
  17360.         ));
  17361.     }
  17362.     public function expenseCategory()
  17363.     {
  17364.         $expenseCategory GeneralConstant::$expenseCategory;
  17365.         return new JsonResponse($expenseCategory);
  17366.     }
  17367.     public function packageDetails()
  17368.     {
  17369.         $packageDetails GeneralConstant::$packageDetails;
  17370.         return new JsonResponse($packageDetails);
  17371.     }
  17372.     public function employeerange()
  17373.     {
  17374.         $employeerange GeneralConstant::$employeerange;
  17375.         return new JsonResponse($employeerange);
  17376.     }
  17377. //    public function getExpenseByCurrentDate(Request $request)
  17378. //    {
  17379. //        $em = $this->getDoctrine()->getManager();
  17380. //        $session = $request->getSession();
  17381. //        $currentTime = new \Datetime();
  17382. //        $currDate = $currentTime->format('Y-m-d');
  17383. //        $partyId = 1313;
  17384. //
  17385. //
  17386. //
  17387. //        $absoluteUrl = $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  17388. //
  17389. //
  17390. //        $expDetails = $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')->createQueryBuilder('E')
  17391. //            ->leftJoin('ApplicationBundle:Currencies', 'C', 'WITH', 'E.currency = C.currencyId')
  17392. //            ->select('E, C.code as currencyName') // Selecting currency name
  17393. //            ->where('E.partyHeadId = :partyId')
  17394. //            ->andWhere('E.createdAt >= :currentDate')
  17395. //            ->setParameter('currentDate', $currDate)
  17396. //            ->setParameter('partyId', $partyId)
  17397. //            ->getQuery()
  17398. //            ->getResult();
  17399. //
  17400. //
  17401. //        $expenseCategories = GeneralConstant::$expenseCategory;
  17402. //
  17403. //        function getExpenseCategoryByMarker($markerHash, $categories)
  17404. //        {
  17405. //            foreach ($categories as $category) {
  17406. //                if ($category['markerHash'] === $markerHash) {
  17407. //                    return $category; // Return full category array
  17408. //                }
  17409. //            }
  17410. //            return null;
  17411. //        }
  17412. //
  17413. //        function getSubcategoryName($category, $subcategoryId)
  17414. //        {
  17415. //            if (!$category || !isset($category['expenseSubcategory'])) {
  17416. //                return null;
  17417. //            }
  17418. //
  17419. //            foreach ($category['expenseSubcategory'] as $subcategory) {
  17420. //                if ($subcategory['id'] == $subcategoryId) {
  17421. //                    return $subcategory;
  17422. //                }
  17423. //            }
  17424. //            return null;
  17425. //        }
  17426. //
  17427. //        function getSubcategoryOptionName($subcategory, $optionId)
  17428. //        {
  17429. //            if (!$subcategory || !isset($subcategory['option'])) {
  17430. //                return null;
  17431. //            }
  17432. //
  17433. //            foreach ($subcategory['option'] as $option) {
  17434. //                if ($option['id'] == $optionId) {
  17435. //                    return $option;
  17436. //                }
  17437. //            }
  17438. //            return null;
  17439. //        }
  17440. //
  17441. //        $expList = [];
  17442. //
  17443. //        foreach ($expDetails as $data) {
  17444. //            $expenseCategory = getExpenseCategoryByMarker($data[0]->getMarkerHash(), $expenseCategories);
  17445. //            $subcategory = getSubcategoryName($expenseCategory, $data[0]->getExpenseSubCategory());
  17446. //            $subcategoryOption = getSubcategoryOptionName($subcategory, $data[0]->getExpenseSubCategoryOption());
  17447. //
  17448. //            $list = [
  17449. //                'id' => $data[0]->getExpenseInvoiceId(),
  17450. //                'amount' => $data[0]->getInvoiceAmount(),
  17451. //                'editFlag' => $data[0]->getEditFlag(),
  17452. //                'deleteFlag' => $data[0]->getDeleteFlag(),
  17453. //                'markerHash' => $data[0]->getMarkerHash(),
  17454. //                'expenseDate' => 1 * $data[0]->getExpenseInvoiceDate()->format('U'),
  17455. //                'expenseDescription' => $data[0]->getDescription(),
  17456. //                'currency' => $data[0]->getCurrency(),
  17457. //                'currencyName' => $data['currencyName'] ?? "Unknown Currency", // Fetching currency name
  17458. //                'currencyMultiplyRate' => $data[0]->getCurrencyMultiply(),
  17459. //                'file' =>  $absoluteUrl.''.'uploads/ExpenseInvoice/'.$data[0]->getFiles(),
  17460. //                'expenseName' => $expenseCategory ? $expenseCategory['name'] : "Unknown Expense",
  17461. //                'child' => [
  17462. //                    'expenseSubCategoryId' => $data[0]->getExpenseSubCategory(),
  17463. //                    'expenseSubcategoryName' => $subcategory ? $subcategory['name'] : "Unknown Subcategory",
  17464. //                    'option' => [
  17465. //                        'expenseSubCategoryOptionId' => $data[0]->getExpenseSubCategoryOption(),
  17466. //                        'expenseSubcategoryOptionName' => $subcategoryOption ? $subcategoryOption['name'] : "Unknown Option"
  17467. //                    ]
  17468. //                ]
  17469. //            ];
  17470. //            $expList[] = $list;
  17471. //        }
  17472. //
  17473. //        return new JsonResponse($expList);
  17474. //    }
  17475.     public function getExpenseByCurrentDate(Request $request)
  17476.     {
  17477.         $em $this->getDoctrine()->getManager();
  17478.         $session $request->getSession();
  17479.         $currentTime = new \Datetime();
  17480.         $currDate $currentTime->format('Y-m-d');
  17481.         $employeeId $session->get(UserConstants::USER_EMPLOYEE_ID);
  17482.         $employeeDetails $em->getRepository('ApplicationBundle\\Entity\\Employee')->createQueryBuilder('E')
  17483.             ->select('E.employeeId, E.accountsHeadId')  // Selecting currency name
  17484.             ->where('E.employeeId = :employeeId')
  17485.             ->setParameter('employeeId'$employeeId)
  17486.             ->getQuery()
  17487.             ->getResult();
  17488. //        $partyId = 1313;
  17489.         $partyId $employeeDetails[0]['accountsHeadId'];
  17490.         $absoluteUrl $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
  17491.         $expDetails $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')->createQueryBuilder('E')
  17492.             ->leftJoin('ApplicationBundle:Currencies''C''WITH''E.currency = C.currencyId')
  17493.             ->select('E, C.code as currencyName'// Selecting currency name
  17494.             ->where('E.partyHeadId = :partyId')
  17495.             ->andWhere('E.createdAt >= :currentDate')
  17496.             ->setParameter('currentDate'$currDate)
  17497.             ->setParameter('partyId'$partyId)
  17498.             ->getQuery()
  17499.             ->getResult();
  17500.         $expenseCategories GeneralConstant::$expenseCategory;
  17501.         function getExpenseCategoryByMarker($markerHash$categories)
  17502.         {
  17503.             foreach ($categories as $category) {
  17504.                 if ($category['markerHash'] === $markerHash) {
  17505.                     return $category;
  17506.                 }
  17507.             }
  17508.             return null;
  17509.         }
  17510.         function getSubcategoryName($category$subcategoryId)
  17511.         {
  17512.             if (!$category || !isset($category['expenseSubcategory'])) {
  17513.                 return null;
  17514.             }
  17515.             foreach ($category['expenseSubcategory'] as $subcategory) {
  17516.                 if ($subcategory['id'] == $subcategoryId) {
  17517.                     return $subcategory;
  17518.                 }
  17519.             }
  17520.             return null;
  17521.         }
  17522.         function getSubcategoryOptionName($subcategory$optionId)
  17523.         {
  17524.             if (!$subcategory || !isset($subcategory['option'])) {
  17525.                 return null;
  17526.             }
  17527.             foreach ($subcategory['option'] as $option) {
  17528.                 if ($option['id'] == $optionId) {
  17529.                     return $option;
  17530.                 }
  17531.             }
  17532.             return null;
  17533.         }
  17534.         $expList = [];
  17535.         $totalAmount 0;
  17536.         foreach ($expDetails as $data) {
  17537.             $expenseCategory getExpenseCategoryByMarker($data[0]->getMarkerHash(), $expenseCategories);
  17538.             $subcategory getSubcategoryName($expenseCategory$data[0]->getExpenseSubCategory());
  17539.             $subcategoryOption getSubcategoryOptionName($subcategory$data[0]->getExpenseSubCategoryOption());
  17540.             $amount floatval($data[0]->getInvoiceAmount());
  17541.             $totalAmount += $amount;
  17542.             $list = [
  17543.                 'id' => $data[0]->getExpenseInvoiceId(),
  17544.                 'amount' => number_format($amount2'.'''),
  17545.                 'editFlag' => $data[0]->getEditFlag(),
  17546.                 'deleteFlag' => $data[0]->getDeleteFlag(),
  17547.                 'markerHash' => $data[0]->getMarkerHash(),
  17548.                 'expenseDate' => $data[0]->getExpenseInvoiceDate()->format('U'),
  17549.                 'expenseDescription' => $data[0]->getDescription(),
  17550.                 'currency' => $data[0]->getCurrency(),
  17551.                 'currencyName' => $data['currencyName'] ?? "Unknown Currency",
  17552.                 'currencyMultiplyRate' => $data[0]->getCurrencyMultiply(),
  17553.                 'filePath' => $absoluteUrl '' 'uploads/ExpenseInvoice/' $data[0]->getFiles(),
  17554.                 'file' => $data[0]->getFiles(),
  17555.                 'expenseName' => $expenseCategory $expenseCategory['name'] : "Unknown Expense",
  17556.                 'child' => [
  17557.                     'expenseSubCategoryId' => $data[0]->getExpenseSubCategory(),
  17558.                     'expenseSubcategoryName' => $subcategory $subcategory['name'] : "Unknown Subcategory",
  17559.                     'option' => [
  17560.                         'expenseSubCategoryOptionId' => $data[0]->getExpenseSubCategoryOption(),
  17561.                         'expenseSubcategoryOptionName' => $subcategoryOption $subcategoryOption['name'] : "Unknown Option"
  17562.                     ]
  17563.                 ]
  17564.             ];
  17565.             $expList[] = $list;
  17566.         }
  17567.         $response = [
  17568.             'totalAmount' => number_format($totalAmount2'.'''),
  17569.             'expenses' => $expList
  17570. //        $employeeId,$partyId
  17571. //            $employeeDetails[0]['accountsHeadId']
  17572.         ];
  17573.         return new JsonResponse($response);
  17574.     }
  17575.     public function currentBalance(Request $request)
  17576.     {
  17577.         $em $this->getDoctrine()->getManager();
  17578.         $ind_head_id = [];
  17579.         $start_date $request->query->get('start_date'"");
  17580.         $end_date $request->query->get('end_date'"");
  17581.         if($end_date=='')
  17582.             $end_date=(new \DateTime())->format('Y-m-d');
  17583. //       return new JsonResponse( Accounts::GetBalanceOnDateByMarkerHash($em,$end_date,[],[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT],1));
  17584.         $dataType '_OWN_';
  17585. //        $dataType='_COMPANY_';//_OWN_
  17586.         $session $request->getSession();
  17587.         $userId=$session->get(UserConstants::USER_TYPE);
  17588.         if ($session->get(UserConstants::USER_TYPE) == UserConstants::USER_TYPE_SYSTEM)
  17589.         $dataType '_COMPANY_';
  17590.         $allowedCards=[];
  17591.         if($dataType=='_OWN_')
  17592.         {
  17593.             $allowedCards=[1,2,3];
  17594.             $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";
  17595.             $stmt $em->getConnection()->fetchAllAssociative($get_kids_sql);
  17596.             
  17597.             $query_output $stmt;
  17598.             if (empty($query_output)) {
  17599.                 $ind_head_id=[0];
  17600.             } else if ($query_output[0]['accounts_head_id'] == || $query_output[0]['accounts_head_id'] == NULL)
  17601.                 $ind_head_id=[0];
  17602.             else {
  17603.                 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'];
  17604.                 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'];
  17605.                 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'];
  17606.             }
  17607.         }
  17608.         else
  17609.         {
  17610.             $setting_qry $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
  17611.                 'name' => 'cash_and_cash_equivalent_parents'
  17612.             ));
  17613.             $cace_parents=[];
  17614.             if ($setting_qry)
  17615.                 $cace_parents json_decode($setting_qry->getData(), true);
  17616.             $ind_head_id=$cace_parents;
  17617.         }
  17618.         $query_head_balance=0;
  17619.         if($dataType=='_COMPANY_')
  17620.         {
  17621.             $ledger_data=Accounts::GetBalanceOnDateByMarkerHash($em,$end_date,[],[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT],1);
  17622.             $query_head_balance += $ledger_data[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['closingBalance'] ?? 0;
  17623.         }
  17624.         else {
  17625.             foreach ($ind_head_id as $ind_head) {
  17626.                 $ledger_data Accounts::LedgerDetailsTransMethod($em$ind_head$start_date$end_date);
  17627.                     $mult $ledger_data['basic_data']['head_nature'] ? ($ledger_data['basic_data']['head_nature'] == 'cr' : -1) : 0;
  17628.                     $query_head_balance += ($mult $ledger_data['query_head_balance'] ?? 0);
  17629.             }
  17630.         }
  17631.         $today_date = new \DateTime();
  17632.         $today_date $today_date->format('Y-m-d');
  17633.         $s_date_obj = \DateTime::createFromFormat('Y-m-d'$today_date);
  17634.         $start_of_month $s_date_obj->format('Y-m-01');  // First day of the month
  17635.         $end_of_month $s_date_obj->format('Y-m-t');  // Last day of the month
  17636.         $expense_date $today_date;
  17637.         $start_of_day = new \DateTime($expense_date ' 00:00:00');
  17638.         $end_of_day = new \DateTime($expense_date ' 23:59:59');
  17639.         $query $em->createQueryBuilder()
  17640.             ->select('b.accountsHeadId''a.current_balance')
  17641.             ->from('ApplicationBundle:BankAccounts''b')
  17642.             ->join('ApplicationBundle:AccAccountsHead''a''WITH''b.accountsHeadId = a.accountsHeadId')
  17643.             ->getQuery();
  17644.         $results $query->getResult();
  17645.         $acc_account_head_data = [];
  17646.         foreach ($results as $result) {
  17647.             $acc_account_head_data[] = [
  17648.                 'current_balance' => $result['current_balance'],
  17649.             ];
  17650.         }
  17651.         $monthly_summary_data $em->getRepository('ApplicationBundle\\Entity\\MonthlySummary')
  17652.             ->createQueryBuilder('m')
  17653.             ->where('m.date >= :start_of_month')
  17654.             ->andWhere('m.date <= :end_of_month')
  17655.             ->setParameter('start_of_month'$start_of_month)
  17656.             ->setParameter('end_of_month'$end_of_month)
  17657.             ->orderBy('m.date''ASC')
  17658.             ->getQuery()
  17659.             ->getResult();
  17660.         $monthly_summary = [];
  17661.         foreach ($monthly_summary_data as $summary) {
  17662.             if ($summary instanceof \ApplicationBundle\Entity\MonthlySummary) {
  17663.                 $monthly_summary[] = [
  17664.                     'date' => $summary->getDate()->format('Y-m-d'),
  17665.                     'cash' => $summary->getCash(),
  17666.                     'revenue' => $summary->getRevenue(),
  17667.                     'expense' => $summary->getExpense(),
  17668.                     'receivable' => $summary->getReceivable(),
  17669.                     'payable' => $summary->getPayable(),
  17670.                     'asset' => $summary->getAsset(),
  17671.                     'liability' => $summary->getLiability()
  17672.                 ];
  17673.             }
  17674.         }
  17675.         $qb $em->createQueryBuilder()
  17676.             ->select('SUM(e.invoiceAmount)')
  17677.             ->from('ApplicationBundle:ExpenseInvoice''e')
  17678.             ->where('e.createdAt BETWEEN :start_of_day AND :end_of_day')
  17679.             ->setParameter('start_of_day'$start_of_day)
  17680.             ->setParameter('end_of_day'$end_of_day);
  17681.         if($dataType=='_OWN_')
  17682.             $qb->andWhere("e.createdUserId = $userId");
  17683.         $total_invoice_amount $qb->getQuery()->getSingleScalarResult();
  17684.         $total_invoice_amount $total_invoice_amount !== null ? (float)$total_invoice_amount 0.00;
  17685.         $acc_account_head_data = isset($acc_account_head_data[0]['current_balance'])
  17686.             ? $acc_account_head_data[0]['current_balance'] : 0.00;
  17687.         $response = [
  17688.             'query_head_balance' => $query_head_balance,
  17689.             'total_today_expense_amount' => number_format($total_invoice_amount2'.'''),
  17690.             'primary_account_balance' => $acc_account_head_data,
  17691.             'allowed_cards' => $allowedCards
  17692.         ];
  17693.         if (!empty($monthly_summary)) {
  17694.             $response array_merge($response$monthly_summary[0]);
  17695.         }
  17696.         return new JsonResponse($response);
  17697.     }
  17698.     public function editExpense(Request $request$id 0)
  17699.     {
  17700.         $em $this->getDoctrine()->getManager();
  17701.         $expenseInvoice $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')->find($id);
  17702.         if (!$expenseInvoice) {
  17703.             return new JsonResponse(['success' => false'message' => 'Expense invoice not found'], 404);
  17704.         }
  17705.         if ($request->isMethod('POST')) {
  17706.             $expenseInvoice->setExpenseInvoiceDate(new \DateTime($request->request->get('expense_date')));
  17707.             $expenseInvoice->setInvoiceAmount($request->request->get('expense_amount'));
  17708.             // Keep the DERIVED amount fields in step with the new invoice amount. `invoice_amount`
  17709.             // is the base/GL amount; `due_amount` = invoice − paid; and the transaction-currency
  17710.             // (`_tc`) fields are the same values in the invoice's own currency (base ÷ fx rate).
  17711.             // Without this the document view — which reads due / getInvoiceAmountForeign()
  17712.             // (invoice_amount_tc) — kept showing the stale pre-edit total (e.g. 20 after editing
  17713.             // the amount to 200).
  17714.             $newAmount = (float) $request->request->get('expense_amount');
  17715.             $paidAmount = (float) $expenseInvoice->getPaidAmount();
  17716.             $newDue $newAmount $paidAmount;
  17717.             $expenseInvoice->setDueAmount($newDue);
  17718.             if ($expenseInvoice->getInvoiceAmountTc() !== null) {
  17719.                 $rate = (float) $expenseInvoice->getFxRateAtOrigin();
  17720.                 $invTc = ($rate 0) ? ($newAmount $rate) : $newAmount;
  17721.                 $dueTc = ($rate 0) ? ($newDue $rate) : $newDue;
  17722.                 $expenseInvoice->setInvoiceAmountTc(number_format($invTc6'.'''));
  17723.                 $expenseInvoice->setDueAmountTc(number_format($dueTc6'.'''));
  17724.             }
  17725.             $expenseInvoice->setPartyId(1313);
  17726.             $expenseInvoice->setExpenseInvoiceTypeId($request->request->get('expense_type'));
  17727.             $expenseInvoice->setMarkerHash($request->request->get('markerHash'));
  17728.             $expenseInvoice->setCurrency($request->request->get('expense_currency_id'));
  17729.             $expenseInvoice->setCurrencyMultiply($request->request->get('expense_currency_multiply'));
  17730.             $expenseInvoice->setExpenseSubcategory($request->request->get('expense_sub_category'));
  17731.             $expenseInvoice->setExpenseSubcategoryOption($request->request->get('expense_sub_category_option'));
  17732.             $expenseInvoice->setWbsCode($request->request->get('wbsCode'''));
  17733.             $expenseInvoice->setWbsActivityName($request->request->get('wbsActivityName'''));
  17734.             if (!empty($request->files->get('file'))) {
  17735.                 $file $request->files->get('file');
  17736.                 $fileName md5(uniqid()) . '.' $file->guessExtension();
  17737.                 $path $fileName;
  17738.                 $upl_dir $_SERVER["DOCUMENT_ROOT"] . '/../web/uploads/ExpenseInvoice/';
  17739.                 if (!file_exists($upl_dir)) {
  17740.                     mkdir($upl_dir0777true);
  17741.                 }
  17742.                 $file $file->move($upl_dir$path);
  17743.                 $expenseInvoice->setFiles($fileName);
  17744.             } else {
  17745.             }
  17746.             $expenseInvoice->setDescription($request->request->get('description'));
  17747.             $em->flush(); //
  17748.             return new JsonResponse(['success' => true]);
  17749.         }
  17750.         return new JsonResponse(['success' => false'message' => 'Invalid request'], 400);
  17751.     }
  17752.     public function deleteExpenseInvoice(Request $request$id 0)
  17753.     {
  17754.         $em $this->getDoctrine()->getManager();
  17755.         //        $id = $request->query->get('id');
  17756.         $expenseInvoice $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')->find($id);
  17757.         if (!$expenseInvoice) {
  17758.             return new JsonResponse(['message' => 'Expense invoice not found'], 404);
  17759.         }
  17760.         $em->remove($expenseInvoice);
  17761.         $em->flush();
  17762.         return new JsonResponse(['message' => 'Expense invoice deleted successfully'], 200);
  17763.     }
  17764. //    public function getChequeListForApp(Request $request)
  17765. //    {
  17766. //        $em = $this->getDoctrine()->getManager();
  17767. //
  17768. //
  17769. //        $qb = $em->getRepository('ApplicationBundle\\Entity\\AccCheck')->createQueryBuilder('C')
  17770. //            ->select(
  17771. //                'c.checkDate',
  17772. //                'c.checkNumber',
  17773. //                'c.checkAmount',
  17774. //                'c.CheckId',
  17775. //                't.documentHash',
  17776. //                't.transactionDate'
  17777. ////                'a.name AS accountsHeadName'
  17778. //            )
  17779. //            ->from('ApplicationBundle:AccCheck', 'c')
  17780. //            ->leftJoin('ApplicationBundle:AccTransactions', 't', 'WITH', 'c.voucherId = t.transactionId')
  17781. //            ->leftJoin('ApplicationBundle:AccTransactionDetails', 'd', 'WITH', 'd.transactionId = c.voucherId')
  17782. //            ->leftJoin('ApplicationBundle:AccAccountsHead', 'a', 'WITH', 'a.accountsHeadId = d.accountsHeadId');
  17783. //
  17784. //
  17785. //        $inventoryData = $qb->getQuery()->getResult();
  17786. //
  17787. //        return $this->json([
  17788. //
  17789. //            'data' => $inventoryData,
  17790. //        ]);
  17791. //    }
  17792.     public function getChequeListForApp(Request $request)
  17793.     {
  17794.         $em $this->getDoctrine()->getManager();
  17795.         $accountsHeadId $request->query->get('accountsHeadId');
  17796.         if (!$accountsHeadId) {
  17797.             return new JsonResponse(['error' => 'accountsHeadId parameter is required'], 400);
  17798.         }
  17799.         $page = (int)$request->query->get('page'1);
  17800.         $limit = (int)$request->query->get('limit'10);
  17801.         $offset = ($page 1) * $limit;
  17802.         $qb $em->createQueryBuilder();
  17803.         $qb->select(
  17804.             'c.checkDate',
  17805.             'c.checkNumber',
  17806.             'c.checkAmount',
  17807.             'c.CheckId',
  17808.             't.documentHash',
  17809.             't.transactionDate',
  17810.             'a.name AS accountsHeadName'
  17811.         )
  17812.             ->from('ApplicationBundle:AccCheck''c')
  17813.             ->leftJoin('ApplicationBundle:AccTransactions''t''WITH''c.voucherId = t.transactionId')
  17814.             ->leftJoin('ApplicationBundle:AccTransactionDetails''d''WITH''d.transactionId = c.voucherId')
  17815.             ->leftJoin('ApplicationBundle:AccAccountsHead''a''WITH''a.accountsHeadId = d.accountsHeadId')
  17816.             ->where('c.accountsHeadId = :accountsHeadId')
  17817.             ->setParameter('accountsHeadId'$accountsHeadId)
  17818.             ->setFirstResult($offset)
  17819.             ->setMaxResults($limit);
  17820.         $results $qb->getQuery()->getArrayResult();
  17821.         // Get total count
  17822.         $countQb $em->createQueryBuilder();
  17823.         $countQb->select('COUNT(c.CheckId)')
  17824.             ->from('ApplicationBundle:AccCheck''c')
  17825.             ->where('c.accountsHeadId = :accountsHeadId')
  17826.             ->setParameter('accountsHeadId'$accountsHeadId);
  17827.         $total $countQb->getQuery()->getSingleScalarResult();
  17828.         // Format dates as timestamp
  17829.         foreach ($results as &$row) {
  17830.             $row['checkDate'] = isset($row['checkDate']) && $row['checkDate'] instanceof \DateTime
  17831.                 $row['checkDate']->getTimestamp()
  17832.                 : '';
  17833.             $row['transactionDate'] = isset($row['transactionDate']) && $row['transactionDate'] instanceof \DateTime
  17834.                 $row['transactionDate']->getTimestamp()
  17835.                 : '';
  17836.             $row['checkNumber'] = $row['checkNumber'] ?? '';
  17837.             $row['checkAmount'] = $row['checkAmount'] ?? '';
  17838.             $row['CheckId'] = $row['CheckId'] ?? '';
  17839.             $row['documentHash'] = !empty($row['documentHash']) ? $row['documentHash'] : '';
  17840.             $row['accountsHeadName'] = !empty($row['accountsHeadName']) ? $row['accountsHeadName'] : '';
  17841.         }
  17842.         return new JsonResponse([
  17843.             'currentPage' => $page,
  17844.             'limit' => $limit,
  17845.             'total' => (int)$total,
  17846.             'data' => $results,
  17847.         ]);
  17848.     }
  17849.     public function MarkerHashCostCenterData()
  17850.     {
  17851.         $data AccountsConstant::$COMBINED_ARRAY;
  17852.         return new JsonResponse([
  17853.             'markerHash' => $data['markerHash'],
  17854.             'costCenter' => $data['costCenter'],
  17855.         ]);
  17856.     }
  17857.     public function agingReportApi(Request $request)
  17858.     {
  17859.         $em $this->getDoctrine()->getManager();
  17860.         $entity 18;
  17861.         $projectCategories $em->getRepository('ApplicationBundle\\Entity\\ProjectCategory')
  17862.             ->findBy(['status' => GeneralConstant::ACTIVE]);
  17863.         $categoryDetails = [];
  17864.         foreach ($projectCategories as $category) {
  17865.             $categoryDetails[] = [
  17866.                 'categoryName' => $category->getCategoryName(),
  17867.                 'categoryId' => $category->getProjectCategoryId(),
  17868.             ];
  17869.         }
  17870.         $reportData = [];
  17871.         $periodType 1;
  17872.         $divide 1;
  17873.         $categoryIds = [];
  17874.         if ($request->isMethod('POST')) {
  17875.             $categoryInput $request->request->get('projectCategoryId');
  17876.             if ($categoryInput) {
  17877.                 $categoryIds is_array($categoryInput) ? $categoryInput explode(','$categoryInput);
  17878.                 $categoryIds array_map('intval'$categoryIds);
  17879.             }
  17880.             $periodType = (int)$request->request->get('period_type'1);
  17881.             $divide = (int)$request->request->get('divide'1);
  17882.         }
  17883.         $monthsPerInterval = ($periodType 12) / $divide;
  17884.         $intervals = [];
  17885.         $startMonth 1;
  17886.         for ($i 0$i $divide$i++) {
  17887.             $endMonth $startMonth $monthsPerInterval 1;
  17888.             $intervals[] = [
  17889.                 'label' => "$startMonth-$endMonth month",
  17890.                 'start' => $startMonth,
  17891.                 'end' => $endMonth
  17892.             ];
  17893.             $startMonth += $monthsPerInterval;
  17894.         }
  17895.         foreach ($intervals as $interval) {
  17896.             $reportData[$interval['label']] = [];
  17897.         }
  17898.         if ($request->isMethod('POST')) {
  17899.             $qb $em->createQueryBuilder()
  17900.                 ->select([
  17901.                     'cf.entity',
  17902.                     'cf.entityId',
  17903.                     'cf.cashFlowAmount',
  17904.                     'cf.cashFlowDate',
  17905.                     'si.salesInvoiceNumber',
  17906.                     'so.salesOrderId',
  17907.                     'so.salesOrderNumber',
  17908.                     'p.projectId',
  17909.                     'p.projectName',
  17910.                     'pc.projectCategoryId',
  17911.                     'pc.categoryName',
  17912.                     'c.clientName',
  17913.                     'c.clientShortCode',
  17914. //                    'e.name',
  17915. //                    'ed.lastname',
  17916.                 ])
  17917.                 ->from('ApplicationBundle:CashFlowProjection''cf')
  17918.                 ->innerJoin('ApplicationBundle:SalesInvoice''si''WITH''si.salesInvoiceId = cf.entityId')
  17919.                 ->innerJoin('ApplicationBundle:SalesOrder''so''WITH''so.salesOrderId = si.salesOrderId')
  17920.                 ->innerJoin('ApplicationBundle:Project''p''WITH''p.projectId = so.projectId')
  17921.                 ->innerJoin('ApplicationBundle:ProjectCategory''pc''WITH''pc.projectCategoryId = p.projectCategoryId')
  17922.                 ->innerJoin('ApplicationBundle:AccClients''c''WITH''c.clientId = so.clientId')
  17923. //                ->innerJoin('ApplicationBundle:Employee', 'e', 'WITH', 'e.employeeId = so.salesPersonId')
  17924.                 ->where('cf.entity = :entity')
  17925.                 ->setParameter('entity'$entity);
  17926.             if (!empty($categoryIds)) {
  17927.                 $qb->andWhere('pc.projectCategoryId IN (:categoryIds)')
  17928.                     ->setParameter('categoryIds'$categoryIds);
  17929.             }
  17930.             $results $qb->getQuery()->getArrayResult();
  17931.             foreach ($results as $item) {
  17932.                 $month = (int)$item['cashFlowDate']->format('m');
  17933.                 // Find the interval label
  17934.                 $intervalLabel null;
  17935.                 foreach ($intervals as $interval) {
  17936.                     if ($month >= $interval['start'] && $month <= $interval['end']) {
  17937.                         $intervalLabel $interval['label'];
  17938.                         break;
  17939.                     }
  17940.                 }
  17941.                 if (!$intervalLabel) continue;
  17942.                 $projectId $item['projectId'];
  17943.                 $salesOrderId $item['salesOrderId'];
  17944.                 if (!isset($reportData[$intervalLabel][$projectId])) {
  17945.                     $reportData[$intervalLabel][$projectId] = [
  17946.                         'projectName' => $item['projectName'],
  17947.                         'projectCategory' => $item['projectCategoryId'],
  17948.                         'projectCategoryName' => $item['categoryName'],
  17949.                         'TotalAmount' => 0,
  17950.                         'salesOrders' => []
  17951.                     ];
  17952.                 }
  17953.                 if (!isset($reportData[$intervalLabel][$projectId]['salesOrders'][$salesOrderId])) {
  17954.                     $reportData[$intervalLabel][$projectId]['salesOrders'][$salesOrderId] = [
  17955.                         'salesOrderNumber' => $item['salesOrderNumber'],
  17956.                         'clientName' => $item['clientName'],
  17957.                         'clientShortCode' => $item['clientShortCode'],
  17958. //                        'firstName' => $item['name'],
  17959. //                        'lastName' => $item['lastname'],
  17960.                         'TotalAmount' => 0,
  17961.                         'invoices' => []
  17962.                     ];
  17963.                 }
  17964.                 $invoice = [
  17965.                     'entity' => $item['entity'],
  17966.                     'entityId' => $item['entityId'],
  17967.                     'amount' => $item['cashFlowAmount'],
  17968.                     'date' => $item['cashFlowDate'] ? $item['cashFlowDate']->format('Y-m-d') : null,
  17969.                     'salesInvoiceNumber' => $item['salesInvoiceNumber']
  17970.                 ];
  17971.                 $reportData[$intervalLabel][$projectId]['salesOrders'][$salesOrderId]['invoices'][] = $invoice;
  17972.                 $reportData[$intervalLabel][$projectId]['salesOrders'][$salesOrderId]['TotalAmount'] += $item['cashFlowAmount'];
  17973.                 $reportData[$intervalLabel][$projectId]['TotalAmount'] += $item['cashFlowAmount'];
  17974.             }
  17975.         }
  17976. //        return new JsonResponse([
  17977. //            'reportData' => $reportData,
  17978. //
  17979. //        ]);
  17980.         return $this->render('@Accounts/pages/report/aging_report.html.twig', [
  17981.             'page_title' => 'Aging Report',
  17982.             'reportData' => $reportData,
  17983.             'periodType' => $periodType,
  17984.             'divide' => $divide,
  17985.             'selectedCategoryIds' => $categoryIds,
  17986.             'category' => $categoryDetails,
  17987.         ]);
  17988.     }
  17989.     public function getParentHead(Request $request)
  17990.     {
  17991.         $em $this->getDoctrine()->getManager();
  17992.         $response Accounts::getParentLedgerHeadsForApi($request$em);
  17993.         if (!$response) {
  17994.             return new JsonResponse([
  17995.                 'status' => 'False',
  17996.                 'message' => 'Something went wrong'
  17997.             ], 500);
  17998.         }
  17999.         return new JsonResponse($response200);
  18000.     }
  18001.     public function getChildHead(Request $request)
  18002.     {
  18003.         $em $this->getDoctrine()->getManager();
  18004.         $parentId $request->query->get('parent_id');
  18005.         if (!$parentId) {
  18006.             return new JsonResponse([
  18007.                 'status' => 'error',
  18008.                 'message' => 'parent_id is required'
  18009.             ], 400);
  18010.         }
  18011.         $response Accounts::getChildHeadData($em$parentId);
  18012.         if (!$response) {
  18013.             return new JsonResponse([
  18014.                 'status' => 'False',
  18015.                 'message' => 'Something went wrong'
  18016.             ], 500);
  18017.         }
  18018.         return new JsonResponse($response200);
  18019.     }
  18020. //    public function getSalesInvoiceDetails(Request $request, $id)
  18021. //    {
  18022. //        $em = $this->getDoctrine()->getManager();
  18023. //
  18024. //        $salesInvoiceDetails = $em
  18025. //            ->getRepository('ApplicationBundle\\Entity\\SalesInvoice')
  18026. //            ->find($id);
  18027. //
  18028. //        if (!$salesInvoiceDetails) {
  18029. //            return new JsonResponse(['data' => null], 200);
  18030. //        }
  18031. //        $salesInvoiceItems = $em
  18032. //            ->getRepository('ApplicationBundle\\Entity\\SalesInvoiceItem')
  18033. //            ->findBy([
  18034. //                'salesInvoiceId' => $salesInvoiceDetails->getSalesInvoiceId()
  18035. //            ]);
  18036. //        $items = [];
  18037. //
  18038. //        foreach ($salesInvoiceItems as $item) {
  18039. //
  18040. //            $product = $em
  18041. //                ->getRepository('ApplicationBundle\\Entity\\InvProducts')
  18042. //                ->findOneBy([
  18043. //                    'id' => $item->getProductId()
  18044. //                ]);
  18045. //            $service = $em
  18046. //                ->getRepository('ApplicationBundle\\Entity\\AccService')
  18047. //                ->findOneBy([
  18048. //                    'serviceId' => $item->getServiceid()
  18049. //                ]);
  18050. //
  18051. //            $items[] = [
  18052. //                'productId' => $item->getProductId(),
  18053. //                'productName' => $product ? $product->getName() : '',
  18054. //                'serviceId' => $item->getServiceId(),
  18055. //                'servceName' => $service ? $service->getServiceName() : '',
  18056. //                'qty' => $item->getQty(),
  18057. //                'unitPrice' => $item->getAmount(),
  18058. //                'total' => $item->getPrice()
  18059. //            ];
  18060. //        }
  18061. //
  18062. //        $accClient = $em
  18063. //            ->getRepository('ApplicationBundle\\Entity\\AccClients')
  18064. //            ->findOneBy([
  18065. //                'clientId' => $salesInvoiceDetails->getClientId()
  18066. //            ]);
  18067. //
  18068. //        $currency = $em
  18069. //            ->getRepository('ApplicationBundle\\Entity\\Currencies')
  18070. //            ->findOneBy([
  18071. //                'currencyId' => $salesInvoiceDetails->getCurrency()
  18072. //            ]);
  18073. //
  18074. //        $data = [
  18075. //            'invoiceNumber' => $salesInvoiceDetails->getSalesInvoiceId(),
  18076. //            'documentNumber' => $salesInvoiceDetails->getDocumentHash(),
  18077. //            'date' => $salesInvoiceDetails->getSalesInvoiceDate()
  18078. //                ? $salesInvoiceDetails->getSalesInvoiceDate()->format('Y-m-d')
  18079. //                : null,
  18080. //            'currencyName' => $currency ? $currency->getName() : null,
  18081. //            'clientName' => $accClient ? $accClient->getClientName() : null,
  18082. //            'clientAddress' => $accClient ? $accClient->getAddressContact() : null,
  18083. //            'taxAmount' => $salesInvoiceDetails ? $salesInvoiceDetails->getTaxDeductionAmount() : 0,
  18084. //            'items' => $items
  18085. //        ];
  18086. //
  18087. //        return new JsonResponse(['data' => $data]);
  18088. //    }
  18089.     public function getSalesInvoiceDetails(Request $request$id)
  18090.     {
  18091.         $em $this->getDoctrine()->getManager();
  18092.         $salesInvoice $em
  18093.             ->getRepository('ApplicationBundle\\Entity\\SalesInvoice')
  18094.             ->find($id);
  18095.         if (!$salesInvoice) {
  18096.             return new Response('Invoice not found'404);
  18097.         }
  18098.         $accClient $em->getRepository('ApplicationBundle\\Entity\\AccClients')
  18099.             ->findOneBy(['clientId' => $salesInvoice->getClientId()]);
  18100.         $currency $em->getRepository('ApplicationBundle\\Entity\\Currencies')
  18101.             ->findOneBy(['currencyId' => $salesInvoice->getCurrency()]);
  18102.         $itemsData $em->getRepository('ApplicationBundle\\Entity\\SalesInvoiceItem')
  18103.             ->findBy(['salesInvoiceId' => $salesInvoice->getSalesInvoiceId()]);
  18104.         $xml = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><Invoice></Invoice>');
  18105.         $xml->addChild('ID'$salesInvoice->getSalesInvoiceId());
  18106.         $xml->addChild('IssueDate'$salesInvoice->getSalesInvoiceDate()->format('Y-m-d'));
  18107.         $xml->addChild('DocumentNumber'$salesInvoice->getDocumentHash());
  18108.         $clientNode $xml->addChild('Customer');
  18109.         $clientNode->addChild('Name'$accClient $accClient->getClientName() : '');
  18110.         $clientNode->addChild('Address'$accClient $accClient->getAddressContact() : '');
  18111.         $xml->addChild('TaxAmount'$salesInvoice->getTaxDeductionAmount() ?? 0);
  18112.         $itemsNode $xml->addChild('Items');
  18113.         foreach ($itemsData as $item) {
  18114.             $product $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
  18115.                 ->find($item->getProductId());
  18116.             $itemNode $itemsNode->addChild('Item');
  18117.             $itemNode->addChild('ProductName'$product $product->getName() : '');
  18118.             $itemNode->addChild('Quantity'$item->getQty());
  18119.             $itemNode->addChild('UnitPrice'$item->getAmount());
  18120.             $itemNode->addChild('Total'$item->getPrice());
  18121.         }
  18122.         $xmlContent $xml->asXML();
  18123.         $response = new Response($xmlContent);
  18124.         $response->headers->set('Content-Type''application/xml');
  18125.         $response->headers->set(
  18126.             'Content-Disposition',
  18127.             'attachment; filename="invoice_'.$salesInvoice->getSalesInvoiceId().'.xml"'
  18128.         );
  18129.         return $response;
  18130.     }
  18131.     private function validateAddExpenseRequest(Request $request)
  18132.     {
  18133.         $expenseType = (int) $request->request->get('expense_type'0);
  18134.         $expenseAmount = (float) $request->request->get('expense_amount'0);
  18135.         $previousAdvanceAmount = (float) $request->request->get('prev_advance_amount'0);
  18136.         $expenseId = (int) $request->request->get('expense_id'0);
  18137.         $expenseToBePaidTo $request->request->get('expense_to_be_paid_to''');
  18138.         $checkId = (int) $request->request->get('check_id'0);
  18139.         $expenseDate $this->parseAddExpenseDate($request->request->get('expense_date'''));
  18140.         $supportedExpenseTypes = array(01235);
  18141.         if (!in_array($expenseType$supportedExpenseTypestrue)) {
  18142.             return 'Invalid expense type selected.';
  18143.         }
  18144.         if (!$expenseDate) {
  18145.             return 'Please select a valid expense date.';
  18146.         }
  18147.         if ($expenseId <= 0) {
  18148.             return 'Please select expense name/head.';
  18149.         }
  18150.         if ($expenseToBePaidTo === '' || (string) $expenseToBePaidTo === '0') {
  18151.             return 'Please select balance against head.';
  18152.         }
  18153.         if ($expenseAmount <= 0) {
  18154.             return 'Expense amount must be greater than zero.';
  18155.         }
  18156.         if ($previousAdvanceAmount 0) {
  18157.             return 'Advance amount cannot be negative.';
  18158.         }
  18159.         if ($previousAdvanceAmount $expenseAmount) {
  18160.             return 'Advance amount cannot be greater than expense amount.';
  18161.         }
  18162.         if ($expenseType === && (int) $request->request->get('poId'0) <= 0) {
  18163.             return 'Please select a purchase order.';
  18164.         }
  18165.         if ($expenseType === && (int) $request->request->get('soId'0) <= 0) {
  18166.             return 'Please select a sales order/project.';
  18167.         }
  18168.         if ($expenseType === && (int) $request->request->get('opportunityId'$request->request->get('leadId'0)) <= 0) {
  18169.             return 'Please select a lead/bid.';
  18170.         }
  18171.         if ($expenseType === && (int) $request->request->get('tour_id'0) <= 0) {
  18172.             return 'Please select a tour.';
  18173.         }
  18174.         if ($checkId && !$this->parseAddExpenseDate($request->request->get('check_date'''))) {
  18175.             return 'Please select a valid cheque date.';
  18176.         }
  18177.         if ((int) $request->request->get('exp_check_expense_distribution_on_product'0) === 1) {
  18178.             if ($expenseType !== 1) {
  18179.                 return 'Product cost distribution is only available for purchase expenses.';
  18180.             }
  18181.             $distributionPoItemIds $request->request->get('exp_distribution_poitemId', array());
  18182.             $distributionAmounts $request->request->get('exp_distribution_amount', array());
  18183.             if (empty($distributionPoItemIds) || empty($distributionAmounts)) {
  18184.                 return 'No purchase items found for product cost distribution.';
  18185.             }
  18186.             $distributedAmount 0;
  18187.             foreach ($distributionAmounts as $distributionAmount) {
  18188.                 $distributedAmount += (float) $distributionAmount;
  18189.             }
  18190.             if (abs($distributedAmount $expenseAmount) > 0.01) {
  18191.                 return 'Distributed product cost must equal the expense amount.';
  18192.             }
  18193.         }
  18194.         $fileValidationError $this->validateAddExpenseFiles($request->files->get('file', array()));
  18195.         if ($fileValidationError !== null) {
  18196.             return $fileValidationError;
  18197.         }
  18198.         return null;
  18199.     }
  18200.     private function parseAddExpenseDate($value)
  18201.     {
  18202.         $value trim((string) $value);
  18203.         if ($value === '') {
  18204.             return null;
  18205.         }
  18206.         $formats = array('F d, Y''Y-m-d''d-m-Y');
  18207.         foreach ($formats as $format) {
  18208.             $date = \DateTime::createFromFormat($format$value);
  18209.             $errors = \DateTime::getLastErrors();
  18210.             if ($date instanceof \DateTime && ($errors === false || ($errors['warning_count'] === && $errors['error_count'] === 0))) {
  18211.                 $date->setTime(000);
  18212.                 return $date;
  18213.             }
  18214.         }
  18215.         return null;
  18216.     }
  18217.     private function validateAddExpenseFiles($files)
  18218.     {
  18219.         $allowedExtensions = array('pdf''jpg''jpeg''png''doc''docx');
  18220.         $maxFileSize 1024 1024;
  18221.         if (!is_array($files)) {
  18222.             $files $files ? array($files) : array();
  18223.         }
  18224.         foreach ($files as $file) {
  18225.             if ($file === null) {
  18226.                 continue;
  18227.             }
  18228.             $extension strtolower((string) $file->guessExtension());
  18229.             if ($extension === '') {
  18230.                 $extension strtolower((string) $file->getClientOriginalExtension());
  18231.             }
  18232.             if (!in_array($extension$allowedExtensionstrue)) {
  18233.                 return 'Only PDF, JPG, JPEG, PNG, DOC, and DOCX files are allowed.';
  18234.             }
  18235.             if ((int) $file->getSize() > $maxFileSize) {
  18236.                 return 'Each attachment must be 5 MB or smaller.';
  18237.             }
  18238.         }
  18239.         return null;
  18240.     }
  18241.     public function exportDxso(Request $request): Response
  18242.     {
  18243.         $data json_decode($request->getContent(), true);
  18244.         $formattedDate = (new \DateTime($data['date']))->format('Ymd');
  18245.         $csvContent Accounts::generateDxsoCsv($data,$formattedDate);
  18246.         return new Response(
  18247.             $csvContent,
  18248.             Response::HTTP_OK,
  18249.             [
  18250.                 'Content-Type' => 'text/csv',
  18251.                 'Content-Disposition' => 'attachment; filename="dxso_file.csv"',
  18252.             ]
  18253.         );
  18254.     }
  18255.     // =========================================================================
  18256.     // S2.6 — Invoice Variant Print Action
  18257.     // =========================================================================
  18258.     /**
  18259.      * Print a specific invoice variant (commercial / customs / lc / import / credit_note).
  18260.      *
  18261.      * Loads the same invoice data as PrintSalesInvoice but renders the
  18262.      * variant-specific template and registers in DocumentRegistry.
  18263.      *
  18264.      * Routes: print_invoice_commercial, print_invoice_customs, print_invoice_lc,
  18265.      *         print_invoice_import, print_credit_note
  18266.      */
  18267.     public function PrintInvoiceVariantAction(Request $request$id 0$invoiceVariant 'commercial')
  18268.     {
  18269.         $em   $this->getDoctrine()->getManager();
  18270.         $data SalesOrderM::GetSalesInvoiceDetails($em$id);
  18271.         // Ensure variant is valid
  18272.         $validVariants = ['commercial''customs''lc''import''credit_note'];
  18273.         if (!in_array($invoiceVariant$validVariants)) {
  18274.             $invoiceVariant 'commercial';
  18275.         }
  18276.         // Register in DocumentRegistry (S2.3) — non-blocking
  18277.         if (!empty($data['si_data'])) {
  18278.             try {
  18279.                 DocumentRegistry::register($em$invoiceVariant'SalesInvoice', (int)$id, [
  18280.                     'tenantId'       => $data['si_data']->getCompanyId(),
  18281.                     'customerId'     => $data['si_data']->getClientId(),
  18282.                     'projectId'      => $data['si_data']->getProjectId(),
  18283.                     'documentNumber' => isset($data['doc_hash']) ? $data['doc_hash'] : null,
  18284.                     'currency'       => $data['si_data']->getCurrency(),
  18285.                     'documentVariant'=> $invoiceVariant,
  18286.                     'createdBy'      => $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  18287.                 ]);
  18288.             } catch (\Exception $e) { /* non-blocking */ }
  18289.         }
  18290.         $company_data Company::getCompanyData($em$data['si_data']->getCompanyId());
  18291.         // Variant labels for print header
  18292.         $variantLabels = [
  18293.             'commercial' => 'Commercial Invoice',
  18294.             'customs'    => 'Customs Invoice',
  18295.             'lc'         => 'Letter of Credit Invoice',
  18296.             'import'     => 'Import Invoice',
  18297.             'credit_note'=> 'Credit Note',
  18298.         ];
  18299.         return $this->render('@Accounts/pages/print/print_invoice_variant.html.twig', [
  18300.             'page_title'      => $variantLabels[$invoiceVariant] . ' — ' . (isset($data['doc_hash']) ? $data['doc_hash'] : ''),
  18301.             'data'            => $data,
  18302.             'invoice_variant' => $invoiceVariant,
  18303.             'variant_label'   => $variantLabels[$invoiceVariant],
  18304.             'company_name'    => $company_data->getName(),
  18305.             'company_data'    => $company_data,
  18306.             'company_address' => $company_data->getAddress(),
  18307.             'company_image'   => $company_data->getImage(),
  18308.             'invoice_footer'  => $company_data->getInvoiceFooter(),
  18309.             'export'          => 'pdf,print',
  18310.         ]);
  18311.     }
  18312. }