<?php
namespace ApplicationBundle\Modules\Accounts\Controller;
use ApplicationBundle\ApplicationBundle;
use ApplicationBundle\Constants\AccountsConstant;
use ApplicationBundle\Constants\GeneralConstant;
use ApplicationBundle\Constants\HumanResourceConstant;
use ApplicationBundle\Constants\InventoryConstant;
use ApplicationBundle\Modules\Sales\Constants\SalesConstant;
use ApplicationBundle\Controller\GenericController;
use ApplicationBundle\Controller\PHPExcel_Cell;
use ApplicationBundle\Entity\AccCheck;
use ApplicationBundle\Entity\AccCostCentre;
use ApplicationBundle\Entity\AccSettings;
use ApplicationBundle\Entity\BankAccounts;
use ApplicationBundle\Entity\BankList;
use ApplicationBundle\Entity\Brs;
use ApplicationBundle\Entity\CheckFormat;
use ApplicationBundle\Entity\ExpenseInvoice;
use ApplicationBundle\Entity\FiscalClosing;
use ApplicationBundle\Entity\FundRequisition;
use ApplicationBundle\Entity\ReceiptCheck;
use ApplicationBundle\Entity\TaxConfig;
use ApplicationBundle\Helper\CountryTemplateResolver;
use ApplicationBundle\Helper\TaxMarkerLookup;
use ApplicationBundle\Helper\Generic;
use ApplicationBundle\Interfaces\SessionCheckInterface;
use ApplicationBundle\Modules\Accounts\Accounts;
use ApplicationBundle\Modules\Accounts\Service\AccountHeadPermissionService;
use ApplicationBundle\Modules\Accounts\Service\AccountHeadExternalMappingService;
use ApplicationBundle\Modules\Authentication\Constants\UserConstants; use ApplicationBundle\Modules\Api\Constants\ApiConstants;
use ApplicationBundle\Modules\FixedAsset\FixedAsset;
use ApplicationBundle\Modules\Inventory\Inventory;
use ApplicationBundle\Modules\Project\ProjectM;
use ApplicationBundle\Modules\Document\DocumentRegistry;
use ApplicationBundle\Modules\Purchase\Purchase;
use ApplicationBundle\Modules\Sales\Client;
use ApplicationBundle\Modules\Sales\SalesOrderM;
use ApplicationBundle\Modules\System\ApprovalFunction;
use ApplicationBundle\Modules\System\DeleteDocument;
use ApplicationBundle\Modules\System\DocValidation;
use ApplicationBundle\Modules\System\MiscActions;
use ApplicationBundle\Modules\System\System;
use ApplicationBundle\Modules\User\Company;
use ApplicationBundle\Modules\User\Users;
use CompanyGroupBundle\Entity\EntityFile;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Ps\PdfBundle\Annotation\Pdf;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\Process\Process;
use Symfony\Component\Routing\Generator\UrlGenerator;
use Symfony\Component\Validator\Constraints\Json;
//use Symfony\Bundle\FrameworkBundle\Console\Application;
//use Symfony\Component\Console\Input\ArrayInput;
//use Symfony\Component\Console\Output\NullOutput;
class AccountsController extends GenericController implements SessionCheckInterface
{
private function getAllocationReportFilters(Request $request)
{
return array(
'tag_type' => trim((string) $request->query->get('tag_type', '')),
'tag_value' => trim((string) $request->query->get('tag_value', '')),
'projectId' => (int) $request->query->get('projectId', 0),
'branchId' => (int) $request->query->get('branchId', 0),
'costCenterId' => (int) $request->query->get('costCenterId', 0),
);
}
private function getAllocationReportSupportData($em, Request $request)
{
$companyId = $this->getLoggedUserCompanyId($request);
$filters = $this->getAllocationReportFilters($request);
$summaryRows = $em->getRepository('ApplicationBundle\\Entity\\TransactionDetailAllocation')
->getAllocationSummary();
$tagTypes = [];
$tagValuesByType = [];
foreach ($summaryRows as $row) {
$type = strtolower(trim((string) ($row['tag_type'] ?? '')));
$value = trim((string) ($row['tag_value'] ?? ''));
if ($type === '' || $value === '') {
continue;
}
if (!isset($tagTypes[$type])) {
$tagTypes[$type] = array(
'id' => $type,
'text' => ucwords(str_replace(array('_', '-'), ' ', $type)),
);
}
if (!isset($tagValuesByType[$type])) {
$tagValuesByType[$type] = array();
}
$tagValuesByType[$type][$value] = array(
'id' => $value,
'text' => $value,
);
}
foreach ($tagValuesByType as $type => $values) {
$tagValuesByType[$type] = array_values($values);
}
return array(
'allocation_filters' => $filters,
'allocation_tag_types' => array_values($tagTypes),
'allocation_tag_values_by_type' => $tagValuesByType,
'project_list' => ProjectM::GetProjectList($em),
'branch_list' => Client::BranchList($em, $companyId),
'cost_centers' => Accounts::CostCenterList($em),
);
}
public function exportDatabase(Request $request)
{
$session = $request->getSession();
$gocDbName = $session->get(UserConstants::USER_DB_NAME);
$gocDbUser = $session->get(UserConstants::USER_DB_USER);
$gocDbPass = $session->get(UserConstants::USER_DB_PASS);
$gocDbHost = $session->get(UserConstants::USER_DB_HOST);
//// $connector = $this->container->get('application_connector');
// $connector = $this->applicationConnector;
// $connector->resetConnection(
// 'default',
// $gocDbName,
// $gocDbUser,
// $gocDbPass,
// $gocDbHost,
// $reset = false);
$process = new Process([
'mysqldump',
'-u',
$gocDbUser, // Replace with your DB username
'-p' . $gocDbPass, // Replace with your DB password
$gocDbName // Replace with your database name
]);
$process->setTimeout(3600); // Increase timeout if needed
$process->run();
if (!$process->isSuccessful()) {
return new Response('Database export failed: ' . $process->getErrorOutput(), Response::HTTP_INTERNAL_SERVER_ERROR);
}
// Get output of the process (SQL dump)
$sqlDump = $process->getOutput();
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/dbase_backup';
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
// Save to a file
$filePath = $upl_dir . 'database_dump.sql'; // Update this path
file_put_contents($filePath, $sqlDump);
return new Response('Database exported successfully to ' . $filePath);
}
public function importDatabase(Request $request)
{
$uploadedFile = $request->files->get('file');
if ($uploadedFile && $uploadedFile->isValid()) {
// Save uploaded file to a temporary location
$filePath = '/path/to/temp/import_file.sql'; // Update this path
$uploadedFile->move(dirname($filePath), basename($filePath));
$process = new Process([
'mysql',
'-u',
'your_db_user', // Replace with your DB username
'-p' . 'your_db_password', // Replace with your DB password
'your_db_name', // Replace with your database name
'<',
$filePath
]);
$process->run();
if (!$process->isSuccessful()) {
return new Response('Database import failed: ' . $process->getErrorOutput(), Response::HTTP_INTERNAL_SERVER_ERROR);
}
return new Response('Database imported successfully!');
}
return new Response('Invalid file or file not uploaded', Response::HTTP_BAD_REQUEST);
}
public function prePopulateDatabaseAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
System::prePopulateDatabase($em);
return new JsonResponse(array(
'success' => true,
));
}
public function selectDataAjaxAccHeadAction(Request $request, $queryStr = '',
$version = 'latest',
$identifier = '_default_',
$apiKey = '_ignore_'
)
{
$em = $this->getDoctrine()->getManager();
$em_goc = $this->getDoctrine()->getManager('company_group');
$companyId = 0;
$skipCurrentUserIdRestriction = $request->get('skipCurrentUserIdRestriction', 0);
$dataOnly = $request->get('dataOnly', 0);
$skipCurrentEmployeeIdRestriction = $request->get('skipCurrentEmployeeIdRestriction', 0);
$skipCurrentUserLoginIdRestriction = $request->get('skipCurrentUserLoginIdRestriction', 0);
$currentUserId = $request->getSession()->get(UserConstants::USER_ID, 0);
$currentEmployeeId = $request->getSession()->get(UserConstants::USER_EMPLOYEE_ID, 0);
$currentUserLoginIds = [];
if ($request->request->get('entity_group', 0)) {
$companyId = 0;
$em = $this->getDoctrine()->getManager('company_group');
} else {
if ($request->request->get('appId', 0) != 0) {
$gocEnabled = 0;
if ($this->container->hasParameter('entity_group_enabled'))
$gocEnabled = $this->container->getParameter('entity_group_enabled');
else
$gocEnabled = 1;
if ($gocEnabled == 1) {
$dataToConnect = System::changeDoctrineManagerByAppId(
$this->getDoctrine()->getManager('company_group'),
$gocEnabled,
$request->request->get('appId', 0)
);
if (!empty($dataToConnect)) {
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$dataToConnect['dbName'],
$dataToConnect['dbUser'],
$dataToConnect['dbPass'],
$dataToConnect['dbHost'],
$reset = true
);
$em = $this->getDoctrine()->getManager();
}
}
} else if ($request->getSession()->get(UserConstants::USER_APP_ID) != 0 && $request->getSession()->get(UserConstants::USER_APP_ID) != null) {
$gocEnabled = 0;
if ($this->container->hasParameter('entity_group_enabled'))
$gocEnabled = $this->container->getParameter('entity_group_enabled');
else
$gocEnabled = 1;
if ($gocEnabled == 1) {
$dataToConnect = System::changeDoctrineManagerByAppId(
$this->getDoctrine()->getManager('company_group'),
$gocEnabled,
$request->getSession()->get(UserConstants::USER_APP_ID)
);
if (!empty($dataToConnect)) {
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$dataToConnect['dbName'],
$dataToConnect['dbUser'],
$dataToConnect['dbPass'],
$dataToConnect['dbHost'],
$reset = true
);
$em = $this->getDoctrine()->getManager();
}
}
}
$companyId = $this->getLoggedUserCompanyId($request);
}
$configData = [];
$isSingleDataset = 1;
$dataSet = $request->request->has('dataset') ? $request->request->get('dataset') : [];
if (is_string($dataSet)) $dataSet = json_decode($dataSet, true);
$valuePairs = $request->get('valuePairs', []);
if (is_string($valuePairs)) $valuePairs = json_decode($valuePairs, true);
$allResult = [];
$datasetFromConfig = [];
if ($identifier != '_default_') {
$config_file = $this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json';
if (!file_exists($config_file)) {
} else {
$fileText = file_get_contents($config_file);
//now replace any value pairs
foreach ($valuePairs as $kkeeyy => $vvaalluuee) {
if (is_array($vvaalluuee)) {
if (isset($vvaalluuee['value']) && isset($vvaalluuee['type'])) {
if ($vvaalluuee['type'] == 'array') $fileText = str_ireplace('_' . $kkeeyy . '_', json_encode($vvaalluuee['value']), $fileText);
if ($vvaalluuee['type'] == 'value') $fileText = str_ireplace('_' . $kkeeyy . '_', $vvaalluuee['value'], $fileText);
if ($vvaalluuee['type'] == 'text') $fileText = str_ireplace('_' . $kkeeyy . '_', $vvaalluuee['value'], $fileText);
} else {
$fileText = str_ireplace('_' . $kkeeyy . '_', json_encode($vvaalluuee), $fileText);
}
}
$fileText = str_ireplace('_' . $kkeeyy . '_', $vvaalluuee, $fileText);
}
$fileText = str_ireplace('_query_', $request->get('query', $queryStr), $fileText);
$fileText = str_ireplace('_itemLimit_', $request->get('itemLimit', '_all_'), $fileText);
$fileText = str_ireplace('_offset_', $request->get('offset', ($request->get('itemLimit', 10))*($request->get('page', 1)-1)), $fileText);
if (!(strpos($fileText, '_CURRENT_USER_LOGIN_IDS_') === false) && $skipCurrentUserLoginIdRestriction == 0) {
$userInfo = [];
if ($request->getSession()->get(UserConstants::USER_TYPE, 0) == UserConstants::USER_TYPE_APPLICANT) {
$userInfo = $em_goc->getRepository('CompanyGroupBundle\\Entity\\EntityLoginLog')->findBy(
array('userId' => $currentUserId)
);
} else {
$userInfo = $em->getRepository('ApplicationBundle\\Entity\\SysLoginLog')->findBy(
array('userId' => $currentUserId)
);
}
foreach ($userInfo as $uLogininfo) {
$currentUserLoginIds[] = $uLogininfo->getLoginId();
}
$fileText = str_ireplace('_CURRENT_USER_LOGIN_IDS_', json_encode($currentUserLoginIds), $fileText);
} else {
$fileText = str_ireplace('_CURRENT_USER_LOGIN_IDS_', '_EMPTY_', $fileText);
}
if (!(strpos($fileText, '_CURRENT_USER_ID_') === false) && $skipCurrentUserIdRestriction == 0) {
$fileText = str_ireplace('_CURRENT_USER_ID_', $currentUserId, $fileText);
} else {
$fileText = str_ireplace('_CURRENT_USER_ID_', '_EMPTY_', $fileText);
}
if (!(strpos($fileText, '_CURRENT_USER_EMPLOYEE_ID_') === false) && $skipCurrentEmployeeIdRestriction == 0) {
if ((strpos($fileText, 'skipCurrentEmployeeIdRestriction') === false)) {
$fileText = str_ireplace('_CURRENT_USER_EMPLOYEE_ID_', $currentEmployeeId, $fileText);
} else {
$fileText = str_ireplace('_CURRENT_USER_EMPLOYEE_ID_', '_EMPTY_', $fileText);
}
} else {
$fileText = str_ireplace('_CURRENT_USER_EMPLOYEE_ID_', '_EMPTY_', $fileText);
}
if ($fileText)
$datasetFromConfig = json_decode($fileText, true);
$skipCurrentUserIdRestriction = isset($datasetFromConfig['skipCurrentUserIdRestriction']) ? $datasetFromConfig['skipCurrentUserIdRestriction'] : $skipCurrentUserIdRestriction;
$skipCurrentEmployeeIdRestriction = isset($datasetFromConfig['skipCurrentEmployeeIdRestriction']) ? $datasetFromConfig['skipCurrentEmployeeIdRestriction'] : $skipCurrentEmployeeIdRestriction;
$skipCurrentUserLoginIdRestriction = isset($datasetFromConfig['skipCurrentUserLoginIdRestriction']) ? $datasetFromConfig['skipCurrentUserLoginIdRestriction'] : $skipCurrentUserLoginIdRestriction;
}
}
if ($dataSet == null) $dataSet = [];
// return new JsonResponse(array(
// 'queryStr'=>$queryStr
// ));
if (!empty($datasetFromConfig)) {
if (isset($datasetFromConfig['tableName'])) {
$isSingleDataset = 1;
$dataSet[] = $datasetFromConfig;
} else {
if (count($datasetFromConfig) == 1)
$isSingleDataset = 1;
$dataSet = $datasetFromConfig;
}
}
if (empty($dataSet)) {
$isSingleDataset = 1;
$singleDataSet = array(
"valueField" => $request->request->has('valueField') ? $request->request->get('valueField') : 'id',
"query" => $request->get('query', $queryStr),
"headMarkers" => $request->get('headMarkers', ''),
"headMarkersStrictMatch" => $request->get('headMarkersStrictMatch', 0),
"itemLimit" => $request->request->has('itemLimit') ? $request->request->get('itemLimit') : 25,
"selectorId" => $request->request->has('selectorId') ? $request->request->get('selectorId') : '_NONE_',
"textField" => $request->request->has('textField') ? $request->request->get('textField') : 'name',
"tableName" => $request->request->has('tableName') ? $request->request->get('tableName') : '',
"isMultiple" => $request->request->has('isMultiple') ? $request->request->get('isMultiple') : 0,
"orConditions" => $request->request->has('orConditions') ? $request->request->get('orConditions') : [],
"andConditions" => $request->request->has('andConditions') ? $request->request->get('andConditions') : [],
"andOrConditions" => $request->request->has('andOrConditions') ? $request->request->get('andOrConditions') : [],
"mustConditions" => $request->request->has('mustConditions') ? $request->request->get('mustConditions') : [],
"joinTableData" => $request->request->has('joinTableData') ? $request->request->get('joinTableData') : [],
"renderTextFormat" => $request->request->has('renderTextFormat') ? $request->request->get('renderTextFormat') : '',
"setDataForSingle" => $request->request->has('setDataForSingle') ? $request->request->get('setDataForSingle') : 0,
"dataId" => $request->request->has('dataId') ? $request->request->get('dataId') : 0,
"lastChildrenOnly" => $request->request->has('lastChildrenOnly') ? $request->request->get('lastChildrenOnly') : 0,
"parentOnly" => $request->request->has('parentOnly') ? $request->request->get('parentOnly') : 0,
"parentIdField" => $request->request->has('parentIdField') ? $request->request->get('parentIdField') : 'parent_id',
"skipDefaultCompanyId" => $request->request->has('skipDefaultCompanyId') ? $request->request->get('skipDefaultCompanyId') : 1,
"offset" => $request->request->has('offset') ? $request->request->get('offset') : 0,
"returnTotalMatchedEntriesFlag" => $request->request->has('returnTotalMatched') ? $request->request->get('returnTotalMatched') : 0,
"nextOffset" => 0,
"totalMatchedEntries" => 0,
"convertToObject" => $request->request->has('convertToObject') ? $request->request->get('convertToObject') : [],
"convertDateToStringFieldList" => $request->request->has('convertDateToStringFieldList') ? $request->request->get('convertDateToStringFieldList') : [],
"orderByConditions" => $request->request->has('orderByConditions') ? $request->request->get('orderByConditions') : [],
"convertToUrl" => $request->request->has('convertToUrl') ? $request->request->get('convertToUrl') : [],
"fullPathList" => $request->request->has('fullPathList') ? $request->request->get('fullPathList') : [],
"ret_data" => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
);
$dataSet[] = $singleDataSet;
}
// $lastResult = [
// 'identifier' => $identifier,
// 'dataSet' => $dataSet,
// ];
// return new JsonResponse($lastResult);
$userId = $request->getSession()->get(UserConstants::USER_ID);
// public static function selectDataSystem($em, $queryStr = '_EMPTY_', $data = [],$userId=0)
foreach ($dataSet as $dsIndex => $dataConfig) {
$companyId = 0;
$queryStringIndividual = $queryStr;
$data = [];
$data_by_id = [];
$setValueArray = [];
$silentChangeSelectize = 0;
$setValue = 0;
$setValueType = 0;// 0 for id , 1 for query
$selectAll = 0;
if ($queryStringIndividual == '_EMPTY_')
$queryStringIndividual = '';
if (isset($dataConfig['query']))
$queryStringIndividual = $dataConfig['query'];
if ($queryStringIndividual == '_EMPTY_')
$queryStringIndividual = '';
$queryStringIndividual = str_replace('_FSLASH_', '/', $queryStringIndividual);
if ($queryStringIndividual === '#setValue:') {
$queryStringIndividual = '';
}
if (!(strpos($queryStringIndividual, '_silent_change_') === false)) {
$silentChangeSelectize = 1;
$queryStringIndividual = str_ireplace('_silent_change_', '', $queryStringIndividual);
}
if (!(strpos($queryStringIndividual, '#setValue:') === false)) {
$setValueArrayBeforeFilter = explode(',', str_replace('#setValue:', '', $queryStringIndividual));
foreach ($setValueArrayBeforeFilter as $svf) {
if ($svf == '_ALL_') {
$selectAll = 1;
$setValueArray = [];
continue;
}
if (is_numeric($svf)) {
$setValueArray[] = ($svf * 1);
$setValue = $svf * 1;
}
}
$queryStringIndividual = '';
}
$valueField = isset($dataConfig['valueField']) ? $dataConfig['valueField'] : 'id';
$headMarkers = isset($dataConfig['headMarkers']) ? $dataConfig['headMarkers'] : ''; //Special Field
$headMarkersStrictMatch = isset($dataConfig['headMarkersStrictMatch']) ? $dataConfig['headMarkersStrictMatch'] : 0; //Special Field
$itemLimit = isset($dataConfig['itemLimit']) ? $dataConfig['itemLimit'] : 25;
$selectorId = isset($dataConfig['selectorId']) ? $dataConfig['selectorId'] : '_NONE_';
$textField = isset($dataConfig['textField']) ? $dataConfig['textField'] : 'name';
$table = isset($dataConfig['tableName']) ? $dataConfig['tableName'] : '';
$isMultiple = isset($dataConfig['isMultiple']) ? $dataConfig['isMultiple'] : 0;
$orConditions = isset($dataConfig['orConditions']) ? $dataConfig['orConditions'] : [];
$andConditions = isset($dataConfig['andConditions']) ? $dataConfig['andConditions'] : [];
$andOrConditions = isset($dataConfig['andOrConditions']) ? $dataConfig['andOrConditions'] : [];
$mustConditions = isset($dataConfig['mustConditions']) ? $dataConfig['mustConditions'] : [];
$joinTableData = isset($dataConfig['joinTableData']) ? $dataConfig['joinTableData'] : [];
$renderTextFormat = isset($dataConfig['renderTextFormat']) ? $dataConfig['renderTextFormat'] : '';
$setDataForSingle = isset($dataConfig['setDataForSingle']) ? $dataConfig['setDataForSingle'] : 0;
$dataId = isset($dataConfig['dataId']) ? $dataConfig['dataId'] : 0;
$lastChildrenOnly = isset($dataConfig['lastChildrenOnly']) ? $dataConfig['lastChildrenOnly'] : 0;
$parentOnly = isset($dataConfig['parentOnly']) ? $dataConfig['parentOnly'] : 0;
$parentIdField = isset($dataConfig['parentIdField']) ? $dataConfig['parentIdField'] : 'parent_id';
$skipDefaultCompanyId = isset($dataConfig['skipDefaultCompanyId']) ? $dataConfig['skipDefaultCompanyId'] : 1;
$offset = isset($dataConfig['offset']) ? $dataConfig['offset'] : 0;
$returnTotalMatchedEntriesFlag = isset($dataConfig['returnTotalMatched']) ? $dataConfig['returnTotalMatched'] : 0;
$nextOffset = 0;
$totalMatchedEntries = 0;
$convertToObjectFieldList = isset($dataConfig['convertToObject']) ? $dataConfig['convertToObject'] : [];
$convertDateToStringFieldList = isset($dataConfig['convertDateToStringFieldList']) ? $dataConfig['convertDateToStringFieldList'] : [];
$orderByConditions = isset($dataConfig['orderByConditions']) ? $dataConfig['orderByConditions'] : [];
$convertToUrl = isset($dataConfig['convertToUrl']) ? $dataConfig['convertToUrl'] : [];
$fullPathList = isset($dataConfig['fullPathList']) ? $dataConfig['fullPathList'] : [];
if (is_string($andConditions)) $andConditions = json_decode($andConditions, true);
if (is_string($orConditions)) $orConditions = json_decode($orConditions, true);
if (is_string($andOrConditions)) $andOrConditions = json_decode($andOrConditions, true);
if (is_string($mustConditions)) $mustConditions = json_decode($mustConditions, true);
if (is_string($joinTableData)) $joinTableData = json_decode($joinTableData, true);
if (is_string($convertToObjectFieldList)) $convertToObjectFieldList = json_decode($convertToObjectFieldList, true);
if (is_string($orderByConditions)) $orderByConditions = json_decode($orderByConditions, true);
if (is_string($convertToUrl)) $convertToUrl = json_decode($convertToUrl, true);
if (is_string($fullPathList)) $fullPathList = json_decode($fullPathList, true);
// return new JsonResponse(array(
// 'dataSet'=>$dataSet,
// 'dataConfig'=>$dataConfig,
// 'hi'=>$this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json',
// 'hiD'=>file_get_contents($this->container->getParameter('kernel.root_dir') . '/../src/ApplicationBundle/Resources/config/api/' . $identifier . 'Config.json')
// ));
if ($table == '') {
$lastResult = array(
'success' => false,
'currentTs' => (new \Datetime())->format('U'),
'isMultiple' => $isMultiple,
'setValueArray' => $setValueArray,
'setValue' => $setValue,
'data' => $data,
'dataId' => $dataId,
'selectorId' => $selectorId,
'dataById' => $data_by_id,
'selectedId' => 0,
'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
);
} else {
$restrictionData = array(
// 'table'=>'relevantField in restriction'
'warehouse_action' => 'warehouseActionIds',
'branch' => 'branchIds',
'warehouse' => 'warehouseIds',
'production_process_settings' => 'productionProcessIds',
);
$restrictionIdList = [];
$filterQryForCriteria = "select ";
$selectQry = "";
// $selectQry=" `$table`.* ";
$selectFieldList = isset($dataConfig['selectFieldList']) ? $dataConfig['selectFieldList'] : ['*'];
$selectPrefix = isset($dataConfig['selectPrefix']) ? $dataConfig['selectPrefix'] : '';
if (is_string($selectFieldList)) $selectFieldList = json_decode($selectFieldList, true);
foreach ($selectFieldList as $selField) {
if ($selectQry != '')
$selectQry .= ", ";
if ($selField == '*')
$selectQry .= " `$table`.$selField ";
else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
if ($selectPrefix == '')
$selectQry .= " count(*) ";
else
$selectQry .= (" count(* ) $selectPrefix" . "_RESULT_COUNT_ ");
} else {
if ($selectPrefix == '')
$selectQry .= " `$table`.`$selField` ";
else
$selectQry .= (" `$table`.`$selField` $selectPrefix" . "$selField ");
}
}
$joinQry = " from $table ";
// $filterQryForCriteria = "select * from $table ";
$joinMustString = '';
$joinOrString = '';
$joinAndString = '';
$joinAndOrString = '';
foreach ($joinTableData as $joinIndex => $joinTableDatum) {
// $conditionStr.=' 1=1 ';
$joinTableName = isset($joinTableDatum['tableName']) ? $joinTableDatum['tableName'] : '=';
$joinTableAlias = $joinTableName . '_' . $joinIndex;
$joinTablePrimaryField = isset($joinTableDatum['joinFieldPrimary']) ? $joinTableDatum['joinFieldPrimary'] : ''; //field of main table
$joinTableOnField = isset($joinTableDatum['joinOn']) ? $joinTableDatum['joinOn'] : ''; //field of joining table
$fieldJoinType = isset($joinTableDatum['fieldJoinType']) ? $joinTableDatum['fieldJoinType'] : '=';
$tableJoinType = isset($joinTableDatum['tableJoinType']) ? $joinTableDatum['tableJoinType'] : 'join';//or inner join
$selectFieldList = isset($joinTableDatum['selectFieldList']) ? $joinTableDatum['selectFieldList'] : ['*'];
$selectPrefix = isset($joinTableDatum['selectPrefix']) ? $joinTableDatum['selectPrefix'] : '';
$joinMustConditions = isset($joinTableDatum['joinMustConditions']) ? $joinTableDatum['joinMustConditions'] : [];
$joinAndConditions = isset($joinTableDatum['joinAndConditions']) ? $joinTableDatum['joinAndConditions'] : [];
$joinAndOrConditions = isset($joinTableDatum['joinAndOrConditions']) ? $joinTableDatum['joinAndOrConditions'] : [];
$joinOrConditions = isset($joinTableDatum['joinOrConditions']) ? $joinTableDatum['joinOrConditions'] : [];
if (is_string($joinAndConditions)) $joinAndConditions = json_decode($joinAndConditions, true);
if (is_string($joinMustConditions)) $joinMustConditions = json_decode($joinMustConditions, true);
if (is_string($joinAndOrConditions)) $joinAndOrConditions = json_decode($joinAndOrConditions, true);
if (is_string($joinOrConditions)) $joinOrConditions = json_decode($joinOrConditions, true);
foreach ($selectFieldList as $selField) {
if ($selField == '*')
$selectQry .= ", `$joinTableAlias`.$selField ";
else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
if ($selectPrefix == '')
$selectQry .= ", count(`$joinTableAlias`." . $joinTableOnField . ") ";
else
$selectQry .= (", count(`$joinTableAlias`." . $joinTableOnField . ") $selectPrefix" . "_RESULT_COUNT_ ");
} else {
if ($selectPrefix == '')
$selectQry .= ", `$joinTableAlias`.`$selField` ";
else
$selectQry .= (", `$joinTableAlias`.`$selField` $selectPrefix" . "$selField ");
}
}
$joinQry .= " $tableJoinType $joinTableName $joinTableAlias on ";
// if($joinTablePrimaryField!='')
// $joinQry .= " `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
// $joinAndString = '';
$joinMustString = '';
if ($joinTablePrimaryField != '')
$joinQry .= " `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
foreach ($joinMustConditions as $mustCondition) {
// $conditionStr.=' 1=1 ';
$ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
$cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
$aliasInCondition = $table;
if (!(strpos($cfield, '.') === false)) {
$fullCfieldArray = explode('.', $cfield);
$aliasInCondition = $fullCfieldArray[0];
$cfield = $fullCfieldArray[1];
}
$cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStringIndividual;
if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
if ($joinMustString != '')
$joinMustString .= " and ";
if ($ctype == 'like') {
$joinMustString .= ("`$joinTableAlias`.$cfield like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($joinMustString != '')
$joinMustString .= " and ";
$joinMustString .= ("`$joinTableAlias`.$cfield like '%" . $word . "%' ");
}
} else if ($ctype == 'not like') {
$joinMustString .= ("`$joinTableAlias`.$cfield not like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($joinMustString != '')
$joinMustString .= " and ";
$joinMustString .= ("`$joinTableAlias`.$cfield not like '%" . $word . "%' ");
}
} else if ($ctype == 'not_in') {
$joinMustString .= " ( ";
if (in_array('null', $cvalue)) {
$joinMustString .= " `$joinTableAlias`.$cfield is not null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$joinMustString .= " and ";
}
if (in_array('', $cvalue)) {
$joinMustString .= "`$joinTableAlias`.$cfield != '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$joinMustString .= " and ";
}
$joinMustString .= "`$joinTableAlias`.$cfield not in (" . implode(',', $cvalue) . ") ) ";
} else if ($ctype == 'in') {
if (in_array('null', $cvalue)) {
$joinMustString .= "`$joinTableAlias`.$cfield is null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$joinMustString .= " and ";
}
if (in_array('', $cvalue)) {
$joinMustString .= "`$joinTableAlias`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$joinMustString .= " and ";
}
$joinMustString .= "`$joinTableAlias`.$cfield in (" . implode(',', $cvalue) . ") ";
} else if ($ctype == '=') {
// if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
// $fullCfieldArray = explode('.', $cfield);
// $aliasInCondition = $fullCfieldArray[0];
// $cfield = $fullCfieldArray[1];
// }
if ($cvalue == 'null' || $cvalue == 'Null')
$joinMustString .= "`$joinTableAlias`.$cfield is null ";
else
$joinMustString .= "`$joinTableAlias`.$cfield = $cvalue ";
} else if ($ctype == '!=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$joinMustString .= "`$joinTableAlias`.$cfield is not null ";
else
$joinMustString .= "`$joinTableAlias`.$cfield != $cvalue ";
} else {
if (is_string($cvalue))
$joinMustString .= "`$joinTableAlias`.$cfield $ctype '" . $cvalue . "' ";
else
$joinMustString .= "`$joinTableAlias`.$cfield $ctype " . $cvalue . " ";
}
}
}
// if ($joinMustString != '') {
// if ($conditionStr != '')
// $conditionStr .= (" and (" . $joinMustString . ") ");
// else
// $conditionStr .= (" (" . $joinMustString . ") ");
// }
// if ($joinMustString != '') {
// $joinQry .= (' and ' . $joinMustString);
//// $joinQry.=' and (';
// }
$mustBracketDone = 0;
// if ($joinTablePrimaryField != '')
// $joinAndString .= " `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
foreach ($joinAndConditions as $andCondition) {
// $conditionStr.=' 1=1 ';
$ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
$cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
$aliasInCondition = $table;
if (!(strpos($cfield, '.') === false)) {
$fullCfieldArray = explode('.', $cfield);
$aliasInCondition = $fullCfieldArray[0];
$cfield = $fullCfieldArray[1];
}
$cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStringIndividual;
if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
if ($joinAndString != '')
$joinAndString .= " and ";
if ($ctype == 'like') {
$joinAndString .= ("`$joinTableAlias`.$cfield like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($joinAndString != '')
$joinAndString .= " and ";
$joinAndString .= ("`$joinTableAlias`.$cfield like '%" . $word . "%' ");
}
} else if ($ctype == 'not like') {
$joinAndString .= ("`$joinTableAlias`.$cfield not like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($joinAndString != '')
$joinAndString .= " and ";
$joinAndString .= ("`$joinTableAlias`.$cfield not like '%" . $word . "%' ");
}
} else if ($ctype == 'not_in') {
$joinAndString .= " ( ";
if (in_array('null', $cvalue)) {
$joinAndString .= " `$joinTableAlias`.$cfield is not null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$joinAndString .= " and ";
}
if (in_array('', $cvalue)) {
$joinAndString .= "`$joinTableAlias`.$cfield != '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$joinAndString .= " and ";
}
$joinAndString .= "`$joinTableAlias`.$cfield not in (" . implode(',', $cvalue) . ") ) ";
} else if ($ctype == 'in') {
if (in_array('null', $cvalue)) {
$joinAndString .= "`$joinTableAlias`.$cfield is null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$joinAndString .= " and ";
}
if (in_array('', $cvalue)) {
$joinAndString .= "`$joinTableAlias`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$joinAndString .= " and ";
}
$joinAndString .= "`$joinTableAlias`.$cfield in (" . implode(',', $cvalue) . ") ";
} else if ($ctype == '=') {
// if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
// $fullCfieldArray = explode('.', $cfield);
// $aliasInCondition = $fullCfieldArray[0];
// $cfield = $fullCfieldArray[1];
// }
if ($cvalue == 'null' || $cvalue == 'Null')
$joinAndString .= "`$joinTableAlias`.$cfield is null ";
else
$joinAndString .= "`$joinTableAlias`.$cfield = $cvalue ";
} else if ($ctype == '!=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$joinAndString .= "`$joinTableAlias`.$cfield is not null ";
else
$joinAndString .= "`$joinTableAlias`.$cfield != $cvalue ";
} else {
if (is_string($cvalue))
$joinAndString .= "`$joinTableAlias`.$cfield $ctype '" . $cvalue . "' ";
else
$joinAndString .= "`$joinTableAlias`.$cfield $ctype " . $cvalue . " ";
}
}
}
// if ($joinAndString != '') {
// if ($conditionStr != '')
// $conditionStr .= (" and (" . $joinAndString . ") ");
// else
// $conditionStr .= (" (" . $joinAndString . ") ");
// }
// if ($joinAndString != '') {
// if ($joinMustString != '' && $mustBracketDone == 0) {
// $joinQry .= ' and (';
// $mustBracketDone = 1;
// }
//
//
// if ($joinQry != '')
// $joinQry .= (" and (" . $joinAndString . ") ");
// else
// $joinQry .= (" (" . $joinAndString . ") ");
//
// }
foreach ($joinAndOrConditions as $andOrCondition) {
// $conditionStr.=' 1=1 ';
$ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
$cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
$aliasInCondition = $table;
if (!(strpos($cfield, '.') === false)) {
$fullCfieldArray = explode('.', $cfield);
$aliasInCondition = $fullCfieldArray[0];
$cfield = $fullCfieldArray[1];
}
$cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStringIndividual;
if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
if ($joinAndOrString != '')
$joinAndOrString .= " or ";
if ($ctype == 'like') {
$joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($joinAndOrString != '')
$joinAndOrString .= " or ";
$joinAndOrString .= ("`$joinTableAlias`.$cfield like '%" . $word . "%' ");
}
} else if ($ctype == 'not like') {
$joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($joinAndOrString != '')
$joinAndOrString .= " or ";
$joinAndOrString .= ("`$joinTableAlias`.$cfield not like '%" . $word . "%' ");
}
} else if ($ctype == 'not_in') {
$joinAndOrString .= " ( ";
if (in_array('null', $cvalue)) {
$joinAndOrString .= " `$joinTableAlias`.$cfield is not null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$joinAndOrString .= " or ";
}
if (in_array('', $cvalue)) {
$joinAndOrString .= "`$joinTableAlias`.$cfield != '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$joinAndOrString .= " or ";
}
$joinAndOrString .= "`$joinTableAlias`.$cfield not in (" . implode(',', $cvalue) . ") ) ";
} else if ($ctype == 'in') {
if (in_array('null', $cvalue)) {
$joinAndOrString .= "`$joinTableAlias`.$cfield is null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$joinAndOrString .= " or ";
}
if (in_array('', $cvalue)) {
$joinAndOrString .= "`$joinTableAlias`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$joinAndOrString .= " or ";
}
$joinAndOrString .= "`$joinTableAlias`.$cfield in (" . implode(',', $cvalue) . ") ";
} else if ($ctype == '=') {
// if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
// $fullCfieldArray = explode('.', $cfield);
// $aliasInCondition = $fullCfieldArray[0];
// $cfield = $fullCfieldArray[1];
// }
if ($cvalue == 'null' || $cvalue == 'Null')
$joinAndOrString .= "`$joinTableAlias`.$cfield is null ";
else
$joinAndOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
} else if ($ctype == '!=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$joinAndOrString .= "`$joinTableAlias`.$cfield is not null ";
else
$joinAndOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
} else {
if (is_string($cvalue))
$joinAndOrString .= "`$joinTableAlias`.$cfield $ctype '" . $cvalue . "' ";
else
$joinAndOrString .= "`$joinTableAlias`.$cfield $ctype " . $cvalue . " ";
}
}
}
// if ($joinAndOrString != '')
// $joinQry .= $joinAndOrString;
// if ($joinAndOrString != '') {
// if ($joinMustString != '' && $mustBracketDone == 0) {
// $joinQry .= ' and (';
// $mustBracketDone = 1;
// }
//
//
// if ($joinQry != '')
// $joinQry .= (" and (" . $joinAndOrString . ") ");
// else
// $joinQry .= (" (" . $joinAndOrString . ") ");
// }
//pika
// $joinOrString = "";
foreach ($joinOrConditions as $orCondition) {
// $conditionStr.=' 1=1 ';
$ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
$cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
$aliasInCondition = $table;
if (!(strpos($cfield, '.') === false)) {
$fullCfieldArray = explode('.', $cfield);
$aliasInCondition = $fullCfieldArray[0];
$cfield = $fullCfieldArray[1];
}
$cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStringIndividual;
if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
if ($joinOrString != '' || $joinAndString != '' || $joinMustString != '')
$joinOrString .= " or ";
if ($ctype == 'like') {
$joinOrString .= ("`$joinTableAlias`.$cfield like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($joinOrString != '')
$joinOrString .= " or ";
$joinOrString .= ("`$joinTableAlias`.$cfield like '%" . $word . "%' ");
}
} else if ($ctype == 'not like') {
$joinOrString .= ("`$joinTableAlias`.$cfield not like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($joinOrString != '')
$joinOrString .= " or ";
$joinOrString .= ("`$joinTableAlias`.$cfield not like '%" . $word . "%' ");
}
} else if ($ctype == 'not_in') {
$joinOrString .= " ( ";
if (in_array('null', $cvalue)) {
$joinOrString .= " `$joinTableAlias`.$cfield is not null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$joinOrString .= " or ";
}
if (in_array('', $cvalue)) {
$joinOrString .= "`$joinTableAlias`.$cfield != '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$joinOrString .= " or ";
}
$joinOrString .= "`$joinTableAlias`.$cfield not in (" . implode(',', $cvalue) . ") ) ";
} else if ($ctype == 'in') {
if (in_array('null', $cvalue)) {
$joinOrString .= "`$joinTableAlias`.$cfield is null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$joinOrString .= " or ";
}
if (in_array('', $cvalue)) {
$joinOrString .= "`$joinTableAlias`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$joinOrString .= " or ";
}
$joinOrString .= "`$joinTableAlias`.$cfield in (" . implode(',', $cvalue) . ") ";
} else if ($ctype == '=') {
// if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
// $fullCfieldArray = explode('.', $cfield);
// $aliasInCondition = $fullCfieldArray[0];
// $cfield = $fullCfieldArray[1];
// }
if ($cvalue == 'null' || $cvalue == 'Null')
$joinOrString .= "`$joinTableAlias`.$cfield is null ";
else
$joinOrString .= "`$joinTableAlias`.$cfield = $cvalue ";
} else if ($ctype == '!=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$joinOrString .= "`$joinTableAlias`.$cfield is not null ";
else
$joinOrString .= "`$joinTableAlias`.$cfield != $cvalue ";
} else {
if (is_string($cvalue))
$joinOrString .= "`$joinTableAlias`.$cfield $ctype '" . $cvalue . "' ";
else
$joinOrString .= "`$joinTableAlias`.$cfield $ctype " . $cvalue . " ";
}
}
}
// if ($joinOrString != '')
// $joinQry .= $joinOrString;
// if ($joinOrString != '') {
// if ($joinMustString != '' && $mustBracketDone == 0) {
// $joinQry .= ' and (';
// $mustBracketDone = 1;
// }
// if ($joinQry != '')
// $joinQry .= (" or (" . $joinOrString . ") ");
// else
// $joinQry .= (" (" . $joinOrString . ") ");
// }
//
// if ($joinMustString != '' && $mustBracketDone == 1) {
// $joinQry .= ' ) ';
//
// }
//
// $joinQry .= " `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
}
$filterQryForCriteria .= $selectQry;
$filterQryForCriteria .= $joinQry;
if ($skipDefaultCompanyId == 0 && $companyId != 0 && !isset($dataConfig['entity_group']))
$filterQryForCriteria .= " where `$table`.`company_id`=" . $companyId . " ";
else
$filterQryForCriteria .= " where 1=1 ";
$conditionStr = "";
$aliasInCondition = $table;
if ($headMarkers != '' && $table == 'acc_accounts_head') {
$markerList = explode(',', $headMarkers);
$spMarkerQry = "SELECT distinct accounts_head_id FROM acc_accounts_head where 1=1 ";
$markerPassedHeads = [];
foreach ($markerList as $mrkr) {
$spMarkerQry .= " and marker_hash like '%" . $mrkr . "%'";
}
$spStmt = $em->getConnection()->fetchAllAssociative($spMarkerQry);
$spStmtResults = $spStmt;
foreach ($spStmtResults as $ggres) {
$markerPassedHeads[] = $ggres['accounts_head_id'];
}
if (!empty($markerPassedHeads)) {
if ($conditionStr != '')
$conditionStr .= " and (";
else
$conditionStr .= " (";
if ($headMarkersStrictMatch != 1) {
foreach ($markerPassedHeads as $mh) {
$conditionStr .= " `$aliasInCondition`.`path_tree` like'%/" . $mh . "/%' or ";
}
}
$conditionStr .= " `$aliasInCondition`.`accounts_head_id` in (" . implode(',', $markerPassedHeads) . ") ";
$conditionStr .= " )";
}
}
if (isset($restrictionData[$table])) {
$userRestrictionData = Users::getUserApplicationAccessSettings($em, $userId)['options'];
if (isset($userRestrictionData[$restrictionData[$table]])) {
$restrictionIdList = $userRestrictionData[$restrictionData[$table]];
if ($restrictionIdList == null)
$restrictionIdList = [];
}
if (!empty($restrictionIdList)) {
if ($conditionStr != '')
$conditionStr .= " and ";
$conditionStr .= " `$table`.$valueField in (" . implode(',', $restrictionIdList) . ") ";
}
}
// $aliasInCondition = $table;
if (!empty($setValueArray) || $selectAll == 1) {
if (!empty($setValueArray)) {
if ($conditionStr != '')
$conditionStr .= " and ";
$conditionStr .= " `$aliasInCondition`.$valueField in (" . implode(',', $setValueArray) . ") ";
}
} else {
// $andString = '';
$andString = $joinAndString; /////New testing
foreach ($andConditions as $andCondition) {
// $conditionStr.=' 1=1 ';
$ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
$cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
$aliasInCondition = $table;
if (!(strpos($cfield, '.') === false)) {
$fullCfieldArray = explode('.', $cfield);
$aliasInCondition = $fullCfieldArray[0];
$cfield = $fullCfieldArray[1];
}
$cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStringIndividual;
if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
if ($andString != '')
$andString .= " and ";
if ($ctype == 'like') {
$andString .= ("`$aliasInCondition`.$cfield like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($andString != '')
$andString .= " and ";
$andString .= ("`$aliasInCondition`.$cfield like '%" . $word . "%' ");
}
} else if ($ctype == 'not like') {
$andString .= ("`$aliasInCondition`.$cfield not like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($andString != '')
$andString .= " and ";
$andString .= ("`$aliasInCondition`.$cfield not like '%" . $word . "%' ");
}
} else if ($ctype == 'not_in') {
$andString .= " ( ";
if (in_array('null', $cvalue)) {
$andString .= " `$aliasInCondition`.$cfield is not null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$andString .= " and ";
}
if (in_array('', $cvalue)) {
$andString .= "`$aliasInCondition`.$cfield != '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$andString .= " and ";
}
$andString .= "`$aliasInCondition`.$cfield not in (" . implode(',', $cvalue) . ") ) ";
} else if ($ctype == 'in') {
if (in_array('null', $cvalue)) {
$andString .= "`$aliasInCondition`.$cfield is null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$andString .= " and ";
}
if (in_array('', $cvalue)) {
$andString .= "`$aliasInCondition`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$andString .= " and ";
}
$andString .= "`$aliasInCondition`.$cfield in (" . implode(',', $cvalue) . ") ";
} else if ($ctype == '=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$andString .= "`$aliasInCondition`.$cfield is null ";
else
$andString .= "`$aliasInCondition`.$cfield = $cvalue ";
} else if ($ctype == '!=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$andString .= "`$aliasInCondition`.$cfield is not null ";
else
$andString .= "`$aliasInCondition`.$cfield != $cvalue ";
} else {
if (is_string($cvalue))
$andString .= "`$aliasInCondition`.$cfield $ctype '" . $cvalue . "' ";
else
$andString .= "`$aliasInCondition`.$cfield $ctype " . $cvalue . " ";
}
}
}
if ($andString != '') {
if ($conditionStr != '')
$conditionStr .= (" and (" . $andString . ") ");
else
$conditionStr .= (" (" . $andString . ") ");
}
// $orString = '';
$orString = $joinOrString; /////New testing
foreach ($orConditions as $orCondition) {
$ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
$cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
$aliasInCondition = $table;
if (!(strpos($cfield, '.') === false)) {
$fullCfieldArray = explode('.', $cfield);
$aliasInCondition = $fullCfieldArray[0];
$cfield = $fullCfieldArray[1];
}
$cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStringIndividual;
if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
if ($orString != '')
$orString .= " or ";
if ($ctype == 'like') {
$orString .= ("`$aliasInCondition`.$cfield like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($orString != '')
$orString .= " or ";
$orString .= ("`$aliasInCondition`.$cfield like '%" . $word . "%' ");
}
} else if ($ctype == 'not like') {
$orString .= ("`$aliasInCondition`.$cfield not like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($orString != '')
$orString .= " or ";
$orString .= ("`$aliasInCondition`.$cfield not like '%" . $word . "%' ");
}
} else if ($ctype == 'not_in') {
$orString .= " ( ";
if (in_array('null', $cvalue)) {
$orString .= " `$aliasInCondition`.$cfield is not null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$orString .= " or ";
}
if (in_array('', $cvalue)) {
$orString .= "`$aliasInCondition`.$cfield != '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$orString .= " or ";
}
$orString .= "`$aliasInCondition`.$cfield not in (" . implode(',', $cvalue) . ") ) ";
} else if ($ctype == 'in') {
$orString .= " ( ";
if (in_array('null', $cvalue)) {
$orString .= " `$aliasInCondition`.$cfield is null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$orString .= " or ";
}
if (in_array('', $cvalue)) {
$orString .= "`$aliasInCondition`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$orString .= " or ";
}
$orString .= "`$aliasInCondition`.$cfield in (" . implode(',', $cvalue) . ") ) ";
} else if ($ctype == '=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$orString .= "`$aliasInCondition`.$cfield is null ";
else
$orString .= "`$aliasInCondition`.$cfield = $cvalue ";
} else if ($ctype == '!=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$orString .= "`$aliasInCondition`.$cfield is not null ";
else
$orString .= "`$aliasInCondition`.$cfield != $cvalue ";
} else {
if (is_string($cvalue))
$orString .= "`$aliasInCondition`.$cfield $ctype '" . $cvalue . "' ";
else
$orString .= "`$aliasInCondition`.$cfield $ctype " . $cvalue . " ";
}
}
}
if ($orString != '') {
if ($conditionStr != '')
$conditionStr .= (" or (" . $orString . ") ");
else
$conditionStr .= (" (" . $orString . ") ");
}
// $andOrString = '';
$andOrString = $joinAndOrString; /////New testing
foreach ($andOrConditions as $andOrCondition) {
$ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
$cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
$aliasInCondition = $table;
if (!(strpos($cfield, '.') === false)) {
$fullCfieldArray = explode('.', $cfield);
$aliasInCondition = $fullCfieldArray[0];
$cfield = $fullCfieldArray[1];
}
$cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStringIndividual;
if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
if ($andOrString != '')
$andOrString .= " or ";
if ($ctype == 'like') {
$andOrString .= (" `$aliasInCondition`.$cfield like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($andOrString != '')
$andOrString .= " or ";
$andOrString .= ("`$aliasInCondition`.$cfield like '%" . $word . "%' ");
}
} else if ($ctype == 'not like') {
$andOrString .= (" `$aliasInCondition`.$cfield not like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($andOrString != '')
$andOrString .= " or ";
$andOrString .= ("`$aliasInCondition`.$cfield not like '%" . $word . "%' ");
}
} else if ($ctype == 'in') {
$andOrString .= " ( ";
if (in_array('null', $cvalue)) {
$andOrString .= " `$aliasInCondition`.$cfield is null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$andOrString .= " or ";
}
if (in_array('', $cvalue)) {
$andOrString .= "`$aliasInCondition`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$andOrString .= " or ";
}
if (!empty($cvalue))
$andOrString .= " `$aliasInCondition`.$cfield in (" . implode(',', $cvalue) . ") ) ";
else
$andOrString .= " ) ";
} else if ($ctype == 'not_in') {
$andOrString .= " ( ";
if (in_array('null', $cvalue)) {
$andOrString .= " `$aliasInCondition`.$cfield is not null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$andOrString .= " or ";
}
if (in_array('', $cvalue)) {
$andOrString .= "`$aliasInCondition`.$cfield != '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$andOrString .= " or ";
}
if (!empty($cvalue))
$andOrString .= "`$aliasInCondition`.$cfield not in (" . implode(',', $cvalue) . ") ) ";
else
$andOrString .= " ) ";
} else if ($ctype == '=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$andOrString .= "`$aliasInCondition`.$cfield is null ";
else
$andOrString .= "`$aliasInCondition`.$cfield = $cvalue ";
} else if ($ctype == '!=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$andOrString .= "`$aliasInCondition`.$cfield is not null ";
else
$andOrString .= "`$aliasInCondition`.$cfield != $cvalue ";
} else {
if (is_string($cvalue))
$andOrString .= "`$aliasInCondition`.$cfield $ctype '" . $cvalue . "' ";
else
$andOrString .= "`$aliasInCondition`.$cfield $ctype " . $cvalue . " ";
}
}
}
if ($andOrString != '') {
if ($conditionStr != '')
$conditionStr .= (" and (" . $andOrString . ") ");
else
$conditionStr .= (" (" . $andOrString . ") ");
}
}
$mustStr = $joinMustString; /////New testing
// $mustStr = '';
///now must conditions
foreach ($mustConditions as $mustCondition) {
// $conditionStr.=' 1=1 ';
$ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
$cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
$aliasInCondition = $table;
if (!(strpos($cfield, '.') === false)) {
$fullCfieldArray = explode('.', $cfield);
$aliasInCondition = $fullCfieldArray[0];
$cfield = $fullCfieldArray[1];
}
$cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStringIndividual;
if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
if ($mustStr != '')
$mustStr .= " and ";
if ($ctype == 'like') {
$mustStr .= ("(`$aliasInCondition`.$cfield like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($mustStr != '')
$mustStr .= " or ";
$mustStr .= ("`$aliasInCondition`.$cfield like '%" . $word . "%' ");
}
$mustStr .= " )";
} else if ($ctype == 'not like') {
$mustStr .= ("`$aliasInCondition`.$cfield not like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($mustStr != '')
$mustStr .= " and ";
$mustStr .= ("`$aliasInCondition`.$cfield not like '%" . $word . "%' ");
}
} else if ($ctype == 'in') {
$mustStr .= " ( ";
if (in_array('null', $cvalue)) {
$mustStr .= " `$aliasInCondition`.$cfield is null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$mustStr .= " or ";
}
if (in_array('', $cvalue)) {
$mustStr .= "`$aliasInCondition`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$mustStr .= " or ";
}
$mustStr .= "`$aliasInCondition`.$cfield in (" . implode(',', $cvalue) . ") ) ";
} else if ($ctype == 'not_in') {
$mustStr .= " ( ";
if (in_array('null', $cvalue)) {
$mustStr .= " `$aliasInCondition`.$cfield is not null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$mustStr .= " and ";
}
if (in_array('', $cvalue)) {
$mustStr .= "`$aliasInCondition`.$cfield != '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$mustStr .= " and ";
}
$mustStr .= "`$aliasInCondition`.$cfield not in (" . implode(',', $cvalue) . ") ) ";
} else if ($ctype == '=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$mustStr .= "`$aliasInCondition`.$cfield is null ";
else
$mustStr .= "`$aliasInCondition`.$cfield = $cvalue ";
} else if ($ctype == '!=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$mustStr .= "`$aliasInCondition`.$cfield is not null ";
else
$mustStr .= "`$aliasInCondition`.$cfield != $cvalue ";
} else {
if (is_string($cvalue))
$mustStr .= "`$aliasInCondition`.$cfield $ctype '" . $cvalue . "' ";
else
$mustStr .= "`$aliasInCondition`.$cfield $ctype " . $cvalue . " ";
}
}
}
if ($mustStr != '') {
if ($conditionStr != '')
$conditionStr .= (" and (" . $mustStr . ") ");
else
$conditionStr .= (" (" . $mustStr . ") ");
}
if ($conditionStr != '')
$filterQryForCriteria .= (" and (" . $conditionStr . ") ");
if ($lastChildrenOnly == 1) {
if ($filterQryForCriteria != '')
$filterQryForCriteria .= ' and ';
$filterQryForCriteria .= " `$table`.`$valueField` not in ( select distinct $parentIdField from $table)";
} else if ($parentOnly == 1) {
if ($filterQryForCriteria != '')
$filterQryForCriteria .= ' and ';
$filterQryForCriteria .= " `$table`.`$valueField` in ( select distinct $parentIdField from $table)";
}
if (!empty($orderByConditions)) {
$filterQryForCriteria .= " order by ";
$fone = 1;
foreach ($orderByConditions as $orderByCondition) {
if ($fone != 1) {
$filterQryForCriteria .= " , ";
}
if (isset($orderByCondition['valueList'])) {
if (is_string($orderByCondition['valueList'])) $orderByCondition['valueList'] = json_decode($orderByCondition['valueList'], true);
if ($orderByCondition['valueList'] == null)
$orderByCondition['valueList'] = [];
$filterQryForCriteria .= " field(" . $orderByCondition['field'] . "," . implode(',', $orderByCondition['valueList']) . "," . $orderByCondition['field'] . ") " . $orderByCondition['sortType'] . " ";
} else
$filterQryForCriteria .= " " . $orderByCondition['field'] . " " . $orderByCondition['sortType'] . " ";
$fone = 0;
}
}
if ($returnTotalMatchedEntriesFlag == 1) {
// $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
//
// $get_kids = $stmt;
}
if ($filterQryForCriteria != '')
if (!empty($setValueArray) || $selectAll == 1) {
} else {
if ($itemLimit != '_ALL_')
$filterQryForCriteria .= " limit $offset, $itemLimit ";
else
$filterQryForCriteria .= " limit $offset, 18446744073709551615 ";
}
$get_kids_sql = $filterQryForCriteria;
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$get_kids = $stmt;
$selectedId = 0;
if ($table == 'warehouse_action') {
if (empty($get_kids)) {
$get_kids_sql_2 = "select * from warehouse_action";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql_2);
$get_kids2 = $stmt;
if (empty($get_kids2))
$get_kids = GeneralConstant::$warehouse_action_list;
}
}
if (!empty($get_kids)) {
$nextOffset = $offset + count($get_kids);
$nextOffset++;
foreach ($get_kids as $pa) {
if (!empty($setValueArray) && $selectAll == 0) {
if (!in_array($pa[$valueField], $setValueArray))
continue;
}
if (!empty($restrictionIdList)) {
if (!in_array($pa[$valueField], $restrictionIdList))
continue;
}
if ($selectAll == 1) {
$setValueArray[] = $pa[$valueField];
$setValue = $pa[$valueField];
} else if (count($get_kids) == 1 && $setDataForSingle == 1) {
$setValueArray[] = $pa[$valueField];
$setValue = $pa[$valueField];
}
if ($valueField != '')
$pa['value'] = $pa[$valueField];
$renderedText = $renderTextFormat;
$compare_array = [];
if ($renderTextFormat != '') {
$renderedText = $renderTextFormat;
$compare_arrayFull = [];
$compare_array = [];
$toBeReplacedData = array(// 'curr'=>'tobereplaced'
);
preg_match_all("/__\w+__/", $renderedText, $compare_arrayFull);
if (isset($compare_arrayFull[0]))
$compare_array = $compare_arrayFull[0];
// $compare_array= preg_split("/__\w+__/",$renderedText);
foreach ($compare_array as $cmpdt) {
$tbr = str_replace("__", "", $cmpdt);
if ($tbr != '') {
if (isset($pa[$tbr])) {
if ($pa[$tbr] == null)
$renderedText = str_replace($cmpdt, '', $renderedText);
else
$renderedText = str_replace($cmpdt, $pa[$tbr], $renderedText);
} else {
$renderedText = str_replace($cmpdt, '', $renderedText);
}
}
}
}
$pa['rendered_text'] = $renderedText;
$pa['text'] = ($textField != '' ? $pa[$textField] : '');
// $pa['compare_array'] = $compare_array;
foreach ($convertToObjectFieldList as $convField) {
if (isset($pa[$convField])) {
$taA = json_decode($pa[$convField], true);
if ($taA == null) $taA = [];
$pa[$convField] = $taA;
} else {
$pa[$convField] = [];
}
}
foreach ($convertDateToStringFieldList as $convField) {
if (is_array($convField)) {
$fld = $convField['field'];
$frmt = isset($convField['format']) ? $convField['format'] : 'Y-m-d H:i:s';
} else {
$fld = $convField;
$frmt = 'Y-m-d H:i:s';
}
if (isset($pa[$fld])) {
$taA = new \DateTime($pa[$fld]);
$pa[$fld] = $taA->format($frmt);
}
}
foreach ($convertToUrl as $convField) {
//
// $fld = $convField;
//
//
// if (isset($pa[$fld])) {
//
//
// $pa[$fld] =
// $this->generateUrl(
// 'dashboard', [
//
// ], UrlGenerator::ABSOLUTE_URL
// ).'/'.$pa[$fld];
//
// }
}
foreach ($fullPathList as $pathField) {
$fld = $pathField;
if (isset($pa[$fld])) {
if ($pa[$fld] !='' && $pa[$fld] !=null) {
$pa[$fld]=($this->generateUrl(
'dashboard', [
], UrlGenerator::ABSOLUTE_URL
).$pa[$fld]);
}
}
}
$pa['currentTs'] = (new \Datetime())->format('U');
$data[] = $pa;
if ($valueField != '') {
$data_by_id[$pa[$valueField]] = $pa;
$selectedId = $pa[$valueField];
}
}
}
if ($dataOnly == 1)
$lastResult = array(
'success' => true,
'data' => $data,
'currentTs' => (new \Datetime())->format('U'),
'restrictionIdList' => $restrictionIdList,
'nextOffset' => $nextOffset,
'totalMatchedEntries' => $totalMatchedEntries,
'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
);
else
$lastResult = array(
'success' => true,
'data' => $data,
'tableName' => $table,
'setValue' => $setValue,
'currentTs' => (new \Datetime())->format('U'),
'restrictionIdList' => $restrictionIdList,
'andConditions' => $andConditions,
'queryStr' => $queryStringIndividual,
'isMultiple' => $isMultiple,
'nextOffset' => $nextOffset,
'totalMatchedEntries' => $totalMatchedEntries,
'selectorId' => $selectorId,
'setValueArray' => $setValueArray,
'silentChangeSelectize' => $silentChangeSelectize,
'convertToObjectFieldList' => $convertToObjectFieldList,
'conditionStr' => $conditionStr,
// 'andStr' => $andString,
// 'andOrStr' => $andOrString,
'dataById' => $data_by_id,
'selectedId' => $selectedId,
'dataId' => $dataId,
'ret_data' => isset($dataConfig['ret_data']) ? $dataConfig['ret_data'] : [],
);
}
$allResult[] = $lastResult;
}
if ($isSingleDataset == 1)
return new JsonResponse($lastResult);
else
return new JsonResponse($allResult);
}
public function GenericDataTableAjax(Request $request)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$listData = MiscActions::GetDtDataAjax($em, $request->isMethod('POST') ? 'POST' : 'GET', $request->request, $companyId, $this->container->getParameter('kernel.root_dir'));
if (isset($listData['data']['encryptedData'])) {
foreach ($listData['data']['encryptedData'] as $k => $d) {
foreach ($d as $l => $f) {
$d[$l] = $this->get('url_encryptor')->encrypt($f);
}
$listData['data']['encryptedData'][$k] = $d;
}
}
if ($request->isMethod('POST') && $request->request->has('returnJson')) {
if ($request->query->has('dataTableQry')) {
return new JsonResponse(
$listData
);
}
}
$data = [];
return new JsonResponse(
$listData
);
// return $this->render('@Inventory/pages/views/delivery_receipts.html.twig',
// array(
// 'page_title' => 'Delivery Receipts',
// 'data' => $data,
//
// )
// );
}
public function RefreshApprovalStatusIfPending(Request $request)
{
$em = $this->getDoctrine()->getManager();
$Entity_list = GeneralConstant::$Entity_list;
$skipEntities = $request->request->has('skipEntities') ? $request->request->get('skipEntities') : [42, 7, 14, 26, 27, 28, 29, 31];
$skipEntitiesById = $request->request->has('skipEntitiesById') ? $request->request->get('skipEntitiesById') : [];
$debugData = array(
'skipEntities' => $skipEntities,
'skipEntitiesById' => $skipEntitiesById,
'allDone' => 1,
'actedOnDoc' => ''
);
$didAct = 0;
$foundAtleastOne = 0;
$lastEntity = 0;
foreach ($Entity_list as $entity => $entityName) {
if (in_array($entity, $skipEntities))
continue;
$lastEntity = $entity;
$debugData['allDone'] = 0;
$doc = null;
// if (class_exists('ApplicationBundle\\Entity\\' . $entityName))
{
$docs = $em->getRepository('ApplicationBundle\\Entity\\' . $entityName)
->findBy(
array(
'approved' => GeneralConstant::APPROVAL_STATUS_PENDING
)
);
}
$entityFieldGetFunction = GeneralConstant::$Entity_id_get_method_list[$entity];
if (!isset($skipEntitiesById[$entity]))
$skipEntitiesById[$entity] = [];
foreach ($docs as $doc) {
if (in_array($doc->$entityFieldGetFunction(), $skipEntitiesById[$entity]))
continue;
$foundAtleastOne = 1;
if ($doc) {
$fully_approved = System::fullyApproved($em, $entity, $doc->$entityFieldGetFunction(), 0, $this->get('mail_module'));
if ($fully_approved == 1)
$debugData['actedOnDoc'] = $doc->getDocumentHash();
$didAct = 1;
$skipEntitiesById[$entity][] = $doc->$entityFieldGetFunction();
} else {
}
if ($didAct == 1)
break;
}
if ($didAct == 1)
break;
}
if ($foundAtleastOne == 0)
$debugData['skipEntities'][] = $lastEntity;
$debugData['skipEntitiesById'] = $skipEntitiesById;
return new JsonResponse(
$debugData
);
}
public function CreateDummyRows(Request $request, $startFrom = 0)
{
//function start
///function end
$em = $this->getDoctrine()->getManager();
// for($i=0;$i<10000;$i++) {
// $startFrom++;
// $get_kids_sql = "INSERT INTO `acc_loan` ( `name`, `type`, `company_id`, `branch_id`, `bank_id`, `accounts_head_id`, `head_nature`, `payment_head_id`, `interest_expense_head_id`, `interest_head_id`, `life_year`, `interest_type`, `interest_rate`, `payment_type`, `payment_rate`, `account_number`, `card_number`, `card_type`, `create_individual_head`, `rentable`, `hit_ledger_on_action`, `parent_id`, `balance`, `bank`, `cash`, `sales`, `asset`, `liability`, `expense`, `revenue`, `payable`, `receivable`, `net_worth`, `monthly_growth`, `status`, `edit_flag`, `delete_flag`, `lock_flag`, `refresh_flag`, `disabled_flag`, `create_login_id`, `edit_login_id`, `created_at`, `updated_at`) VALUES ( 'a', 'a', $startFrom, '1', '1', '1', 'cr', '1', '1', '1', 'adsad', '1', '1', '1', '1', 'ssadada', 'adadad', 'ada', '1', '1', '1', '1', '900', '06868', '6866', '8686', '86868', '6868', '686', '6868', '686', '6868', '686', '6868', '3', '1', '1', '1', '1', '1', '1', '1', '2021-01-11 16:40:20', '2019-09-18 19:29:55');";
// $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
//
//
// }
for ($i = 0; $i < 50000; $i++) {
$startFrom++;
$get_kids_sql = "INSERT INTO `employee_attendance_log` ( `attendance_id`, `current_lat`, `current_lng`, `is_from_assigned_area`, `log`, `popup_init`, `popup_response`, `delay_response_count`, `last_start_time`, `last_end_time`, `total_work_time_sec`, `current_work_status`, `current_address`, `employee_id`, `is_present`, `count_as_absent`, `presence_required`, `is_holiday`, `is_weekend`, `is_approved_leave`) VALUES ( $startFrom, '121', '1212121', '1', '" . '[{\\"date\\":\\"2021 - 01 - 11 15:47:47\\",\\"type\\":1,\\"lat\\":124567,\\"lng\\":56888},{\\"date\\":\\"2021 - 01 - 11 15:47:47\\",\\"type\\":1,\\"lat\\":124567,\\"lng\\":56888},{\\"date\\":\\"2021 - 01 - 11 15:47:47\\",\\"type\\":1,\\"lat\\":124567,\\"lng\\":56888},{\\"date\\":\\"2021 - 01 - 11 15:47:47\\",\\"type\\":1,\\"lat\\":124567,\\"lng\\":56888}]' . "', '2021-01-11 20:11:06', '2021-01-29 20:11:21', NULL, '2020-12-10 01:56:00', '2021-01-29 20:11:32', '36000', '1', 'sdsdsdssssssssssssss', '3', '1', '1', '1', '1', '1', '1');";
$stmt = $em->getConnection()->executeStatement($get_kids_sql);
}
$url = $this->generateUrl(
'test_insert_lot_of_rows'
);
if ($startFrom < 1000000)
return $this->redirect($url . "/" . $startFrom);
else
return new Response(1);
}
public function CreateSalesInvoice(Request $request)
{
//function start
///function end
$em = $this->getDoctrine()->getManager();
return new JsonResponse(Accounts::GetBalanceOnDateByMarkerHash($em, '2021-01-21', [], [], 1));
$childEm = $this->getDoctrine()->getManager('company_group');
ob_start();
phpinfo();
$phpinfo = ob_get_contents();
ob_end_clean();
$em = $this->getDoctrine()->getManager();
return $this->render(
'@Accounts/pages/input_forms/sales_invoice.html.twig',
array(
'page_title' => 'Create Sales Invoice',
'phpinfo' => $phpinfo,
'debug_data' => $this->getDoctrine()->getManager('company_group'),
'debug_data_2' => Company::getMonthlyDataForDashboard($this->getDoctrine()->getManager(), 1)
)
);
//refreshing/ assigning invoice/order/challan/grn/stock requisition etc id to voucher as entity id
$tocheckEntityList = array(
8 => 'Grn',
9 => 'PurchaseInvoice',
10 => 'ExpenseInvoice',
16 => 'DeliveryReceipt',
18 => 'SalesInvoice',
20 => 'StockTransfer',
21 => 'StockReceivedNote',
30 => 'ServiceChallan',
41 => 'ItemReceivedAndReplacement',
44 => 'StockConsumptionNote',
47 => 'FixedAssetConversionNote',
48 => 'FixedAssetDisposalNote',
53 => 'Production',
);
foreach ($tocheckEntityList as $entity => $entityName) {
$entityList = $em->getRepository('ApplicationBundle\\Entity\\' . $entityName)->findBy(
array()
);
foreach ($entityList as $entry) {
$voucherIds = method_exists($entry, 'getVoucherIds') ? json_decode($entry->getVoucherIds(), true) : [];
$getMethod = GeneralConstant::$Entity_id_get_method_list[$entity];
if ($voucherIds == null)
$voucherIds = [];
if (!empty($voucherIds)) {
$transactions = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findBy(
array(
'transactionId' => $voucherIds
)
);
foreach ($transactions as $transaction) {
$transaction->setEntityId($entry->$getMethod());
$transaction->setEntity($entity);
$transaction->setEntityDocHash($entry->getDocumentHash());
$em->flush();
}
}
}
}
// return $this->render('phpinfo.html.twig', array(
// 'phpinfo'=>$phpinfo,
// ));
//If we want to change the childEm to a different database:
/**
* IMPORTANT: The $reset parameter is used to clear all Units of Work fro
* the EntityManager, this means anything that was not previously flushed
* will be lost if you do $reset = true.
*
* Separately, $reset is necessary if you want to apply changes across
* multiple EntityManagers in one Controller. Make sure you flush, then
* $reset, and you will be good to go.
*/
/**
* get your new database parameters here..
*/
// $connector = $this->container->get('application_connector');
// $connector->resetConnection('company_group', 'bengal_v2', "root", "", "localhost", $reset = true);
$soList = $em->getRepository('ApplicationBundle\\Entity\\SalesOrder')->findBy(
array()
);
foreach ($soList as $so) {
// SalesOrderM::checkIfSalesOrderComplete($em, $so->getSalesOrderId());
}
//childEM is now connected to the new database.
// $childEm = $this->getDoctrine()->getManager('company_group')
// ->getRepository("ApplicationBundle\\Entity\\AccSuppliers")
// ->findAll();
return $this->render(
'@Accounts/pages/input_forms/sales_invoice.html.twig',
array(
'page_title' => 'Create Sales Invoice',
'phpinfo' => $phpinfo,
'debug_data' => $this->getDoctrine()->getManager('company_group'),
'debug_data_2' => Company::getMonthlyDataForDashboard($this->getDoctrine()->getManager(), 1)
)
);
}
public function GetFilteredCostCentres(Request $request, $headId = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$asArray = $request->query->has('asArray') ? $request->query->get('asArray') : 0;
return new JsonResponse(array(
'costCentreList' => Accounts::CostCenterListFilteredByHeadId($em, $companyId, $headId, $asArray)
));
}
public function GetAllocationRules(Request $request)
{
$em = $this->getDoctrine()->getManager();
$accountId = (int) $request->query->get('account_id', 0);
if ($accountId <= 0) {
return new JsonResponse([
'success' => true,
'data' => [],
]);
}
$rules = $em->getRepository('ApplicationBundle\\Entity\\AllocationRule')->findByAccountId($accountId);
$data = [];
foreach ($rules as $rule) {
$data[] = [
'id' => $rule->getId(),
'account_id' => $rule->getAccountId(),
'tag_type' => $rule->getTagType(),
'tag_value' => $rule->getTagValue(),
'percentage' => (float) $rule->getPercentage(),
];
}
return new JsonResponse([
'success' => true,
'data' => $data,
]);
}
public function RefreshFunction(Request $request)
{
$em = $this->getDoctrine()->getManager();
//
// UPDATE `acc_accounts_head` SET `head_nature`='dr' WHERE path_tree like '%/1/%' or path_tree like '%/5/%';
//UPDATE `acc_accounts_head` SET `head_nature`='cr' WHERE path_tree like '%/3/%' or path_tree like '%/4/%';
$dataList2 = $em->getRepository('ApplicationBundle\\Entity\\StoreRequisitionItem')->findBy(
array()
);
foreach ($dataList2 as $dt2) {
if ($dt2->getNote() == "" || $dt2->getNote() == null) {
//find tagged data
$tagData = [];
$note = "";
$tagData = json_decode($dt2->getTagData(), true);
if ($tagData) {
foreach ($tagData as $tg) {
$data1 = $em->getRepository('ApplicationBundle\\Entity\\StockRequisitionItem')->findOneBy(
array(
'id' => $tg['detailsId']
)
);
if ($data1) {
if ($data1->getNote() == "" || $data1->getNote() == null) {
$note .= ", ";
$note .= $data1->getNote();
}
}
}
}
$dt2->setNote($note);
}
}
$em->flush();
$dataList2 = $em->getRepository('ApplicationBundle\\Entity\\PurchaseRequisitionItem')->findBy(
array()
);
foreach ($dataList2 as $dt2) {
if ($dt2->getNote() == "" || $dt2->getNote() == null) {
//find tagged data
$tagData = [];
$note = "";
$tagData = json_decode($dt2->getTagData(), true);
if ($tagData) {
foreach ($tagData as $tg) {
$data1 = $em->getRepository('ApplicationBundle\\Entity\\StoreRequisitionItem')->findOneBy(
array(
'id' => $tg['detailsId']
)
);
if ($data1) {
if ($data1->getNote() == "" || $data1->getNote() == null) {
$note .= ", ";
$note .= $data1->getNote();
}
}
}
}
$dt2->setNote($note);
}
}
$em->flush();
return new Response(1);
// $query_here=$em->getRepository('ApplicationBundle\\Entity\\EncryptedSignature')
// ->findOneBy(
// array(
// 'userId'=>4
// )
// );
// if($query_here)
// {
// $dt=$query_here->getData();
// }
// else
// {
// return false;
// }
//
//
//
// $iv = '1234567812345678';
// $data=openssl_encrypt('ki koro miavai', "AES-128-CBC", 'monada', OPENSSL_RAW_DATA, $iv);
//// $decrypted = openssl_decrypt(base64_decode(base64_encode($data)), "AES-128-CBC", 'monada', OPENSSL_RAW_DATA, $iv);
// $decrypted = openssl_decrypt(base64_decode($dt), "AES-128-CBC", 'monada', OPENSSL_RAW_DATA, $iv);
//
// return new JsonResponse(array("success"=>false,'decoded_data'=>$decrypted,'data'=>base64_encode($data)));
//1st remove any category that is not assigned to remove redundancy
//now
}
public function RefreshHeadCode(Request $request)
{
$head_list = [];
$digits = [];
//first get max level
$em = $this->getDoctrine()->getManager();
$max_level = 0;
$query = "SELECT max(head_level) max_level from acc_accounts_head where company_id=" . $this->getLoggedUserCompanyId($request);
$stmt = $em->getConnection()->fetchAllAssociative($query);
$results = $stmt;
if ($results) {
$max_level = $results[0]['max_level'];
}
//now create multipliers
for ($i = 1; $i <= $max_level; $i++) {
$query = "SELECT count(accounts_head_id) count_of_level from acc_accounts_head where head_level=$i and company_id=" . $this->getLoggedUserCompanyId($request);
$stmt = $em->getConnection()->fetchAllAssociative($query);
$res = $stmt;
if ($res) {
$c = $res[0]['count_of_level'];
$m = 1;
$t = 1;
for ($m = 1; $t <= $c; $m++) {
$t = $t * 10;
}
// while($c/10>0)
// {
// $m+=1;
// $c = $c % 10;
// }
$digits[$i] = $m;
} else
$digits[$i] = 0;
}
//now get all acc heads and serialize them based on parent id
$query = "SELECT * from acc_accounts_head where company_id=" . $this->getLoggedUserCompanyId($request) . " ORDER BY parent_id ASC";
// $query="SELECT accounts_head_id, type_hash, prefix_hash, assoc_hash, number_hash from acc_transactions where status=".GeneralConstant::ACTIVE;
$stmt = $em->getConnection()->fetchAllAssociative($query);
$results = $stmt;
$update_qry = "";
foreach ($results as $entry) {
$new_code = '';
$path = explode('/', $entry['path_tree']);
$path_string = '';
$new_ser = 1;
foreach ($path as $head_id) {
if ($head_id != '' && $head_id != 0) {
if ($head_id == $entry['parent_id']) {
$new_ser = $head_list[$head_id]['last_serial'] + 1;
$head_list[$head_id]['last_serial'] + $new_ser;
}
$new_code = $new_code + $head_list[$head_id]['code'] * 1;
}
}
//now this oneonly
for ($k = 0; $k < $digits[$entry['head_level']]; $k++)
$new_code = 10 * $new_code;
//now last zeroes
for ($j = $entry['head_level']; $j <= $max_level; $j++) {
for ($k = 0; $k < $digits[$j]; $k++)
$new_code = 10 * $new_code;
}
$head_list[$entry['accounts_head_id']] = array(
'code' => $new_code,
'last_serial' => 0
);
$update_qry .= "UPDATE acc_accounts_head set ledger_head_code=$new_code
where accounts_head_id=" . $entry['accounts_head_id'] . "; ";
}
$stmt = $em->getConnection()->fetchAllAssociative($update_qry);
return $this->redirectToRoute('dashboard');
}
public function RefreshHeadLevel(Request $request)
{
$em = $this->getDoctrine()->getManager();
$assign_list = array();
// $new_cc = $em
// ->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
// ->findOneBy(
// array(
// 'name' => 'accounting_year_start',
// )
// );
$heads = [];
$query = "SELECT * from acc_accounts_head where company_id=" . $this->getLoggedUserCompanyId($request) . " ORDER BY parent_id ASC";
// $query="SELECT accounts_head_id, type_hash, prefix_hash, assoc_hash, number_hash from acc_transactions where status=".GeneralConstant::ACTIVE;
$stmt = $em->getConnection()->fetchAllAssociative($query);
$results = $stmt;
$update_qry = "";
$head_list_by_id = [];
$child_list_by_parent_id = [];
$zero_parent_head_ids = [];
foreach ($results as $entry) {
$head_list_by_id[$entry['accounts_head_id']] = $entry;
$parent_id = $entry['parent_id'];
if ($parent_id == null || $parent_id == '' || $parent_id == 0) {
$zero_parent_head_ids[] = $entry['accounts_head_id'];
$parent_id = 0;
}
if (!isset($child_list_by_parent_id[$parent_id]))
$child_list_by_parent_id[$parent_id] = array();
$child_list_by_parent_id[$parent_id][] = $entry['accounts_head_id'];
}
foreach ($zero_parent_head_ids as $parId) {
$heads[$parId] = array(
'level' => 1
);
$next_ids = $child_list_by_parent_id[$parId];
$cur_level = 1;
$infLoopBreaker = 0;
while (!empty($next_ids) && $infLoopBreaker < 100) {
$cur_level = $cur_level + 1;
$new_next_ids = [];
foreach ($next_ids as $childId) {
$entry = $head_list_by_id[$childId];
if ($cur_level == $entry['head_level']) {
} else {
$update_qry .= "UPDATE acc_accounts_head set head_level=$cur_level
where accounts_head_id=" . $entry['accounts_head_id'] . "; ";
}
if (isset($child_list_by_parent_id[$childId]))
array_merge($new_next_ids, array_diff($new_next_ids, $child_list_by_parent_id[$childId]));
$heads[$entry['accounts_head_id']] = array(
'level' => $cur_level
);
}
$next_ids = $new_next_ids;
$infLoopBreaker++;
}
}
// System::log_it($this->container->getParameter('kernel.root_dir'), json_encode($zero_parent_head_ids), 'head_level_test');
//
// foreach ($results as $entry) {
// if ($entry['parent_id'] == 0 || $entry['parent_id'] == '') {
// //top parent
// $heads[$entry['accounts_head_id']] = array(
// 'level' => 1
// );
// } else {
// $cur_level = 1 + $heads[$entry['parent_id']]['level'];
// if ($cur_level == $entry['head_level']) {
// } else {
// $update_qry .= "UPDATE acc_accounts_head set head_level=$cur_level
// where accounts_head_id=" . $entry['accounts_head_id'] . "; ";
// }
//
//
// $heads[$entry['accounts_head_id']] = array(
// 'level' => $cur_level
// );
// }
// }
if ($update_qry != '') {
$stmt = $em->getConnection()->fetchAllAssociative($update_qry);
}
// $Transactions=$stmt;
return $this->redirectToRoute('opening_head_balance_assign');
}
public function PrintCheckRegister(Request $request)
{
$em = $this->getDoctrine()->getManager();
$company_data = Company::getCompanyData($em, $this->getLoggedUserCompanyId($request));
$head_list = Accounts::HeadList($em);
$voucher_list = Accounts::VoucherListForCheckRegister($em);
$find_array = array(
'type' => 1
);
if ($request->query->has('viewOption')) {
if ($request->query->get('viewOption') == 1)
$find_array = ['active' => GeneralConstant::ACTIVE];
if ($request->query->get('viewOption') == 2)
$find_array = ['active' => GeneralConstant::INACTIVE];
}
$assignedflag = $request->query->has('assign_flag') ? $request->query->get('assign_flag') : 0;
if ($assignedflag == 1)
$find_array['assigned'] = 1;
$check_query = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccCheck')
->findBy(
$find_array,
array(
'checkNumber' => 'ASC',
)
);
$check_data = [];
$check_data_by_bank = [];
$start_date = $request->query->has('start_date') ? (new \DateTime($request->query->get('start_date'))) : '';
$end_date = $request->query->has('end_date') ? (new \DateTime($request->query->get('end_date') . ' ' . ' 23:59:59.999')) : '';
// if($end_date!='')
// $end_date->modify('+1 day');
$book_list_by_bank = [];
foreach ($check_query as $entry) {
$checkTransDate = $entry->getTransactionDate();
if ($checkTransDate == null)
continue;
if ($start_date != '' && ($checkTransDate instanceof \DateTime) && ($start_date > $checkTransDate))
continue;
if ($end_date != '' && ($checkTransDate instanceof \DateTime) && ($end_date < $checkTransDate))
continue;
$v_date = isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['date'] : '';
// if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
if ($start_date != '' && ($v_date instanceof \DateTime) && ($start_date > $v_date))
continue;
// if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
if ($end_date != '' && ($v_date instanceof \DateTime) && ($end_date < $v_date))
continue;
// if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
// continue;
// if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
// continue;
$checkDate = ($entry->getCheckDate() instanceof \DateTime) ? $entry->getCheckDate()->format('m/d/Y') : '';
$assignedDate = ($entry->getAssignedDate() instanceof \DateTime) ? $entry->getAssignedDate()->format('m/d/Y') : '';
if (!isset($book_list_by_bank[$entry->getAccountsHeadId()])) $book_list_by_bank[$entry->getAccountsHeadId()] = [];
if (!in_array($entry->getBookNumber(), $book_list_by_bank[$entry->getAccountsHeadId()])) {
$book_list_by_bank[$entry->getAccountsHeadId()][] = $entry->getBookNumber();
}
$check_data_by_bank[$entry->getAccountsHeadId()][] = array(
'checkId' => $entry->getCheckId(),
'checkNumber' => sprintf("%07d", $entry->getCheckNumber()),
'checkNarration' => $entry->getCheckNarration(),
'voucherNarration' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['desc'] : '',
'voucherDate' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['date']->format('m/d/Y') : '',
'accountNumber' => $entry->getAccountNumber(),
'checkDate' => $checkDate,
'head' => $head_list[$entry->getAccountsHeadId()]['name'],
'head_id' => $entry->getAccountsHeadId(),
'received_head' => isset($head_list[$entry->getRecAccountsHeadId()]) ? $head_list[$entry->getRecAccountsHeadId()]['name'] : '',
'received_head_id' => $entry->getRecAccountsHeadId(),
'received_head_id_list' => $entry->getRecAccountsHeadIdList(),
'assignedDate' => $assignedDate,
'checkAmount' => $entry->getCheckAmount(),
'voucher_number' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['doc_hash'] : '',
'voucher_id' => $entry->getVoucherId(),
);
}
$count_details_by_bank = [];
if ($request->query->has('countDetails')) {
$check_query = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccCheck')
->findAll();
$count_details_by_bank = [];
$assigned_books = [];
foreach ($check_query as $entry) {
if (isset($count_details_by_bank[$entry->getAccountsHeadId()])) {
$count_details_by_bank[$entry->getAccountsHeadId()]['total_chk'] += 1;
if ($entry->getAssigned() == 1)
$count_details_by_bank[$entry->getAccountsHeadId()]['total_ass'] += 1;
else
$count_details_by_bank[$entry->getAccountsHeadId()]['total_avail'] += 1;
if (!in_array($entry->getBookNumber(), $assigned_books)) {
$count_details_by_bank[$entry->getAccountsHeadId()]['books'] .= (', ' . $entry->getBookNumber());
array_push($assigned_books, $entry->getBookNumber());
}
} else {
$count_details_by_bank[$entry->getAccountsHeadId()]['total_chk'] = 1;
$count_details_by_bank[$entry->getAccountsHeadId()]['total_ass'] = 0;
$count_details_by_bank[$entry->getAccountsHeadId()]['total_avail'] = 0;
if ($entry->getAssigned() == 1)
$count_details_by_bank[$entry->getAccountsHeadId()]['total_ass'] = 1;
else
$count_details_by_bank[$entry->getAccountsHeadId()]['total_avail'] = 1;
array_push($assigned_books, $entry->getBookNumber());
$count_details_by_bank[$entry->getAccountsHeadId()]['books'] = (' ' . $entry->getBookNumber());
}
}
}
foreach ($voucher_list as $key => $entry) {
$v_date = $entry['date'];
// if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
if ($start_date != '' && ($v_date instanceof \DateTime) && ($start_date > $v_date))
continue;
// if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
if ($end_date != '' && ($v_date instanceof \DateTime) && ($end_date < $v_date))
continue;
if (!in_array($entry['prMethod'], [3, 4]))
continue;
// if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
// continue;
// if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
// continue;
$trans_details = $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(
array(
'transactionId' => $key,
'position' => 'cr'
)
);
foreach ($trans_details as $value) {
$checkDate = $entry['date']->format('m/d/Y');
$assignedDate = $entry['date']->format('m/d/Y');
$dr_details = $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(
array(
'transactionId' => $key,
'position' => 'dr'
)
);
$rec_id_list = [];
$rec_narr = "";
foreach ($dr_details as $dt) {
$rec_id_list[] = $dt->getAccountsHeadId();
$rec_narr .= $head_list[$dt->getAccountsHeadId()]['name'];
$rec_narr .= ", ";
}
$check_data_by_bank[$value->getAccountsHeadId()][] = array(
'checkId' => 0,
'checkNumber' => $entry['prReference'],
'checkNarration' => $rec_narr,
'voucherNarration' => $entry['desc'],
'voucherDate' => $entry['date']->format('m/d/Y'),
'accountNumber' => '',
'checkDate' => $checkDate,
'head' => $head_list[$value->getAccountsHeadId()]['name'],
'head_id' => $value->getAccountsHeadId(),
'received_head' => $rec_narr,
'received_head_id' => 0,
'received_head_id_list' => json_encode($rec_id_list),
'assignedDate' => $assignedDate,
'checkAmount' => $value->getAmount(),
'voucher_number' => $entry['doc_hash'],
'voucher_id' => $key,
);
}
}
if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
$html = $this->renderView(
'@Accounts/pages/print/check_register_print.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => 'Cheque Register ',
// 'ledger_data'=>$ledger_det,
'export' => "pdf,print",
'check_data' => $check_data_by_bank,
'count_details_by_bank' => $count_details_by_bank,
'page_header' => 'Cheque Register',
'document_type' => 'Cheque Register',
// 'document_mark_image'=>$document_mark['original'],
'page_header_sub' => 'Add',
'start_date' => $start_date,
'end_date' => $end_date,
'head_list' => Accounts::HeadList($em),
// 'provisional'=>$provisional_option,
// 'type_list'=>$type_list,
// 'child_list'=>$child_list,
// 'trans_data_by_closing'=>$trans_data_by_closing,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'book_list_by_bank' => $book_list_by_bank,
'invoice_footer' => $company_data->getInvoiceFooter(),
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
// 'desc_head_list'=>$desc_tree_list,
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
//
)
);
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
// 'orientation' => 'landscape',
// 'enable-javascript' => true,
// 'javascript-delay' => 1000,
'no-stop-slow-scripts' => false,
'no-background' => false,
'lowquality' => false,
'encoding' => 'utf-8',
// 'images' => true,
// 'cookie' => array(),
'dpi' => 300,
'image-dpi' => 300,
// 'enable-external-links' => true,
// 'enable-internal-links' => true
));
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="Cheque_Register.pdf"'
)
);
}
return $this->render(
'@Accounts/pages/print/check_register_print.html.twig',
array(
'page_title' => 'Cheque Register ',
// 'ledger_data'=>$ledger_det,
'export' => "pdf,print",
'check_data' => $check_data_by_bank,
'count_details_by_bank' => $count_details_by_bank,
'page_header' => 'Cheque Register',
'document_type' => 'Cheque Register',
// 'document_mark_image'=>$document_mark['original'],
'page_header_sub' => 'Add',
'start_date' => $start_date,
'end_date' => $end_date,
'head_list' => Accounts::HeadList($em),
// 'provisional'=>$provisional_option,
// 'type_list'=>$type_list,
// 'child_list'=>$child_list,
// 'trans_data_by_closing'=>$trans_data_by_closing,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'book_list_by_bank' => $book_list_by_bank,
'invoice_footer' => $company_data->getInvoiceFooter(),
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
// 'desc_head_list'=>$desc_tree_list,
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
// 'p'=>$p
)
);
}
public function CheckRegister(Request $request)
{
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
$startCheckRaw = trim((string)$request->request->get('checkNumberStart'));
$endCheckRaw = trim((string)$request->request->get('checkNumberEnd'));
$accountNumber = trim((string)$request->request->get('accountNumber'));
$bookNumber = trim((string)$request->request->get('bookNumber'));
$accountsHeadId = (int)$request->request->get('accountsHeadId');
$formatId = (int)$request->request->get('formatId');
$errors = [];
if ($accountsHeadId <= 0) {
$errors[] = 'Please select account.';
}
if ($accountNumber === '') {
$errors[] = 'Please enter account number.';
}
if ($bookNumber === '') {
$errors[] = 'Please enter cheque book number.';
}
if ($startCheckRaw === '' || !ctype_digit($startCheckRaw)) {
$errors[] = 'Please enter a valid starting cheque number.';
}
if ($endCheckRaw !== '' && !ctype_digit($endCheckRaw)) {
$errors[] = 'Please enter a valid ending cheque number.';
}
if ($formatId <= 0) {
$errors[] = 'Please select cheque layout format.';
}
if (empty($errors)) {
$startCheck = (int)$startCheckRaw;
$endCheck = $endCheckRaw === '' ? $startCheck : (int)$endCheckRaw;
if ($startCheck <= 0) {
$errors[] = 'Please enter a valid starting cheque number.';
} elseif ($endCheck < $startCheck) {
$errors[] = 'Ending cheque number cannot be smaller than starting cheque number.';
} else {
for ($p = $startCheck; $p <= $endCheck; $p++) {
$duplicate = $em->getRepository('ApplicationBundle\\Entity\\AccCheck')
->createQueryBuilder('c')
->where('c.accountsHeadId = :headId')
->andWhere('c.checkNumber = :checkNumber')
->setParameter('headId', $accountsHeadId)
->setParameter('checkNumber', $p)
->getQuery()
->getOneOrNullResult();
if ($duplicate) {
$errors[] = 'Cheque number ' . $p . ' already exists for this account head.';
break;
}
}
}
}
if (!empty($errors)) {
$this->addFlash('error', implode(' ', $errors));
} else {
for ($p = $startCheck; $p <= $endCheck; $p++) {
$new = new AccCheck();
$new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
$new->setCheckNumber($p);
$new->setAccountsHeadId($accountsHeadId);
$new->setAccountNumber($accountNumber);
$new->setBookNumber($bookNumber);
$new->setActive(GeneralConstant::ACTIVE);
$new->setAssigned(0);
$new->setStatus(3); // pending. will stay like that till its bounced or confirmed transation physically
$new->setFormatId($formatId);
$new->setType(1);
$new->setDetails(1);
$em->persist($new);
}
$em->flush();
$this->addFlash('success', 'Cheque range added.');
}
}
return $this->render(
'@Accounts/pages/views/check_register.html.twig',
array(
'page_title' => 'Cheque Register',
'head_list' => Accounts::HeadList($em),
'format_list' => Accounts::CheckFormatList($em),
)
);
}
public function BankGuaranteeList(Request $request)
{
$em = $this->getDoctrine()->getManager();
return $this->render(
'@Application/pages/accounts/settings/bank_guarantee_list.html.twig',
array(
'page_title' => 'Bank Guarantees',
'bgTypes' => AccountsConstant::$BankGuarnteeTypes,
)
);
}
public function BankGuaranteeView(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$check_here = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccCheck')
->findOneBy(
array(
'CheckId' => $request->request->get('checkId', $id),
// 'approved' => GeneralConstant::APPROVED,
)
);
$existingBidData = null;
if ($check_here->getOpportunityId()) {
$lead = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\Opportunity')
->findOneBy(
array(
'opportunityId' => $check_here->getOpportunityId(),
// 'approved' => GeneralConstant::APPROVED,
)
);
if ($lead)
$existingBidData = json_decode($lead->getBidInformation(), true);
}
if ($existingBidData == null)
$existingBidData = [];
// return new JsonResponse($check_here);
return $this->render(
'@Application/pages/accounts/settings/view_bank_guarantee.html.twig',
array(
'page_title' => 'Bank Guarantee',
'data' => $check_here,
'bgTypes' => AccountsConstant::$BankGuarnteeTypes,
'bidDataList' => SalesConstant::$bidDataList,
'existingBidData' => $existingBidData,
'head_list' => Accounts::getParentLedgerHeads($em),
)
);
}
public function ApproveBankGuarantee(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$success = ProjectM::PaymentReceivedInstrumentApproveAction($em, $id);
return new JsonResponse(array('success' => $success));
}
public function CheckManagement(Request $request)
{
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
if ($request->request->has('carryForwardCheck')) {
$rows = $request->request->get('checkNumber');
$accountsHeadIds = $request->request->get('accountsHeadId', []);
$accountNumbers = $request->request->get('accountNumber', []);
$bookNumbers = $request->request->get('bookNumber', []);
$checkTypes = $request->request->get('checkType', []);
$checkAmounts = $request->request->get('checkAmount', []);
$checkDates = $request->request->get('checkDate', []);
$checkNarrations = $request->request->get('checkNarration', []);
$receivedHeads = $request->request->get('receivedHead', []);
$errors = [];
$submittedKeys = [];
$parsedRows = [];
if (!is_array($rows) || count($rows) < 1) {
$errors[] = 'Please add at least one cheque row.';
} else {
foreach ($rows as $key => $value) {
$rowNo = $key + 1;
$checkNumber = trim((string)$value);
$accountsHeadId = isset($accountsHeadIds[$key]) ? (int)$accountsHeadIds[$key] : 0;
$accountNumber = isset($accountNumbers[$key]) ? trim((string)$accountNumbers[$key]) : '';
$bookNumber = isset($bookNumbers[$key]) ? trim((string)$bookNumbers[$key]) : '';
$checkType = isset($checkTypes[$key]) ? trim((string)$checkTypes[$key]) : '';
$checkAmount = isset($checkAmounts[$key]) ? trim((string)$checkAmounts[$key]) : '';
$checkDateRaw = isset($checkDates[$key]) ? trim((string)$checkDates[$key]) : '';
$checkNarration = isset($checkNarrations[$key]) ? trim((string)$checkNarrations[$key]) : '';
$receivedHead = isset($receivedHeads[$key]) ? (int)$receivedHeads[$key] : 0;
if ($accountsHeadId <= 0) {
$errors[] = 'Please select bank account in row ' . $rowNo . '.';
}
if ($accountNumber === '') {
$errors[] = 'Please enter account number in row ' . $rowNo . '.';
}
if ($bookNumber === '') {
$errors[] = 'Please enter book number in row ' . $rowNo . '.';
}
if ($checkNumber === '' || !ctype_digit($checkNumber)) {
$errors[] = 'Please enter a valid cheque number in row ' . $rowNo . '.';
}
if ($checkType === '' || !in_array((int)$checkType, array(1, 2), true)) {
$errors[] = 'Please select cheque type in row ' . $rowNo . '.';
}
if ($checkAmount === '' || !is_numeric($checkAmount) || (float)$checkAmount <= 0) {
$errors[] = 'Please enter a valid amount in row ' . $rowNo . '.';
}
if ($checkDateRaw === '') {
$errors[] = 'Please enter cheque date in row ' . $rowNo . '.';
}
if ($receivedHead <= 0) {
$errors[] = 'Please select assigned account in row ' . $rowNo . '.';
}
$duplicateKey = $accountsHeadId . '|' . $checkNumber;
if ($checkNumber !== '' && isset($submittedKeys[$duplicateKey])) {
$errors[] = 'Cheque number ' . $checkNumber . ' is duplicated in the submitted rows.';
}
$submittedKeys[$duplicateKey] = 1;
if ($accountsHeadId > 0 && $checkNumber !== '' && ctype_digit($checkNumber)) {
$duplicate = $em->getRepository('ApplicationBundle\\Entity\\AccCheck')
->createQueryBuilder('c')
->where('c.accountsHeadId = :headId')
->andWhere('c.checkNumber = :checkNumber')
->setParameter('headId', $accountsHeadId)
->setParameter('checkNumber', (int)$checkNumber)
->getQuery()
->getOneOrNullResult();
if ($duplicate) {
$errors[] = 'Cheque number ' . $checkNumber . ' already exists for this account head.';
}
}
try {
$checkDate = new \DateTime($checkDateRaw);
} catch (\Exception $e) {
$errors[] = 'Please enter a valid cheque date in row ' . $rowNo . '.';
$checkDate = null;
}
$parsedRows[] = array(
'accountsHeadId' => $accountsHeadId,
'accountNumber' => $accountNumber,
'bookNumber' => $bookNumber,
'checkNumber' => $checkNumber,
'checkType' => $checkType,
'checkAmount' => $checkAmount,
'checkDate' => $checkDate,
'checkNarration' => $checkNarration,
'receivedHead' => $receivedHead,
);
}
}
if (empty($errors)) {
foreach ($parsedRows as $row) {
$new = new AccCheck();
$new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
$new->setCheckNumber($row['checkNumber']);
$new->setAccountsHeadId($row['accountsHeadId']);
$new->setAccountNumber($row['accountNumber']);
$new->setBookNumber($row['bookNumber']);
$new->setActive(GeneralConstant::ACTIVE);
$new->setAssigned(1);
$new_id_list = [$row['receivedHead']];
$new->setRecAccountsHeadId($row['receivedHead']);
$new->setRecAccountsHeadIdList(json_encode($new_id_list));
$new->setCheckNarration($row['checkNarration']);
$new->setCheckAmount($row['checkAmount']);
$checkDate = $row['checkDate'];
$new->setCheckDate($checkDate);
$new->setTransactionDate($checkDate);
$new->setLedgerHitDate($checkDate);
$new->setVoucherId(0);
$new->setStatus(3);
$new->setFormatId(0);
$new->setType($row['checkType']);
$new->setDetails(1);
$em->persist($new);
}
$em->flush();
$this->addFlash('success', 'Carry forward cheques added.');
} else {
$this->addFlash('error', implode(' ', array_unique($errors)));
}
} else {
$startCheckRaw = trim((string)$request->request->get('checkNumberStart'));
$endCheckRaw = trim((string)$request->request->get('checkNumberEnd'));
$accountNumber = trim((string)$request->request->get('accountNumber'));
$bookNumber = trim((string)$request->request->get('bookNumber'));
$accountsHeadId = (int)$request->request->get('accountsHeadId');
$formatId = (int)$request->request->get('formatId');
$errors = [];
if ($accountsHeadId <= 0) {
$errors[] = 'Please select account.';
}
if ($accountNumber === '') {
$errors[] = 'Please enter account number.';
}
if ($bookNumber === '') {
$errors[] = 'Please enter cheque book number.';
}
if ($startCheckRaw === '' || !ctype_digit($startCheckRaw)) {
$errors[] = 'Please enter a valid starting cheque number.';
}
if ($endCheckRaw !== '' && !ctype_digit($endCheckRaw)) {
$errors[] = 'Please enter a valid ending cheque number.';
}
if ($formatId <= 0) {
$errors[] = 'Please select cheque layout format.';
}
if (empty($errors)) {
$startCheck = (int)$startCheckRaw;
$endCheck = $endCheckRaw === '' ? $startCheck : (int)$endCheckRaw;
if ($startCheck <= 0) {
$errors[] = 'Please enter a valid starting cheque number.';
} elseif ($endCheck < $startCheck) {
$errors[] = 'Ending cheque number cannot be smaller than starting cheque number.';
} else {
for ($p = $startCheck; $p <= $endCheck; $p++) {
$duplicate = $em->getRepository('ApplicationBundle\\Entity\\AccCheck')->findOneBy(array(
'accountsHeadId' => $accountsHeadId,
'accountNumber' => $accountNumber,
'bookNumber' => $bookNumber,
'checkNumber' => $p,
'destroyed' => [0, null],
));
if ($duplicate) {
$errors[] = 'Cheque number ' . $p . ' already exists for this account and book.';
break;
}
}
}
}
if (empty($errors)) {
for ($p = $startCheck; $p <= $endCheck; $p++) {
$new = new AccCheck();
$new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
$new->setCheckNumber($p);
$new->setAccountsHeadId($accountsHeadId);
$new->setAccountNumber($accountNumber);
$new->setBookNumber($bookNumber);
$new->setActive(GeneralConstant::ACTIVE);
$new->setAssigned(0);
$new->setStatus(3);
$new->setFormatId($formatId);
$new->setType(1);
$new->setDetails(1);
$em->persist($new);
}
$em->flush();
$this->addFlash('success', 'Cheque range added.');
} else {
$this->addFlash('error', implode(' ', array_unique($errors)));
}
}
}
return $this->render(
'@Application/pages/accounts/settings/check_management.html.twig',
array(
'page_title' => 'Cheque Management',
'head_list' => Accounts::getParentLedgerHeads($em),
'format_list' => Accounts::CheckFormatList($em),
)
);
}
public function CheckManagementEntryForApp(Request $request)
{
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
$check_number_list = [];
if ($request->request->has('carryForwardCheck')) {
foreach ($request->request->get('checkNumber') as $key => $value) {
$new = new AccCheck();
$new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
$new->setCheckNumber($value);
$new->setAccountsHeadId($request->request->get('accountsHeadId')[$key]);
$new->setAccountNumber($request->request->get('accountNumber')[$key]);
$new->setBookNumber($request->request->get('bookNumber')[$key]);
$new->setActive(GeneralConstant::ACTIVE);
$new->setAssigned(1);
$new_id_list = [$request->request->get('receivedHead')[$key]];
$new->setRecAccountsHeadId($request->request->get('receivedHead')[$key]);
$new->setRecAccountsHeadIdList(json_encode($new_id_list));
$new->setCheckNarration($request->request->get('checkNarration')[$key]);
$new->setCheckAmount($request->request->get('checkAmount')[$key]);
$new->setCheckDate(new \DateTime($request->request->get('checkDate')[$key]));
$new->setTransactionDate(new \DateTime($request->request->get('checkDate')[$key]));
$new->setLedgerHitDate(new \DateTime($request->request->get('checkDate')[$key]));
$new->setVoucherId(0);
$new->setStatus(3); // pending. will stay like that till its bounced or confirmed transation physically
$new->setFormatId(0);
$new->setType($request->request->get('checkType')[$key]);
$new->setDetails(1);
$em->persist($new);
$em->flush();
}
} else if ($request->request->get('checkNumberEnd') != '')
for ($p = $request->request->get('checkNumberStart'); $p <= $request->request->get('checkNumberEnd'); $p++) {
$new = new AccCheck();
$new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
$new->setCheckNumber($p);
$new->setAccountsHeadId($request->request->get('accountsHeadId'));
$new->setAccountNumber($request->request->get('accountNumber'));
$new->setBookNumber($request->request->get('bookNumber'));
$new->setActive(GeneralConstant::ACTIVE);
$new->setAssigned(0);
$new->setStatus(3); // pending. will stay like that till its bounced or confirmed transation physically
$new->setFormatId($request->request->get('formatId'));
$new->setType(1);
$new->setDetails(1);
$em->persist($new);
$em->flush();
}
}
// return $this->render(
// 'ApplicationBundle:pages/accounts/settings:check_management.html.twig',
// array(
// 'page_title' => 'Cheque Management',
// 'head_list' => Accounts::getParentLedgerHeads($em),
// 'format_list' => Accounts::CheckFormatList($em),
// )
// );
return new JsonResponse([
'success' => true,
]);
}
public function SecurityCheckManagement(Request $request)
{
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
$check_here = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccCheck')
->findOneBy(
array(
'CheckId' => $request->request->get('checkId'),
// 'approved' => GeneralConstant::APPROVED,
)
);
if ($check_here) {
$ind_head_id_list = $request->request->get('recAccountsHeadId');
$new_id_list = [];
foreach ($ind_head_id_list as $ind_head_id) {
$new_id_list[] = $ind_head_id;
}
$check_here->setRecAccountsHeadId(null);
$check_here->setRecAccountsHeadIdList(json_encode($new_id_list));
$check_here->setCheckNarration($request->request->get('check_narration'));
$check_here->setCheckAmount($request->request->get('check_assigned_amount'));
// $check_here->setCheckDate(new \DateTime($request->request->get('checkDate')[$k]));
// $check_here->setCheckDate(new \DateTime($request->request->get('date')));
$check_here->setAssigned(1);
$check_here->setStatus(1); // pending. will stay like that till its bounced or confirmed transation physically
$check_here->setFormatId($request->request->get('formatId'));
$check_here->setType(1);
$check_here->setSecurityCheck(1);
$check_here->setDetails(1);
// $em->persist($new);
$em->flush();
}
}
$sec_check = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccCheck')
->findBy(
array(
'active' => GeneralConstant::ACTIVE,
'assigned' => [0, null],
'destroyed' => [0, null],
'securityCheck' => [0, null],
'type' => 1,
// 'approved' => GeneralConstant::APPROVED,
)
);
$assignable_check_list = [];
foreach ($sec_check as $s) {
$assignable_check_list[] = array(
'checkId' => $s->getCheckId(),
'id' => $s->getCheckId(),
'value' => $s->getCheckId(),
'accountsHeadId' => $s->getAccountsHeadId(),
'text' => $s->getAccountNumber() . "-" . sprintf("%07d", $s->getCheckNumber()),
'name' => $s->getAccountNumber() . "-" . sprintf("%07d", $s->getCheckNumber())
);
}
return $this->render(
'@Application/pages/accounts/settings/security_check.html.twig',
array(
'page_title' => 'Security Cheque Management',
'assignableCheckList' => $assignable_check_list,
'heads' => Accounts::getLedgerHeadsWithParents($em),
'format_list' => Accounts::CheckFormatList($em),
)
);
}
public function ChequeListAjax(Request $request)
{
$em = $this->getDoctrine()->getManager();
$allowed_ids = [];
$companyId = $this->getLoggedUserCompanyId($request);
$viewOption = 1;
if ($request->query->has('viewOption'))
$viewOption = $request->query->get('viewOption');
$listData = Accounts::GetChequetListForChequeListAjax($em, $viewOption, $request->isMethod('POST') ? 'POST' : 'GET', $request->request, $companyId);
// if ($request->isMethod('POST'))
{
if ($request->query->has('dataTableQry')) {
return new JsonResponse(
$listData
);
}
}
return $this->render(
'@Sales/pages/list_tables/client_list.html.twig',
// return $this->render('ApplicationBundle:pages/dashboard:test_pix_invent.html.twig',
array(
'page_title' => 'Cheque List',
)
);
}
public function GetCheckList(Request $request)
{
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
$head_list = Accounts::HeadList($em);
$voucher_list = Accounts::VoucherListForCheckRegister($em);
$find_array = array(
'type' => 1
);
if ($request->request->has('viewOption')) {
if ($request->request->get('viewOption') == 1)
$find_array = ['active' => GeneralConstant::ACTIVE];
if ($request->request->get('viewOption') == 2)
$find_array = ['active' => GeneralConstant::INACTIVE];
}
$assignedflag = $request->request->has('assign_flag') ? $request->request->get('assign_flag') : 0;
$unassignedflag = $request->request->has('unassign_flag') ? $request->request->get('unassign_flag') : 0;
$securityCheckFlag = $request->request->has('security_check_flag') ? $request->request->get('security_check_flag') : 0;
if ($assignedflag == 1)
$find_array['assigned'] = 1;
if ($unassignedflag == 1)
$find_array['assigned'] = [0, null];
if ($securityCheckFlag == 1)
$find_array['securityCheck'] = 1;
$check_query = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccCheck')
->findBy(
$find_array,
array(
// 'checkNumber'=>'ASC'
'CheckId' => 'ASC'
)
);
$check_data = [];
$start_date = $request->request->has('start_date') ? (new \DateTime($request->request->get('start_date'))) : '';
$end_date = $request->request->has('end_date') ? (new \DateTime($request->request->get('end_date') . ' ' . ' 23:59:59.999')) : '';
// if($end_date!='')
// $end_date->modify('+1 day');
$book_list_by_bank = [];
foreach ($check_query as $entry) {
if ($assignedflag == 1) {
if ($securityCheckFlag == 0) {
$checkTransDate = $entry->getTransactionDate();
if ($checkTransDate == null)
continue;
if ($start_date != '' && ($checkTransDate instanceof \DateTime) && ($start_date > $checkTransDate))
continue;
if ($end_date != '' && ($checkTransDate instanceof \DateTime) && ($end_date < $checkTransDate))
continue;
}
}
$v_date = isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['date'] : '';
// if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
if ($start_date != '' && ($v_date instanceof \DateTime) && ($start_date > $v_date))
continue;
// if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
if ($end_date != '' && ($v_date instanceof \DateTime) && ($end_date < $v_date))
continue;
$checkDate = ($entry->getCheckDate() instanceof \DateTime) ? $entry->getCheckDate()->format('m/d/Y') : '';
$assignedDate = ($entry->getAssignedDate() instanceof \DateTime) ? $entry->getAssignedDate()->format('m/d/Y') : '';
if (!isset($book_list_by_bank[$entry->getAccountsHeadId()])) $book_list_by_bank[$entry->getAccountsHeadId()] = [];
if (!in_array($entry->getBookNumber(), $book_list_by_bank[$entry->getAccountsHeadId()])) {
$book_list_by_bank[$entry->getAccountsHeadId()][] = $entry->getBookNumber();
}
$check_data[] = array(
'checkId' => $entry->getCheckId(),
// 'checkNumber'=>$entry->getCheckNumber(),
'checkNumber' => sprintf("%07d", $entry->getCheckNumber()),
'checkNarration' => $entry->getCheckNarration(),
'voucherNarration' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['desc'] : '',
'voucherDate' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['date']->format('m/d/Y') : '',
'accountNumber' => $entry->getAccountNumber(),
'checkDate' => $checkDate,
'active' => $entry->getActive(),
'head' => isset($head_list[$entry->getAccountsHeadId()]) ? $head_list[$entry->getAccountsHeadId()]['name'] : '',
'head_id' => $entry->getAccountsHeadId(),
'received_head' => isset($head_list[$entry->getRecAccountsHeadId()]) ? $head_list[$entry->getRecAccountsHeadId()]['name'] : '',
'received_head_id' => $entry->getRecAccountsHeadId(),
'received_head_id_list' => $entry->getRecAccountsHeadIdList(),
'assignedDate' => $assignedDate,
'checkAmount' => $entry->getCheckAmount(),
'voucher_number' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['doc_hash'] : '',
'voucher_id' => $entry->getVoucherId(),
'printed' => $entry->getPrinted(),
);
}
$count_details_by_bank = [];
if ($request->request->has('countDetails')) {
$check_query = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccCheck')
->findAll();
$count_details_by_bank = [];
$assigned_books = [];
foreach ($check_query as $entry) {
if (isset($count_details_by_bank[$entry->getAccountsHeadId()])) {
$count_details_by_bank[$entry->getAccountsHeadId()]['total_chk'] += 1;
if ($entry->getAssigned() == 1)
$count_details_by_bank[$entry->getAccountsHeadId()]['total_ass'] += 1;
else
$count_details_by_bank[$entry->getAccountsHeadId()]['total_avail'] += 1;
if (!in_array($entry->getBookNumber(), $assigned_books)) {
$count_details_by_bank[$entry->getAccountsHeadId()]['books'] .= (', ' . $entry->getBookNumber());
array_push($assigned_books, $entry->getBookNumber());
}
} else {
$count_details_by_bank[$entry->getAccountsHeadId()]['total_chk'] = 1;
$count_details_by_bank[$entry->getAccountsHeadId()]['total_ass'] = 0;
$count_details_by_bank[$entry->getAccountsHeadId()]['books'] = '';
$count_details_by_bank[$entry->getAccountsHeadId()]['total_avail'] = 0;
if ($entry->getAssigned() == 1)
$count_details_by_bank[$entry->getAccountsHeadId()]['total_ass'] = 1;
else
$count_details_by_bank[$entry->getAccountsHeadId()]['total_avail'] = 1;
if (!in_array($entry->getBookNumber(), $assigned_books)) {
$count_details_by_bank[$entry->getAccountsHeadId()]['books'] = (' ' . $entry->getBookNumber());
array_push($assigned_books, $entry->getBookNumber());
}
}
}
}
if ($securityCheckFlag == 0) {
foreach ($voucher_list as $key => $entry) {
$v_date = $entry['date'];
// if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
if ($start_date != '' && ($v_date instanceof \DateTime) && ($start_date > $v_date))
continue;
// if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
if ($end_date != '' && ($v_date instanceof \DateTime) && ($end_date < $v_date))
continue;
if (!in_array($entry['prMethod'], [3, 4]))
continue;
// if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
// continue;
// if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
// continue;
$trans_details = $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(
array(
'transactionId' => $key,
'position' => 'cr'
)
);
foreach ($trans_details as $value) {
$checkDate = $entry['date']->format('m/d/Y');
$assignedDate = $entry['date']->format('m/d/Y');
$dr_details = $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(
array(
'transactionId' => $key,
'position' => 'dr'
)
);
$rec_id_list = [];
$rec_narr = "";
foreach ($dr_details as $dt) {
$rec_id_list[] = $dt->getAccountsHeadId();
$rec_narr .= $head_list[$dt->getAccountsHeadId()]['name'];
$rec_narr .= ", ";
}
$check_data[] = array(
'checkId' => 0,
'checkNumber' => $entry['prReference'],
'checkNarration' => $rec_narr,
'voucherNarration' => $entry['desc'],
'voucherDate' => $entry['date']->format('m/d/Y'),
'accountNumber' => '',
'checkDate' => $checkDate,
'head' => $head_list[$value->getAccountsHeadId()]['name'],
'head_id' => $value->getAccountsHeadId(),
'received_head' => $rec_narr,
'received_head_id' => 0,
'received_head_id_list' => json_encode($rec_id_list),
'assignedDate' => $assignedDate,
'checkAmount' => $value->getAmount(),
'voucher_number' => $entry['doc_hash'],
'voucher_id' => $key,
'printed' => 1,
);
}
}
}
if ($check_data) {
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));
}
return new JsonResponse(array("success" => false, 'start_date' => $start_date, 'end_date' => $end_date,));
}
return new JsonResponse(array("success" => false));
}
public function GetCheckListForVoucher(Request $request)
{
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
$cr_table_heads = $request->request->get('cr_table_heads', []);
$dr_table_heads = $request->request->get('dr_table_heads', []);
$voucher_heads = [];
$v_id = $request->request->get('v_id', 0);
$voucher_list = Accounts::VoucherList($em, $v_id, 1);
foreach ($voucher_list as $t) {
foreach ($t['det'] as $td)
$voucher_heads[] = $td['head_id'];
}
$head_list = Accounts::HeadList($em, array_merge($cr_table_heads, $dr_table_heads, $voucher_heads));
$checkAssignType = $request->request->get('checkAssignType');
$cr_table_heads_amount = $request->request->get('cr_table_heads_amount');
$check_list = [];
$check_list_array = [];
$check_list_by_ac_head = [];
if ($request->request->get('checkModalType') == 'edit') {
//first check if the voucher is already tagged ( usually for edit)
if ($v_id != 0) {
$check_query = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccCheck')
->findBy(
array(
'voucherId' => $v_id,
'active' => GeneralConstant::ACTIVE,
'destroyed' => [0, null],
'securityCheck' => [0, null],
),
array(
// 'checkNumber'=>'ASC'
'CheckId' => 'ASC'
)
);
foreach ($check_query as $entry) {
$checkDate = ($entry->getCheckDate() instanceof \DateTime) ? $entry->getCheckDate()->format('m/d/Y') : '';
$assignedDate = ($entry->getAssignedDate() instanceof \DateTime) ? $entry->getAssignedDate()->format('m/d/Y') : '';
$chk = array(
'checkId' => $entry->getCheckId(),
'checkNumber' => sprintf("%07d", $entry->getCheckNumber()),
'accountNumber' => $entry->getAccountNumber(),
'checkDate' => $checkDate,
'head' => $head_list[$entry->getAccountsHeadId()]['name'],
'head_id' => $entry->getAccountsHeadId(),
'received_head' => isset($head_list[$entry->getRecAccountsHeadId()]) ? $head_list[$entry->getRecAccountsHeadId()]['name'] : '',
'received_head_id' => $entry->getRecAccountsHeadId(),
'received_head_id_list' => $entry->getRecAccountsHeadIdList(),
'assignedDate' => $assignedDate,
'checkAmount' => $entry->getCheckAmount(),
'voucher_number' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['doc_hash'] : '',
'voucher_id' => $entry->getVoucherId(),
);
$check_list_by_ac_head[$entry->getAccountsHeadId()][] = $chk;
$check_list[$entry->getCheckId()] = $chk;
}
}
//now getting un assigned checks for the same heads
$check_query = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccCheck')
->findBy(
array(
'accountsHeadId' => $cr_table_heads,
'active' => GeneralConstant::ACTIVE,
'assigned' => [0, null],
'destroyed' => [0, null],
'securityCheck' => [0, null],
),
array(
// 'checkNumber'=>'ASC'
'CheckId' => 'ASC'
)
);
foreach ($check_query as $entry) {
$checkDate = ($entry->getCheckDate() instanceof \DateTime) ? $entry->getCheckDate()->format('m/d/Y') : '';
$assignedDate = ($entry->getAssignedDate() instanceof \DateTime) ? $entry->getAssignedDate()->format('m/d/Y') : '';
$chk = array(
'checkId' => $entry->getCheckId(),
'checkNumber' => sprintf("%07d", $entry->getCheckNumber()),
'accountNumber' => $entry->getAccountNumber(),
'checkDate' => $checkDate,
'head' => $head_list[$entry->getAccountsHeadId()]['name'],
'head_id' => $entry->getAccountsHeadId(),
'received_head' => isset($head_list[$entry->getRecAccountsHeadId()]) ? $head_list[$entry->getRecAccountsHeadId()]['name'] : '',
'received_head_id' => $entry->getRecAccountsHeadId(),
'assignedDate' => $assignedDate,
'checkAmount' => $entry->getCheckAmount(),
'voucher_number' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['doc_hash'] : '',
'voucher_id' => $entry->getVoucherId(),
);
$check_list_by_ac_head[$entry->getAccountsHeadId()][] = $chk;
$check_list[$entry->getCheckId()] = $chk;
}
// if(empty($check_query))
if ($check_list) {
return new JsonResponse(array(
"success" => true,
"content" => $check_list,
"check_list_by_ac_head" => $check_list_by_ac_head,
"check_list" => $check_list,
'head_list' => $head_list
));
}
}
if ($request->request->get('checkModalType') == 'view') {
$check_query = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccCheck')
->findBy(
array(
'voucherId' => $v_id
)
);
foreach ($check_query as $entry) {
$checkDate = ($entry->getCheckDate() instanceof \DateTime) ? $entry->getCheckDate()->format('m/d/Y') : '';
$assignedDate = ($entry->getAssignedDate() instanceof \DateTime) ? $entry->getAssignedDate()->format('m/d/Y') : '';
$chk = array(
'checkId' => $entry->getCheckId(),
'checkNumber' => sprintf("%07d", $entry->getCheckNumber()),
'accountNumber' => $entry->getAccountNumber(),
'checkDate' => $checkDate,
'checkNarration' => $entry->getCheckNarration(),
'head' => $head_list[$entry->getAccountsHeadId()]['name'],
'head_id' => $entry->getAccountsHeadId(),
'printed' => $entry->getPrinted(),
'received_head' => isset($head_list[$entry->getRecAccountsHeadId()]) ? $head_list[$entry->getRecAccountsHeadId()]['name'] : '',
'received_head_id' => $entry->getRecAccountsHeadId(),
'received_head_id_list' => $entry->getRecAccountsHeadIdList(),
'assignedDate' => $assignedDate,
'checkAmount' => $entry->getCheckAmount(),
'voucher_number' => isset($voucher_list[$entry->getVoucherId()]) ? $voucher_list[$entry->getVoucherId()]['doc_hash'] : '',
'voucher_id' => $entry->getVoucherId(),
);
$check_list_by_ac_head[$entry->getAccountsHeadId()][] = $chk;
$check_list[$entry->getCheckId()] = $chk;
$check_list_array[] = $chk;
}
if (!empty($check_list)) {
return new JsonResponse(array(
"success" => true,
"content" => $check_list,
// "check_list_by_ac_head"=>$check_list_by_ac_head,
"check_list" => $check_list_array,
'head_list' => $head_list
));
}
}
return new JsonResponse(array("success" => false));
}
return new JsonResponse(array("success" => false));
}
public function GetCheckListForBrs(Request $request)
{
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
$bank_head = $request->request->get('bank_head');
$statement_date = $request->request->get('statement_date');
$statement_date_dt = new \DateTime($statement_date);
$statement_date_str = $statement_date_dt->format('Y-m-d');
$head_list = Accounts::HeadList($em);
// $voucher_list=Accounts::VoucherList($em);
$voucher_list = Accounts::VoucherListForBrs($em, $bank_head);
$check_list = [];
$check_list_array = [];
$check_list_by_ac_head = [];
$get_kids_sql = "SELECT * FROM acc_check ";
// $get_kids_sql.=" Where status=3 and check_date <='".$statement_date_str." 00:00:00' and ( rec_accounts_head_id=".$bank_head;
$get_kids_sql .= " Where status=3 and ledger_hit_date <='" . $statement_date_str . " 00:00:00' and ( rec_accounts_head_id=" . $bank_head;
// $get_kids_sql.=" Where status=3 and transaction_date <='".$statement_date_str." 00:00:00' and ( rec_accounts_head_id=".$bank_head;
$get_kids_sql .= " or accounts_head_id=" . $bank_head . ") ";
$get_kids_sql .= ' ORDER BY check_id ASC';
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
if (!empty($query_output)) {
foreach ($query_output as $entry) {
// if($entry['type']==1)
// {
// $sub=($entry['rec_accounts_head_id']==$bank_head?0:$entry['check_amount']);
// $add=($entry['rec_accounts_head_id']==$bank_head?$entry['check_amount']:0);
// }
// if($entry['type']==2)
// {
$sub = ($entry['rec_accounts_head_id'] == $bank_head ? 0 : $entry['check_amount']);
$add = ($entry['rec_accounts_head_id'] == $bank_head ? $entry['check_amount'] : 0);
// }
$checkDate = ($entry['check_date'] instanceof \DateTime) ? $entry['check_date']->format('m-d-Y') : (new \DateTime($entry['check_date']))->format('m-d-Y');
$assignedDate = ($entry['assigned_date'] instanceof \DateTime) ? $entry['assigned_date']->format('m-d-Y') : '';
$chk = array(
'checkId' => $entry['check_id'],
'checkNumber' => $entry['check_number'],
'accountNumber' => $entry['acc_number'],
'checkDate' => $checkDate,
'head' => $head_list[$entry['accounts_head_id']]['name'],
'head_id' => $entry['accounts_head_id'],
'check_type' => $entry['type'],
'received_head' => isset($head_list[$entry['rec_accounts_head_id']]) ? $head_list[$entry['rec_accounts_head_id']]['name'] : '',
'received_head_id' => $entry['rec_accounts_head_id'],
'assignedDate' => $assignedDate,
'checkAmount' => $entry['check_amount'],
'sub' => $sub,
'add' => $add,
'received_head_id_list' => ($entry['rec_accounts_head_id_list'] == null) ? [] : json_decode($entry['rec_accounts_head_id_list'], true),
'voucherNumber' => isset($voucher_list[$entry['voucher_id']]) ? $voucher_list[$entry['voucher_id']]['doc_hash'] : '',
'voucherDate' => isset($voucher_list[$entry['voucher_id']]) ? $voucher_list[$entry['voucher_id']]['date']->format('m-d-Y') : '',
'transactionDate' => isset($voucher_list[$entry['voucher_id']]) ? $voucher_list[$entry['voucher_id']]['date']->format('m-d-Y') : '',
'voucher_id' => $entry['voucher_id'],
);
// $check_list_by_ac_head[$entry->getAccountsHeadId()][]=$chk;
$check_list[$entry['check_id']] = $chk;
$check_list_array[] = $chk;
}
}
foreach ($voucher_list as $key => $entry) {
$v_date = $entry['date'];
$l_date = $entry['ledgerHitDate'];
if ($l_date == null)
$l_date = $v_date;
// if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
// if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
if ($entry['ledgerHit'] != 1)
continue;
if ($statement_date_dt != '' && ($l_date instanceof \DateTime) && ($statement_date_dt < $l_date))
continue;
if ($entry['document_type'] != 6) {
if (!in_array($entry['prMethod'], [3, 4]))
continue;
}
if ($entry['document_type'] == 6) {
if (!in_array($entry['prMethod'], [1]))
continue;
}
if ($entry['provisional'] != 1)
continue;
if (!in_array($bank_head, $entry['pendReconIdList']))
continue;
// if($start_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($start_date>$entry->getCheckDate()))
// continue;
// if($end_date!=''&&($entry->getCheckDate() instanceof \DateTime)&&($end_date<$entry->getCheckDate()))
// continue;
if ($entry['document_type'] == 4 || $entry['document_type'] == 6)
$trans_details = $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(
array(
'transactionId' => $key,
'position' => 'cr',
// 'accountsHeadId'=>$bank_head
)
);
else
$trans_details = $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(
array(
'transactionId' => $key,
'position' => 'cr',
'accountsHeadId' => $bank_head
)
);
if (!empty($trans_details)) {
foreach ($trans_details as $k2 => $value) {
$checkDate = $entry['date']->format('m/d/Y');
if ($l_date != null)
$ledgerHitDate = $entry['ledgerHitDate']->format('m/d/Y');
else
$ledgerHitDate = $entry['date']->format('m/d/Y');
$assignedDate = $entry['date']->format('m/d/Y');
$dr_details = $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(
array(
'transactionId' => $key,
'position' => 'dr'
)
);
$rec_id_list = [];
$rec_narr = "";
foreach ($dr_details as $dt) {
$rec_id_list[] = $dt->getAccountsHeadId();
$rec_narr .= $head_list[$dt->getAccountsHeadId()]['name'];
$rec_narr .= ", ";
}
$chk = array(
'checkId' => 'v' . $key . "_" . $value->getTransactionDetailsId(),
'checkNumber' => $entry['prReference'],
'prRef' => $entry['earlyPrReference'],
'accountNumber' => '',
'sub' => ($value->getAccountsHeadId() == $bank_head) ? $value->getAmount() : 0,
'add' => ($value->getAccountsHeadId() != $bank_head) ? $value->getAmount() : 0,
'checkDate' => $ledgerHitDate,
'head' => $head_list[$value->getAccountsHeadId()]['name'],
'head_id' => $value->getAccountsHeadId(),
'check_type' => 1,
'received_head' => $rec_narr,
'received_head_id' => 0,
'received_head_id_list' => $rec_id_list,
// 'received_head_id_list' => json_encode($rec_id_list),
'assignedDate' => $assignedDate,
'checkAmount' => $value->getAmount(),
'voucherNumber' => $entry['doc_hash'],
'voucherDate' => $v_date->format('m-d-Y'),
'transactionDate' => $v_date->format('m-d-Y'),
'voucher_id' => $key,
);
// $check_list_by_ac_head[$entry->getAccountsHeadId()][]=$chk;
$check_list['v' . $key . "_" . $value->getTransactionDetailsId()] = $chk;
$check_list_array[] = $chk;
}
}
}
///old
// $get_kids_sql="select acc_closing_balance.balance, acc_closing_balance.opening, acc_closing_balance.date,
// acc_accounts_head.path_tree,
// acc_accounts_head.head_nature
// from acc_closing_balance
// join acc_accounts_head on acc_accounts_head.accounts_head_id=acc_closing_balance.accounts_head_id ";
//// $get_kids_sql.=" Where parent_id in(".implode(",", $path_array).")";
// $get_kids_sql.=" where acc_accounts_head.accounts_head_id=".$bank_head;
//
// $get_kids_sql .=" AND acc_closing_balance.date <='".$statement_date_str." 00:00:00' ";
//
//
//
// $get_kids_sql.=" Order by acc_closing_balance.date desc LIMIT 1";
// $stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
//
// $query_output = $stmt;
///old end
$head_last_balance_data = [];
$head_last_balance = 0;
//new method
$balance_data = Accounts::GetBalanceOnDate($em, $statement_date_str, []);
$head_last_balance = $balance_data[$bank_head]['end_balance']['balance'];
//new end
// if(!empty($query_output))
// {
// $head_last_balance_data=$query_output[0] ;
// $head_last_balance=$query_output[0]['balance'] ;
// }
// else
// {
// $head_last_balance_data=array() ;
// $head_last_balance=$head_list[$bank_head]['opening_balance'] ;
// }
// if($check_list){
if ($check_list || $head_last_balance != 0) {
return new JsonResponse(array(
"success" => true,
"content" => $check_list,
// "check_list_by_ac_head"=>$check_list_by_ac_head,
'def_date' => $statement_date_dt->format('F d, Y'),
"check_list" => $check_list,
"check_list_array" => $check_list_array,
'head_list' => $head_list,
'head_last_balance_data' => $head_last_balance_data,
'head_last_balance' => $head_last_balance,
));
}
return new JsonResponse(array("success" => false));
}
return new JsonResponse(array("success" => false));
}
public function CreatePurchaseInvoice(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
$data = $request->request;
$entity_id = array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice']; //change
$dochash = $request->request->get('docHash'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash,
$id
)) {
$this->addFlash(
'error',
'Sorry Couldnot insert Data.'
);
} else {
$funcname = 'PurchaseInvoice';
$doc_id = $id;
DeleteDocument::$funcname($em, $doc_id, 0);
$create_new_pi = Accounts::CreatePurchaseInvoice($id, $this->getDoctrine()->getManager(), $data, $request->getSession()->get(UserConstants::USER_LOGIN_ID));
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice'],
$create_new_pi['pi_id'],
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice'],
$create_new_pi['pi_id'],
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$this->addFlash(
'success',
'New Invoice Added.'
);
$url = $this->generateUrl(
'view_purchase_invoice'
);
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),
"Purchase Invoice : " . $dochash . " Has Been Created And is Under Processing",
'pos',
System::getPositionIdsByDepartment($em, [GeneralConstant::ACCOUNTS_DEPARTMENT, GeneralConstant::PURCHASE_DEPARTMENT]),
'success',
$url . "/" . $create_new_pi['pi_id'],
"Purchase Bill"
);
return $this->redirect($url . "/" . $create_new_pi['pi_id']);
}
}
$extData = [];
$extDetailsData = [];
if ($id == 0) {
} else {
$extTrans = $em->getRepository('ApplicationBundle\\Entity\\PurchaseInvoice')->findOneBy(
array(
'purchaseInvoiceId' => $id, ///material
)
);
//now if its not editable, redirect to view
if ($extTrans) {
if ($extTrans->getEditFlag() != 1) {
$url = $this->generateUrl(
'view_purchase_invoice'
);
return $this->redirect($url . "/" . $id);
} else {
$extData = $extTrans;
$extDetailsData = $em->getRepository('ApplicationBundle\\Entity\\PurchaseInvoiceItem')->findBy(
array(
'purchaseInvoiceId' => $id, ///material
)
);
}
} else {
}
}
return $this->render(
'@Accounts/pages/input_forms/purchase_invoice.html.twig',
array(
'page_title' => 'Purchase Invoice',
'extData' => $extData,
'extDetailsData' => $extDetailsData,
'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
'grn_list' => Inventory::GrnListForPi($this->getDoctrine()->getManager()),
'grn_list_array' => Inventory::GrnListForPiArray($this->getDoctrine()->getManager()),
'warehouse_action_list' => Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), '')
// 'dt_debug'=>$data
// 'po'=>Inventory::getPurchaseOrderList
)
);
}
public function CreateServicePurchaseInvoice(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
$data = $request->request;
$entity_id = array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice']; //change
$dochash = $request->request->get('docHash'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash,
$id
)) {
$this->addFlash(
'error',
'Sorry Couldnot insert Data.'
);
} else {
$funcname = 'PurchaseInvoice';
$doc_id = $id;
DeleteDocument::$funcname($em, $doc_id, 0);
$create_new_pi = Accounts::CreatePurchaseInvoice($id, $this->getDoctrine()->getManager(), $data, $request->getSession()->get(UserConstants::USER_LOGIN_ID));
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice'],
$create_new_pi['pi_id'],
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice'],
$create_new_pi['pi_id'],
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$this->addFlash(
'success',
'New Invoice Added.'
);
$url = $this->generateUrl(
'view_purchase_invoice'
);
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),
"Purchase Invoice : " . $dochash . " Has Been Created And is Under Processing",
'pos',
System::getPositionIdsByDepartment($em, [GeneralConstant::ACCOUNTS_DEPARTMENT, GeneralConstant::PURCHASE_DEPARTMENT]),
'success',
$url . "/" . $create_new_pi['pi_id'],
"Purchase Bill"
);
return $this->redirect($url . "/" . $create_new_pi['pi_id']);
}
}
$extData = [];
$extDetailsData = [];
if ($id == 0) {
} else {
$extTrans = $em->getRepository('ApplicationBundle\\Entity\\PurchaseInvoice')->findOneBy(
array(
'purchaseInvoiceId' => $id, ///material
)
);
//now if its not editable, redirect to view
if ($extTrans) {
if ($extTrans->getEditFlag() != 1) {
$url = $this->generateUrl(
'view_purchase_invoice'
);
return $this->redirect($url . "/" . $id);
} else {
$extData = $extTrans;
$extDetailsData = $em->getRepository('ApplicationBundle\\Entity\\PurchaseInvoiceItem')->findBy(
array(
'purchaseInvoiceId' => $id, ///material
)
);
}
} else {
}
}
return $this->render(
'@Accounts/pages/input_forms/service_purchase_invoice.html.twig',
array(
'page_title' => 'Service Purchase Invoice',
'extData' => $extData,
'extDetailsData' => $extDetailsData,
'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
'grn_list' => Inventory::GrnListForPi($this->getDoctrine()->getManager()),
'grn_list_array' => Inventory::GrnListForPiArray($this->getDoctrine()->getManager()),
'warehouse_action_list' => Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), '')
// 'dt_debug'=>$data
// 'po'=>Inventory::getPurchaseOrderList
)
);
}
//=========================================================================
// Previous CreateExpenseInvoice
//=========================================================================
/*
public function CreateExpenseInvoice(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
$data = $request->request;
$expBillType = $data->get('expenseTypeId');
foreach ($data->get('expBillCheckMarkedExpense') as $row) {
$entity_id = array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice']; //change
$result = $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')
->findBy(
array(
'typeHash' => 'EI',
'prefixHash' => $data->get('expBillTypeId')[$row],
'assocHash' => $data->get('expBillPartyHeadId')[$row],
)
);
$count = count($result);
$count++;
$dochash = 'EI/' . $data->get('expBillTypeId')[$row] . '/' . $data->get('expBillPartyHeadId')[$row] . '/' . $count; //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash,
$id
)) {
$this->addFlash(
'error',
'Sorry Couldnot insert Data.'
);
} else {
$new_ei = Accounts::CreateExpenseInvoice(
$this->getDoctrine()->getManager(),
$data,
$row,
$expBillType,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
$new_ei['ei_id'],
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
$new_ei['ei_id'],
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
}
}
}
$extData = $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')
->findOneBy(
array(
'expenseInvoiceId' => $id,
)
);
if (!$extData)
$extData = [];
return $this->render(
'@Accounts/pages/input_forms/expense_bill.html.twig',
array(
'page_title' => 'Expense Bills',
'extData' => $extData,
'party_list' => Accounts::getParentLedgerHeads($this->getDoctrine()->getManager(), 'ep'),
'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
'supplier_list_by_ac_head' => Accounts::SupplierListByAcHead($this->getDoctrine()->getManager()),
'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
'grn_list' => Inventory::GrnListForEi($this->getDoctrine()->getManager(), 1),
'grn_list_array' => Inventory::GrnListForEiArray($this->getDoctrine()->getManager(), 1),
// 'po'=>Inventory::getPurchaseOrderList
)
);
}
*/
public function CreateExpenseInvoice(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$em_goc = $this->getDoctrine()->getManager('company_group');
// ====================================================================
// POST – Create or Edit
// ====================================================================
if ($request->isMethod('POST')) {
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
// Verify approval signature before doing anything
if (!DocValidation::isSignatureOk($em, $loginId, $approveHash)) {
return new JsonResponse([
'success' => false,
'errorText' => 'Approval Hash Mismatch',
'errorStr' => 'Approval Hash Mismatch',
]);
}
// Build cost-distribution map from parallel arrays
$exp_distribution_poitemId = $request->request->get('exp_distribution_poitemId', []);
$exp_distribution_amount = $request->request->get('exp_distribution_amount', []);
$costDistributionData = [];
foreach ($exp_distribution_poitemId as $k => $poItemId) {
$costDistributionData[$poItemId] = [
'poItemId' => $poItemId,
'amount' => $exp_distribution_amount[$k],
];
}
// Normalise any date string to Y-m-d, defaulting to today
$normaliseDate = static function (string $raw): string {
if ($raw === '') return date('Y-m-d');
$ts = strtotime($raw);
return ($ts !== false) ? date('Y-m-d', $ts) : date('Y-m-d');
};
// ----------------------------------------------------------------
// Build $expenseDataList from whichever input path was used.
// Every row is treated as a fully independent invoice (no parent/child).
//
// PATH A – flat arrays from the Twig form (expenseDate[], …)
// PATH B – JSON blob in `expenseData` (mobile / API)
// PATH C – classic single-field POST (legacy fallback)
// ----------------------------------------------------------------
$expenseDataList = [];
$flatDates = $request->request->get('expenseDate', []);
if (!empty($flatDates) && is_array($flatDates)) {
// PATH A
$flatTypes = $request->request->get('expenseType', []);
$flatSubTypes = $request->request->get('expenseSubType', []);
$flatDocIds = $request->request->get('docId', []);
$flatAmounts = $request->request->get('expenseAmount', []);
$flatExpenseIds = $request->request->get('expenseId', []);
$flatCcIds = $request->request->get('ccId', []);
$flatToBePaidTo = $request->request->get('expenseToBePaidTo', []);
$flatCurrencyIds = $request->request->get('currencyId', []);
$flatCurrRates = $request->request->get('currencyMultiplyRate', []);
$flatFroms = $request->request->get('expenseFrom', []);
$flatFromNotes = $request->request->get('expenseFromNote', []);
$flatTos = $request->request->get('expenseTo', []);
$flatToNotes = $request->request->get('expenseToNote', []);
$flatDescs = $request->request->get('description', []);
$flatMarkers = $request->request->get('expenseMarkerHash', []);
$flatWbsCodes = $request->request->get('wbsCode', []);
$flatWbsActivityNames = $request->request->get('wbsActivityName', []);
$flatUploaded = $request->request->get('uploadedFile', []);
$flatInvoiceIds = $request->request->get('invoiceId', []);
$flatInvoiceBalancing = $request->request->get('invoiceBalancing', []);
$rowCount = count($flatDates);
for ($i = 0; $i < $rowCount; $i++) {
$toNote = (string)($flatToNotes[$i] ?? '');
$toNote = trim($toNote) === '0' ? '' : $toNote;
$expenseDataList[] = [
'expenseType' => (int)($flatTypes[$i] ?? 0),
'expenseSubType' => (int)($flatSubTypes[$i] ?? 0),
'expenseId' => (int)($flatExpenseIds[$i] ?? 0),
'ccId' => (int)($flatCcIds[$i] ?? 0),
'currencyId' => (int)($flatCurrencyIds[$i] ?? 0),
'currencyMultiply' => 1,
'currencyMultiplyRate' => (float)($flatCurrRates[$i] ?? 1),
'docId' => (int)($flatDocIds[$i] ?? 0),
'expenseToBePaidTo' => $flatToBePaidTo[$i] ?? 0,
'expenseFrom' => (int)($flatFroms[$i] ?? 0),
'expenseFromNote' => (string)($flatFromNotes[$i] ?? ''),
'expenseTo' => (int)($flatTos[$i] ?? 0),
'expenseToNote' => $toNote,
'expenseAmount' => (float)($flatAmounts[$i] ?? 0),
'previousAdvanceAmount' => 0,
'checkDate' => '',
'checkNumber' => '',
'checkNarration' => '',
'checkId' => 0,
'description' => (string)($flatDescs[$i] ?? ''),
'expenseMarkerHash' => (string)($flatMarkers[$i] ?? ''),
'markerHash' => (string)($flatMarkers[$i] ?? ''),
'wbsCode' => (string)($flatWbsCodes[$i] ?? ''),
'wbsActivityName' => (string)($flatWbsActivityNames[$i] ?? ''),
'expenseDate' => $normaliseDate((string)($flatDates[$i] ?? '')),
'invoiceBalancing' => (int)($flatInvoiceBalancing[$i] ?? 0),
'attachedFile' => [],
'uploadedFile' => (string)($flatUploaded[$i] ?? ''),
'expenseInvocationStrategyOnGrn' => null,
'expenseInvocationTypeOnItems' => null,
'isChildInvoice' => 0,
'costDistributionData' => $costDistributionData,
'expenseDistributionOnProduct' => 0,
'expenseSubCategory' => 0,
'expenseSubCategoryOption' => 0,
'expense_sub_category' => 0,
'expense_sub_category_option' => 0,
'invoiceId' => (int)($flatInvoiceIds[$i] ?? 0),
];
}
} else {
$expense_data = $request->request->get('expenseData', []);
$expense_type = $request->request->get('expense_type', 0);
if (is_string($expense_data)) {
$expense_data = json_decode($expense_data, true);
}
if (!empty($expense_data)) {
// PATH B – JSON / mobile
$currTs = (new \DateTime())->format('U');
foreach ($expense_data as $idx => $expData) {
// Save embedded base64 image to disk
if (isset($expData['imageBase64'])) {
$imgData = base64_decode(
preg_replace('#^data:image/\w+;base64,#i', '', $expData['imageBase64'])
);
$fileName = $currTs . md5(uniqid()) . '.png';
$storePath = 'uploads/ExpenseInvoice/';
MiscActions::RemoveExpiredFiles($em_goc);
$uplDir = $this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath;
if (!file_exists($uplDir)) {
mkdir($uplDir, 0777, true);
}
$fp = $uplDir . $fileName;
if (file_exists($fp)) { chmod($fp, 0755); unlink($fp); }
file_put_contents(
$this->container->getParameter('kernel.root_dir')
. '/../web/uploads/ExpenseInvoice/' . $fileName,
$imgData
);
$expense_data[$idx]['uploadedFile'] = $storePath . $fileName;
}
if (!isset($expData['attachedFile'])) {
$expense_data[$idx]['attachedFile'] = [];
}
$expense_data[$idx]['expenseDate'] = $normaliseDate((string)($expData['expenseDate'] ?? ''));
$expense_data[$idx]['isChildInvoice'] = 0;
$expenseDataList[] = $expense_data[$idx];
}
} else {
// PATH C – legacy single-field POST
$expenseDataList[] = [
'expenseType' => $expense_type,
'currencyId' => $request->request->get('expense_currency_id', 0),
'currencyMultiply' => $request->request->get('expense_currency_multiply', 1),
'currencyMultiplyRate' => $request->request->get('expense_currency_multiply_rate', 1),
'expenseSubType' => $request->request->get('expense_sub_type', 0),
'expenseId' => $request->request->get('expense_id', 0),
'ccId' => $request->request->get('ccId', 0),
'docId' => $expense_type == 1 ? $request->request->get('poId')
: ($expense_type == 2 ? $request->request->get('soId')
: ($expense_type == 3 ? $request->request->get('opportunityId', $request->request->get('leadId'))
: ($expense_type == 5 ? $request->request->get('tour_id') : 0))),
'expenseToBePaidTo' => $request->request->get('expense_to_be_paid_to', 0),
'expenseFrom' => $request->request->get('expense_from', 0),
'checkDate' => $request->request->get('check_date', ''),
'checkNumber' => $request->request->get('check_number', ''),
'checkNarration' => $request->request->get('check_narration', ''),
'checkId' => $request->request->get('check_id', 0),
'expenseFromNote' => $request->request->get('expense_from_note', ''),
'expenseTo' => $request->request->get('expense_to_' . $expense_type, 0),
'expenseToNote' => $request->request->get('expense_to_note_' . $expense_type, ''),
'expenseAmount' => $request->request->get('expense_amount', ''),
'previousAdvanceAmount' => $request->request->get('prev_advance_amount', 0),
'description' => $request->request->get('description', ''),
'expenseMarkerHash' => $request->request->get('markerHash', ''),
'markerHash' => $request->request->get('markerHash', ''),
'wbsCode' => $request->request->get('wbsCode', ''),
'wbsActivityName' => $request->request->get('wbsActivityName', ''),
'expenseDate' => $normaliseDate((string)$request->request->get('expense_date', '')),
'expenseInvocationStrategyOnGrn' => $request->request->get('expenseInvocationStrategyOnGrn', null),
'expenseInvocationTypeOnItems' => $request->request->get('expenseInvocationTypeOnItems', null),
'invoiceBalancing' => $request->request->has('auto_balance' . $expense_type)
? $request->request->get('auto_balance' . $expense_type) : 0,
'attachedFile' => $request->files->get('file', []),
'expenseSubCategory' => $request->request->get('expense_sub_category', 0),
'expenseSubCategoryOption' => $request->request->get('expense_sub_category_option', 0),
'uploadedFile' => $request->request->get('uploadedFile', ''),
'expenseDistributionOnProduct' => $request->request->get('exp_check_expense_distribution_on_product', 0),
'isChildInvoice' => 0,
'costDistributionData' => $costDistributionData,
'expense_sub_category' => $request->request->get('expense_sub_category', 0),
'expense_sub_category_option' => $request->request->get('expense_sub_category_option', 0),
];
}
}
$isEdit = ($id > 0);
// Resolves _OWN_ / _OWN_ADVANCE_ to the employee's ledger head
$resolveOwnHead = function (string $headField, array $expData, array &$data) use ($em, $request): ?JsonResponse {
$sql = "SELECT accounts_head_id, advance_head_id, employee_id, user_id
FROM employee
WHERE user_id = " . (int)$request->getSession()->get(UserConstants::USER_ID) . "
LIMIT 1";
$rows = $em->getConnection()->fetchAllAssociative($sql);
if (empty($rows)) {
return new JsonResponse(['success' => false, 'errorText' => 'You are not listed as Employee', 'errorStr' => 'You are not listed as Employee']);
}
if (empty($rows[0][$headField]) || $rows[0][$headField] == 0) {
$label = ($headField === 'advance_head_id') ? 'Employee Advance Head' : 'Employee Head';
return new JsonResponse(['success' => false, 'errorText' => "Could not Find $label", 'errorStr' => "Could not Find $label"]);
}
$data['party_head_id'] = $rows[0][$headField];
$data['description'] = $expData['expenseToNote'];
$data['personal_expense_flag'] = 1;
$data['expense_of_user_id'] = $rows[0]['user_id'];
$data['expense_of_employee_id'] = $rows[0]['employee_id'];
return null;
};
// ----------------------------------------------------------------
// Save each row as its own independent invoice.
// All tracking arrays are declared OUTSIDE the loop so they
// accumulate entries across all iterations.
// ----------------------------------------------------------------
$new_ei = [];
$lastSavedEiId = 0;
$lastSavedEiResult = [];
$firstSavedEiId = 0;
$allSavedIds = [];
$allDocAmounts = [];
$allDocHash = [];
foreach ($expenseDataList as $expData) {
$expBillType = (int)($expData['expenseType'] ?? 0);
// For edit: use each row's own invoiceId; fall back to $id for single-row edits
$currentEiId = ($isEdit && !empty($expData['invoiceId']))
? (int)$expData['invoiceId']
: ($isEdit ? $id : 0);
$data = [
'doc_id' => $expData['docId'] ?? 0,
'expense_id' => $expData['expenseId'] ?? 0,
'party_id' => '',
'party_head_id' => $expData['expenseToBePaidTo'] ?? 0,
'advance_amount_to_assign' => (float)($expData['previousAdvanceAmount'] ?? 0),
'invoice_amount' => (float)($expData['expenseAmount'] ?? 0),
'description' => $expData['description'] ?? '',
'expense_to_note' => $expData['expenseToNote'] ?? '',
'expense_from_note' => $expData['expenseFromNote'] ?? '',
'wbsCode' => $expData['wbsCode'] ?? '',
'wbsActivityName' => $expData['wbsActivityName'] ?? '',
'currencyId' => $expData['currencyId'] ?? 0,
'currencyMultiply' => $expData['currencyMultiply'] ?? 1,
'currencyMultiplyRate' => $expData['currencyMultiplyRate'] ?? 1,
'date' => $expData['expenseDate'],
'file' => $expData['attachedFile'] ?? [],
'uploadedFile' => $expData['uploadedFile'] ?? '',
'expense_from' => $expData['expenseFrom'] ?? 0,
'check_date' => $expData['checkDate'] ?? '',
'check_number' => $expData['checkNumber'] ?? '',
'check_narration' => $expData['checkNarration'] ?? '',
'check_id' => $expData['checkId'] ?? 0,
'expenseMarkerHash' => $expData['markerHash'] ?? '',
'expenseSubCategory' => $expData['expense_sub_category'] ?? 0,
'expenseSubCategoryOption' => $expData['expense_sub_category_option'] ?? 0,
'invoiceBalancing' => $expData['invoiceBalancing'] ?? 0,
'expenseInvocationStrategyOnGrn' => $expData['expenseInvocationStrategyOnGrn'] ?? null,
'expenseInvocationTypeOnItems' => $expData['expenseInvocationTypeOnItems'] ?? null,
'expenseDistributionOnProduct' => $expData['expenseDistributionOnProduct'] ?? 0,
'costDistributionData' => $expData['costDistributionData'] ?? [],
];
if ($request->request->has('latitude')) {
$data['latitude'] = $request->request->get('latitude');
$data['longitude'] = $request->request->get('longitude');
}
// Resolve marker hash → accounts_head_id
if (!empty($expData['expenseMarkerHash'])) {
$sql = "SELECT accounts_head_id FROM acc_accounts_head
WHERE marker_hash LIKE '%" . $expData['expenseMarkerHash'] . "%'
LIMIT 1";
$rows = $em->getConnection()->fetchAllAssociative($sql);
if (empty($rows)) {
return new JsonResponse(['success' => false, 'errorText' => 'Could not find relevant Expense Head']);
}
$data['expense_id'] = $rows[0]['accounts_head_id'];
}
// Resolve _OWN_ / _OWN_ADVANCE_ to employee ledger head
$paidTo = $expData['expenseToBePaidTo'] ?? 0;
if ($paidTo == '_OWN_' || $paidTo == -1) {
$err = $resolveOwnHead('accounts_head_id', $expData, $data);
if ($err) return $err;
}
if ($paidTo == '_OWN_ADVANCE_' || $paidTo == -2) {
$err = $resolveOwnHead('advance_head_id', $expData, $data);
if ($err) return $err;
}
$new_ei = [];
switch ($expBillType) {
case 0: // General
case 1: // PO-linked
case 2: // SO-linked
case 3: // Lead-linked
case 5: // Tour/travel
if ($isEdit) {
$new_ei = Accounts::EditExpenseInvoiceFromAddExpense(
$this->getDoctrine()->getManager(),
$data, '', $expBillType, $loginId,
0, 0, 0,
(int)($expData['ccId'] ?? 0),
0, 0, 0,
$currentEiId
);
} else {
$new_ei = Accounts::CreateExpenseInvoiceFromAddExpense(
$this->getDoctrine()->getManager(),
$data, '', $expBillType, $loginId,
0, 0, 0,
(int)($expData['ccId'] ?? 0),
0, 0
);
}
break;
default:
continue 2;
}
// Register each successfully saved invoice
if (!empty($new_ei['ei_id'])) {
$savedEiId = (int)$new_ei['ei_id'];
$allSavedIds[] = $savedEiId;
$allDocAmounts[$savedEiId] = (float)($expData['expenseAmount'] ?? 0);
$allDocHash[$savedEiId] = $new_ei['ei_doc_hash'] ?? '';
$eiEntityId = array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'];
$options = [
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[$eiEntityId]['entity_view_route_path_name']
),
];
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options, $eiEntityId, $savedEiId, $loginId
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
$eiEntityId, $savedEiId, $loginId, $approveRole, $approveHash
);
if ($firstSavedEiId === 0) {
$firstSavedEiId = $savedEiId;
}
$lastSavedEiId = $savedEiId;
$lastSavedEiResult = $new_ei;
}
}
// END foreach
// Use the last saved invoice for response URLs
$responseEi = !empty($lastSavedEiResult) ? $lastSavedEiResult : [];
$eiEntityId = array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'];
$eiEntityDetails = GeneralConstant::$Entity_list_details[$eiEntityId];
$viewUrl = $this->generateUrl(
$eiEntityDetails['entity_view_route_path_name'],
['id' => $responseEi['ei_id'] ?? 0]
);
$printUrl = isset($eiEntityDetails['entity_print_route_path_name'])
? $this->generateUrl(
$eiEntityDetails['entity_print_route_path_name'],
['id' => $responseEi['ei_id'] ?? 0]
)
: $viewUrl;
return new JsonResponse([
'success' => true,
'docId' => $responseEi['ei_id'] ?? '',
'docHash' => $responseEi['ei_doc_hash'] ?? '',
'documentId' => $responseEi['ei_id'] ?? '',
'documentHash' => $responseEi['ei_doc_hash'] ?? '',
'documentAmount' => (float)($expenseDataList[0]['expenseAmount'] ?? 0),
'allDocIds' => $allSavedIds,
'allDocAmounts' => $allDocAmounts,
'allDocHashes' => $allDocHash,
'viewUrl' => $viewUrl,
'docPrintMainUrl' => $printUrl,
'isEdit' => $isEdit,
]);
}
// ====================================================================
// GET – Render form; pre-fill when $id > 0 (edit mode)
// ====================================================================
$extData = [];
$existingRows = [];
if ($id > 0) {
$extData = $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')
->findOneBy(['expenseInvoiceId' => $id]);
if ($extData) {
$existingRows[] = [
'id' => $extData->getExpenseInvoiceId(),
'expenseType' => $extData->getExpenseTypeId(),
'expenseSubType' => $extData->getExpenseSubcategory() ?? 0,
'expenseId' => $extData->getPartyId(),
'ccId' => $extData->getCostCenterId() ?? 0,
'currencyId' => $extData->getCurrency() ?? 0,
'currencyMultiply' => $extData->getCurrencyMultiply() ?? 1,
'currencyMultiplyRate' => $extData->getCurrencyMultiplyRate() ?? 1,
'docId' => $extData->getPurchaseOrderId() ?? 0,
'docIdtext' => '',
'expenseToBePaidTo' => $extData->getPartyHeadId() ?? 0,
'expenseFrom' => $extData->getExpenseFrom() ?? 0,
'expenseFromNote' => $extData->getExpenseFromNote() ?? '',
'expenseTo' => 0,
'expenseToNote' => $extData->getExpenseToNote() ?? '',
'expenseAmount' => $extData->getInvoiceAmount() ?? 0,
'previousAdvanceAmount' => $extData->getAdvanceAmount() ?? 0,
'checkDate' => '',
'checkNumber' => '',
'checkNarration' => '',
'checkId' => 0,
'description' => $extData->getDescription() ?? '',
'expenseMarkerHash' => $extData->getMarkerHash() ?? '',
'wbsCode' => $extData->getWbsCode() ?? '',
'wbsActivityName' => $extData->getWbsActivityName() ?? '',
'expenseDate' => $extData->getExpenseInvoiceDate()
? $extData->getExpenseInvoiceDate()->format('F d, Y')
: date('F d, Y'),
'invoiceBalancing' => 0,
'uploadedFile' => $extData->getFiles() ?? '',
'attachedFile' => [],
'expenseInvocationStrategyOnGrn' => $extData->getExpenseInvocationStrategyOnGrn(),
'expenseInvocationTypeOnItems' => $extData->getExpenseInvocationTypeOnItems(),
'isChildInvoice' => 0,
'refId' => 0,
'invoiceId' => $extData->getExpenseInvoiceId(),
];
} else {
$extData = [];
}
}
return $this->render(
'@Accounts/pages/input_forms/expense_bill.html.twig',
[
'page_title' => $id > 0 ? 'Edit Expense Bill' : 'Create Expense Bill',
'isEdit' => ($id > 0),
'editId' => $id,
'extData' => $extData,
'existingRows' => $existingRows,
'party_list' => Accounts::getParentLedgerHeads($em, 'ep'),
'warehouse' => Inventory::WarehouseListArray($em),
'supplier' => Inventory::ProductSupplierList($em),
'supplier_list_by_ac_head' => Accounts::SupplierListByAcHead($em),
'supplier_list_array' => Inventory::ProductSupplierListArray($em),
'po_list_array' => Purchase::PurchaseOrderListArray($em),
'po_list' => Purchase::PurchaseOrderList($em),
'product_list' => Inventory::ProductList($em),
'grn_list' => Inventory::GrnListForEi($em, 1),
'grn_list_array' => Inventory::GrnListForEiArray($em, 1),
]
);
}
public function PendingInvoiceList(Request $request)
{
return $this->render(
'@Accounts/pages/list/pending_list.html.twig',
array(
'page_title' => 'Pending Invoices'
)
);
}
public function SalesInvoiceList(Request $request)
{
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$companyId = $this->getLoggedUserCompanyId($request);
$userRestrictions = [];
$selectiveDocumentsFlag = 0;
$allowedLoginIds = [];
$canSeeAllSo = 1;
$allowedSpIds = 'all';
$allowedClientIds = 'all';
$allowedLoginIds = 'all';
$salesPersonList = Client::SalesPersonList($this->getDoctrine()->getManager());
$clientList = SalesOrderM::GetClientList($em, [], $companyId);
$userType = $session->get(UserConstants::USER_TYPE);
$userId = $session->get(UserConstants::USER_ID);
$selectiveQryArray = array('status' => GeneralConstant::ACTIVE);
if ($userType == UserConstants::USER_TYPE_CLIENT) {
$selectiveQryArray['clientId'] = $session->get(UserConstants::CLIENT_ID);
$allowedClientIds = [$session->get(UserConstants::CLIENT_ID)];
}
if ($userType == UserConstants::USER_TYPE_GENERAL) {
$userRestrictions = Users::getUserApplicationAccessSettings($em, $userId)['options'];
$selectiveDocumentsFlag = 1; //by default will show only selective
if (isset($userRestrictions['canSeeAllSo'])) {
if ($userRestrictions['canSeeAllSo'] == 1) {
$selectiveDocumentsFlag = 0;
$canSeeAllSo = 1;
}
}
if ($selectiveDocumentsFlag == 1) {
$allowedLoginIds = MiscActions::getLoginIdsByUserId($em, $session->get(UserConstants::USER_ID));
}
}
$q = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\SalesInvoice')
->findBy(
$selectiveQryArray
);
$stage_list = array(
1 => 'Pending',
2 => 'Complete',
4 => 'Pending Payment',
);
$data = [];
$salesOrders = SalesOrderM::SalesOrderList($em);
foreach ($q as $entry) {
$clientId = $entry->getClientId();
$spId = $clientList[$entry->getClientId()]['sales_person_id'];
// $client=$em->getRepository('ApplicationBundle\\Entity\\AccClients')
// ->findOneBy(
// array(
// 'clientId'=>$clientId
// )
// );
if ($selectiveDocumentsFlag == 1) {
//1st check by sales person
$spCheckFailed = 1;
if (isset($salesPersonList[$spId])) {
if ($salesPersonList[$spId]['userId'] == $userId) {
$spCheckFailed = 0;
}
}
if ($spCheckFailed == 0) {
} else if (in_array($entry->getCreatedLoginId(), $allowedLoginIds) || in_array($entry->getEditedLoginId(), $allowedLoginIds)) {
} else {
continue;
}
}
$data[] = array(
'doc_date' => $entry->getSalesInvoiceDate(),
'doc_date_str' => $entry->getSalesInvoiceDate()->format('F d, Y'),
'id' => $entry->getSalesInvoiceId(),
'doc_hash' => $entry->getDocumentHash(),
'invoice_amount' => $entry->getInvoiceAmount(),
'sales_order_id' => $entry->getSalesOrderId(),
'sales_person_id' => $spId,
'sales_person_name' => isset($salesPersonList[$spId]) ? $salesPersonList[$spId]['name'] : '',
'so_amount' => $entry->getSoAmount(),
'client_name' => $clientList[$clientId]['client_name'],
'client_code' => $clientList[$clientId]['client_code'],
'client_contact_number' => $clientList[$clientId]['contact_number'],
'sales_order_name' => isset($salesOrders[$entry->getSalesOrderId()]) ? $salesOrders[$entry->getSalesOrderId()]['name'] : '',
'sales_or_service' => $entry->getSalesOrService(),
'stage' => $stage_list[$entry->getStage()]
);
}
if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
return new JsonResponse(
array(
'page_title' => 'Sales Invoices',
'data' => $data,
'userType' => $userType,
'orderConfirmationPendingFlag' => 0,
'users' => Users::getUserListById($em),
'canSeeAllSo' => $canSeeAllSo,
'allowedSpIds' => $allowedSpIds,
'allowedClientIds' => $allowedClientIds,
'allowedLoginIds' => $allowedLoginIds,
'sales_person_list' => $salesPersonList,
'success' => empty($data) ? false : true
)
);
}
return $this->render(
'@Accounts/pages/list/sales_invoices.html.twig',
array(
'page_title' => 'Sales Invoices',
'data' => $data,
'canSeeAllSo' => $canSeeAllSo,
'allowedSpIds' => $allowedSpIds,
'allowedClientIds' => $allowedClientIds,
'allowedLoginIds' => $allowedLoginIds,
)
);
}
public function PurchaseInvoiceList(Request $request)
{
$q = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\PurchaseInvoice')
->findBy(
array(
'status' => GeneralConstant::ACTIVE,
)
);
$stage_list = array(
1 => 'Pending',
2 => 'Complete',
4 => 'Pending Payment',
);
$data = [];
foreach ($q as $entry) {
$data[] = array(
'doc_date' => $entry->getPurchaseInvoiceDate(),
'id' => $entry->getPurchaseInvoiceId(),
'doc_hash' => $entry->getDocumentHash(),
'invoice_amount' => $entry->getInvoiceAmount(),
'stage' => $stage_list[$entry->getStage()]
);
}
// return new JsonResponse($data);
return $this->render(
'@Accounts/pages/list/purchase_invoices.html.twig',
array(
'page_title' => 'Purchase Invoices',
'data' => $data
)
);
}
public function ViewSalesInvoice(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$absoluteUrl = $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
$dt = SalesOrderM::GetSalesInvoiceDetails($em, $id);
return $this->render(
// '@Accounts/pages/views/view_sales_invoice.html.twig',
'@Accounts/pages/views/view_sales_invoice_demo.html.twig',
array(
'page_title' => 'View',
'data' => $dt,
'absoluteUrl' => $absoluteUrl,
'auto_created' => $dt['auto_created'],
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['SalesInvoice'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => $dt['auto_created'] == 0 ? System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SalesInvoice'],
$id,
$dt['created_by'],
$dt['edited_by']
) : []
)
);
}
public function CorrectCheckProblem(Request $request)
{
$em = $this->getDoctrine()->getManager();
$check_list_in_brs = array();
$docData = $em->getRepository('ApplicationBundle\\Entity\\Brs')->findBy(
array(
// 'brsId'=>$id
// 'approved'=>1
)
);
foreach ($docData as $doc) {
$details_data = json_decode($doc->getData(), true);
if ($details_data) {
$pending_check_no_list = [];
if (isset($details_data["pending_cn"])) {
foreach ($details_data["pending_cn"] as $key => $value) {
if (!isset($check_list_in_brs[$value])) {
$check_list_in_brs[$value] = array(
'check_amount' => 0,
'narration' => ""
);
}
if (isset($details_data["pending_check_amount"])) {
if ($check_list_in_brs[$value]['check_amount'] == 0)
$check_list_in_brs[$value]['check_amount'] = $details_data["pending_check_amount"][$key];
}
}
}
if (isset($details_data["cleared_cn"])) {
foreach ($details_data["cleared_cn"] as $key => $value) {
if (!isset($check_list_in_brs[$value])) {
$check_list_in_brs[$value] = array(
'check_amount' => 0,
'narration' => ""
);
}
if (isset($details_data["cleared_check_amount"])) {
if ($check_list_in_brs[$value]['check_amount'] == 0)
$check_list_in_brs[$value]['check_amount'] = $details_data["cleared_check_amount"][$key];
}
}
}
}
}
foreach ($check_list_in_brs as $key => $value) {
$ck = $em->getRepository('ApplicationBundle\\Entity\\AccCheck')->findOneBy(
array(
// 'brsId'=>$id
'checkNumber' => $key
)
);
if ($ck) {
$ck->setCheckAmount($value['check_amount']);
$ck->setAssigned(1);
if ($ck->getCheckDate() == null)
$ck->setCheckDate($ck->getLedgerHitDate());
if ($ck->getVoucherId() == null)
$ck->setVoucherId(0);
$em->flush();
}
}
// $dt=Accounts::GetBrsDetails($em,$id);
return new JsonResponse($check_list_in_brs);
}
public function ViewBrs(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = Accounts::GetBrsDetails($em, $id);
return $this->render(
'@Accounts/pages/views/brs_view.html.twig',
array(
'page_title' => 'BRS',
'data' => $dt,
'auto_created' => $dt['auto_created'],
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['Brs'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => $dt['auto_created'] == 0 ? System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['Brs'],
$id,
$dt['created_by'],
$dt['edited_by']
) : []
)
);
}
public function PrintBrs(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$data = Accounts::GetBrsDetails($em, $id);
$company_data = Company::getCompanyData($em, $this->getLoggedUserCompanyId($request));
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
return $this->render(
'@Accounts/pages/print/print_brs.html.twig',
array(
'export' => 'print',
'page_title' => 'BRS' . $data['doc_hash'],
'data' => $data,
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'page_header' => 'BRS',
'document_type' => 'Sales Bill',
'page_header_sub' => 'Add',
// 'type_list'=>$type_list,
// 'mis_data'=>$mis_data,
// 'mis_print'=>$mis_print,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
)
);
}
public function ViewFinancialBudget(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = Accounts::GetFinancialBudgetDetails($em, $id);
return $this->render(
'@Accounts/pages/views/financial_budget.html.twig',
array(
'page_title' => 'Financial Budget',
'data' => $dt,
'auto_created' => $dt['auto_created'],
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['FinancialBudget'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => $dt['auto_created'] == 0 ? System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['FinancialBudget'],
$id,
$dt['created_by'],
$dt['edited_by']
) : []
)
);
}
public function PrintFinancialBudget(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$data = Accounts::GetFinancialBudgetDetails($em, $id);
$company_data = Company::getCompanyData($em, $this->getLoggedUserCompanyId($request));
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
return $this->render(
'@Accounts/pages/print/financial_budget.html.twig',
array(
'export' => 'print',
'page_title' => 'Financial Budget' . $data['doc_hash'],
'data' => $data,
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'page_header' => 'BRS',
'document_type' => 'Sales Bill',
'page_header_sub' => 'Add',
// 'type_list'=>$type_list,
// 'mis_data'=>$mis_data,
// 'mis_print'=>$mis_print,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
)
);
}
public function PrintSalesInvoice(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
if ($id != 0)
$data = SalesOrderM::GetSalesInvoiceDetails($em, $id);
else if ($request->query->has('printType'))
$data = SalesOrderM::GetSalesInvoiceDetails(
$em,
$id,
$request->query->get('printType'),
$request->query->get('invoiceIds', []),
$request->query->get('soId', 0)
);
// S2.3 — register in Document Variant Engine (additive, non-blocking)
if (!empty($data['si_data'])) {
try {
$invoiceVariant = $request->query->get('invoiceVariant', 'final');
DocumentRegistry::register(
$em,
in_array($invoiceVariant, ['commercial','customs','lc','import','credit_note','proforma']) ? $invoiceVariant : 'final',
'SalesInvoice',
(int)$id,
[
'tenantId' => $data['si_data']->getCompanyId(),
'customerId' => $data['si_data']->getClientId(),
'projectId' => $data['si_data']->getProjectId(),
'documentNumber' => isset($data['doc_hash']) ? $data['doc_hash'] : null,
'currency' => $data['si_data']->getCurrency(),
'createdBy' => $request->getSession()->get(UserConstants::USER_LOGIN_ID),
]
);
} catch (\Exception $e) { /* registry is non-blocking */ }
}
// $company_data = Company::getCompanyData($em, $this->getLoggedUserCompanyId($request));
$company_data = Company::getCompanyData($em, $data['si_data']->getCompanyId());
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
$printTemplate = CountryTemplateResolver::resolve(
$this->get('twig'),
$em,
$data['si_data']->getCompanyId(),
'@Accounts/pages/print/print_sales_invoice.html.twig'
);
$taxMarkers = TaxMarkerLookup::forCompany($em, $data['si_data']->getCompanyId());
if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
$html = $this->renderView(
$printTemplate,
array(
//full array here
'pdf' => true,
'page_title' => 'Sales Bill ' . $data['doc_hash'],
'data' => $data,
'export' => 'pdf,print',
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'page_header' => 'New Product',
'document_type' => 'Sales Bill',
'page_header_sub' => 'Add',
// 'type_list'=>$type_list,
// 'mis_data'=>$mis_data,
// 'mis_print'=>$mis_print,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
'taxMarkers' => $taxMarkers,
)
);
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
// 'orientation' => 'landscape',
// 'enable-javascript' => true,
// 'javascript-delay' => 1000,
'no-stop-slow-scripts' => false,
'no-background' => false,
'lowquality' => false,
'encoding' => 'utf-8',
// 'images' => true,
// 'cookie' => array(),
'dpi' => 300,
'image-dpi' => 300,
// 'enable-external-links' => true,
// 'enable-internal-links' => true
));
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="sales_invoice_' . $id . '.pdf"'
)
);
}
return $this->render(
$printTemplate,
array(
'page_title' => 'Sales Bill ' . $data['doc_hash'],
'data' => $data,
'export' => 'pdf,print',
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'page_header' => 'New Product',
'document_type' => 'Sales Bill',
'page_header_sub' => 'Add',
// 'type_list'=>$type_list,
// 'mis_data'=>$mis_data,
// 'mis_print'=>$mis_print,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
'taxMarkers' => $taxMarkers,
)
);
}
public function GetPurchaseInvoiceBalancingData(Request $request)
{
$heads = $request->request->get('heads');
$ids = $request->request->get('ids');
$em = $this->getDoctrine()->getManager();
return new JsonResponse(array(
"success" => false,
"content" => Accounts::GetPurchaseInvoiceBalancingData($em, $heads, $ids)
));
}
public function GetSalesInvoiceBalancingData(Request $request)
{
$heads = $request->request->get('heads');
$ids = $request->request->get('ids');
$em = $this->getDoctrine()->getManager();
return new JsonResponse(array(
"success" => false,
"content" => Accounts::GetSalesInvoiceBalancingData($em, $heads, $ids)
));
}
public function GetSelectedHeadsHistory(Request $request, $mis_start_date = '', $mis_end_date = '')
{
$em = $this->getDoctrine()->getManager();
$start_date = "";
$end_date = "";
// $em=$this->getDoctrine()->getManager();
if ($mis_start_date != '' && $mis_start_date != 0)
$start_date = $mis_start_date;
if ($mis_end_date != '' && $mis_start_date != 0)
$end_date = $mis_start_date;
$engine = $this->container->get('twig');
$pids = array_unique(explode("::", $_POST["pids"]));
$Content = $engine->render(
'@Accounts/pages/report/selected_head_details.html.twig',
Accounts::GetVoucherMisDetails($em, $pids, $start_date, $end_date)
);
// $stockPosition=$engine->render('@Sales/pages/report/selected_products_stock_position.html.twig', array('pSalesDetails'=>$ProductSales));
return new JsonResponse(array("success" => false, "content" => $Content));
// return new JsonResponse(array("success"=>false,"content"=>$Content, "stockPosition"=>$stockPosition));
}
public function EditVoucher(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$Transaction = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
'transactionId' => $id,
'editFlag' => 1,
'lockFlag' => [0, null],
'disabledFlag' => [0, null],
));
if ($Transaction) {
if ($Transaction->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
return $this->redirectToRoute('edit_journal_voucher', array('id' => $id));
}
} else {
// $this->container->get("session")->setFlash("error", "Pikachu is not allowed");
$this->addFlash(
'error',
'The Action was not allowed.'
);
$url = $request->headers->get("referer");
// return $this->render('@Purchase/pages/list_tables/quotation.html.twig',
// array(
// 'page_title'=>'Quotation Calculator'
//
// )
// );
return new RedirectResponse($url);
}
//
//
// return $this->render('@Accounts/pages/input_forms/journal_voucher.html.twig',
// array(
// 'page_title'=>'Create Journal Voucher'
// )
// );
}
public function RefreshDocHash(Request $request, $entity_id)
{
// $response = new StreamedResponse();
// $response->setCallback(function () {
$em = $this->getDoctrine()->getManager();
$assign_list = array();
$new_cc = $em
->getRepository('ApplicationBundle\\Entity\\AccSettings')
->findOneBy(
array(
'name' => 'accounting_year_start',
)
);
$query = "SELECT transaction_id, type_hash, prefix_hash, assoc_hash, number_hash from acc_transactions where status=" . GeneralConstant::ACTIVE;
$date_start = "";
$date_start_str = "";
if ($new_cc) {
$date_start = new \DateTime($new_cc->getData());
$date_start_str = $date_start->format('Y-m-d');
}
if ($new_cc)
$query .= " AND transaction_date>= '" . $date_start_str . " 00:00:00' ";
$query .= " ORDER BY transaction_date ASC";
$stmt = $em->getConnection()->fetchAllAssociative($query);
$Transactions = $stmt;
$update_qry = "";
foreach ($Transactions as $entry) {
if (isset($assign_list[$entry['type_hash'] . '_' . $entry['prefix_hash'] . '_' . $entry['assoc_hash']])) {
$to_be_assigned = $assign_list[$entry['type_hash'] . '_' . $entry['prefix_hash'] . '_' . $entry['assoc_hash']]['last_no_hash'] + 1;
if ($to_be_assigned == $entry['number_hash']) {
} else {
$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'
where transaction_id=" . $entry['transaction_id'] . "; ";
}
$assign_list[$entry['type_hash'] . '_' . $entry['prefix_hash'] . '_' . $entry['assoc_hash']]['last_no_hash'] = $to_be_assigned;
} else {
$assign_list[$entry['type_hash'] . '_' . $entry['prefix_hash'] . '_' . $entry['assoc_hash']]['last_no_hash'] = $entry['number_hash'];
}
}
$stmt = $em->getConnection()->fetchAllAssociative($update_qry);
// $Transactions=$stmt;
return $this->redirectToRoute('dashboard');
}
public function RefreshTransactions(Request $request)
{
// $response = new StreamedResponse();
// $response->setCallback(function () {
$em = $this->getDoctrine()->getManager();
//1st get all brscleared vids for heads
$brs_cleared_vids_by_head = [];
$Transaction = $em->getRepository('ApplicationBundle\\Entity\\Brs')->findBy(
array(
// 'approved'=>GeneralConstant::APPROVED,
// 'transactionId'=>$tids
// 'ledgerHit'=>1,
)
);
foreach ($Transaction as $doc) {
$data = json_decode($doc->getData(), true);
if (isset($data['cleared_check_id'])) {
$check_ids = $data['cleared_check_id'];
// $recon_dates=$data['recon_date'];
$v_ids = $data['cleared_vid'];
foreach ($v_ids as $vid) {
if (isset($brs_cleared_vids_by_head[$doc->getAccountsHeadId()])) {
$brs_cleared_vids_by_head[$doc->getAccountsHeadId()][] = $vid;
} else {
$brs_cleared_vids_by_head[$doc->getAccountsHeadId()] = [$vid];
}
}
}
// $tids[]=$d->getTransactionId();
}
$bank_settings = $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
'name' => 'bank_parents'
));
$bank_id_list = [];
if ($bank_settings)
$bank_id_list = json_decode($bank_settings->getData());
$head_list = Accounts::HeadListFullPath($em);
$bank_head_list = [];
$bank_head_list_array = [];
foreach ($head_list as $k => $v) {
// if($k==210)
// continue;
foreach ($bank_id_list as $bid) {
$q_str = '/' . $bid . '/';
$path_string = $v['path'];
$debug_it[] = [$q_str, $path_string, strpos($path_string, $q_str)];
if (strpos($path_string, $q_str) !== false) {
$bank_head_list[$k] = $v;
$bank_head_list_array[] = $k;
} else {
}
}
}
///temporarily adding pending reconlist for vouchers
$Transaction = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findBy(
array(
'approved' => GeneralConstant::APPROVED,
// 'transactionId'=>$tids
// 'ledgerHit'=>1,
)
);
foreach ($Transaction as $d) {
$tids[] = $d->getTransactionId();
}
$TransactionDetails = $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')->findBy(
array(
'accountsHeadId' => $tids,
// 'ledgerHit'=>1,
)
);
$det_by_trans_id = [];
foreach ($TransactionDetails as $d) {
if (in_array($d->getAccountsHeadId(), $bank_head_list_array)) {
if (isset($brs_cleared_vids_by_head[$d->getAccountsHeadId()])) {
if (in_array($d->getTransactionId(), $brs_cleared_vids_by_head[$d->getAccountsHeadId()])) {
continue;
}
}
if (isset($det_by_trans_id[$d->getTransactionId()])) {
$det_by_trans_id[$d->getTransactionId()]['pendReconIdList'][] = $d->getAccountsHeadId();
} else {
$det_by_trans_id[$d->getTransactionId()] = array(
'pendReconIdList' => [$d->getAccountsHeadId()]
);
}
}
}
foreach ($det_by_trans_id as $tid => $d) {
$Transaction = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(
array(
'approved' => GeneralConstant::APPROVED,
'transactionId' => $tid
// 'ledgerHit'=>1,
)
);
if ($Transaction) {
if (empty($d['pendReconIdList'])) {
$Transaction->setProvisional(0);
$Transaction->setPendingReconciliationIdList(json_encode([]));
} else {
$Transaction->setPendingReconciliationIdList(json_encode($d['pendReconIdList']));
$Transaction->setProvisional(1);
}
$em->flush();
}
}
// echo 'Refreshing Transactions\n';
// flush();
//
// $new_cc = $em
// ->getRepository('ApplicationBundle\\Entity\\AccSettings')
// ->findOneBy(
// array(
// 'name' => 'accounting_year_start',
// )
// );
//
// $query="UPDATE acc_transactions set ledger_hit=0 ";
// $date_start="";
// $date_start_str="";
// if($new_cc) {
// $date_start = new \DateTime($new_cc->getData());
// $date_start_str=$date_start->format('Y-m-d');
// }
// if($new_cc)
// $query.=" where transaction_date>= '".$date_start_str." 00:00:00' ";
//
//
// $stmt = $em->getConnection()->fetchAllAssociative($query);
//
// echo 'Refreshing Transactions\n';
// flush();
// sleep(2);
//
// $Transactions=$em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
// 'approved'=>1,
// 'ledgerHit'=>0
// )
// ,array(
// 'transactionDate'=>'ASC'
// ));
//// foreach($Transactions as $test)
//// {
//// echo 'processing v_id'.$test->getTransactionId().'\n';
//// flush();
// if($Transactions) {
// ApprovalFunction::AccTransactions($em, $Transactions->getTransactionId());
// return $this->redirectToRoute('refresh_transactions');
// }
// else
// return $this->redirectToRoute('dashboard');
//
//
// sleep(2);
//
//// return $this->redirectToRoute('refresh_transactions');
//
// }
//// echo 'Hello World';
//// flush();
//// sleep(2);
//// echo 'Hello World';
//// flush();
// });
// $response->send();
// $httpKernel->terminate($request, $response);
// ApprovalFunction::AccTransactions($em,$id);
// $done=MiscActions::refreshTransactions($em);
//
// $this->addFlash(
// 'success',
// 'The Action was Successful.'
// );
//
//
//
return $this->redirectToRoute('dashboard');
}
public function RefreshDatabase(Request $request, $refdate = '')
{
$em = $this->getDoctrine()->getManager();
if ($refdate == '')
$refdate = '2018-11-10';
////starting correcting the delivery confirmations
//1st get the required delivery confirmation list
$get_kids_sql = " SELECT * FROM `delivery_confirmation` WHERE `delivery_confirmation_date` >= '" . $refdate . " 00:00:00'
ORDER BY `delivery_confirmation`.`delivery_confirmation_id` ASC";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$get_kids = $stmt;
$dc_id_list = [];
$dc_det_by_id = [];
foreach ($get_kids as $kid) {
$dc_id_list[] = $kid['delivery_confirmation_id'];
$dc_det_by_id[$kid['delivery_confirmation_id']] = $kid;
}
//now
foreach ($dc_id_list as $k => $dc_id) {
//1st get delivery receipt date
$dr = $em->getRepository('ApplicationBundle\\Entity\\DeliveryReceipt')
->findOneBy(
array(
'deliveryReceiptId' => $dc_det_by_id[$dc_id]['delivery_receipt_id'],
)
);
if ($dr) {
$todate = new \Datetime();
$next_one_date = $todate->format('Y-m-d') . ' 23:59:59';
if (isset($dc_id_list[$k + 1]))
$next_one_date = $dc_det_by_id[$dc_id_list[$k + 1]]['created_at'];
$qry = "select * from sales_invoice where sales_invoice_date>='" . $dc_det_by_id[$dc_id]['created_at'] .
"' and sales_invoice_date< '" . $next_one_date . "' ORDER BY `sales_invoice`.`sales_invoice_date` ASC limit 1";
$stmt = $em->getConnection()->fetchAllAssociative($qry);
$get_kids = $stmt;
if (!empty($get_kids)) {
$voucher_list = json_decode($get_kids[0]['voucher_ids'], true);
$qry1 = "update sales_invoice set
sales_invoice_date='" . $dr->getDeliveryReceiptDate()->format('Y-m-d H:i:s') . "' ,
receipt_id_list='" . json_encode([$dr->getDeliveryReceiptId()]) . "'
where sales_invoice_id=" . $get_kids[0]['sales_invoice_id'];
$stmt = $em->getConnection()->executeStatement($qry1);
$qry1 = "update acc_transactions set
transaction_date='" . $dr->getDeliveryReceiptDate()->format('Y-m-d H:i:s') . "' ,
ledger_hit_date='" . $dr->getDeliveryReceiptDate()->format('Y-m-d H:i:s') . "'
where transaction_id in (" . implode(', ', $voucher_list) . ")";
$stmt = $em->getConnection()->executeStatement($qry1);
$qry1 = "update acc_transaction_details set
transaction_date='" . $dr->getDeliveryReceiptDate()->format('Y-m-d H:i:s') . "' ,
ledger_hit_date='" . $dr->getDeliveryReceiptDate()->format('Y-m-d H:i:s') . "'
where transaction_id in (" . implode(', ', $voucher_list) . ")";
$stmt = $em->getConnection()->executeStatement($qry1);
// $get_kids=$stmt;
}
}
}
// MiscActions::refreshDatabase($em);
$this->addFlash(
'success',
'The Action was Successful.'
);
return $this->redirectToRoute('dashboard');
}
public function RefreshClosing(Request $request)
{
$em = $this->getDoctrine()->getManager();
$debug_data = [];
$autoStartFixedAssetDepreciation = 0;
$autoStartLedgerHit = 0;
$autoStartInventoryRefresh = 0;
$inventoryRefreshed = 0;
$modifyAccTransFlag = 0;
$lastRefreshDate = '';
if ($request->query->has('rectifyGrnExpIdTag')) {
$pos = $em->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')->findBy(array(
'approved' => 1,
// 'ledgerHit' => 0
));
foreach ($pos as $po) {
$Grns = $em->getRepository('ApplicationBundle\\Entity\\Grn')->findBy(
array(
'purchaseOrderId' => $po->getPurchaseOrderId(),
'approved' => 1,
// 'ledgerHit' => 0
),
array(
'grnDate' => 'asc'
)
);
$eis = $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')->findBy(
array(
'purchaseOrderId' => $po->getPurchaseOrderId(),
'approved' => 1,
// 'ledgerHit' => 0
),
array(
'expenseInvoiceDate' => 'asc'
)
);
$first_grn_found = 0;
foreach ($Grns as $grn) {
$grn->setExpenseAmount(0);
$grn->setExpensePendingBalanceAmount(0);
$em->flush();
if ($first_grn_found == 1) continue;
// if ($grn->getExpenseAmount() == 0 || $grn->getExpenseAmount() == null || $grn->getExpenseAmount() == '')
// continue;
$grnExpAmount = $grn->getExpenseAmount();
$conditionFailed = 1;
$chkAmount = 0;
$total_price_value = 0;
$tot_expense = 0;
$eisObjList = [];
$passedEiIds = [];
$eiIds = [];
$passedEis = [];
$eiAmounts = [];
$grnItems = $em->getRepository('ApplicationBundle\\Entity\\GrnItem')
->findBy(
array(
'grnId' => $grn->getGrnId()
)
);
foreach ($grnItems as $key => $entry) {
$total_price_value += $entry->getLocalPrice() * $entry->getQty();
}
foreach ($eis as $ei) {
$ei->setGrnIds(json_encode([]));
$em->flush();
$eiAmounts[$ei->getExpenseInvoiceId()] = $ei->getInvoiceAmount();
$eisObjList[$ei->getExpenseInvoiceId()] = $ei;
$eiIds[] = $ei->getExpenseInvoiceId();
if ($ei->getExpenseInvoiceDate() <= $grn->getGrnDate()) {
$passedEiIds[] = $ei->getExpenseInvoiceId();
$passedEis[$ei->getExpenseInvoiceId()] = $ei;
$tot_expense += (1 * $ei->getInvoiceAmount());
}
}
//adding frm po ended
$expense_mult = ($total_price_value != 0 ? (($total_price_value + $tot_expense) / $total_price_value) : 0);
foreach ($grnItems as $key => $entry) {
$entry->setPriceWithExpense($entry->getLocalPrice() * $expense_mult);
}
$grn->setExpenseAmount($tot_expense);
$grn->setExpensePendingBalanceAmount($tot_expense);
// if ($conditionFailed == 0) {
foreach ($passedEis as $ei) {
$ei->setGrnIds(json_encode([$grn->getGrnId()]));
$em->flush();
}
// }
$first_grn_found = 1;
}
}
}
if ($request->query->has('autoStartLedgerHit'))
$autoStartLedgerHit = 1;
if ($request->query->has('autoStartInventoryRefresh'))
$autoStartInventoryRefresh = $request->query->get('autoStartInventoryRefresh');
if ($request->query->has('modifyAccTransFlag'))
$modifyAccTransFlag = $request->query->get('modifyAccTransFlag');
if ($request->query->has('inventoryRefreshed'))
$inventoryRefreshed = $request->query->get('inventoryRefreshed');
if ($request->query->has('lastRefreshDate'))
$lastRefreshDate = $request->query->get('lastRefreshDate');
if ($request->query->has('autoStartFixedAssetDepreciation'))
$autoStartFixedAssetDepreciation = 1;
if ($request->isMethod('POST')) {
// $Transaction = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
// 'approved' => 1,
// 'ledgerHit' => 0
// ));
if ($request->request->has('fixedAssetDep')) {
$apData = FixedAsset::TakeDepreciationActionBook($em, [], $this->getLoggedUserCompanyId($request));
$ap = $apData['continueFlag'];
if ($ap == 1) {
// $skip_ids[] = $get_kids[0]['transaction_id'];
return new JsonResponse(array(
"success" => true,
'workData' => $apData
));
} else {
return new JsonResponse(array(
"success" => false,
'workData' => $apData
));
}
} else {
$skip_ids = [];
if ($request->request->has('skipIds'))
$skip_ids = $request->request->get('skipIds');
$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';
// $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';
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$get_kids = $stmt;
$vid = 0;
$vname = '';
if (!empty($get_kids)) {
$ap = ApprovalFunction::AccTransactions($em, $get_kids[0]['transaction_id']);
if ($ap == 0)
$skip_ids[] = $get_kids[0]['transaction_id'];
return new JsonResponse(array(
"success" => true,
"debugData" => $ap,
"v_id" => $get_kids[0]['transaction_id'],
"v_name" => $get_kids[0]['document_hash'],
"skip_ids" => $skip_ids,
));
} else {
return new JsonResponse(array(
"success" => false,
"v_id" => 0,
"v_name" => "",
"skip_ids" => $skip_ids,
));
}
}
}
// MiscActions::refreshDatabase($em);
return $this->render(
'@Application/pages/accounts/settings/refresh_combo_action.html.twig',
array(
'page_title' => 'Debug',
'debug_data' => $debug_data,
'autoStartLedgerHit' => $autoStartLedgerHit,
'autoStartInventoryRefresh' => $autoStartInventoryRefresh,
'inventoryRefreshed' => $inventoryRefreshed,
'modifyAccTransFlag' => $modifyAccTransFlag,
'lastRefreshDate' => $lastRefreshDate,
'autoStartFixedAssetDepreciation' => $autoStartFixedAssetDepreciation,
// 'voucherDetails'=>$v_details,
// 'heads'=>Accounts::HeadList($em),
// 'transaction'=>$Transaction
)
);
// return $this->redirectToRoute('dashboard');
}
public function ResetClosing(Request $request)
{
$em = $this->getDoctrine()->getManager();
$debug_data = [];
if ($request->isMethod('POST')) {
// $Transaction = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
// 'approved' => 1,
// 'ledgerHit' => 0
// ));
$skip_ids = [];
if ($request->request->has('skipIds'))
$skip_ids = $request->request->get('skipIds');
$get_kids_sql = ' UPDATE `acc_accounts_head` SET `current_balance`=opening_balance,`current_balance_reconciled`=opening_balance WHERE 1;
UPDATE `acc_transactions` SET `ledger_hit`=0 WHERE 1;
UPDATE `acc_transaction_details` SET `ledger_hit`=0 WHERE 1;
UPDATE `acc_clients` SET `client_due`=(select opening_balance from acc_accounts_head
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;
UPDATE `acc_clients` SET `initial_opening_balance`=(select opening_balance from acc_accounts_head
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;
UPDATE `acc_clients` SET `client_due`=(select sum(opening_balance) from acc_accounts_head
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;
UPDATE `acc_clients` SET `initial_opening_balance`=(select sum(opening_balance) from acc_accounts_head
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;
UPDATE `acc_clients` SET `client_received`=0 where 1;
UPDATE `acc_suppliers` SET `supplier_due`=(select opening_balance from acc_accounts_head
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;
UPDATE `acc_suppliers` SET `supplier_due`=(select sum(opening_balance) from acc_accounts_head
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;
UPDATE `acc_suppliers` SET `supplier_paid`=0 where 1;
truncate `acc_closing_balance`;
truncate `acc_actual_closing_balance`;
truncate `monthly_summary`;
UPDATE company SET revenue=0, asset=0, liability=0, expense=0, payable=0 , receivable=0, net_worth=0, monthly_growth=0 WHERE 1;';
//UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
$stmt = $em->getConnection()->executeStatement($get_kids_sql);
// $get_kids=$stmt;
$vid = 0;
$vname = '';
$head_list = [];
$headDataList = [];
// $curr_id = $head_id;
$get_kids_sql = 'select * from acc_accounts_head where accounts_head_id not in (select distinct parent_id from acc_accounts_head) ;';
//UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query = $stmt;
if (!empty($query)) ///exists so lets edit rather than creating new
{
foreach ($query as $entry) {
if (!isset($headDataList[$entry['company_id']]))
$headDataList[$entry['company_id']] = array();
$primary_head_data = array();
$primary_head_data['id'] = $entry['accounts_head_id'];
$primary_head_data['addition'] = $entry['current_balance'];
$primary_head_data['headNature'] = $entry['head_nature'];
$primary_head_data['headType'] = $entry['type'];
$primary_head_data['pathTree'] = $entry['path_tree'];
$headDataList[$entry['company_id']][] = $primary_head_data;
}
}
foreach ($headDataList as $companyId => $headDataDetails) {
Company::updateMonthlySummary($em, $headDataDetails, $companyId, '_opening_date_', '_ALL_');
}
return new JsonResponse(array(
"success" => true,
"skip_ids" => $skip_ids,
));
}
// MiscActions::refreshDatabase($em);
// return $this->redirectToRoute('dashboard');
}
public function GetNonLedgerHitVoucherCount(Request $request)
{
$em = $this->getDoctrine()->getManager();
$debug_data = [];
// $Transaction = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
// 'approved' => 1,
// 'ledgerHit' => 0
// ));
$skip_ids = [];
$v_count = 0;
if ($request->request->has('skipIds'))
$skip_ids = $request->request->get('skipIds');
$get_kids_sql = 'select count(transaction_id) v_count from acc_transactions where approved=1 and ledger_hit=0 ';
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$get_kids = $stmt;
if (!empty($get_kids))
$v_count = (1 * $get_kids[0]['v_count']);
$vid = 0;
$vname = '';
return new JsonResponse(array(
"success" => true,
"v_count" => $v_count,
"skip_ids" => $skip_ids,
));
// MiscActions::refreshDatabase($em);
// return $this->redirectToRoute('dashboard');
}
public function RefreshPath(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$head_id = $id;
$get_kids_sql = " SELECT accounts_head_id FROM acc_accounts_head
WHERE acc_accounts_head.accounts_head_id >" . $head_id . " limit 1";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$head = $stmt;
if (!empty($head)) {
Accounts::AddHeadPath($em, $head[0]['accounts_head_id']);
return new JsonResponse(array(
"success" => true,
"last_id" => $head[0]['accounts_head_id'],
// "r"=>$r,
// "debug_data"=>System::encryptSignature($r)
));
} else {
return new JsonResponse(array(
"success" => false,
"last_id" => $head_id,
// "r"=>$r,
// "debug_data"=>System::encryptSignature($r)
));
}
// return $this->redirectToRoute('dashboard');
}
public function RefreshHeadNature(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$head_id = $id;
$assetParentHead = $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findOneBy(array(
'type' => AccountsConstant::ASSET,
'head_level' => 1
));
$libParentHead = $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findOneBy(array(
'type' => AccountsConstant::LIABILITY,
'head_level' => 1
));
$incParentHead = $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findOneBy(array(
'type' => AccountsConstant::INCOME,
'head_level' => 1
));
$expParentHead = $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findOneBy(array(
'type' => AccountsConstant::EXPENSE,
'head_level' => 1
));
if ($assetParentHead) {
$stmt = $em->getConnection()->executeStatement("update acc_accounts_head set head_nature='dr' , `type`='ast' where path_tree like '%/" . $assetParentHead->getAccountsHeadId() . "/%' ");
// $head=$stmt;
}
if ($expParentHead) {
$stmt = $em->getConnection()->executeStatement("update acc_accounts_head set head_nature='dr' , `type`='exp' where path_tree like '%/" . $expParentHead->getAccountsHeadId() . "/%' ");
// $head=$stmt;
}
if ($incParentHead) {
$stmt = $em->getConnection()->executeStatement("update acc_accounts_head set head_nature='cr' , `type`='inc' where path_tree like '%/" . $incParentHead->getAccountsHeadId() . "/%' ");
// $head=$stmt;
}
if ($libParentHead) {
$stmt = $em->getConnection()->executeStatement("update acc_accounts_head set head_nature='cr' , `type`='lib' where path_tree like '%/" . $libParentHead->getAccountsHeadId() . "/%' ");
// $head=$stmt;
}
if (!empty($head)) {
return new JsonResponse(array(
"success" => true,
"last_id" => $head[0]['accounts_head_id'],
// "r"=>$r,
// "debug_data"=>System::encryptSignature($r)
));
} else {
return new JsonResponse(array(
"success" => false,
"last_id" => $head_id,
// "r"=>$r,
// "debug_data"=>System::encryptSignature($r)
));
}
// return $this->redirectToRoute('dashboard');
}
public function RefreshCombo(Request $request)
{
$em = $this->getDoctrine()->getManager();
$debug_data = [];
//test
$wrong_voucher_list = [];
$ind_voucherAmounts = [];
$ind_voucherIds = [];
// $ind_voucherAmounts=[];
$transactions = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')
->findBy(
array(
'approved' => 1,
'ledgerHit' => 1,
)
);
foreach ($transactions as $d) {
$ind_voucherAmounts[$d->getTransactionId()] = 0;
$ind_voucherIds[] = $d->getTransactionId();
}
$transactions = $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')
->findBy(
array(
'transactionId' => $ind_voucherIds,
)
);
foreach ($transactions as $d) {
if ($d->getPosition() == 'cr')
$ind_voucherAmounts[$d->getTransactionId()] += $d->getAmount();
elseif ($d->getPosition() == 'dr')
$ind_voucherAmounts[$d->getTransactionId()] -= $d->getAmount();
}
foreach ($ind_voucherAmounts as $k => $d) {
if ($d >= 1 || $d <= -1)
$wrong_voucher_list[$k] = $d;
}
$debug_data = $wrong_voucher_list;
//test ends
return new JsonResponse(
$debug_data
);
// return $this->render(
// 'ApplicationBundle:pages/accounts/settings:refresh_combo_action.html.twig',
// array(
// 'page_title' => 'Refresh',
// 'debug_data' => $debug_data,
// 'autoStartLedgerHit' => 0,
// 'autoStartInventoryRefresh' => 0,
// 'inventoryRefreshed' => 0,
// 'lastRefreshDate' => '',
// 'autoStartFixedAssetDepreciation' => 0,
//
// // 'voucherDetails'=>$v_details,
// // 'heads'=>Accounts::HeadList($em),
// // 'transaction'=>$Transaction
// )
// );
// return $this->redirectToRoute('dashboard');
}
/**
* Core A — recompute acc_accounts_head.current_balance from the ledger.
*
* Two modes:
* - per-voucher: POST/GET transaction id (?id= or ?transaction_id=) → rebuilds
* only the heads that voucher touches (+ their subtree/ancestor chains).
* This is the on-page "Recompute balances" fix for the voucher view and the
* hook for the inline amount editor (so editing an amount can no longer
* leave current_balance stale, as it did on the NETZE tenant).
* - full: ?all=1 → rebuilds every ledger-backed head in the tenant.
*
* Dry-run unless ?apply=1. Unbacked heads (no ledger rows behind them, e.g.
* unposted opening balances) are reported but never written unless
* ?include_unbacked=1.
*/
public function RebuildVoucherBalances(Request $request)
{
$em = $this->getDoctrine()->getManager();
$apply = (int) $request->get('apply', 0) === 1;
$includeUnbacked = (int) $request->get('include_unbacked', 0) === 1;
$all = (int) $request->get('all', 0) === 1;
$txId = $request->get('id', $request->get('transaction_id', null));
$headIds = [];
if (!$all) {
if ($txId === null || $txId === '') {
return new JsonResponse(['ok' => 0, 'error' => 'Provide a transaction id, or all=1 for a full rebuild.'], 400);
}
$details = $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')
->findBy(array('transactionId' => (int) $txId));
foreach ($details as $d) {
$headIds[] = (int) $d->getAccountsHeadId();
}
if (empty($headIds)) {
return new JsonResponse(['ok' => 0, 'error' => 'No ledger lines found for transaction ' . $txId . '.'], 404);
}
}
try {
$result = \ApplicationBundle\Modules\Accounts\Service\LedgerRebuildService::recompute($em, [
'headIds' => $headIds,
'apply' => $apply,
'includeUnbacked' => $includeUnbacked,
]);
} catch (\Throwable $e) {
return new JsonResponse(['ok' => 0, 'error' => $e->getMessage()], 500);
}
return new JsonResponse(array_merge(
['ok' => 1, 'scope' => $all ? 'all' : ('transaction:' . $txId)],
$result['summary'],
['rows' => array_slice($result['rows'], 0, 100)]
));
}
public function OpeningHeadBalanceForce(Request $request)
{
$em = $this->getDoctrine()->getManager();
$new_cc = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccSettings')
->findOneBy(
array(
'name' => 'accounting_year_start',
)
);
$start_date_str = $new_cc ? $new_cc->getData() : "";
$start_date = new \DateTime($start_date_str);
$query_head_list = [];
$head_list = [];
$debug_data = [];
$customer_heads = [];
$get_kids_sql = ' select distinct `accounts_head_id` from acc_clients where 1;';
//UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$get_kids = $stmt;
foreach ($get_kids as $kid)
$customer_heads[] = $kid['accounts_head_id'];
$get_kids_sql = ' select distinct `advance_head_id` from acc_clients where 1;';
//UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$get_kids = $stmt;
foreach ($get_kids as $kid)
$customer_heads[] = $kid['advance_head_id'];
if ($request->isMethod('POST')) {
$data = [];
if ($request->request->has('dataHere'))
$data = json_decode($request->request->get('dataHere'), true);
if (!empty($data)) {
if (isset($data['head_id'])) {
//1st get all head data
$get_kids_sql = ' UPDATE `acc_accounts_head` SET opening_balance=0 WHERE 1;';
//UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$em->flush();
$get_kids_sql = "SELECT acc_accounts_head.name,
acc_accounts_head.opening_balance,
acc_accounts_head.current_balance,
acc_accounts_head.current_balance_reconciled,
acc_accounts_head.path_tree,
acc_accounts_head.head_nature,
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
on acc_accounts_head.parent_id=b.accounts_head_id WHERE acc_accounts_head.company_id=" .
$this->getLoggedUserCompanyId($request) . " ORDER BY name ASC";
$get_kids_sql .= '';
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$get_kids = $stmt;
foreach ($get_kids as $kid) {
$m = array();
$par_list = array_filter(explode('/', $kid["path_tree"]));
$m["id"] = $kid["accounts_head_id"];
$m["value"] = $kid["accounts_head_id"];
$m["text"] = $kid["name"] . (($kid["advance_of"] == null || $kid["advance_of"] == 0) ? '' : ' (Advance)');
$m["parent_name"] = $kid["parent_name"];
$m["type"] = $kid["type"];
$m["head_nature"] = $kid["head_nature"];
$m["opening"] = $kid["opening_balance"];
// $m["opening"] = 0;
$m["newOpening"] = 0;
$m["newCurrentBalance"] = 0;
$m["newCurrentBalanceReconciled"] = 0;
$m["current_balance"] = $kid["current_balance"];
$m["reconciled_balance"] = $kid["current_balance_reconciled"];
$m["parent_id"] = $kid["parent_id"];
$m["allParents"] = $par_list;
$m["cc_enabled"] = $kid["cc_enabled"];
$m["child_total_balance"] = 0;
$head_list[$kid["accounts_head_id"]] = $m;
}
//next check the change in opening
foreach ($data['head_id'] as $k => $h) {
if (isset($head_list[$h])) {
$to_add = 0;
// $to_add=(1*$data['head_opening'][$k])-(1*$head_list[$h]['opening']);
$child_nature = $head_list[$h]['head_nature'];
// if(!isset($head_list[$h]['to_add']))
// {
// $head_list[$h]['to_add']=$to_add;
// }
// $head_list[$h]['opening']=$head_list[$h]['opening']+$to_add;
// $head_list[$h]['current_balance']=$head_list[$h]['current_balance']+$to_add;
// $head_list[$h]['reconciled_balance']=$head_list[$h]['reconciled_balance']+$to_add;
$to_add_cb = (1 * str_replace(",", "", $data['head_opening'][$k]));
$head_list[$h]['newOpening'] = $head_list[$h]['newOpening'] + $to_add_cb;
$head_list[$h]['newCurrentBalance'] = $head_list[$h]['newCurrentBalance'] + $to_add_cb;
$head_list[$h]['newCurrentBalanceReconciled'] = $head_list[$h]['newCurrentBalanceReconciled'] + $to_add_cb;
$head_list[$h]['child_total_balance'] = $head_list[$h]['child_total_balance'] + $to_add_cb;
// if($to_add!=0)
{
foreach ($head_list[$h]['allParents'] as $par) {
if (isset($head_list[$par])) {
$to_add_par = 0;
$to_add_cb = ($child_nature == $head_list[$par]['head_nature']) ? (1 * $to_add_cb) : ((-1) * $to_add_cb);
if (!isset($head_list[$par]['child_total_balance'])) {
$head_list[$par]['child_total_balance'] = $to_add_cb;
} else {
$head_list[$par]['child_total_balance'] = $head_list[$par]['child_total_balance'] + $to_add_cb;
}
$head_list[$par]['newOpening'] = $head_list[$par]['newOpening'] + $to_add_cb;
$head_list[$par]['newCurrentBalance'] = $head_list[$par]['newCurrentBalance'] + $to_add_cb;
$head_list[$par]['newCurrentBalanceReconciled'] = $head_list[$par]['newCurrentBalanceReconciled'] + $to_add_cb;
}
}
}
}
}
foreach ($head_list as $k => $head) {
// if (isset($head['to_add']) && $head['to_add'] != 0) {
// $query_head_list[]=$k;
// }
if (isset($head['child_total_balance'])) {
if ($head['newOpening'] != $head['opening']) {
$to_add = $head['newOpening'] - $head['opening'];
$head_list[$k]['to_add'] = $head['newOpening'] - $head['opening'];
$head_list[$k]['opening'] = $head['opening'] + $to_add;
$head_list[$k]['current_balance'] = $head['current_balance'] + $to_add;
$head_list[$k]['reconciled_balance'] = $head['reconciled_balance'] + $to_add;
$query_head_list[] = $k;
}
}
}
//if no change then dont use that
//add teh change to all the closings found in that criteria be ware of the head natures
$closings = $em->getRepository('ApplicationBundle\\Entity\\AccClosingBalance')->findBy(
array(
'accountsHeadId' => $query_head_list
)
);
foreach ($closings as $closing) {
//check if the date is >= to start_date
if ($closing->getDate() >= $start_date) {
$to_add = isset($head_list[$closing->getAccountsHeadId()]['to_add']) ? $head_list[$closing->getAccountsHeadId()]['to_add'] : 0;
if ($to_add != 0) {
$closing->setOpening($closing->getOpening() + $to_add);
$closing->setBalance($closing->getBalance() + $to_add);
// $closing->setAddition($closing->getAddition() + $to_add);
}
}
}
$em->flush();
//add teh change to all the actual closings found in that criteria be ware of the head natures
$closings = $em->getRepository('ApplicationBundle\\Entity\\AccActualClosingBalance')->findBy(
array(
'accountsHeadId' => $query_head_list
)
);
foreach ($closings as $closing) {
//check if the date is >= to start_date
if ($closing->getDate() >= $start_date) {
$to_add = isset($head_list[$closing->getAccountsHeadId()]['to_add']) ? $head_list[$closing->getAccountsHeadId()]['to_add'] : 0;
if ($to_add != 0) {
$closing->setOpening($closing->getOpening() + $to_add);
$closing->setBalance($closing->getBalance() + $to_add);
// $closing->setAddition($closing->getAddition() + $to_add);
}
}
}
$em->flush();
//add teh change to all the Heads found in that criteria be ware of the head natures
$heads = $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findBy(
array(
'accountsHeadId' => $query_head_list
)
);
foreach ($heads as $head) {
$to_add = isset($head_list[$head->getAccountsHeadId()]['to_add']) ? $head_list[$head->getAccountsHeadId()]['to_add'] : 0;
if ($to_add != 0) {
$head->setOpeningBalance($head_list[$head->getAccountsHeadId()]['opening']);
$head->setCurrentBalance($head_list[$head->getAccountsHeadId()]['current_balance']);
$head->setCurrentBalanceReconciled($head_list[$head->getAccountsHeadId()]['reconciled_balance']);
}
}
$em->flush();
}
}
$this->addFlash(
'success',
'The Action was Successful.'
);
// MiscActions::refreshTransactions($em);
// return $this->redirectToRoute('dashboard');
$debug_data = $head_list;
}
$child_head_list = Accounts::getParentLedgerHeads($em, '', '', []);
return $this->render(
'@Accounts/pages/input_forms/opening_head_balance_assign.html.twig',
array(
'page_title' => 'Assign Head Opening',
'head_list' => $child_head_list,
'customer_heads' => $customer_heads,
'start_date' => $start_date,
'mod_head_list' => $head_list,
'query_head_list' => $query_head_list,
'debug_data' => $debug_data
// 'voucherDetails'=>$v_details,
// 'heads'=>Accounts::HeadList($em),
// 'transaction'=>$Transaction
)
);
}
public function OpeningHeadBalance(Request $request)
{
$em = $this->getDoctrine()->getManager();
$new_cc = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccSettings')
->findOneBy(
array(
'name' => 'accounting_year_start',
)
);
$start_date_str = $new_cc ? $new_cc->getData() : "";
$start_date = new \DateTime($start_date_str);
$query_head_list = [];
$head_list = [];
$debug_data = [];
$customer_heads = [];
$get_kids_sql = ' select distinct `accounts_head_id` from acc_clients where 1;';
//UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$get_kids = $stmt;
foreach ($get_kids as $kid)
$customer_heads[] = $kid['accounts_head_id'];
$get_kids_sql = ' select distinct `advance_head_id` from acc_clients where 1;';
//UPDATE company SET sales=0, expense=0, payable=0 ,net_worth=0, monthly_growth=0 WHERE 1;';
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$get_kids = $stmt;
foreach ($get_kids as $kid)
$customer_heads[] = $kid['advance_head_id'];
if ($request->isMethod('POST')) {
$data = [];
if ($request->request->has('dataHere'))
$data = json_decode($request->request->get('dataHere'), true);
if (!empty($data)) {
if (isset($data['head_id'])) {
//1st get all head data
$get_kids_sql = "SELECT acc_accounts_head.name,
acc_accounts_head.opening_balance,
acc_accounts_head.current_balance,
acc_accounts_head.current_balance_reconciled,
acc_accounts_head.path_tree,
acc_accounts_head.head_nature,
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
on acc_accounts_head.parent_id=b.accounts_head_id WHERE acc_accounts_head.company_id=" .
$this->getLoggedUserCompanyId($request) . " ORDER BY name ASC";
$get_kids_sql .= '';
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$get_kids = $stmt;
foreach ($get_kids as $kid) {
$m = array();
$par_list = array_filter(explode('/', $kid["path_tree"]));
$m["id"] = $kid["accounts_head_id"];
$m["value"] = $kid["accounts_head_id"];
$m["text"] = $kid["name"] . (($kid["advance_of"] == null || $kid["advance_of"] == 0) ? '' : ' (Advance)');
$m["parent_name"] = $kid["parent_name"];
$m["type"] = $kid["type"];
$m["head_nature"] = $kid["head_nature"];
$m["opening"] = $kid["opening_balance"];
$m["newOpening"] = 0;
$m["newCurrentBalance"] = 0;
$m["newCurrentBalanceReconciled"] = 0;
$m["current_balance"] = $kid["current_balance"];
$m["reconciled_balance"] = $kid["current_balance_reconciled"];
$m["parent_id"] = $kid["parent_id"];
$m["allParents"] = $par_list;
$m["cc_enabled"] = $kid["cc_enabled"];
$m["child_total_balance"] = 0;
$head_list[$kid["accounts_head_id"]] = $m;
}
//next check the change in opening
foreach ($data['head_id'] as $k => $h) {
if (isset($head_list[$h])) {
$to_add = 0;
// $to_add=(1*$data['head_opening'][$k])-(1*$head_list[$h]['opening']);
$child_nature = $head_list[$h]['head_nature'];
// if(!isset($head_list[$h]['to_add']))
// {
// $head_list[$h]['to_add']=$to_add;
// }
// $head_list[$h]['opening']=$head_list[$h]['opening']+$to_add;
// $head_list[$h]['current_balance']=$head_list[$h]['current_balance']+$to_add;
// $head_list[$h]['reconciled_balance']=$head_list[$h]['reconciled_balance']+$to_add;
$to_add_cb = (1 * str_replace(",", "", $data['head_opening'][$k]));
$head_list[$h]['newOpening'] = $head_list[$h]['newOpening'] + $to_add_cb;
$head_list[$h]['newCurrentBalance'] = $head_list[$h]['newCurrentBalance'] + $to_add_cb;
$head_list[$h]['newCurrentBalanceReconciled'] = $head_list[$h]['newCurrentBalanceReconciled'] + $to_add_cb;
$head_list[$h]['child_total_balance'] = $head_list[$h]['child_total_balance'] + $to_add_cb;
// if($to_add!=0)
{
foreach ($head_list[$h]['allParents'] as $par) {
if (isset($head_list[$par])) {
$to_add_par = 0;
$to_add_cb = ($child_nature == $head_list[$par]['head_nature']) ? (1 * $to_add_cb) : ((-1) * $to_add_cb);
if (!isset($head_list[$par]['child_total_balance'])) {
$head_list[$par]['child_total_balance'] = $to_add_cb;
} else {
$head_list[$par]['child_total_balance'] = $head_list[$par]['child_total_balance'] + $to_add_cb;
}
$head_list[$par]['newOpening'] = $head_list[$par]['newOpening'] + $to_add_cb;
$head_list[$par]['newCurrentBalance'] = $head_list[$par]['newCurrentBalance'] + $to_add_cb;
$head_list[$par]['newCurrentBalanceReconciled'] = $head_list[$par]['newCurrentBalanceReconciled'] + $to_add_cb;
}
}
}
}
}
foreach ($head_list as $k => $head) {
// if (isset($head['to_add']) && $head['to_add'] != 0) {
// $query_head_list[]=$k;
// }
if (isset($head['child_total_balance'])) {
if ($head['newOpening'] != $head['opening']) {
$to_add = $head['newOpening'] - $head['opening'];
$head_list[$k]['to_add'] = $head['newOpening'] - $head['opening'];
$head_list[$k]['opening'] = $head['opening'] + $to_add;
$head_list[$k]['current_balance'] = $head['current_balance'] + $to_add;
$head_list[$k]['reconciled_balance'] = $head['reconciled_balance'] + $to_add;
$query_head_list[] = $k;
}
}
}
//if no change then dont use that
//add teh change to all the closings found in that criteria be ware of the head natures
$closings = $em->getRepository('ApplicationBundle\\Entity\\AccClosingBalance')->findBy(
array(
'accountsHeadId' => $query_head_list
)
);
foreach ($closings as $closing) {
//check if the date is >= to start_date
if ($closing->getDate() >= $start_date) {
$to_add = isset($head_list[$closing->getAccountsHeadId()]['to_add']) ? $head_list[$closing->getAccountsHeadId()]['to_add'] : 0;
if ($to_add != 0) {
$closing->setOpening($closing->getOpening() + $to_add);
$closing->setBalance($closing->getBalance() + $to_add);
// $closing->setAddition($closing->getAddition() + $to_add);
}
}
}
$em->flush();
//add teh change to all the actual closings found in that criteria be ware of the head natures
$closings = $em->getRepository('ApplicationBundle\\Entity\\AccActualClosingBalance')->findBy(
array(
'accountsHeadId' => $query_head_list
)
);
foreach ($closings as $closing) {
//check if the date is >= to start_date
if ($closing->getDate() >= $start_date) {
$to_add = isset($head_list[$closing->getAccountsHeadId()]['to_add']) ? $head_list[$closing->getAccountsHeadId()]['to_add'] : 0;
if ($to_add != 0) {
$closing->setOpening($closing->getOpening() + $to_add);
$closing->setBalance($closing->getBalance() + $to_add);
// $closing->setAddition($closing->getAddition() + $to_add);
}
}
}
$em->flush();
//add teh change to all the Heads found in that criteria be ware of the head natures
$heads = $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findBy(
array(
'accountsHeadId' => $query_head_list
)
);
foreach ($heads as $head) {
$to_add = isset($head_list[$head->getAccountsHeadId()]['to_add']) ? $head_list[$head->getAccountsHeadId()]['to_add'] : 0;
if ($to_add != 0) {
$head->setOpeningBalance($head_list[$head->getAccountsHeadId()]['opening']);
$head->setCurrentBalance($head_list[$head->getAccountsHeadId()]['current_balance']);
$head->setCurrentBalanceReconciled($head_list[$head->getAccountsHeadId()]['reconciled_balance']);
}
}
$em->flush();
}
}
$this->addFlash(
'success',
'The Action was Successful.'
);
// MiscActions::refreshTransactions($em);
// return $this->redirectToRoute('dashboard');
$debug_data = $head_list;
}
$child_head_list = Accounts::getParentLedgerHeads($em, '', '', []);
return $this->render(
'@Accounts/pages/input_forms/opening_head_balance_assign.html.twig',
array(
'page_title' => 'Assign Head Opening',
'head_list' => $child_head_list,
'start_date' => $start_date,
'mod_head_list' => $head_list,
'query_head_list' => $query_head_list,
'customer_heads' => $customer_heads,
'debug_data' => $debug_data
// 'voucherDetails'=>$v_details,
// 'heads'=>Accounts::HeadList($em),
// 'transaction'=>$Transaction
)
);
}
public function EditJournalVoucher(Request $request, $id)
{
$v_details = [];
$Transaction = [];
if ($id != 0) {
$em = $this->getDoctrine()->getManager();
$Transaction = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
'transactionId' => $id,
'editFlag' => 1,
'lockFlag' => [0, null],
'disabledFlag' => [0, null],
));
if ($Transaction) {
$v_details = Accounts::GetVoucherDetails($em, $id);
} else {
// $this->container->get("session")->setFlash("error", "Pikachu is not allowed");
$this->addFlash(
'error',
'The Action was not allowed.'
);
}
}
if ($request->isMethod('POST')) {
// Generic::debugMessage($_POST);
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
$dochash = $request->request->get('voucherNumber'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isEditable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash
)) {
$this->addFlash(
'error',
'Sorry Couldnot insert Data.'
);
} else {
//1st delete the doc
$funcname = 'AccTransactions';
$doc_id = $request->request->get('extTransId');
DeleteDocument::$funcname($em, $doc_id, 0);
$ledgerHeads = $request->request->get('ledgerHeads');
$notes = $request->request->get('trNote');
$costCenters = $request->request->get('costCenters');
$drAmount = $request->request->get('drAmount');
$crAmount = $request->request->get('crAmount');
$check_allowed = 0;
if ($request->request->has('check_allowed'))
$check_allowed = 1;
$em_goc = $this->getDoctrine()->getManager('company_group');
$post_data = $request->request;
$TransID = Accounts::EditExistingTrans(
$this->getDoctrine()->getManager(),
$doc_id,
$request->request->get('date'),
array_sum($request->request->get('drAmount')),
AccountsConstant::VOUCHER_JOURNAL,
$request->request->get('description'),
(empty($request->request->get('voucherNumber')) ? Generic::simpleRandString() : $request->request->get('voucherNumber')),
$request->request->get('type_hash'),
$request->request->get('prefix_hash'),
$request->request->get('assoc_hash'),
$request->request->get('number_hash'),
$check_allowed,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request)
);
for ($i = 0; $i < count($ledgerHeads); $i++) {
if (!empty($drAmount[$i]) && $drAmount[$i] != 0) {
Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('date'),
$TransID,
Generic::CurrToInt($drAmount[$i]),
$ledgerHeads[$i],
$notes[$i],
AccountsConstant::DEBIT,
isset($costCenters[$i]) ? $costCenters[$i] : 0,
[],
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
}
if (!empty($crAmount[$i]) && $crAmount[$i] != 0) {
Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('date'),
$TransID,
Generic::CurrToInt($crAmount[$i]),
$ledgerHeads[$i],
$notes[$i],
AccountsConstant::CREDIT,
isset($costCenters[$i]) ? $costCenters[$i] : 0,
[],
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
}
}
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = 2; //created
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AccTransactions']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
$TransID,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
3 //journal voucher
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
$TransID,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$trans_here = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccTransactions')
->findOneBy(
array(
'transactionId' => $TransID
)
);
//notify
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),
"Journal Voucher : " . $trans_here->getDocumentHash() . " is Created Right Now",
'all',
"",
'success',
"",
"Journal"
);
$this->addFlash(
'success',
'New Transaction Added.'
);
}
}
return $this->render(
'@Accounts/pages/input_forms/journal_voucher.html.twig',
array(
'page_title' => 'Edit Journal Voucher',
'voucherDetails' => $v_details,
// 'heads'=>Accounts::HeadList($em),
'transaction' => $Transaction
)
);
}
public function CancelCheck(Request $request, $voucherId = 0)
{
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
// Generic::debugMessage($_POST);
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
$dochash = $request->request->get('voucherNumber'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash,
$voucherId
)) {
$this->addFlash(
'error',
'Sorry Couldnot insert Data.'
);
} else {
$funcname = 'AccTransactions';
$doc_id = $voucherId;
DeleteDocument::$funcname($em, $doc_id, 0);
$ledgerHeads = $request->request->get('ledgerHeads');
$notes = $request->request->get('trNote');
$costCenters = $request->request->get('costCenters');
$drAmount = $request->request->get('drAmount');
$crAmount = $request->request->get('crAmount');
$check_allowed = 0;
if ($request->request->has('check_allowed'))
$check_allowed = 1;
$TransID = Accounts::CreateNewTransaction(
$voucherId,
$this->getDoctrine()->getManager(),
$request->request->get('date'),
array_sum($request->request->get('drAmount')),
AccountsConstant::VOUCHER_JOURNAL,
$request->request->get('description'),
(empty($request->request->get('voucherNumber')) ? Generic::simpleRandString() : $request->request->get('voucherNumber')),
$request->request->get('type_hash'),
$request->request->get('prefix_hash'),
$request->request->get('assoc_hash'),
$request->request->get('number_hash'),
$check_allowed,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request)
);
for ($i = 0; $i < count($ledgerHeads); $i++) {
if (!empty($drAmount[$i]) && $drAmount[$i] != 0) {
Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('date'),
$TransID,
Generic::CurrToInt($drAmount[$i]),
$ledgerHeads[$i],
$notes[$i],
AccountsConstant::DEBIT,
isset($costCenters[$i]) ? $costCenters[$i] : 0,
[],
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
}
if (!empty($crAmount[$i]) && $crAmount[$i] != 0) {
Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('date'),
$TransID,
Generic::CurrToInt($crAmount[$i]),
$ledgerHeads[$i],
$notes[$i],
AccountsConstant::CREDIT,
isset($costCenters[$i]) ? $costCenters[$i] : 0,
[],
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
}
}
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AccTransactions']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
$TransID,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
3 //journal voucher
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
$TransID,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$trans_here = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccTransactions')
->findOneBy(
array(
'transactionId' => $TransID
)
);
//notify
$this->addFlash(
'success',
'New Transaction Added.'
);
$url = $this->generateUrl(
'view_voucher'
);
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),
"Journal Voucher : " . $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
'pos',
System::getPositionIdsByDepartment($em, GeneralConstant::ACCOUNTS_DEPARTMENT),
'success',
$url . "/" . $TransID,
"Journal"
);
return $this->redirect($url . "/" . $TransID);
}
}
//for edits
$extVoucherData = [];
$extVoucherDetailsData = [];
if ($voucherId == 0) {
} else {
$extTrans = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(
array(
'transactionId' => $voucherId, ///material
)
);
//now if its not editable, redirect to view
if ($extTrans) {
if ($extTrans->getEditFlag() != 1) {
$url = $this->generateUrl(
'view_voucher'
);
return $this->redirect($url . "/" . $voucherId);
} else {
$extVoucherData = $extTrans;
$extVoucherDetailsData = Accounts::GetVoucherDataForEdit($em, $voucherId);
}
} else {
}
}
return $this->render(
'@Accounts/pages/input_forms/journal_voucher.html.twig',
array(
'page_title' => 'Create Journal Voucher',
'transaction' => [],
'extVoucherData' => $extVoucherData,
'extVoucherDetailsData' => $extVoucherDetailsData
)
);
}
public function ToggleActiveCheck(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$chk = $em->getRepository("ApplicationBundle\\Entity\\AccCheck")->findOneBy(array(
'CheckId' => $id
));
if ($chk) {
if ($chk->getActive() == GeneralConstant::ACTIVE) {
$chk->setActive(GeneralConstant::INACTIVE);
$chk->setAssigned(null);
$chk->setVoucherId(null);
$chk->setCheckAmount(null);
$chk->setTransactionDate(null);
$chk->setCheckDate(null);
$chk->setReconDate(null);
$chk->setLedgerHitDate(null);
$chk->setRecAccountsHeadIdList(null);
$chk->setRecAccountsHeadId(null);
} else
$chk->setActive(GeneralConstant::ACTIVE);
$em->flush();
}
// $chk->setActive(GeneralConstant::INACTIVE);
$em->flush();
//for edits
$extVoucherData = [];
$extVoucherDetailsData = [];
// if($voucherId==0)
// {
//
// }
// else
// {
//
// $extTrans=$em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(
// array(
// 'transactionId'=>$voucherId, ///material
//
// )
// );
//
//
// //now if its not editable, redirect to view
// if($extTrans) {
// if ($extTrans->getEditFlag() != 1) {
// $url = $this->generateUrl(
// 'view_voucher'
// );
// return $this->redirect($url . "/" . $voucherId);
// }
// else
// {
// $extVoucherData=$extTrans;
// $extVoucherDetailsData=Accounts::GetVoucherDataForEdit($em,$voucherId);
// }
// }
// else
// {
//
// }
//
// }
//
//
// return $this->render('@Accounts/pages/input_forms/journal_voucher.html.twig',
// array(
// 'page_title'=>'Create Journal Voucher',
// 'transaction'=>[],
// 'extVoucherData'=>$extVoucherData,
// 'extVoucherDetailsData'=>$extVoucherDetailsData
// )
// );
return new JsonResponse(array(
"success" => $chk ? true : false,
"id" => $id,
"currStatus" => $chk ? $chk->getActive() : ''
// "file_path"=>$file_path,
// "r"=>$r,
// "debug_data"=>System::encryptSignature($r)
));
// $url = $this->generateUrl(
// 'check_management'
// );
// return $this->redirect($url);
}
public function CreateFundTransfer(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$voucherId = $id;
if ($request->isMethod('POST')) {
// Generic::debugMessage($_POST);
$em = $this->getDoctrine()->getManager();
MiscActions::RemoveExpiredDocs($em);
$numberHash = MiscActions::GetNumberHash($em, 'JV', "GN", $request->request->get('projectId') ?: 0, '', 1);
$dochash = 'JV' . '/' . "GN" . '/' . $request->request->get('projectId') ?: 0 . '/' . $numberHash;
$entity_id = array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
// $dochash = $request->request->get('voucherNumber'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash,
$id
)) {
$this->addFlash(
'error',
'Sorry Couldnot insert Data.'
);
} else {
$funcname = 'AccTransactions';
$doc_id = $voucherId;
DeleteDocument::$funcname($em, $doc_id, 0);
$ledgerHeads = $request->request->get('ledgerHeads');
$notes = $request->request->get('trNote');
$costCenters = $request->request->get('costCenters');
$drAmount = $request->request->get('drAmount');
$crAmount = $request->request->get('crAmount');
$check_allowed = 0;
if ($request->request->has('check_allowed'))
$check_allowed = 1;
$em_goc = $this->getDoctrine()->getManager('company_group');
$post_data = $request->request;
$TransID = Accounts::CreateNewTransaction(
$voucherId,
$this->getDoctrine()->getManager(),
$request->request->get('date'),
array_sum($request->request->get('drAmount')),
AccountsConstant::VOUCHER_JOURNAL,
$request->request->get('description'),
(empty($request->request->get('voucherNumber')) ? Generic::simpleRandString() : $request->request->get('voucherNumber')),
$request->request->get('type_hash'),
$request->request->get('prefix_hash'),
$request->request->get('assoc_hash'),
$request->request->get('number_hash'),
$check_allowed,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request)
);
$file_path_list = [];
if ($TransID != 0)
if (!empty($request->files)) {
MiscActions::RemoveFilesForEntityDoc($em_goc, 'AccTransactions', $TransID);
$storePath = 'uploads/Voucher/';
$path = "";
$file_path = "";
$session = $request->getSession();
MiscActions::RemoveExpiredFiles($em_goc);
foreach ($request->files as $uploadedFileGG) {
// if($uploadedFile->getImage())
// var_dump($uploadedFile->getFile());
// var_dump($uploadedFile);
$tempD = $uploadedFileGG;
if (!is_array($uploadedFileGG)) {
$uploadedFileGG = array();
$uploadedFileGG[] = $tempD;
}
foreach ($uploadedFileGG as $uploadedFile) {
if ($uploadedFile != null) {
$extension = $uploadedFile->guessExtension();
$size = $uploadedFile->getSize();
$fileName = 'TRANS_' . $TransID . '_' . (md5(uniqid())) . '.' . $uploadedFile->guessExtension();
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath;
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
if (file_exists($upl_dir . '' . $path)) {
chmod($upl_dir . '' . $path, 0755);
unlink($upl_dir . '' . $path);
}
$file = $uploadedFile->move($upl_dir, $path);
$expireNever = 1;
$expireTs = 0;
$EntityFile = new EntityFile();
$EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath . $path);
$EntityFile->setName($path);
$EntityFile->setMarker('_GEN_');
$EntityFile->setExtension($extension);
$EntityFile->setExpireTs($expireTs);
$EntityFile->setSize($size);
$EntityFile->setRelativePath($storePath . $path);
$EntityFile->setEntityName('AccTransactions');
$EntityFile->setEntityBundle('ApplicationBundle');
$EntityFile->setEntityId($TransID);
$EntityFile->setEntityIdField('transactionId');
$EntityFile->setModifyFieldSetter('setFiles');
$EntityFile->setDocIdForApplicant(0);
$EntityFile->setUserId($session->get(UserConstants::USER_ID, 0));
$EntityFile->setAppId($session->get(UserConstants::USER_APP_ID, 0));
$EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID, 0));
$EntityFile->setUserType($session->get(UserConstants::USER_TYPE, 0));
$em_goc->persist($EntityFile);
$em_goc->flush();
$EntityFileId = $EntityFile->getId();
}
if ($path != "")
$file_path_list[] = ($storePath . $path);
}
}
$g_path = $this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath . $path;
$v = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
'transactionId' => $TransID,
));
if ($v) {
$v->setFiles(implode(',', $file_path_list));
$em->flush();
} else {
}
}
for ($i = 0; $i < count($ledgerHeads); $i++) {
if (!empty($drAmount[$i]) && $drAmount[$i] != 0) {
Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('date'),
$TransID,
Generic::CurrToInt($drAmount[$i]),
$ledgerHeads[$i],
$notes[$i],
AccountsConstant::DEBIT,
isset($costCenters[$i]) ? $costCenters[$i] : 0,
[],
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
}
if (!empty($crAmount[$i]) && $crAmount[$i] != 0) {
Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('date'),
$TransID,
Generic::CurrToInt($crAmount[$i]),
$ledgerHeads[$i],
$notes[$i],
AccountsConstant::CREDIT,
isset($costCenters[$i]) ? $costCenters[$i] : 0,
[],
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
}
}
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AccTransactions']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
$TransID,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
3 //journal voucher
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
$TransID,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$trans_here = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccTransactions')
->findOneBy(
array(
'transactionId' => $TransID
)
);
//notify
$this->addFlash(
'success',
'New Transaction Added.'
);
$url = $this->generateUrl(
'view_voucher'
);
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),
"Journal Voucher : " . $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
'pos',
System::getPositionIdsByDepartment($em, GeneralConstant::ACCOUNTS_DEPARTMENT),
'success',
// $url . "/" . $TransID,
$url . "/" . $TransID,
"Journal"
);
return new JsonResponse(
array(
'success' => true,
)
);
}
}
//for edits
$extVoucherData = [];
$extVoucherDetailsData = [];
if ($voucherId == 0) {
} else {
$extTrans = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(
array(
'transactionId' => $voucherId, ///material
)
);
//now if its not editable, redirect to view
if ($extTrans) {
if ($extTrans->getEditFlag() != 1) {
$url = $this->generateUrl(
'view_voucher'
);
return $this->redirect($url . "/" . $voucherId);
} else {
$extVoucherData = $extTrans;
$extVoucherDetailsData = Accounts::GetVoucherDataForEdit($em, $voucherId);
}
} else {
}
}
return $this->render(
'@Accounts/pages/input_forms/journal_voucher.html.twig',
array(
'page_title' => 'Create Journal Voucher',
'transaction' => [],
'extVoucherData' => $extVoucherData,
'extVoucherDetailsData' => $extVoucherDetailsData
)
);
}
public function CreateFinancialBudget(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
// Generic::debugMessage($_POST);
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['FinancialBudget']; //change
$dochash = $request->request->get('voucherNumber'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash,
$id
)) {
$this->addFlash(
'error',
'Sorry Couldnot insert Data.'
);
} else {
$funcname = 'FinancialBudget';
$doc_id = $id;
DeleteDocument::$funcname($em, $doc_id, 0);
$ledgerHeads = $request->request->get('ledgerHeads');
$notes = [];
$costCenters = $request->request->get('costCenters');
$drAmount = $request->request->get('drAmount');
$crAmount = $request->request->get('crAmount');
$check_allowed = 0;
$BudgetId = Accounts::CreateNewBudget(
$id,
$this->getDoctrine()->getManager(),
$request->request->get('start_date'),
$request->request->get('end_date'),
array_sum($request->request->get('drAmount')),
$request->request->get('description'),
(empty($request->request->get('voucherNumber')) ? Generic::simpleRandString() : $request->request->get('voucherNumber')),
$request->request->get('type_hash'),
$request->request->get('prefix_hash'),
$request->request->get('assoc_hash'),
$request->request->get('number_hash'),
$check_allowed,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request)
);
for ($i = 0; $i < count($ledgerHeads); $i++) {
if (!empty($drAmount[$i]) && $drAmount[$i] != 0) {
Accounts::CreateNewBudgetDetails(
$this->getDoctrine()->getManager(),
$request->request->get('start_date'),
$request->request->get('end_date'),
$BudgetId,
Generic::CurrToInt($drAmount[$i]),
$ledgerHeads[$i],
// $notes[$i],
AccountsConstant::DEBIT,
isset($costCenters[$i]) ? $costCenters[$i] : 0,
[],
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
}
if (!empty($crAmount[$i]) && $crAmount[$i] != 0) {
Accounts::CreateNewBudgetDetails(
$this->getDoctrine()->getManager(),
$request->request->get('start_date'),
$request->request->get('end_date'),
$BudgetId,
Generic::CurrToInt($crAmount[$i]),
$ledgerHeads[$i],
// $notes[$i],
AccountsConstant::CREDIT,
isset($costCenters[$i]) ? $costCenters[$i] : 0,
[],
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
}
}
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['FinancialBudget']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['FinancialBudget'],
$BudgetId,
$request->getSession()->get(UserConstants::USER_LOGIN_ID) //journal voucher
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['FinancialBudget'],
$BudgetId,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$trans_here = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\FinancialBudget')
->findOneBy(
array(
'budgetId' => $BudgetId
)
);
//notify
$this->addFlash(
'success',
'New Budget Added.'
);
$url = $this->generateUrl(
'view_financial_budget'
);
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),
"Financial Budget : " . $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
'pos',
System::getPositionIdsByDepartment($em, GeneralConstant::ACCOUNTS_DEPARTMENT),
'success',
$url . "/" . $BudgetId,
"Journal"
);
// return $this->redirect($url."/".$BudgetId);
}
}
//for edits
$extBudgetData = [];
$extBudgetDetailsData = [];
if ($id == 0) {
} else {
$extTrans = $em->getRepository('ApplicationBundle\\Entity\\FinancialBudget')->findOneBy(
array(
'budgetId' => $id, ///material
)
);
//now if its not editable, redirect to view
if ($extTrans) {
if ($extTrans->getEditFlag() != 1) {
$url = $this->generateUrl(
'view_financial_budget'
);
return $this->redirect($url . "/" . $id);
} else {
$extBudgetData = $extTrans;
$extBudgetDetailsData = Accounts::GetBudgetDataForEdit($em, $id);
}
} else {
}
}
return $this->render(
'@Accounts/pages/input_forms/financial_budget.html.twig',
array(
'page_title' => 'Create Financial Budget',
'transaction' => [],
'currBudgetList' => $em->getRepository('ApplicationBundle\\Entity\\FinancialBudget')->findBy(
array(
// 'budgetId'=>$id, ///material
'CompanyId' => $this->getLoggedUserCompanyId($request), ///material
)
),
'headListForBudget' => Accounts::HeadListFullPathExtended($em, '>', $this->getLoggedUserCompanyId($request)),
'extBudgetData' => $extBudgetData,
'extBudgetDetailsData' => $extBudgetDetailsData
)
);
}
public function CreateJournalVoucher(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$voucherId = $id;
if ($request->isMethod('POST')) {
// Generic::debugMessage($_POST);
$em = $this->getDoctrine()->getManager();
MiscActions::RemoveExpiredDocs($em);
$entity_id = array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
$dochash = $request->request->get('voucherNumber'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash,
$id
)) {
$this->addFlash(
'error',
'Sorry Could not insert Data.'
);
} else {
$funcname = 'AccTransactions';
$doc_id = $voucherId;
DeleteDocument::$funcname($em, $doc_id, 0);
$ledgerHeads = $request->request->get('ledgerHeads');
$notes = $request->request->get('trNote');
$costCenters = $request->request->get('costCenters');
$drAmount = $request->request->get('drAmount');
$crAmount = $request->request->get('crAmount');
$check_allowed = 0;
if ($request->request->has('check_allowed'))
$check_allowed = 1;
$em_goc = $this->getDoctrine()->getManager('company_group');
$post_data = $request->request;
$TransID = Accounts::CreateNewTransaction(
$voucherId,
$this->getDoctrine()->getManager(),
$request->request->get('date'),
array_sum($request->request->get('drAmount')),
AccountsConstant::VOUCHER_JOURNAL,
$request->request->get('description'),
(empty($request->request->get('voucherNumber')) ? Generic::simpleRandString() : $request->request->get('voucherNumber')),
$request->request->get('type_hash'),
$request->request->get('prefix_hash'),
$request->request->get('assoc_hash'),
$request->request->get('number_hash'),
$check_allowed,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request)
);
$file_path_list = [];
if ($TransID != 0)
if (!empty($request->files)) {
MiscActions::RemoveFilesForEntityDoc($em_goc, 'AccTransactions', $TransID);
$storePath = 'uploads/Voucher/';
$path = "";
$file_path = "";
$session = $request->getSession();
MiscActions::RemoveExpiredFiles($em_goc);
foreach ($request->files as $uploadedFileGG) {
// if($uploadedFile->getImage())
// var_dump($uploadedFile->getFile());
// var_dump($uploadedFile);
$tempD = $uploadedFileGG;
if (!is_array($uploadedFileGG)) {
$uploadedFileGG = array();
$uploadedFileGG[] = $tempD;
}
foreach ($uploadedFileGG as $uploadedFile) {
if ($uploadedFile != null) {
$extension = $uploadedFile->guessExtension();
$size = $uploadedFile->getSize();
$fileName = 'TRANS_' . $TransID . '_' . (md5(uniqid())) . '.' . $uploadedFile->guessExtension();
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath;
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
if (file_exists($upl_dir . '' . $path)) {
chmod($upl_dir . '' . $path, 0755);
unlink($upl_dir . '' . $path);
}
$file = $uploadedFile->move($upl_dir, $path);
$expireNever = 1;
$expireTs = 0;
$EntityFile = new EntityFile();
$EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath . $path);
$EntityFile->setName($path);
$EntityFile->setMarker('_GEN_');
$EntityFile->setExtension($extension);
$EntityFile->setExpireTs($expireTs);
$EntityFile->setSize($size);
$EntityFile->setRelativePath($storePath . $path);
$EntityFile->setEntityName('AccTransactions');
$EntityFile->setEntityBundle('ApplicationBundle');
$EntityFile->setEntityId($TransID);
$EntityFile->setEntityIdField('transactionId');
$EntityFile->setModifyFieldSetter('setFiles');
$EntityFile->setDocIdForApplicant(0);
$EntityFile->setUserId($session->get(UserConstants::USER_ID, 0));
$EntityFile->setAppId($session->get(UserConstants::USER_APP_ID, 0));
$EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID, 0));
$EntityFile->setUserType($session->get(UserConstants::USER_TYPE, 0));
$em_goc->persist($EntityFile);
$em_goc->flush();
$EntityFileId = $EntityFile->getId();
}
if ($path != "")
$file_path_list[] = ($storePath . $path);
}
}
$g_path = $this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath . $path;
$v = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
'transactionId' => $TransID,
));
if ($v) {
$v->setFiles(implode(',', $file_path_list));
$em->flush();
} else {
}
}
for ($i = 0; $i < count($ledgerHeads); $i++) {
if (!empty($drAmount[$i]) && $drAmount[$i] != 0) {
Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('date'),
$TransID,
Generic::CurrToInt($drAmount[$i]),
$ledgerHeads[$i],
$notes[$i],
AccountsConstant::DEBIT,
isset($costCenters[$i]) ? $costCenters[$i] : 0,
[],
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
0,
0,
'_UNSET_',
$request->request->get('currency')[$i],
1,
$request->request->get('currencyMultiplyRate')[$i]
);
}
if (!empty($crAmount[$i]) && $crAmount[$i] != 0) {
Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('date'),
$TransID,
Generic::CurrToInt($crAmount[$i]),
$ledgerHeads[$i],
$notes[$i],
AccountsConstant::CREDIT,
isset($costCenters[$i]) ? $costCenters[$i] : 0,
[],
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
0,
0,
'_UNSET_',
$request->request->get('currency')[$i],
1,
$request->request->get('currencyMultiplyRate')[$i]
);
}
}
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AccTransactions']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
$TransID,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
3 //journal voucher
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
$TransID,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$trans_here = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccTransactions')
->findOneBy(
array(
'transactionId' => $TransID
)
);
//notify
$url = $this->generateUrl(
'view_voucher'
);
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),
"Journal Voucher : " . $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
'pos',
System::getPositionIdsByDepartment($em, GeneralConstant::ACCOUNTS_DEPARTMENT),
'success',
// $url . "/" . $TransID,
$url . "/" . $TransID,
"Journal"
);
if ($request->request->has('returnJson')) {
$doc = $trans_here;
return new JsonResponse(array(
'success' => true,
'documentHash' => $trans_here->getDocumentHash(),
'documentId' => $TransID,
'documentIdPadded' => str_pad($TransID, 8, '0', STR_PAD_LEFT),
'documentDate' => $trans_here->getTransactionDate()->format('Y-m-d'),
'documentAmount' => $trans_here->getTransactionAmount(),
'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
'viewUrl' => $url . "/" . $TransID,
'docPrintMainUrl' => $this->generateUrl('print_voucher'),
));
} else {
$this->addFlash(
'success',
'New Document Created'
);
return $this->redirect($url . "/" . $TransID);
}
}
}
//for edits
$extVoucherData = [];
$extVoucherDetailsData = [];
if ($voucherId == 0) {
} else {
$extTrans = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(
array(
'transactionId' => $voucherId, ///material
)
);
//now if its not editable, redirect to view
if ($extTrans) {
if ($extTrans->getEditFlag() != 1) {
$url = $this->generateUrl(
'view_voucher'
);
return $this->redirect($url . "/" . $voucherId);
} else {
$extVoucherData = $extTrans;
$extVoucherDetailsData = Accounts::GetVoucherDataForEdit($em, $voucherId);
}
} else {
}
}
return $this->render(
'@Accounts/pages/input_forms/journal_voucher.html.twig',
array(
'page_title' => 'Create Journal Voucher',
'transaction' => [],
'extVoucherData' => $extVoucherData,
'extVoucherDetailsData' => $extVoucherDetailsData
)
);
}
public function CreateContraVoucher(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$voucherId = $id;
$details_ids = [];
if ($request->isMethod('POST')) {
// Generic::debugMessage($_POST);
$em = $this->getDoctrine()->getManager();
MiscActions::RemoveExpiredDocs($em);
$entity_id = array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
$dochash = $request->request->get('voucherNumber'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash,
$id
)) {
$this->addFlash(
'error',
'Sorry Could not insert Data.'
);
} else {
$funcname = 'AccTransactions';
$doc_id = $voucherId;
DeleteDocument::$funcname($em, $doc_id, 0);
$ledgerHeads = $request->request->get('ledgerHeads');
$notes = $request->request->get('trNote');
$costCenters = $request->request->get('costCenters');
$drAmount = $request->request->get('drAmount');
$crAmount = $request->request->get('crAmount');
$currencies = $request->request->get('currency', []);
$currencyMultiplyRates = $request->request->get('currencyMultiplyRate', []);
$em = $this->getDoctrine()->getManager();
$check_allowed = 0;
$provisional = 0;
if ($request->request->has('check_allowed'))
$check_allowed = 1;
if ($request->request->has('provisional'))
$provisional = 1;
$em_goc = $this->getDoctrine()->getManager('company_group');
$post_data = $request->request;
$TransID = Accounts::CreateNewTransaction(
$voucherId,
$this->getDoctrine()->getManager(),
$request->request->get('date'),
array_sum($request->request->get('drAmount')),
AccountsConstant::VOUCHER_CONTRA,
$request->request->get('description'),
(empty($request->request->get('voucherNumber')) ? Generic::simpleRandString() : $request->request->get('voucherNumber')),
$request->request->get('type_hash'),
$request->request->get('prefix_hash'),
$request->request->get('assoc_hash'),
$request->request->get('number_hash'),
$check_allowed,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request),
'',
$provisional,
0,
$request->request->has('checkAssignType') ? $request->request->get('checkAssignType') : 1,
$request->request->has('prReference') ? $request->request->get('prReference') : '',
0,
'_UNSET_',
'_UNSET_',
0,
'',
'',
isset($currencies[0]) ? $currencies[0] : 0,
1,
isset($currencyMultiplyRates[0]) ? $currencyMultiplyRates[0] : 1
);
$file_path_list = [];
if ($TransID != 0)
if (!empty($request->files)) {
MiscActions::RemoveFilesForEntityDoc($em_goc, 'AccTransactions', $TransID);
$storePath = 'uploads/Voucher/';
$path = "";
$file_path = "";
$session = $request->getSession();
MiscActions::RemoveExpiredFiles($em_goc);
foreach ($request->files as $uploadedFileGG) {
// if($uploadedFile->getImage())
// var_dump($uploadedFile->getFile());
// var_dump($uploadedFile);
$tempD = $uploadedFileGG;
if (!is_array($uploadedFileGG)) {
$uploadedFileGG = array();
$uploadedFileGG[] = $tempD;
}
foreach ($uploadedFileGG as $uploadedFile) {
if ($uploadedFile != null) {
$extension = $uploadedFile->guessExtension();
$size = $uploadedFile->getSize();
$fileName = 'TRANS_' . $TransID . '_' . (md5(uniqid())) . '.' . $uploadedFile->guessExtension();
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath;
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
if (file_exists($upl_dir . '' . $path)) {
chmod($upl_dir . '' . $path, 0755);
unlink($upl_dir . '' . $path);
}
$file = $uploadedFile->move($upl_dir, $path);
$expireNever = 1;
$expireTs = 0;
$EntityFile = new EntityFile();
$EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath . $path);
$EntityFile->setName($path);
$EntityFile->setMarker('_GEN_');
$EntityFile->setExtension($extension);
$EntityFile->setExpireTs($expireTs);
$EntityFile->setSize($size);
$EntityFile->setRelativePath($storePath . $path);
$EntityFile->setEntityName('AccTransactions');
$EntityFile->setEntityBundle('ApplicationBundle');
$EntityFile->setEntityId($TransID);
$EntityFile->setEntityIdField('transactionId');
$EntityFile->setModifyFieldSetter('setFiles');
$EntityFile->setDocIdForApplicant(0);
$EntityFile->setUserId($session->get(UserConstants::USER_ID, 0));
$EntityFile->setAppId($session->get(UserConstants::USER_APP_ID, 0));
$EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID, 0));
$EntityFile->setUserType($session->get(UserConstants::USER_TYPE, 0));
$em_goc->persist($EntityFile);
$em_goc->flush();
$EntityFileId = $EntityFile->getId();
}
if ($path != "")
$file_path_list[] = ($storePath . $path);
}
}
$g_path = $this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath . $path;
$v = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
'transactionId' => $TransID,
));
if ($v) {
$v->setFiles(implode(',', $file_path_list));
$em->flush();
} else {
}
}
$check_here = [];
$id_list_for_check = [];
$details_ids = [];
for ($i = 0; $i < count($ledgerHeads); $i++) {
if (!empty($drAmount[$i]) && $drAmount[$i] != 0) {
$id_list_for_check[$ledgerHeads[$i]] = $ledgerHeads[$i];
Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('date'),
$TransID,
Generic::CurrToInt($drAmount[$i]),
$ledgerHeads[$i],
$notes[$i],
AccountsConstant::DEBIT,
isset($costCenters[$i]) ? $costCenters[$i] : 0,
[],
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
0,
0,
'_UNSET_',
isset($currencies[$i]) ? $currencies[$i] : 0,
1,
isset($currencyMultiplyRates[$i]) ? $currencyMultiplyRates[$i] : 1
);
}
if (!empty($crAmount[$i]) && $crAmount[$i] != 0) {
Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('date'),
$TransID,
Generic::CurrToInt($crAmount[$i]),
$ledgerHeads[$i],
$notes[$i],
AccountsConstant::CREDIT,
isset($costCenters[$i]) ? $costCenters[$i] : 0,
[],
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
0,
0,
'_UNSET_',
isset($currencies[$i]) ? $currencies[$i] : 0,
1,
isset($currencyMultiplyRates[$i]) ? $currencyMultiplyRates[$i] : 1
);
}
}
if ($request->request->has('check_id')) {
$check_assign_type = $request->request->get('checkAssignType');
foreach ($request->request->get('check_id') as $k => $value) {
$check_here = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccCheck')
->findOneBy(
array(
'CheckId' => $value
)
);
if ($check_assign_type == 1) {
$ind_head_id = json_decode($request->request->get('check_received_id')[$k], true)[0];
$check_here->setRecAccountsHeadId($id_list_for_check[$ind_head_id]);
$check_here->setRecAccountsHeadIdList(json_encode([$id_list_for_check[$ind_head_id]]));
}
if ($check_assign_type == 2) {
$ind_head_id_list = json_decode($request->request->get('check_received_id')[$k], true);
$new_id_list = [];
foreach ($ind_head_id_list as $ind_head_id) {
$new_id_list[] = $id_list_for_check[$ind_head_id];
}
$check_here->setRecAccountsHeadId(null);
$check_here->setRecAccountsHeadIdList(json_encode($new_id_list));
}
$check_here->setCheckNarration($request->request->get('check_narration')[$k]);
$check_here->setCheckAmount($request->request->get('check_assigned_amount')[$k]);
$check_here->setCheckDate(new \DateTime($request->request->get('checkDate')[$k]));
$check_here->setTransactionDate(new \DateTime($request->request->get('date')));
// $check_here->setCheckDate(new \DateTime($request->request->get('date')));
$check_here->setAssigned(1);
$check_here->setVoucherId($TransID);
}
}
//approval system
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
// Accounts::UpdatePurchasePayments($em,$pi_list,$po_list,$details_ids, $request->request->get('date'));
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AccTransactions']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
$TransID,
$loginId,
4 //contra voucher
);
System::createEditSignatureHash(
$em,
array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
$TransID,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$url = $this->generateUrl(
'view_voucher'
);
$trans_here = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccTransactions')
->findOneBy(
array(
'transactionId' => $TransID
)
);
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),
"Contra Voucher : " . $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
'pos',
System::getPositionIdsByDepartment($em, GeneralConstant::ACCOUNTS_DEPARTMENT),
'success',
$url . "/" . $TransID,
"Contra Voucher"
);
if ($request->request->has('returnJson')) {
$doc = $trans_here;
return new JsonResponse(array(
'success' => true,
'documentHash' => $trans_here->getDocumentHash(),
'documentId' => $TransID,
'documentIdPadded' => str_pad($TransID, 8, '0', STR_PAD_LEFT),
'documentDate' => $trans_here->getTransactionDate()->format('Y-m-d'),
'documentAmount' => $trans_here->getTransactionAmount(),
'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
'viewUrl' => $url . "/" . $TransID,
'docPrintMainUrl' => $this->generateUrl('print_voucher'),
));
} else {
$this->addFlash(
'success',
'New Document Created'
);
return $this->redirect($url . "/" . $TransID);
}
}
}
$extVoucherData = [];
$extVoucherDetailsData = [];
if ($voucherId == 0) {
} else {
$extTrans = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(
array(
'transactionId' => $voucherId, ///material
)
);
//now if its not editable, redirect to view
if ($extTrans) {
if ($extTrans->getEditFlag() != 1) {
$url = $this->generateUrl(
'view_voucher'
);
return $this->redirect($url . "/" . $voucherId);
} else {
$extVoucherData = $extTrans;
$extVoucherDetailsData = Accounts::GetVoucherDataForEdit($em, $voucherId);
}
} else {
}
}
return $this->render(
'@Accounts/pages/input_forms/contra_voucher.html.twig',
array(
'page_title' => 'Create Contra Voucher',
'test' => $details_ids,
'extVoucherData' => $extVoucherData,
'extVoucherDetailsData' => $extVoucherDetailsData,
'supplier_list' => Accounts::SupplierListForPv($this->getDoctrine()->getManager()),
'supplier_list_by_ac_head' => Accounts::SupplierListByAcHead($this->getDoctrine()->getManager()),
'supplier_list_by_advance_head' => Accounts::SupplierListByAdvanceHead($this->getDoctrine()->getManager())
)
);
}
public function CreatePaymentVoucher(Request $request, $id = 0)
{
$details_ids = [];
$voucherId = $id;
$em = $this->getDoctrine()->getManager();
$FundRequisitionDetails = $em->getRepository(FundRequisition::class)->findAll();
$prePopulateData = [];
$skipInvoiceBalancing = $request->get('skipInvoiceBalancing', 0);
if ($request->request->get('payslip_ids', '') != '') {
$payslip_ids_array = explode(',', $request->request->get('payslip_ids', ''));
$payslips = $em->getRepository('ApplicationBundle\\Entity\\Payslip')->findBy(
array(
'payslipId' => $payslip_ids_array, ///material
)
);
foreach ($payslips as $payslip) {
$employee = $em->getRepository('ApplicationBundle\\Entity\\Employee')->findOneBy(array(
'employeeId' => $payslip->getSysId())
);
$dtHead = 0;
if ($employee)
$dtHead = $employee->getAccountsHeadId();
if ($dtHead != '' && $dtHead != 0 && $dtHead != null)
$prePopulateData[] = array(
'accountsHeadId' => $dtHead,
'position' => 'dr',
'payslipId' => $payslip->getPayslipId(),
'payslipPaymentType' => $request->request->get('disburse_type', 'bank'),
'amount' => $request->request->get('disburse_type', 'bank') == 'bank' ? $payslip->getBankTransfer() : $payslip->getHandCash(),
'note' => $employee->getName(),
);
}
} else if ($request->isMethod('POST')) {
// Generic::debugMessage($_POST);
$em = $this->getDoctrine()->getManager();
MiscActions::RemoveExpiredDocs($em);
$entity_id = array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
$dochash = $request->request->get('voucherNumber'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash,
$id
)) {
if ($request->request->has('returnJson')) {
return new JsonResponse(array(
'success' => false,
'documentHash' => 0,
'documentId' => 0,
));
} else
$this->addFlash(
'error',
'Sorry Could not insert Data.'
);
} else {
$funcname = 'AccTransactions';
$doc_id = $voucherId;
DeleteDocument::$funcname($em, $doc_id, 0);
$ledgerHeads = $request->request->get('ledgerHeads');
$notes = $request->request->get('trNote');
$costCenters = $request->request->get('costCenters');
$drAmount = $request->request->get('drAmount');
$crAmount = $request->request->get('crAmount');
$em = $this->getDoctrine()->getManager();
$pi_list = [];
$po_list = [];
$ei_list = [];
//1stly lets set the invoices po etc before we save the transaction normally
if ($request->request->has('ei_id'))
$ei_list = array(
'id' => $request->request->get('ei_id'),
'aa' => $request->request->get('ei_aa'),
'ei_head_id' => $request->request->get('ei_head_id')
);
if ($request->request->has('pi_id'))
$pi_list = array(
'id' => $request->request->get('pi_id'),
'aa' => $request->request->get('pi_aa')
);
if ($request->request->has('po_id'))
$po_list = array(
'id' => $request->request->get('po_id'),
'aa' => $request->request->get('po_aa')
);
$check_allowed = 0;
$provisional = 0;
if ($request->request->has('check_allowed'))
$check_allowed = 1;
if ($request->request->has('provisional'))
$provisional = 1;
$em_goc = $this->getDoctrine()->getManager('company_group');
$post_data = $request->request;
$TransID = Accounts::CreateNewTransaction(
$voucherId,
$this->getDoctrine()->getManager(),
$request->request->get('date'),
array_sum($request->request->get('drAmount')),
AccountsConstant::VOUCHER_PAYMENT,
$request->request->get('description'),
(empty($request->request->get('voucherNumber')) ? Generic::simpleRandString() : $request->request->get('voucherNumber')),
$request->request->get('type_hash'),
$request->request->get('prefix_hash'),
$request->request->get('assoc_hash'),
$request->request->get('number_hash'),
$check_allowed,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request),
'',
$provisional,
0,
$request->request->has('checkAssignType') ? $request->request->get('checkAssignType') : 1,
$request->request->has('prReference') ? $request->request->get('prReference') : '',
0,
'_UNSET_',
'_UNSET_',
0,
'',
'',
$request->request->get('currency', [''])[0]
);
$check_here = [];
$id_list_for_check = [];
$file_path_list = [];
if ($TransID != 0)
if (!empty($request->files)) {
MiscActions::RemoveFilesForEntityDoc($em_goc, 'AccTransactions', $TransID);
$storePath = 'uploads/Voucher/';
$path = "";
$file_path = "";
$session = $request->getSession();
MiscActions::RemoveExpiredFiles($em_goc);
foreach ($request->files as $uploadedFileGG) {
// if($uploadedFile->getImage())
// var_dump($uploadedFile->getFile());
// var_dump($uploadedFile);
$tempD = $uploadedFileGG;
if (!is_array($uploadedFileGG)) {
$uploadedFileGG = array();
$uploadedFileGG[] = $tempD;
}
foreach ($uploadedFileGG as $uploadedFile) {
if ($uploadedFile != null) {
$extension = $uploadedFile->guessExtension();
$size = $uploadedFile->getSize();
$fileName = 'TRANS_' . $TransID . '_' . (md5(uniqid())) . '.' . $uploadedFile->guessExtension();
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath;
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
if (file_exists($upl_dir . '' . $path)) {
chmod($upl_dir . '' . $path, 0755);
unlink($upl_dir . '' . $path);
}
$file = $uploadedFile->move($upl_dir, $path);
$expireNever = 1;
$expireTs = 0;
$EntityFile = new EntityFile();
$EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath . $path);
$EntityFile->setMarker('_GEN_');
$EntityFile->setName($path);
$EntityFile->setExtension($extension);
$EntityFile->setExpireTs($expireTs);
$EntityFile->setSize($size);
$EntityFile->setRelativePath($storePath . $path);
$EntityFile->setEntityName(GeneralConstant::$Entity_list[$entity_id]);
$EntityFile->setEntityBundle('ApplicationBundle');
$EntityFile->setEntityId($TransID);
$EntityFile->setEntityIdField(GeneralConstant::$Entity_id_field_list[$entity_id]);
$EntityFile->setModifyFieldSetter('setFiles');
$EntityFile->setDocIdForApplicant(0);
$EntityFile->setUserId($session->get(UserConstants::USER_ID, 0));
$EntityFile->setAppId($session->get(UserConstants::USER_APP_ID, 0));
$EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID, 0));
$EntityFile->setUserType($session->get(UserConstants::USER_TYPE, 0));
$em_goc->persist($EntityFile);
$em_goc->flush();
$EntityFileId = $EntityFile->getId();
}
if ($path != "")
$file_path_list[] = ($storePath . $path);
}
}
$g_path = $this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath . $path;
$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(
GeneralConstant::$Entity_id_field_list[$entity_id] => $TransID,
));
if ($v) {
$v->setFiles(implode(',', $file_path_list));
$em->flush();
} else {
}
}
$details_ids = [];
for ($i = 0; $i < count($ledgerHeads); $i++) {
if (!empty($drAmount[$i]) && $drAmount[$i] != 0) {
$id_list_for_check[$ledgerHeads[$i]] = $ledgerHeads[$i]; //initially same all
//now lets see if any supplier exists and if yes , sprlit the value in advance and normal
$supplier_list = Accounts::SupplierListThreeTypes($this->getDoctrine()->getManager());
$supplier_head_id_list = [];
$s_b_ac_h = $supplier_list[1];
$s_b_advance_h = $supplier_list[2];
// $s_list=self::SupplierListForPv();
$head_index_calibrate = [];
$supplier_by_id = '';
if (array_key_exists($ledgerHeads[$i], $s_b_ac_h)) {
$supplier_by_id = $s_b_ac_h[$ledgerHeads[$i]];
}
if (array_key_exists($ledgerHeads[$i], $s_b_advance_h)) {
$supplier_by_id = $s_b_advance_h[$ledgerHeads[$i]];
}
if ($supplier_by_id != '') {
$gt = 0;
//use normal transaction
$tot = 0;
if ($request->request->has('pi_id') || $request->request->has('ei_id')) {
if ($request->request->has('pi_id'))
foreach ($request->request->get('pi_id') as $k => $v) {
if ($request->request->get('pi_head_id')[$k] == $ledgerHeads[$i])
$tot += $request->request->get('pi_aa')[$k];
}
if ($request->request->has('ei_id'))
foreach ($request->request->get('ei_id') as $k => $v) {
if ($request->request->get('ei_head_id')[$k] == $ledgerHeads[$i])
$tot += $request->request->get('ei_aa')[$k];
}
if ($tot > 0) {
$id_list_for_check[$ledgerHeads[$i]] = $supplier_by_id['supplier_head_id'];
$details_ids[$supplier_by_id['supplier_head_id']] = Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('date'),
$TransID,
Generic::CurrToInt($tot),
$supplier_by_id['supplier_head_id'],
$notes[$i],
AccountsConstant::DEBIT,
isset($costCenters[$i]) ? $costCenters[$i] : 0,
array($pi_list, $po_list, $ei_list),
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$provisional,
0,
'_UNSET_',
$request->request->get('currency')[$i],
1,
$request->request->get('currencyMultiplyRate')[$i],
isset($request->request->get('payslipId', [])[$i]) ? $request->request->get('payslipId', [])[$i] : 0,
isset($request->request->get('payslipPaymentType', [])[$i]) ? $request->request->get('payslipPaymentType', [])[$i] : 0
);
}
}
$gt = $gt + $tot;
//now advance transaction
$tot = 0;
if ($request->request->has('po_id')) {
foreach ($request->request->get('po_id') as $k => $v) {
if ($request->request->get('po_head_id')[$k] == $ledgerHeads[$i])
$tot += $request->request->get('po_aa')[$k];
}
if ($tot > 0) {
$id_list_for_check[$ledgerHeads[$i]] = $supplier_by_id['supplier_advance_head_id'];
$details_ids[$supplier_by_id['supplier_advance_head_id']] = Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('date'),
$TransID,
Generic::CurrToInt($tot),
$supplier_by_id['supplier_advance_head_id'],
$notes[$i],
AccountsConstant::DEBIT,
isset($costCenters[$i]) ? $costCenters[$i] : 0,
array($pi_list, $po_list, $ei_list),
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$provisional,
0,
'_UNSET_',
$request->request->get('currency')[$i],
1,
$request->request->get('currencyMultiplyRate')[$i],
isset($request->request->get('payslipId', [])[$i]) ? $request->request->get('payslipId', [])[$i] : 0,
isset($request->request->get('payslipPaymentType', [])[$i]) ? $request->request->get('payslipPaymentType', [])[$i] : 0
);
}
}
$gt = $gt + $tot;
//now assigning rest as normal trans
Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('date'),
$TransID,
Generic::CurrToInt($drAmount[$i] - $gt),
$ledgerHeads[$i],
$notes[$i],
AccountsConstant::DEBIT,
isset($costCenters[$i]) ? $costCenters[$i] : 0,
array($pi_list, $po_list, $ei_list),
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$provisional,
0,
'_UNSET_',
$request->request->get('currency')[$i],
1,
$request->request->get('currencyMultiplyRate')[$i],
isset($request->request->get('payslipId', [])[$i]) ? $request->request->get('payslipId', [])[$i] : 0,
isset($request->request->get('payslipPaymentType', [])[$i]) ? $request->request->get('payslipPaymentType', [])[$i] : 0
);
} else
$details_ids[$ledgerHeads[$i]] = Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('date'),
$TransID,
Generic::CurrToInt($drAmount[$i]),
$ledgerHeads[$i],
$notes[$i],
AccountsConstant::DEBIT,
isset($costCenters[$i]) ? $costCenters[$i] : 0,
array($pi_list, $po_list, $ei_list),
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$provisional,
0,
'_UNSET_',
$request->request->get('currency')[$i],
1,
$request->request->get('currencyMultiplyRate')[$i],
isset($request->request->get('payslipId', [])[$i]) ? $request->request->get('payslipId', [])[$i] : 0,
isset($request->request->get('payslipPaymentType', [])[$i]) ? $request->request->get('payslipPaymentType', [])[$i] : 0
);
}
if (!empty($crAmount[$i]) && $crAmount[$i] != 0) {
$details_ids[$ledgerHeads[$i]] = Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('date'),
$TransID,
Generic::CurrToInt($crAmount[$i]),
$ledgerHeads[$i],
$notes[$i],
AccountsConstant::CREDIT,
isset($costCenters[$i]) ? $costCenters[$i] : 0,
array($pi_list, $po_list, $ei_list),
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$provisional,
0,
'_UNSET_',
$request->request->get('currency')[$i],
1,
$request->request->get('currencyMultiplyRate')[$i],
isset($request->request->get('payslipId', [])[$i]) ? $request->request->get('payslipId', [])[$i] : 0,
isset($request->request->get('payslipPaymentType', [])[$i]) ? $request->request->get('payslipPaymentType', [])[$i] : 0
);
}
}
if ($request->request->has('check_id')) {
$check_assign_type = $request->request->has('checkAssignType') ? $request->request->get('checkAssignType') : 1;
foreach ($request->request->get('check_id') as $k => $value) {
$check_here = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccCheck')
->findOneBy(
array(
'CheckId' => $value
)
);
if ($check_assign_type == 1) {
$ind_head_id = json_decode($request->request->get('check_received_id')[$k], true)[0];
$check_here->setRecAccountsHeadId($id_list_for_check[$ind_head_id]);
$check_here->setRecAccountsHeadIdList(json_encode([$id_list_for_check[$ind_head_id]]));
}
if ($check_assign_type == 2) {
$ind_head_id_list = json_decode($request->request->get('check_received_id')[$k], true);
$new_id_list = [];
foreach ($ind_head_id_list as $ind_head_id) {
$new_id_list[] = $id_list_for_check[$ind_head_id];
}
$check_here->setRecAccountsHeadId(null);
$check_here->setRecAccountsHeadIdList(json_encode($new_id_list));
}
$check_here->setCheckNarration($request->request->get('check_narration')[$k]);
$check_here->setCheckAmount($request->request->get('check_assigned_amount')[$k]);
$check_here->setCheckDate(new \DateTime($request->request->get('checkDate')[$k]));
$check_here->setTransactionDate(new \DateTime($request->request->get('date')));
// $check_here->setCheckDate(new \DateTime($request->request->get('date')));
$check_here->setAssigned(1);
$check_here->setVoucherId($TransID);
}
}
//approval system
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
Accounts::UpdatePurchasePayments($em, $pi_list, $po_list, $details_ids, $request->request->get('date'));
Accounts::UpdateExpensePayments($em, $ei_list, $details_ids, $request->request->get('date'));
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AccTransactions']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
$TransID,
$loginId,
5 //payment voucher
);
System::createEditSignatureHash(
$em,
array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
$TransID,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$url = $this->generateUrl(
'view_voucher'
);
$trans_here = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccTransactions')
->findOneBy(
array(
'transactionId' => $TransID
)
);
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),
"Debit Voucher : " . $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
'pos',
System::getPositionIdsByDepartment($em, GeneralConstant::ACCOUNTS_DEPARTMENT),
'success',
$url . "/" . $TransID,
"Debit Voucher"
);
if ($request->request->has('returnJson')) {
$doc = $trans_here;
return new JsonResponse(array(
'success' => true,
'documentHash' => $trans_here->getDocumentHash(),
'documentId' => $TransID,
'documentIdPadded' => str_pad($TransID, 8, '0', STR_PAD_LEFT),
'documentDate' => $trans_here->getTransactionDate()->format('Y-m-d'),
'documentAmount' => $trans_here->getTransactionAmount(),
'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
'viewUrl' => $url . "/" . $TransID,
'docPrintMainUrl' => $this->generateUrl('print_voucher'),
));
} else {
$this->addFlash(
'success',
'New Document Created'
);
return $this->redirect($url . "/" . $TransID);
}
}
}
//for edits
$extVoucherData = [];
$extVoucherDetailsData = [];
if ($voucherId == 0) {
} else {
$extTrans = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(
array(
'transactionId' => $voucherId, ///material
)
);
//now if its not editable, redirect to view
if ($extTrans) {
if ($extTrans->getEditFlag() != 1) {
$url = $this->generateUrl(
'view_voucher'
);
return $this->redirect($url . "/" . $voucherId);
} else {
$extVoucherData = $extTrans;
$extVoucherDetailsData = Accounts::GetVoucherDataForEdit($em, $voucherId);
}
} else {
}
}
return $this->render(
'@Accounts/pages/input_forms/payment_voucher.html.twig',
array(
'page_title' => 'Create Payment Voucher',
'test' => $details_ids,
'prePopulateData' => $prePopulateData,
'skipInvoiceBalancing' => $skipInvoiceBalancing,
'extVoucherData' => $extVoucherData,
'extVoucherDetailsData' => $extVoucherDetailsData,
'supplier_list' => Accounts::SupplierListForPv($this->getDoctrine()->getManager()),
'supplier_list_by_ac_head' => Accounts::SupplierListByAcHead($this->getDoctrine()->getManager()),
'supplier_list_by_advance_head' => Accounts::SupplierListByAdvanceHead($this->getDoctrine()->getManager()),
'fundRequisitionDetails' => $FundRequisitionDetails
)
);
}
public function CreateReceiptVoucher(Request $request, $id = 0)
{
$details_ids = [];
$voucherId = $id;
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
// Generic::debugMessage($_POST);
$em = $this->getDoctrine()->getManager();
MiscActions::RemoveExpiredDocs($em);
$entity_id = array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
$dochash = $request->request->get('voucherNumber'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash,
$id
)) {
if ($request->request->has('returnJson')) {
return new JsonResponse(array(
'success' => false,
'documentHash' => 0,
'documentId' => 0,
));
} else
$this->addFlash(
'error',
'Sorry Could not insert Data.'
);
} else {
$funcname = 'AccTransactions';
$doc_id = $voucherId;
DeleteDocument::$funcname($em, $doc_id, 0);
$ledgerHeads = $request->request->get('ledgerHeads');
$notes = $request->request->get('trNote');
$costCenters = $request->request->get('costCenters');
$drAmount = $request->request->get('drAmount');
$crAmount = $request->request->get('crAmount');
$em = $this->getDoctrine()->getManager();
$pi_list = [];
$po_list = [];
$ei_list = [];
//1stly lets set the invoices po etc before we save the transaction normally
if ($request->request->has('ei_id'))
$ei_list = array(
'id' => $request->request->get('ei_id'),
'aa' => $request->request->get('ei_aa'),
'ei_head_id' => $request->request->get('ei_head_id')
);
if ($request->request->has('pi_id'))
$pi_list = array(
'id' => $request->request->get('pi_id'),
'aa' => $request->request->get('pi_aa')
);
if ($request->request->has('po_id'))
$po_list = array(
'id' => $request->request->get('po_id'),
'aa' => $request->request->get('po_aa')
);
$check_allowed = 0;
$provisional = 0;
$pr_method = 0;
$check_number = '';
if ($request->request->has('check_allowed'))
$check_allowed = 1;
if ($request->request->has('provisional'))
$provisional = 1;
// if($request->request->has('provisional'))
$pr_method = $request->request->get('receipt_method');
// $check_number=$request->request->get('receipt_method');
$em_goc = $this->getDoctrine()->getManager('company_group');
$post_data = $request->request;
$TransID = Accounts::CreateNewTransaction(
$voucherId,
$this->getDoctrine()->getManager(),
$request->request->get('date'),
array_sum($request->request->get('drAmount')),
AccountsConstant::VOUCHER_RECEIPT,
$request->request->get('description'),
(empty($request->request->get('voucherNumber')) ? Generic::simpleRandString() : $request->request->get('voucherNumber')),
$request->request->get('type_hash'),
$request->request->get('prefix_hash'),
$request->request->get('assoc_hash'),
$request->request->get('number_hash'),
$check_allowed,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request),
'',
$provisional,
0,
$pr_method
);
$file_path_list = [];
if ($TransID != 0)
if (!empty($request->files)) {
MiscActions::RemoveFilesForEntityDoc($em_goc, 'AccTransactions', $TransID);
$storePath = 'uploads/Voucher/';
$path = "";
$file_path = "";
$session = $request->getSession();
MiscActions::RemoveExpiredFiles($em_goc);
foreach ($request->files as $uploadedFileGG) {
// if($uploadedFile->getImage())
// var_dump($uploadedFile->getFile());
// var_dump($uploadedFile);
$tempD = $uploadedFileGG;
if (!is_array($uploadedFileGG)) {
$uploadedFileGG = array();
$uploadedFileGG[] = $tempD;
}
foreach ($uploadedFileGG as $uploadedFile) {
if ($uploadedFile != null) {
$extension = $uploadedFile->guessExtension();
$size = $uploadedFile->getSize();
$fileName = 'TRANS_' . $TransID . '_' . (md5(uniqid())) . '.' . $uploadedFile->guessExtension();
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath;
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
if (file_exists($upl_dir . '' . $path)) {
chmod($upl_dir . '' . $path, 0755);
unlink($upl_dir . '' . $path);
}
$file = $uploadedFile->move($upl_dir, $path);
$expireNever = 1;
$expireTs = 0;
$EntityFile = new EntityFile();
$EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath . $path);
$EntityFile->setMarker('_GEN_');
$EntityFile->setName($path);
$EntityFile->setExtension($extension);
$EntityFile->setExpireTs($expireTs);
$EntityFile->setSize($size);
$EntityFile->setRelativePath($storePath . $path);
$EntityFile->setEntityName('AccTransactions');
$EntityFile->setEntityBundle('ApplicationBundle');
$EntityFile->setEntityId($TransID);
$EntityFile->setEntityIdField('transactionId');
$EntityFile->setModifyFieldSetter('setFiles');
$EntityFile->setDocIdForApplicant(0);
$EntityFile->setUserId($session->get(UserConstants::USER_ID, 0));
$EntityFile->setAppId($session->get(UserConstants::USER_APP_ID, 0));
$EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID, 0));
$EntityFile->setUserType($session->get(UserConstants::USER_TYPE, 0));
$em_goc->persist($EntityFile);
$em_goc->flush();
$EntityFileId = $EntityFile->getId();
}
if ($path != "")
$file_path_list[] = ($storePath . $path);
}
}
$g_path = $this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath . $path;
$v = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(array(
'transactionId' => $TransID,
));
if ($v) {
$v->setFiles(implode(',', $file_path_list));
$em->flush();
} else {
}
}
$check_here = [];
$id_list_for_check = [];
$debit_head = '';
$credit_head = '';
$debit_amount = '';
$details_ids = [];
for ($i = 0; $i < count($ledgerHeads); $i++) {
// if(!empty($drAmount[$i]) && $drAmount[$i]!=0){
if (!empty($crAmount[$i]) && $crAmount[$i] != 0) {
$id_list_for_check[$ledgerHeads[$i]] = $ledgerHeads[$i]; //initially same all
//now lets see if any supplier exists and if yes , sprlit the value in advance and normal
$supplier_list = Accounts::ClientListThreeTypes($this->getDoctrine()->getManager());
$supplier_head_id_list = [];
$s_b_ac_h = $supplier_list[1];
$s_b_advance_h = $supplier_list[2];
// $s_list=self::SupplierListForPv();
$head_index_calibrate = [];
$supplier_by_id = '';
if (array_key_exists($ledgerHeads[$i], $s_b_ac_h)) {
$supplier_by_id = $s_b_ac_h[$ledgerHeads[$i]];
}
if (array_key_exists($ledgerHeads[$i], $s_b_advance_h)) {
$supplier_by_id = $s_b_advance_h[$ledgerHeads[$i]];
}
if ($supplier_by_id != '') {
$credit_head = $supplier_by_id['client_head_id'];
$gt = 0;
//use normal transaction
$tot = 0;
if ($request->request->has('pi_id')) {
foreach ($request->request->get('pi_id') as $k => $v) {
if ($request->request->get('pi_head_id')[$k] == $ledgerHeads[$i])
$tot += $request->request->get('pi_aa')[$k];
}
if ($tot > 0) {
$id_list_for_check[$ledgerHeads[$i]] = $supplier_by_id['client_head_id'];
$details_ids[$supplier_by_id['client_head_id']] = Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('date'),
$TransID,
Generic::CurrToInt($tot),
$supplier_by_id['client_head_id'],
$notes[$i],
AccountsConstant::CREDIT,
isset($costCenters[$i]) ? $costCenters[$i] : 0,
array($pi_list, $po_list, $ei_list),
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$provisional
);
}
}
$gt = $gt + $tot;
//now advance transaction
$tot = 0;
if ($request->request->has('po_id')) {
foreach ($request->request->get('po_id') as $k => $v) {
if ($request->request->get('po_head_id')[$k] == $ledgerHeads[$i])
$tot += $request->request->get('po_aa')[$k];
}
if ($tot > 0) {
$id_list_for_check[$ledgerHeads[$i]] = $supplier_by_id['client_advance_head_id'];
$details_ids[$supplier_by_id['client_advance_head_id']] = Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('date'),
$TransID,
Generic::CurrToInt($tot),
$supplier_by_id['client_advance_head_id'],
$notes[$i],
AccountsConstant::CREDIT,
isset($costCenters[$i]) ? $costCenters[$i] : 0,
array($pi_list, $po_list, $ei_list),
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$provisional
);
}
}
$gt = $gt + $tot;
Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('date'),
$TransID,
Generic::CurrToInt($crAmount[$i] - $gt),
$ledgerHeads[$i],
$notes[$i],
AccountsConstant::CREDIT,
isset($costCenters[$i]) ? $costCenters[$i] : 0,
array($pi_list, $po_list, $ei_list),
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$provisional,
0,
'_UNSET_',
$request->request->get('currency')[$i],
1,
$request->request->get('currencyMultiplyRate')[$i]
);
} else {
$credit_head = $ledgerHeads[$i];
$details_ids[$ledgerHeads[$i]] = Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('date'),
$TransID,
Generic::CurrToInt($crAmount[$i]),
$ledgerHeads[$i],
$notes[$i],
AccountsConstant::CREDIT,
isset($costCenters[$i]) ? $costCenters[$i] : 0,
array($pi_list, $po_list, $ei_list),
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$provisional,
0,
'_UNSET_',
$request->request->get('currency')[$i],
1,
$request->request->get('currencyMultiplyRate')[$i]
);
}
}
// if(!empty($crAmount[$i]) && $crAmount[$i]!=0){
if (!empty($drAmount[$i]) && $drAmount[$i] != 0) {
$debit_head = $ledgerHeads[$i];
$debit_amount = Generic::CurrToInt($drAmount[$i]);
$details_ids[$ledgerHeads[$i]] = Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('date'),
$TransID,
Generic::CurrToInt($drAmount[$i]),
$ledgerHeads[$i],
$notes[$i],
AccountsConstant::DEBIT,
isset($costCenters[$i]) ? $costCenters[$i] : 0,
array($pi_list, $po_list, $ei_list),
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$provisional,
0,
'_UNSET_',
$request->request->get('currency')[$i],
1,
$request->request->get('currencyMultiplyRate')[$i]
);
}
}
if ($pr_method == 2) {
// foreach($request->request->get('check_id') as $k=>$value)
// {
$check_here = new AccCheck();
$check_here->setRecAccountsHeadId($debit_head);
$check_here->setRecAccountsHeadIdList(json_encode([$debit_head]));
$check_here->setAccountsHeadId($credit_head);
// $check_here->setCheckNarration($request->request->get('check_narration')[$k]);
$check_here->setCheckAmount($debit_amount);
$check_here->setCheckDate(new \DateTime($request->request->get('receiptCheckDate')));
$check_here->setTransactionDate(new \DateTime($request->request->get('date')));
// $check_here->setCheckDate(new \DateTime($request->request->get('date')));
$check_here->setAssigned(1);
$check_here->setActive(1);
$check_here->setDetails('');
$check_here->setCheckNumber($request->request->get('receiptCheckNo'));
$check_here->setStatus(3);
$check_here->setType(2); //receipt check
$check_here->setVoucherId($TransID);
// }
$em->persist($check_here);
$em->flush();
}
//approval system
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
Accounts::UpdateSalesPayments($em, $pi_list, $po_list, $details_ids, $request->request->get('date'));
// Accounts::UpdateExpensePayments($em,$ei_list,$details_ids, $request->request->get('date'));
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AccTransactions']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
$TransID,
$loginId,
AccountsConstant::VOUCHER_RECEIPT //Receipt voucher
);
System::createEditSignatureHash(
$em,
array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
$TransID,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$url = $this->generateUrl(
'view_voucher'
);
$trans_here = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccTransactions')
->findOneBy(
array(
'transactionId' => $TransID
)
);
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),
"Receipt Voucher : " . $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
'pos',
System::getPositionIdsByDepartment($em, GeneralConstant::ACCOUNTS_DEPARTMENT),
'success',
$url . "/" . $TransID,
"Receipt Voucher"
);
if ($request->request->has('returnJson')) {
$doc = $trans_here;
return new JsonResponse(array(
'success' => true,
'documentHash' => $trans_here->getDocumentHash(),
'documentId' => $TransID,
'documentIdPadded' => str_pad($TransID, 8, '0', STR_PAD_LEFT),
'documentDate' => $trans_here->getTransactionDate()->format('Y-m-d'),
'documentAmount' => $trans_here->getTransactionAmount(),
'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
'viewUrl' => $url . "/" . $TransID,
'docPrintMainUrl' => $this->generateUrl('print_voucher'),
));
} else {
$this->addFlash(
'success',
'New Document Created'
);
return $this->redirect($url . "/" . $TransID);
}
}
}
$extVoucherData = [];
$extVoucherDetailsData = [];
if ($voucherId == 0) {
} else {
$extTrans = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findOneBy(
array(
'transactionId' => $voucherId, ///material
)
);
//now if its not editable, redirect to view
if ($extTrans) {
if ($extTrans->getEditFlag() != 1) {
$url = $this->generateUrl(
'view_voucher'
);
return $this->redirect($url . "/" . $voucherId);
} else {
$extVoucherData = $extTrans;
$extVoucherDetailsData = Accounts::GetVoucherDataForEdit($em, $voucherId);
}
} else {
}
}
return $this->render(
'@Accounts/pages/input_forms/receipt_voucher.html.twig',
array(
'page_title' => 'Create Receipt Voucher',
'test' => $details_ids,
'extVoucherData' => $extVoucherData,
'extVoucherDetailsData' => $extVoucherDetailsData,
'client_list' => SalesOrderM::GetClientList($this->getDoctrine()->getManager()),
'client_list_by_ac_head' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
'client_list_by_advance_head' => SalesOrderM::GetClientListByAdvanceHead($this->getDoctrine()->getManager())
)
);
}
public function CheckFormat(Request $request, $id = 0)
{
$data = array(
'formatId' => '',
'name' => '',
'width' => 6,
'height' => 2,
'checkPayToLeft' => '130px',
'checkPayToTop' => '58px',
'checkAmountLeft' => '451px',
'checkAmountTop' => '88px',
'checkAiWLeft' => '131px',
'checkAiWTop' => '82px',
'checkDateLeft' => '487px',
'checkDatePartLeft' => '459px',
'checkDateD1Left' => '-49px',
'checkDateD2Left' => '-28px',
'checkDateM1Left' => '-10px',
'checkDateM2Left' => '10px',
'checkDateY1Left' => '27px',
'checkDateY2Left' => '47px',
'checkDateY3Left' => '64px',
'checkDateY4Left' => '85px',
'checkDateTop' => '34px',
'checkDatePartTop' => '31px',
'checkImage' => '',
'dateDividerDisabled' => 1,
);
if ($request->isMethod('POST')) {
$post = $request->request;
if ($request->request->get('formatId') != '') {
$query_here = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\CheckFormat')
->findOneBy(
array(
'formatId' => $request->request->get('formatId')
)
);
if (!empty($query_here))
$new = $query_here;
} else
$new = new CheckFormat();
$new->setName($request->request->get('name'));
$new->setWidth($request->request->get('width'));
$new->setHeight($request->request->get('height'));
$new->setCheckPayToLeft($request->request->get('checkPayToLeft'));
$new->setCheckPayToTop($request->request->get('checkPayToTop'));
$new->setCheckAmountLeft($request->request->get('checkAmountLeft'));
$new->setCheckAmountTop($request->request->get('checkAmountTop'));
$new->setCheckAiWLeft($request->request->get('checkAiWLeft'));
$new->setCheckAiWTop($request->request->get('checkAiWTop'));
$new->setCheckDateLeft($request->request->get('checkDateLeft'));
$new->setCheckDateTop($request->request->get('checkDateTop'));
$new->setCheckDatePartLeft($request->request->get('checkDatePartLeft'));
$new->setCheckDatePartTop($request->request->get('checkDatePartTop'));
$new->setCheckDateD1Left($request->request->get('checkDateD1Left'));
$new->setCheckDateD2Left($request->request->get('checkDateD2Left'));
$new->setCheckDateM1Left($request->request->get('checkDateM1Left'));
$new->setCheckDateM2Left($request->request->get('checkDateM2Left'));
$new->setCheckDateY1Left($request->request->get('checkDateY1Left'));
$new->setCheckDateY2Left($request->request->get('checkDateY2Left'));
$new->setCheckDateY3Left($request->request->get('checkDateY3Left'));
$new->setCheckDateY4Left($request->request->get('checkDateY4Left'));
$new->setDateDividerDisabled($request->request->has('dateDividerDisabled') ? 1 : 0);
$new->setCheckImage($request->request->get('checkImage'));
$em = $this->getDoctrine()->getManager();
$em->persist($new);
$em->flush();
}
if ($id != 0) {
$query_here = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\CheckFormat')
->findOneBy(
array(
'formatId' => $id
)
);
if ($query_here)
$data = $query_here;
} else if ($request->query->has('formatId')) {
$query_here = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\CheckFormat')
->findOneBy(
array(
'formatId' => $request->query->get('formatId')
)
);
if ($query_here)
$data = $query_here;
}
return $this->render(
'@Application/pages/accounts/settings/check_format.html.twig',
array(
'page_title' => 'Cheque Format',
'data' => $data,
'formatList' => $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\CheckFormat')
->findBy(
array( // 'formatId' => $request->query->get('formatId')
)
)
// 'incomeLedgerHeads'=>Accounts::getChildLedgerHeads($this->getDoctrine()->getManager(),AccountsConstant::INCOME)
)
);
}
public function PrintCheck(Request $request, $id)
{
$data = array(
'formatId' => '',
'name' => '',
'width' => 6,
'height' => 2,
'checkPayToLeft' => '130px',
'checkPayToTop' => '58px',
'checkAmountLeft' => '451px',
'checkAmountTop' => '88px',
'checkAiWLeft' => '131px',
'checkAiWTop' => '82px',
'checkDateLeft' => '487px',
'checkDatePartLeft' => '459px',
'checkDateD1Left' => '-49px',
'checkDateD2Left' => '-28px',
'checkDateM1Left' => '-10px',
'checkDateM2Left' => '10px',
'checkDateY1Left' => '27px',
'checkDateY2Left' => '47px',
'checkDateY3Left' => '64px',
'checkDateY4Left' => '85px',
'checkDateTop' => '34px',
'checkDatePartTop' => '31px',
'checkImage' => '',
'marginTopAdd' => '0',
'dateDividerDisabled' => 1
);
$print_ac_payee_tag = 0;
if ($request->query->has('print_ac_payee_tag'))
if ($request->query->get('print_ac_payee_tag') == 1)
$print_ac_payee_tag = $request->query->get('print_ac_payee_tag');
//first get check data
$check_query = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccCheck')
->findOneBy(
array(
'CheckId' => $id
)
);
//now get the format data
if (!empty($check_query))
$query_here = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\CheckFormat')
->findOneBy(
array(
'formatId' => $check_query->getFormatId()
)
);
if (!empty($query_here))
$data = $query_here;
$inv_parts = explode('.', number_format($check_query->getCheckAmount(), 2, '.', ''));
return $this->render(
'@Accounts/pages/print/print_check.html.twig',
array(
'page_title' => 'Print Check',
'red' => 0,
'data' => $data,
'print_ac_payee_tag' => $print_ac_payee_tag,
'check_data' => $check_query,
'amount_in_word_integer' => Accounts::ConvertNumberToWords($inv_parts[0]),
'amount_in_word_dec' => Accounts::ConvertNumberToWords((isset($inv_parts[1])) ? $inv_parts[1] * 1 : 0),
)
);
}
public function MarkCheckPrinted(Request $request, $id)
{
//first get check data
$check_query = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccCheck')
->findOneBy(
array(
'CheckId' => $id
)
);
$check_query->setPrinted(1);
$em = $this->getDoctrine()->getManager();
$em->flush();
return 1;
}
public function RemoveFile(Request $request)
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$EntityFileId = 0;
$relId = 0;
MiscActions::RemoveExpiredFiles($em_goc);
if ($request->isMethod('POST')) {
$post = $request->request;
$relId = $post->get('relId');
$afterRemoveConfig = $post->get('afterRemoveConfig', []);
if ($post->get('path', '') != '') {
MiscActions::RemoveFileByPath($em_goc, $post->get('path', ''), $afterRemoveConfig);
return new JsonResponse(array(
"success" => true,
"relId" => $relId,
));
} else if ($post->get('conditionOptions', []) != []) {
MiscActions::RemoveFileByCondition($em_goc, $post->get('conditionOptions', []));
return new JsonResponse(array(
"success" => true,
"relId" => $relId,
));
} else if ($post->get('fileId', 0) != 0) {
MiscActions::RemoveFileById($em_goc, $post->get('fileId', 0), $afterRemoveConfig);
return new JsonResponse(array(
"success" => true,
"relId" => $relId,
));
}
}
return new JsonResponse(array(
"success" => false,
"relId" => $relId,
));
}
public function FileUpload(Request $request)
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$EntityFileId = 0;
$file_path_list = [];
if ($request->isMethod('POST')) {
$post_data = $request->request;
if ($request->request->get('clearExistingFilesForThisDoc', 0) == 1) {
MiscActions::RemoveFilesForEntityDoc($em_goc, $request->request->get('entityName', ''), $request->request->get('entityId', 0));
}
if ($post_data->has('isBase64') || $post_data->has('imageBase64')) {
$imageBase64 = $post_data->get('imageBase64');
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $imageBase64));
$fileName = md5(uniqid()) . '.png';
if ($request->request->has('buddybee_profile_image_flag'))
$storePath = 'uploads/applicants/';
if ($request->request->has('central_profile_image_flag'))
$storePath = 'uploads/UserImage/';
if ($request->request->has('expense_invoice_attachment'))
$storePath = 'uploads/ExpenseInvoice/';
if ($request->request->has('voucher_attachment'))
$storePath = 'uploads/Voucher/';
if ($request->request->has('leave_attachment'))
$storePath = 'uploads/LeaveDoc/';
if ($request->request->has('sales_invoice_attachment'))
$storePath = 'uploads/SalesInvoice/';
if ($request->request->has('purchase_invoice_attachment'))
$storePath = 'uploads/PurchaseInvoice/';
if ($request->request->has('po_attachment'))
$storePath = 'uploads/PurchaseOrder/';
if ($request->request->has('so_attachment'))
$storePath = 'uploads/SalesOrder/';
if ($request->request->has('product_mrp_attachment'))
$storePath = 'uploads/PriceDoc/';
if ($request->request->has('pr_attachment'))
$storePath = 'uploads/PurchaseRequisition/';
if ($request->request->has('so_amendment_attachment'))
$storePath = 'uploads/SoAmendment/';
if ($request->request->has('fund_requisition_attachment'))
$storePath = 'uploads/FundRequisition/';
if ($request->request->has('delivery_order_attachment'))
$storePath = 'uploads/DeliveryOrder/';
if ($request->request->has('proforma_invoice_attachment'))
$storePath = 'uploads/ProformaInvoice/';
if ($request->request->has('insurance_pay_request_attachment'))
$storePath = 'uploads/InsurancePayRequest/';
if ($request->request->has('grn_attachment'))
$storePath = 'uploads/Grn/';
if ($request->request->has('service_challan_attachment'))
$storePath = 'uploads/ServiceChallan/';
if ($request->request->has('stock_requisition_attachment'))
$storePath = 'uploads/StockRequisition/';
if ($request->request->has('store_requisition_attachment'))
$storePath = 'uploads/StoreRequisition/';
if ($request->request->has('stock_transfer_attachment'))
$storePath = 'uploads/StockTransfer/';
if ($request->request->has('stock_received_note_attachment'))
$storePath = 'uploads/StockReceivedNote/';
if ($request->request->has('delivery_receipt_attachment'))
$storePath = 'uploads/DeliveryReceipt/';
if ($request->request->has('item_received_and_replacement_attachment'))
$storePath = 'uploads/ItemReceivedAndReplacement/';
if ($request->request->has('stock_consumption_note_attachment'))
$storePath = 'uploads/StockConsumptionNote/';
if ($request->request->has('general_attachment'))
$storePath = 'uploads/General/';
if ($request->request->has('product_datasheets_attachment'))
$storePath = 'uploads/Product/Datasheets/';
if ($request->request->has('sales_proposal_cover_attachment'))
$storePath = 'uploads/SalesProposal/';
$path = "";
$file_path = "";
$session = $request->getSession();
MiscActions::RemoveExpiredFiles($em_goc);
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath;
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
if (file_exists($upl_dir . '' . $path)) {
chmod($upl_dir . '' . $path, 0755);
unlink($upl_dir . '' . $path);
}
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ExpenseInvoice/' . $path;
file_put_contents($upl_dir, $data);
if ($path != "")
$file_path_list[] = ($storePath . $path);
$g_path = $this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath . $path;
} else {
$storePath = $request->request->get('storePath', 'uploads/FileUploads/');
if ($request->request->has('buddybee_profile_image_flag'))
$storePath = 'uploads/applicants/';
if ($request->request->has('central_profile_image_flag'))
$storePath = 'uploads/UserImage/';
if ($request->request->has('expense_invoice_attachment'))
$storePath = 'uploads/ExpenseInvoice/';
if ($request->request->has('voucher_attachment'))
$storePath = 'uploads/Voucher/';
if ($request->request->has('leave_attachment'))
$storePath = 'uploads/LeaveDoc/';
if ($request->request->has('sales_invoice_attachment'))
$storePath = 'uploads/SalesInvoice/';
if ($request->request->has('po_attachment'))
$storePath = 'uploads/PurchaseOrder/';
if ($request->request->has('so_attachment'))
$storePath = 'uploads/SalesOrder/';
if ($request->request->has('product_mrp_attachment'))
$storePath = 'uploads/PriceDoc/';
if ($request->request->has('pr_attachment'))
$storePath = 'uploads/PurchaseRequisition/';
if ($request->request->has('purchase_invoice_attachment'))
$storePath = 'uploads/PurchaseInvoice/';
if ($request->request->has('so_amendment_attachment'))
$storePath = 'uploads/SoAmendment/';
if ($request->request->has('fund_requisition_attachment'))
$storePath = 'uploads/FundRequisition/';
if ($request->request->has('delivery_order_attachment'))
$storePath = 'uploads/DeliveryOrder/';
if ($request->request->has('proforma_invoice_attachment'))
$storePath = 'uploads/ProformaInvoice/';
if ($request->request->has('insurance_pay_request_attachment'))
$storePath = 'uploads/InsurancePayRequest/';
if ($request->request->has('grn_attachment'))
$storePath = 'uploads/Grn/';
if ($request->request->has('service_challan_attachment'))
$storePath = 'uploads/ServiceChallan/';
if ($request->request->has('stock_requisition_attachment'))
$storePath = 'uploads/StockRequisition/';
if ($request->request->has('store_requisition_attachment'))
$storePath = 'uploads/StoreRequisition/';
if ($request->request->has('stock_transfer_attachment'))
$storePath = 'uploads/StockTransfer/';
if ($request->request->has('stock_received_note_attachment'))
$storePath = 'uploads/StockReceivedNote/';
if ($request->request->has('delivery_receipt_attachment'))
$storePath = 'uploads/DeliveryReceipt/';
if ($request->request->has('item_received_and_replacement_attachment'))
$storePath = 'uploads/ItemReceivedAndReplacement/';
if ($request->request->has('stock_consumption_note_attachment'))
$storePath = 'uploads/StockConsumptionNote/';
if ($request->request->has('general_attachment'))
$storePath = 'uploads/General/';
if ($request->request->has('product_datasheets_attachment'))
$storePath = 'uploads/Product/Datasheets/';
if ($request->request->has('sales_proposal_cover_attachment'))
$storePath = 'uploads/SalesProposal/';
$path = "";
$file_path = "";
$session = $request->getSession();
MiscActions::RemoveExpiredFiles($em_goc);
foreach ($request->files as $uploadedFileGG) {
// if($uploadedFile->getImage())
// var_dump($uploadedFile->getFile());
// var_dump($uploadedFile);
$tempD = $uploadedFileGG;
if (!is_array($uploadedFileGG)) {
$uploadedFileGG = array();
$uploadedFileGG[] = $tempD;
}
foreach ($uploadedFileGG as $uploadedFile) {
if ($uploadedFile != null) {
$extension = $uploadedFile->guessExtension();
$size = $uploadedFile->getSize();
$fileName = md5(uniqid()) . '.' . $uploadedFile->guessExtension();
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath;
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
if (file_exists($upl_dir . '' . $path)) {
chmod($upl_dir . '' . $path, 0755);
unlink($upl_dir . '' . $path);
}
$file = $uploadedFile->move($upl_dir, $path);
$expireTs = $request->request->get('expireTs', 0);
$expireNever = $request->request->get('expireNever', 0);
if ($expireNever == 1) {
$expireTs = 0;
} else {
if ($expireTs == 0) {
if ($request->request->get('expiryDays', 0) != 0) {
$currDate = new \DateTime();
$currDate->modify('+' . $request->request->get('expiryDays', 0) . ' day');
$expireTs = $currDate->format('U');
} else if ($request->request->get('expiryDate', '') != '') {
$currDate = new \DateTime($request->request->get('expiryDate', ''));
$currDate->modify('+14 day');
$expireTs = $currDate->format('U');
} else {
$currDate = new \DateTime();
$currDate->modify('+720 day');
$expireTs = $currDate->format('U');
}
}
}
$EntityFile = new EntityFile();
$EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath . $path);
$EntityFile->setMarker($request->request->get('markerHash', '_GEN_'));
$EntityFile->setName($path);
$EntityFile->setExtension($extension);
$EntityFile->setExpireTs($expireTs);
$EntityFile->setSize($size);
$EntityFile->setRelativePath($storePath . $path);
$EntityFile->setEntityName($request->request->get('entityName', ''));
$EntityFile->setEntityBundle($request->request->get('entityBundle', 'CompanyGroupBundle'));
$EntityFile->setEntityId($request->request->get('entityId', 0));
$EntityFile->setEntityIdField($request->request->get('entityIdField', ''));
$EntityFile->setModifyFieldSetter($request->request->get('modifyFieldSetter', ''));
$EntityFile->setDocIdForApplicant($request->request->get('docId', 0));
$EntityFile->setUserId($session->get(UserConstants::USER_ID, 0));
$EntityFile->setAppId($session->get(UserConstants::USER_APP_ID, 0));
$EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID, 0));
$EntityFile->setUserType($session->get(UserConstants::USER_TYPE, 0));
$em_goc->persist($EntityFile);
$em_goc->flush();
$EntityFileId = $EntityFile->getId();
}
if ($path != "")
$file_path_list[] = ($storePath . $path);
}
}
$g_path = $this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath . $path;
}
$baseUrl = $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
// $img_file = file_get_contents($g_path);
// $r = base64_encode($img_file);
// $url = url('dashboard');
return new JsonResponse(array(
"success" => true,
"file_path" => implode(',', $file_path_list),
"file_url" => $baseUrl . implode(',' . $baseUrl, $file_path_list),
"fileId" => $EntityFileId,
"refId" => $request->request->get('refId', 0),
"rowId" => $request->request->get('rowId', 0),
// "r"=>$r,
// "debug_data"=>System::encryptSignature($r)
));
}
return new JsonResponse(array(
"success" => false,
"file_path" => '',
"refId" => $request->request->get('refId', 0),
"rowId" => $request->request->get('rowId', 0),
));
}
public function BankReconExcelUpload(Request $request)
{
if ($request->isMethod('POST')) {
$post = $request->request;
$path = "";
$file_path = "";
// var_dump($request->files);
// var_dump($request->getFile());
foreach ($request->files as $uploadedFile) {
// if($uploadedFile->getImage())
// var_dump($uploadedFile->getFile());
// var_dump($uploadedFile);
if ($uploadedFile != null) {
$fileName = md5(uniqid()) . '.' . $uploadedFile->guessExtension();
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/';
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
$file = $uploadedFile->move($upl_dir, $path);
}
}
// print_r($file);
if ($path != "")
$file_path = 'uploads/FileUploads/' . $path;
$g_path = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' . $path;
//
// $img_file = file_get_contents($g_path);
// $r=base64_encode($img_file);
$row = 1;
$csv_data = [];
if (($handle = fopen($g_path, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$csv_data[$row] = $data;
// echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
// for ($c=0; $c < $num; $c++) {
// echo $data[$c] . "<br />\n";
// }
}
fclose($handle);
}
//now getting the relevant checks
$check_list = [];
foreach ($csv_data as $data_row) {
$get_kids_sql = "SELECT acc_check.*,
DATE_FORMAT(acc_transactions.transaction_date, '%b %d,%Y') trans_date,
DATE_FORMAT(acc_check.check_date, '%b %d,%Y') chk_date,
acc_transactions.document_hash FROM acc_check
JOIN acc_transactions on acc_check.voucher_id= acc_transactions.transaction_id
WHERE acc_check.check_number like '$data_row[0]' LIMIT 1";
// $get_kids_sql .=' ORDER BY name ASC';
$stmt = $this->getDoctrine()->getConnection()->fetchAllAssociative($get_kids_sql);
$check_here = $stmt;
if ($check_here) {
// $transdate = strtotime( $check_here['transaction_date'] );
// $checkdate = strtotime( $check_here['check_date'] );
$recondate = strtotime($data_row[1]);
$recondatestr = date('F d,Y', $recondate);
$new_check_data = array(
'checkId' => $check_here[0]['check_id'],
'checkNumber' => $check_here[0]['check_number'],
'voucherId' => $check_here[0]['voucher_id'],
'voucherNumber' => $check_here[0]['document_hash'],
'checkDate' => $check_here[0]['chk_date'],
'transactionDate' => $check_here[0]['trans_date'],
'reconDate' => $recondatestr,
);
$check_list[] = $new_check_data;
}
}
return new JsonResponse(array(
"success" => true,
"file_path" => $file_path,
"csv_data" => $csv_data,
"check_data" => $check_list,
// "debug_data"=>System::encryptSignature($r)
));
}
return new JsonResponse(array(
"success" => false,
"file_path" => '',
));
}
public function AddExpense(Request $request)
{
$details_ids = [];
$em = $this->getDoctrine()->getManager();
$em_goc = $this->getDoctrine()->getManager('company_group');
$expenseSubTypes = GeneralConstant::$expenseSubTypes;
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
$dochash = $request->request->get('voucherNumber'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isSignatureOk($em, $loginId, $approveHash)) {
// $this->addFlash(
// 'error',
// 'Sorry Could Not insert Data.'
// );
return new JsonResponse(array(
"success" => false,
'errorText' => 'Approval Hash Mismatch',
'errorStr' => 'Approval Hash Mismatch'
));
} else {
$new_ei = [];
$expenseDataList = array();
$primaryInvoiceId = 0;
$hasChildInvoice = 0;
$primaryInvoiceData = [];
$expense_data = $request->request->get('expenseData', []);
$exp_distribution_poitemId = $request->request->get('exp_distribution_poitemId', []);
$exp_distribution_amount = $request->request->get('exp_distribution_amount', []);
$costDistributionData = [];
foreach ($exp_distribution_poitemId as $key => $value) {
$costDistributionData[$value] = array(
'poItemId' => $value,
'amount' => $exp_distribution_amount[$key],
);
}
$expense_type = $request->request->get('expense_type', 0);
if (is_string($expense_data)) $expense_data = json_decode($expense_data, true);
if (!empty($expense_data)) {
//multiple invoices so add childs and parent
if (count($expense_data) > 1) $hasChildInvoice = 1;
if ($hasChildInvoice == 1)
$expenseDataList[] = array(
"expenseType" => 4, //primary
"expenseSubType" => 0,
"expenseId" => 0,
"ccId" => 0,
"currencyId" => 0,
"currencyMultiply" => 1,
"currencyMultiplyRate" => 1,
"docId" => 0,
"expenseToBePaidTo" => 0,
"expenseFrom" => 0,
"expenseFromNote" => '',
"expenseTo" => 0,
"expenseToNote" => 0,
"expenseAmount" => 0,
"previousAdvanceAmount" => 0,
"checkDate" => '',
"checkNumber" => '',
"checkNarration" => '',
"checkId" => 0,
"description" => '',
"expenseMarkerHash" => '',
"expenseDate" => $expense_data[0]['expenseDate'],
"invoiceBalancing" => 0,
"attachedFile" => [],
"uploadedFile" => '',
'expenseInvocationStrategyOnGrn' => null,
'expenseInvocationTypeOnItems' => null,
"isChildInvoice" => 0,
"costDistributionData" => $costDistributionData,
);
$currTime = new \DateTime();
$currTs = $currTime->format('U');
foreach ($expense_data as $key => $expData) {
if (isset($expData['imageBase64'])) {
$imageBase64 = $expData['imageBase64'];
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $imageBase64));
$fileName = $currTs . (md5(uniqid())) . '.png';
$storePath = 'uploads/ExpenseInvoice/';
$path = "";
$file_path = "";
$session = $request->getSession();
MiscActions::RemoveExpiredFiles($em_goc);
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath;
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
if (file_exists($upl_dir . '' . $path)) {
chmod($upl_dir . '' . $path, 0755);
unlink($upl_dir . '' . $path);
}
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ExpenseInvoice/' . $path;
file_put_contents($upl_dir, $data);
if ($path != "")
$file_path = $storePath . $path;
$expense_data[$key]['uploadedFile'] = $file_path;
}
if (!isset($expData['attachedFile'])) {
$expense_data[$key]['attachedFile'] = [];
}
$expense_data[$key]['isChildInvoice'] = $hasChildInvoice == 1 ? 1 : 0;
$expenseDataList[] = $expense_data[$key];
}
} else {
$expense_type = $request->request->get('expense_type', 0);
$expenseDataList[] = array(
"expenseType" => $expense_type,
"currencyId" => $request->request->get('expense_currency_id', 0),
"currencyMultiply" => $request->request->get('expense_currency_multiply', 1),
"currencyMultiplyRate" => $request->request->get('expense_currency_multiply_rate', 1),
"expenseSubType" => $request->request->get('expense_sub_type', 0),
"expenseId" => $request->request->get('expense_id', 0),
"ccId" => $request->request->get('ccId', 0),
"docId" => $expense_type == 1 ? $request->request->get('poId')
: ($expense_type == 2 ? $request->request->get('soId')
: ($expense_type == 3 ? $request->request->get('opportunityId', $request->request->get('leadId'))
: ($expense_type == 5 ? $request->request->get('tour_id') : 0))),
"directProjectId" => $request->request->get('directProjectId', 0),
"expenseToBePaidTo" => $request->request->get('expense_to_be_paid_to', 0),
"expenseFrom" => $request->request->get('expense_from', 0),
"checkDate" => $request->request->get('check_date', ''),
"checkNumber" => $request->request->get('check_number', ''),
"checkNarration" => $request->request->get('check_narration', ''),
"checkId" => $request->request->get('check_id', 0),
"expenseFromNote" => $request->request->get('expense_from_note', ''),
"expenseTo" => $request->request->get('expense_to_' . $expense_type, 0),
"expenseToNote" => $request->request->get('expense_to_note_' . $expense_type, ''),
"expenseAmount" => $request->request->get('expense_amount', ''),
"previousAdvanceAmount" => $request->request->get('prev_advance_amount', 0),
"description" => $request->request->get('description', ''),
"expenseMarkerHash" => $request->request->get('markerHash', ''),
"expenseDate" => $request->request->get('expense_date'),
'expenseInvocationStrategyOnGrn' => $request->request->get('expenseInvocationStrategyOnGrn', null),
'expenseInvocationTypeOnItems' => $request->request->get('expenseInvocationTypeOnItems', null),
"invoiceBalancing" => $request->request->has('auto_balance' . $expense_type) ? $request->request->get('auto_balance' . $expense_type) : 0,
"attachedFile" => $request->files->get('file', []),
"expenseSubCategory" => $request->request->get('expense_sub_category', 0),
"expenseSubCategoryOption" => $request->request->get('expense_sub_category_option', 0),
"uploadedFile" => $request->request->get('uploadedFile', ''),
"expenseDistributionOnProduct" => $request->request->get('exp_check_expense_distribution_on_product', 0),
"isChildInvoice" => 0,
"costDistributionData" => $costDistributionData,
);
}
///SIngle one
///
// System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($expenseDataList),'test_mult_exp');
foreach ($expenseDataList as $expData) {
// Generic::debugMessage($_POST);
$new_ei = [];
$em = $this->getDoctrine()->getManager();
// $to_assign=0;
if ($expData['expenseType'] == 4) { ////// primary Invoice
$expBillType = 4;
$data = array(
'doc_id' => $expData['docId'],
'expense_id' => $expData['expenseId'],
'party_id' => '',
'party_head_id' => $expData['expenseToBePaidTo'],
'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
'invoice_amount' => $expData['expenseAmount'],
'description' => $expData['description'],
'expense_to_note' => $expData['expenseToNote'],
'expense_from_note' => $expData['expenseFromNote'],
"currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
"currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
"currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
'date' => $expData['expenseDate'],
'file' => $expData['attachedFile'],
'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
'expense_from' => $expData['expenseFrom'],
'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
);
if ($request->request->has('latitude')) {
$data['latitude'] = $request->request->get('latitude');
$data['longitude'] = $request->request->get('longitude');
}
$new_ei = Accounts::CreateExpenseInvoiceFromAddExpense(
$this->getDoctrine()->getManager(),
$data,
'',
$expBillType,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
0,
0,
0,
$expData['ccId'],
$expData['isChildInvoice'],
$primaryInvoiceId,
1
);
//now add Approval info
}
if ($expData['expenseType'] == 0) {
$expBillType = 0;
$data = array(
'doc_id' => $expData['docId'],
'expense_id' => $expData['expenseId'],
'party_id' => '',
'party_head_id' => $expData['expenseToBePaidTo'],
'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
'invoice_amount' => $expData['expenseAmount'],
'description' => $expData['description'],
'expense_to_note' => $expData['expenseToNote'],
'expense_from_note' => $expData['expenseFromNote'],
'date' => $expData['expenseDate'],
'file' => $expData['attachedFile'],
"currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
"currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
"currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
'expense_from' => $expData['expenseFrom'],
'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
'expenseMarkerHash' => isset($expData['markerHash']) ? $expData['markerHash'] : '',
'expenseSubCategory' => isset($expData['expense_sub_category']) ? $expData['expense_sub_category'] : 0,
'expenseSubCategoryOption' => isset($expData['expense_sub_category_option']) ? $expData['expense_sub_category_option'] : 0,
);
if ($request->request->has('latitude')) {
$data['latitude'] = $request->request->get('latitude');
$data['longitude'] = $request->request->get('longitude');
}
if ($expData['expenseMarkerHash'] != '') {
$get_kids_sql = "SELECT accounts_head_id FROM acc_accounts_head where marker_hash like '%" . $expData['expenseMarkerHash'] . "%' limit 1";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
if (empty($query_output))
return new JsonResponse(array("success" => false, 'errorText' => 'Could not find relevant Expense Head'));
else
$data['expense_id'] = $query_output[0]['accounts_head_id'];
}
if ($expData['expenseToBePaidTo'] == '_OWN_' || $expData['expenseToBePaidTo'] == -1) //own expense entry from app
{
$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";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
if (empty($query_output)) {
// $query_output[0] = $data['expense_id'];///// TEMP
return new JsonResponse(array(
"success" => false,
'errorText' => 'You are not listed as Employee',
'errorStr' => 'You are not listed as Employee',
));
} else if ($query_output[0]['accounts_head_id'] == 0 || $query_output[0]['accounts_head_id'] == NULL)
return new JsonResponse(array(
"success" => false,
'errorText' => 'Could not Find Employee Head',
'errorStr' => 'Could not Find Employee Head',
));
else {
$data['party_head_id'] = $query_output[0]['accounts_head_id'];
$data['description'] = $expData['expenseToNote'];
$data['personal_expense_flag'] = 1;
$data['expense_of_user_id'] = $query_output[0]['user_id'];
$data['expense_of_employee_id'] = $query_output[0]['employee_id'];
}
}
if ($expData['expenseToBePaidTo'] == '_OWN_ADVANCE_' || $expData['expenseToBePaidTo'] == -2) //own expense entry from app
{
$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";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
if (empty($query_output)) {
// $query_output[0] = $data['expense_id'];///// TEMP
return new JsonResponse(array(
"success" => false,
'errorText' => 'You are not listed as Employee',
'errorStr' => 'You are not listed as Employee',
));
} else if ($query_output[0]['advance_head_id'] == 0 || $query_output[0]['advance_head_id'] == NULL)
return new JsonResponse(array(
"success" => false,
'errorText' => 'Could not Find Employee Advance Head',
'errorStr' => 'Could not Find Employee Advance Head',
));
else {
$data['party_head_id'] = $query_output[0]['advance_head_id'];
$data['description'] = $expData['expenseToNote'];
$data['personal_expense_flag'] = 1;
$data['expense_of_user_id'] = $query_output[0]['user_id'];
$data['expense_of_employee_id'] = $query_output[0]['employee_id'];
}
}
$new_ei = Accounts::CreateExpenseInvoiceFromAddExpense(
$this->getDoctrine()->getManager(),
$data,
'',
$expBillType,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
0,
0,
0,
$expData['ccId'],
$expData['isChildInvoice'],
$primaryInvoiceId
);
//now add Approval info
}
//for purchase
if ($expData['expenseType'] == 1) {
$expBillType = 1;
$po_data = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')
->findOneBy(
array(
'purchaseOrderId' => $expData['docId']
)
);
// $balanceable_advance=$so_data->getBalanceableAdvanceAmount();
$data = array(
'doc_id' => $expData['docId'],
'expense_id' => $expData['expenseId'],
'party_id' => '',
'party_head_id' => $expData['expenseToBePaidTo'],
'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
'invoice_amount' => $expData['expenseAmount'],
'description' => $expData['description'],
'expense_to_note' => $expData['expenseToNote'],
'expense_from_note' => $expData['expenseFromNote'],
'expenseInvocationStrategyOnGrn' => $expData['expenseInvocationStrategyOnGrn'],
'expenseInvocationTypeOnItems' => $expData['expenseInvocationTypeOnItems'],
'date' => $expData['expenseDate'],
'file' => $expData['attachedFile'],
"currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
"currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
"currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
'expense_from' => $expData['expenseFrom'],
'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
'costDistributionData' => isset($expData['costDistributionData']) ? $expData['costDistributionData'] : 0,
'expenseDistributionOnProduct' => isset($expData['expenseDistributionOnProduct']) ? $expData['expenseDistributionOnProduct'] : 0,
);
if ($expData['expenseToBePaidTo'] == '_OWN_' || $expData['expenseToBePaidTo'] == -1) //own expense entry from app
{
$get_kids_sql = "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " . $request->getSession()->get(UserConstants::USER_ID) . " limit 1";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
if (empty($query_output)) {
// $query_output[0] = $data['expense_id'];///// TEMP
return new JsonResponse(array(
"success" => false,
'errorText' => 'You are not listed as Employee',
'errorStr' => 'You are not listed as Employee',
));
} else if ($query_output[0]['accounts_head_id'] == 0 || $query_output[0]['accounts_head_id'] == NULL)
return new JsonResponse(array(
"success" => false,
'errorText' => 'Could not Find Employee Head',
'errorStr' => 'Could not Find Employee Head',
));
else {
$data['party_head_id'] = $query_output[0]['accounts_head_id'];
$data['description'] = $expData['expenseToNote'];
$data['personal_expense_flag'] = 1;
$data['expense_of_user_id'] = $query_output[0]['user_id'];
$data['expense_of_employee_id'] = $query_output[0]['employee_id'];
}
}
if ($expData['expenseToBePaidTo'] == '_OWN_ADVANCE_' || $expData['expenseToBePaidTo'] == -2) //own expense entry from app
{
$get_kids_sql = "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " . $request->getSession()->get(UserConstants::USER_ID) . " limit 1";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
if (empty($query_output)) {
// $query_output[0] = $data['expense_id'];///// TEMP
return new JsonResponse(array(
"success" => false,
'errorText' => 'You are not listed as Employee',
'errorStr' => 'You are not listed as Employee',
));
} else if ($query_output[0]['advance_head_id'] == 0 || $query_output[0]['advance_head_id'] == NULL)
return new JsonResponse(array(
"success" => false,
'errorText' => 'Could not Find Employee Advance Head',
'errorStr' => 'Could not Find Employee Advance Head',
));
else {
$data['party_head_id'] = $query_output[0]['advance_head_id'];
$data['description'] = $expData['expenseToNote'];
$data['personal_expense_flag'] = 1;
$data['expense_of_user_id'] = $query_output[0]['user_id'];
$data['expense_of_employee_id'] = $query_output[0]['employee_id'];
}
}
$new_ei = Accounts::CreateExpenseInvoiceFromAddExpense(
$this->getDoctrine()->getManager(),
$data,
'',
$expBillType,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
0,
$po_data->getProjectId(),
0,
$expData['ccId'],
$expData['isChildInvoice'],
$primaryInvoiceId
);
//now add Approval info
}
if ($expData['expenseType'] == 2) {
$data = $request->request;
// <option value="1">Against Purchase</option>
// <option value="2">Against Sales</option>
// <option value="3">Against Maintenance</option>
$expBillType = 2;
$so_data = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\SalesOrder')
->findOneBy(
array(
'salesOrderId' => $expData['docId']
)
);
$supplier_data = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccSuppliers')
->findOneBy(
array(
'accountsHeadId' => $expData['expenseToBePaidTo']
)
);
// $balanceable_advance=$so_data->getBalanceableAdvanceAmount();
$data = array(
'doc_id' => $expData['docId'],
'expense_id' => $expData['expenseId'],
'party_id' => $supplier_data ? $supplier_data->getSupplierId() : 0,
'party_head_id' => $expData['expenseToBePaidTo'],
'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
'invoice_amount' => $expData['expenseAmount'],
'description' => $expData['description'],
'expense_to_note' => $expData['expenseToNote'],
'expense_from_note' => $expData['expenseFromNote'],
"currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
"currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
"currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
'expenseInvocationStrategyOnGrn' => $expData['expenseInvocationStrategyOnGrn'],
'expenseInvocationTypeOnItems' => $expData['expenseInvocationTypeOnItems'],
'date' => $expData['expenseDate'],
'file' => $expData['attachedFile'],
'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
'expense_from' => $expData['expenseFrom'],
'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
);
if ($expData['expenseToBePaidTo'] == '_OWN_' || $expData['expenseToBePaidTo'] == -1) //own expense entry from app
{
$get_kids_sql = "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " . $request->getSession()->get(UserConstants::USER_ID) . " limit 1";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
if (empty($query_output)) {
// $query_output[0] = $data['expense_id'];///// TEMP
return new JsonResponse(array(
"success" => false,
'errorText' => 'You are not listed as Employee',
'errorStr' => 'You are not listed as Employee',
));
} else if ($query_output[0]['accounts_head_id'] == 0 || $query_output[0]['accounts_head_id'] == NULL)
return new JsonResponse(array(
"success" => false,
'errorText' => 'Could not Find Employee Head',
'errorStr' => 'Could not Find Employee Head',
));
else {
$data['party_head_id'] = $query_output[0]['accounts_head_id'];
$data['description'] = $expData['expenseToNote'];
$data['personal_expense_flag'] = 1;
$data['expense_of_user_id'] = $query_output[0]['user_id'];
$data['expense_of_employee_id'] = $query_output[0]['employee_id'];
}
}
if ($expData['expenseToBePaidTo'] == '_OWN_ADVANCE_' || $expData['expenseToBePaidTo'] == -2) //own expense entry from app
{
$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";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
if (empty($query_output)) {
// $query_output[0] = $data['expense_id'];///// TEMP
return new JsonResponse(array(
"success" => false,
'errorText' => 'You are not listed as Employee',
'errorStr' => 'You are not listed as Employee',
));
} else if ($query_output[0]['advance_head_id'] == 0 || $query_output[0]['advance_head_id'] == NULL)
return new JsonResponse(array(
"success" => false,
'errorText' => 'Could not Find Employee Advance Head',
'errorStr' => 'Could not Find Employee Advance Head',
));
else {
$data['party_head_id'] = $query_output[0]['advance_head_id'];
$data['description'] = $expData['expenseToNote'];
$data['personal_expense_flag'] = 1;
$data['expense_of_user_id'] = $query_output[0]['user_id'];
$data['expense_of_employee_id'] = $query_output[0]['employee_id'];
}
}
$new_ei = Accounts::CreateExpenseInvoiceFromAddExpense(
$this->getDoctrine()->getManager(),
$data,
'',
$expBillType,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
0,
((int) ($expData['directProjectId'] ?? 0) > 0 ? (int) $expData['directProjectId'] : ($so_data ? $so_data->getProjectId() : 0)),
0,
$expData['ccId'],
$expData['isChildInvoice'],
$primaryInvoiceId
);
}
if ($expData['expenseType'] == 3) {
$data = $request->request;
$expBillType = 3;
$so_data = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\Opportunity')
->findOneBy(
array(
'opportunityId' => $expData['docId']
)
);
$supplier_data = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccSuppliers')
->findOneBy(
array(
'accountsHeadId' => $expData['expenseToBePaidTo']
)
);
// $balanceable_advance=$so_data->getBalanceableAdvanceAmount();
$data = array(
'doc_id' => $expData['docId'],
'expense_id' => $expData['expenseId'],
'party_id' => $supplier_data ? $supplier_data->getSupplierId() : 0,
'party_head_id' => $expData['expenseToBePaidTo'],
'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
'invoice_amount' => $expData['expenseAmount'],
'description' => $expData['description'],
'expense_to_note' => $expData['expenseToNote'],
'expense_from_note' => $expData['expenseFromNote'],
"currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
"currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
"currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
'expenseInvocationStrategyOnGrn' => $expData['expenseInvocationStrategyOnGrn'],
'expenseInvocationTypeOnItems' => $expData['expenseInvocationTypeOnItems'],
'date' => $expData['expenseDate'],
'file' => $expData['attachedFile'],
'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
'expense_from' => $expData['expenseFrom'],
'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
);
if ($expData['expenseToBePaidTo'] == '_OWN_' || $expData['expenseToBePaidTo'] == -1) //own expense entry from app
{
$get_kids_sql = "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " . $request->getSession()->get(UserConstants::USER_ID) . " limit 1";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
if (empty($query_output)) {
// $query_output[0] = $data['expense_id'];///// TEMP
return new JsonResponse(array(
"success" => false,
'errorText' => 'You are not listed as Employee',
'errorStr' => 'You are not listed as Employee',
));
} else if ($query_output[0]['accounts_head_id'] == 0 || $query_output[0]['accounts_head_id'] == NULL)
return new JsonResponse(array(
"success" => false,
'errorText' => 'Could not Find Employee Head',
'errorStr' => 'Could not Find Employee Head',
));
else {
$data['party_head_id'] = $query_output[0]['accounts_head_id'];
$data['description'] = $expData['expenseToNote'];
$data['personal_expense_flag'] = 1;
$data['expense_of_user_id'] = $query_output[0]['user_id'];
$data['expense_of_employee_id'] = $query_output[0]['employee_id'];
}
}
if ($expData['expenseToBePaidTo'] == '_OWN_ADVANCE_' || $expData['expenseToBePaidTo'] == -2) //own expense entry from app
{
$get_kids_sql = "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " . $request->getSession()->get(UserConstants::USER_ID) . " limit 1";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
if (empty($query_output)) {
// $query_output[0] = $data['expense_id'];///// TEMP
return new JsonResponse(array(
"success" => false,
'errorText' => 'You are not listed as Employee',
'errorStr' => 'You are not listed as Employee',
));
} else if ($query_output[0]['advance_head_id'] == 0 || $query_output[0]['advance_head_id'] == NULL)
return new JsonResponse(array(
"success" => false,
'errorText' => 'Could not Find Employee Advance Head',
'errorStr' => 'Could not Find Employee Advance Head',
));
else {
$data['party_head_id'] = $query_output[0]['advance_head_id'];
$data['description'] = $expData['expenseToNote'];
$data['personal_expense_flag'] = 1;
$data['expense_of_user_id'] = $query_output[0]['user_id'];
$data['expense_of_employee_id'] = $query_output[0]['employee_id'];
}
}
$new_ei = Accounts::CreateExpenseInvoiceFromAddExpense(
$this->getDoctrine()->getManager(),
$data,
'',
$expBillType,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
0,
((int) ($expData['directProjectId'] ?? 0) > 0 ? (int) $expData['directProjectId'] : ($so_data ? $so_data->getProjectId() : 0)),
0,
$expData['ccId'],
$expData['isChildInvoice'],
$primaryInvoiceId
);
}
if ($expData['expenseType'] == 5) {
$expBillType = 0;
// Fetch the Tour data
$tour_data = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\PlanVisit')
->findOneBy([
'id' => $expData['docId']
]);
$supplier_data = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccSuppliers')
->findOneBy([
'accountsHeadId' => $expData['expenseToBePaidTo']
]);
$data = [
'doc_id' => $expData['docId'],
'expense_id' => $expData['expenseId'],
'party_id' => $supplier_data ? $supplier_data->getSupplierId() : '',
'party_head_id' => $expData['expenseToBePaidTo'],
'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
'invoice_amount' => $expData['expenseAmount'],
'description' => $expData['description'],
'expense_to_note' => $expData['expenseToNote'],
'expense_from_note' => $expData['expenseFromNote'],
'date' => $expData['expenseDate'],
'file' => $expData['attachedFile'],
'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
'expense_from' => $expData['expenseFrom'],
'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
'expenseMarkerHash' => isset($expData['markerHash']) ? $expData['markerHash'] : '',
'expenseSubCategory' => isset($expData['expense_sub_category']) ? $expData['expense_sub_category'] : 0,
'expenseSubCategoryOption' => isset($expData['expense_sub_category_option']) ? $expData['expense_sub_category_option'] : 0,
'tour_title' => $tour_data ? $tour_data->getTitle() : '',
'tour_document_hash' => $tour_data ? $tour_data->getDocumentHash() : '',
'tour_id' => $tour_data ? $tour_data->getId() : ''
];
if ($request->request->has('latitude')) {
$data['latitude'] = $request->request->get('latitude');
$data['longitude'] = $request->request->get('longitude');
}
// Handle personal expense if own head
if ($expData['expenseToBePaidTo'] == '_OWN_' || $expData['expenseToBePaidTo'] == -1) {
$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";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
if (empty($query_output)) {
return new JsonResponse([
"success" => false,
'errorText' => 'You are not listed as Employee',
'errorStr' => 'You are not listed as Employee',
]);
}
$data['party_head_id'] = $query_output[0]['accounts_head_id'];
$data['description'] = $expData['expenseToNote'];
$data['personal_expense_flag'] = 1;
$data['expense_of_user_id'] = $query_output[0]['user_id'];
$data['expense_of_employee_id'] = $query_output[0]['employee_id'];
}
// Handle own advance
if ($expData['expenseToBePaidTo'] == '_OWN_ADVANCE_' || $expData['expenseToBePaidTo'] == -2) {
$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";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
if (empty($query_output)) {
return new JsonResponse([
"success" => false,
'errorText' => 'You are not listed as Employee',
'errorStr' => 'You are not listed as Employee',
]);
}
$data['party_head_id'] = $query_output[0]['advance_head_id'];
$data['description'] = $expData['expenseToNote'];
$data['personal_expense_flag'] = 1;
$data['expense_of_user_id'] = $query_output[0]['user_id'];
$data['expense_of_employee_id'] = $query_output[0]['employee_id'];
}
// Create Expense Invoice
$new_ei = Accounts::CreateExpenseInvoiceFromAddExpense(
$this->getDoctrine()->getManager(),
$data,
'',
$expBillType,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
0,
0,
0,
$expData['ccId'],
$expData['isChildInvoice'],
$primaryInvoiceId
);
}
if ($expData['isChildInvoice'] != 1 && isset($new_ei['ei_id'])) {
$primaryInvoiceId = $new_ei['ei_id'];
}
}
//single end
if ($primaryInvoiceId != 0) {
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
$primaryInvoiceId,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
$primaryInvoiceId,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
}
return new JsonResponse(array(
"success" => true,
'docId' => isset($new_ei['ei_id']) ? $new_ei['ei_id'] : '',
'docHash' => isset($new_ei['ei_doc_hash']) ? $new_ei['ei_doc_hash'] : '',
));
}
}
return new JsonResponse(array(
"success" => true,
'docId' => isset($new_ei['ei_id']) ? $new_ei['ei_id'] : '',
'docHash' => isset($new_ei['ei_doc_hash']) ? $new_ei['ei_doc_hash'] : '',
'expenseSubTypes' => $expenseSubTypes
));
//
// return $this->render('@Accounts/pages/input_forms/payment_voucher.html.twig',
// array(
// 'page_title'=>'Create Payment Voucher',
// 'test'=>$details_ids,
// 'supplier_list'=>Accounts::SupplierListForPv($this->getDoctrine()->getManager()),
// 'supplier_list_by_ac_head'=>Accounts::SupplierListByAcHead($this->getDoctrine()->getManager()),
// 'supplier_list_by_advance_head'=>Accounts::SupplierListByAdvanceHead($this->getDoctrine()->getManager())
// )
// );
}
public function AddExpenseForApp(Request $request)
{
$details_ids = [];
$em = $this->getDoctrine()->getManager();
$em_goc = $this->getDoctrine()->getManager('company_group');
$expenseSubTypes = GeneralConstant::$expenseSubTypes;
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['AccTransactions']; //change
$dochash = $request->request->get('voucherNumber'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole', 1);
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isSignatureOk($em, $loginId, $approveHash)) {
// $this->addFlash(
// 'error',
// 'Sorry Could Not insert Data.'
// );
return new JsonResponse(array(
"success" => false,
'errorText' => 'Approval Hash Mismatch',
'errorStr' => 'Approval Hash Mismatch'
));
} else {
$new_ei = [];
$expenseDataList = array();
$primaryInvoiceId = 0;
$hasChildInvoice = 0;
$primaryInvoiceData = [];
$expense_data = $request->request->get('expenseData', []);
if (is_string($expense_data)) $expense_data = json_decode($expense_data, true);
if (!empty($expense_data)) {
//multiple invoices so add childs and parent
if (count($expense_data) > 1) $hasChildInvoice = 1;
if ($hasChildInvoice == 1)
$expenseDataList[] = array(
"expenseType" => 4, //primary
"expenseSubType" => 0,
"expenseId" => 0,
"ccId" => 0,
"currencyId" => 0,
"currencyMultiply" => 1,
"currencyMultiplyRate" => 1,
"docId" => 0,
"expenseToBePaidTo" => 0,
"expenseFrom" => 0,
"expenseFromNote" => '',
"expenseTo" => 0,
"expenseToNote" => 0,
"expenseAmount" => 0,
"previousAdvanceAmount" => 0,
"checkDate" => '',
"checkNumber" => '',
"checkNarration" => '',
"checkId" => 0,
"description" => '',
"expenseMarkerHash" => '',
"expenseDate" => $expense_data[0]['expenseDate'],
"invoiceBalancing" => 0,
"attachedFile" => [],
"uploadedFile" => '',
'expenseInvocationStrategyOnGrn' => null,
'expenseInvocationTypeOnItems' => null,
"isChildInvoice" => 0,
);
$currTime = new \DateTime();
$currTs = $currTime->format('U');
foreach ($expense_data as $key => $expData) {
if (isset($expData['imageBase64'])) {
$imageBase64 = $expData['imageBase64'];
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $imageBase64));
$fileName = $currTs . (md5(uniqid())) . '.png';
$storePath = 'uploads/ExpenseInvoice/';
$path = "";
$file_path = "";
$session = $request->getSession();
MiscActions::RemoveExpiredFiles($em_goc);
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath;
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
if (file_exists($upl_dir . '' . $path)) {
chmod($upl_dir . '' . $path, 0755);
unlink($upl_dir . '' . $path);
}
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ExpenseInvoice/' . $path;
file_put_contents($upl_dir, $data);
if ($path != "")
$file_path = $storePath . $path;
$expense_data[$key]['uploadedFile'] = $file_path;
}
if (!isset($expData['attachedFile'])) {
$expense_data[$key]['attachedFile'] = [];
}
$expense_data[$key]['isChildInvoice'] = $hasChildInvoice == 1 ? 1 : 0;
$expenseDataList[] = $expense_data[$key];
}
} else {
$expense_type = $request->request->get('expense_type', 0);
$expenseDataList[] = array(
"expenseType" => $expense_type,
"currencyId" => $request->request->get('expense_currency_id', 0),
"currencyMultiply" => $request->request->get('expense_currency_multiply', 1),
"currencyMultiplyRate" => $request->request->get('expense_currency_multiply_rate', 1),
"expenseSubType" => $request->request->get('expense_sub_type', 0),
"expenseId" => $request->request->get('expense_id', 0),
"ccId" => $request->request->get('ccId', 0),
"docId" => $expense_type == 1 ? $request->request->get('poId') : ($expense_type == 2 ? $request->request->get('soId') : 0),
"expenseToBePaidTo" => $request->request->get('expense_to_be_paid_to', 0),
"expenseFrom" => $request->request->get('expense_from', 0),
"checkDate" => $request->request->get('check_date', ''),
"checkNumber" => $request->request->get('check_number', ''),
"checkNarration" => $request->request->get('check_narration', ''),
"checkId" => $request->request->get('check_id', 0),
"expenseFromNote" => $request->request->get('expense_from_note', ''),
"expenseTo" => $request->request->get('expense_to_' . $expense_type, 0),
"expenseToNote" => $request->request->get('expense_to_note_' . $expense_type, ''),
"expenseAmount" => $request->request->get('expense_amount', ''),
"previousAdvanceAmount" => $request->request->get('prev_advance_amount', 0),
"description" => $request->request->get('description', ''),
"expenseMarkerHash" => $request->request->get('markerHash', ''),
"expenseDate" => $request->request->get('expense_date'),
'expenseInvocationStrategyOnGrn' => $request->request->get('expenseInvocationStrategyOnGrn', null),
'expenseInvocationTypeOnItems' => $request->request->get('expenseInvocationTypeOnItems', null),
"invoiceBalancing" => $request->request->has('auto_balance' . $expense_type) ? $request->request->get('auto_balance' . $expense_type) : 0,
"attachedFile" => $request->files->get('file', []),
"uploadedFile" => $request->request->get('uploadedFile', ''),
"expenseSubCategory" => $request->request->get('expense_sub_category', 0),
"expenseSubCategoryOption" => $request->request->get('expense_sub_category_option', 0),
"isChildInvoice" => 0,
);
}
///SIngle one
///
// System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($expenseDataList),'test_mult_exp');
foreach ($expenseDataList as $expData) {
// Generic::debugMessage($_POST);
$new_ei = [];
$em = $this->getDoctrine()->getManager();
// $to_assign=0;
if ($expData['expenseType'] == 4) { ////// primary Invoice
$expBillType = 4;
$data = array(
'doc_id' => $expData['docId'],
'expense_id' => $expData['expenseId'],
'party_id' => '',
'party_head_id' => $expData['expenseToBePaidTo'],
'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
'invoice_amount' => $expData['expenseAmount'],
'description' => $expData['description'],
'expense_to_note' => $expData['expenseToNote'],
'expense_from_note' => $expData['expenseFromNote'],
"currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
"currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
"currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
'date' => $expData['expenseDate'],
'file' => $expData['attachedFile'],
'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
'expense_from' => $expData['expenseFrom'],
'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
);
if ($request->request->has('latitude')) {
$data['latitude'] = $request->request->get('latitude');
$data['longitude'] = $request->request->get('longitude');
}
$new_ei = Accounts::CreateExpenseInvoiceFromAddExpense(
$this->getDoctrine()->getManager(),
$data,
'',
$expBillType,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
0,
0,
0,
$expData['ccId'],
$expData['isChildInvoice'],
$primaryInvoiceId,
1
);
//now add Approval info
}
if ($expData['expenseType'] == 0) {
$expBillType = 0;
$data = array(
'doc_id' => $expData['docId'],
'expense_id' => $expData['expenseId'],
'party_id' => '',
'party_head_id' => $expData['expenseToBePaidTo'],
'advance_amount_to_assign' => isset($expData['previousAdvanceAmount']) ? $expData['previousAdvanceAmount'] : '',
'invoice_amount' => $expData['expenseAmount'],
'description' => $expData['description'],
'expense_to_note' => isset($expData['expenseToNote']) ? $expData['expenseToNote'] : '',
'expense_from_note' => isset($expData['expenseFromNote']) ? $expData['expenseFromNote'] : '',
'date' => $expData['expenseDate'],
'file' => $expData['attachedFile'],
"currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
"currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
"currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
'expense_from' => isset($expData['expenseFrom']) ? $expData['expenseFrom'] : '',
'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
'markerHash' => isset($expData['expenseMarkerHash']) ? $expData['expenseMarkerHash'] : 0,
'expenseSubCategory' => isset($expData['expenseSubCategory']) ? $expData['expenseSubCategory'] : 0,
'expenseSubCategoryOption' => isset($expData['expenseSubCategoryOption']) ? $expData['expenseSubCategoryOption'] : 0,
);
if ($request->request->has('latitude')) {
$data['latitude'] = $request->request->get('latitude');
$data['longitude'] = $request->request->get('longitude');
}
if ($expData['expenseMarkerHash'] != '') {
$get_kids_sql = "SELECT accounts_head_id FROM acc_accounts_head where marker_hash like '%" . $expData['expenseMarkerHash'] . "%' limit 1";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
if (empty($query_output))
return new JsonResponse(array("success" => false, 'errorText' => 'Could not find relevant Expense Head'));
else
$data['expense_id'] = $query_output[0]['accounts_head_id'];
}
if ($expData['expenseToBePaidTo'] == '_OWN_' || $expData['expenseToBePaidTo'] == -1) //own expense entry from app
{
$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";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
if (empty($query_output)) {
// $query_output[0] = $data['expense_id'];///// TEMP
return new JsonResponse(array(
"success" => false,
'errorText' => 'You are not listed as Employee',
'errorStr' => 'You are not listed as Employee',
));
} else if ($query_output[0]['accounts_head_id'] == 0 || $query_output[0]['accounts_head_id'] == NULL)
return new JsonResponse(array(
"success" => false,
'errorText' => 'Could not Find Employee Head',
'errorStr' => 'Could not Find Employee Head',
));
else {
$data['party_head_id'] = $query_output[0]['accounts_head_id'];
// $data['description'] = $expData['expenseToNote'];
$data['description'] = $expData['description'];
$data['personal_expense_flag'] = 1;
$data['expense_of_user_id'] = $query_output[0]['user_id'];
$data['expense_of_employee_id'] = $query_output[0]['employee_id'];
}
}
if ($expData['expenseToBePaidTo'] == '_OWN_ADVANCE_' || $expData['expenseToBePaidTo'] == -2) //own expense entry from app
{
$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";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
if (empty($query_output)) {
// $query_output[0] = $data['expense_id'];///// TEMP
return new JsonResponse(array(
"success" => false,
'errorText' => 'You are not listed as Employee',
'errorStr' => 'You are not listed as Employee',
));
} else if ($query_output[0]['advance_head_id'] == 0 || $query_output[0]['advance_head_id'] == NULL)
return new JsonResponse(array(
"success" => false,
'errorText' => 'Could not Find Employee Advance Head',
'errorStr' => 'Could not Find Employee Advance Head',
));
else {
$data['party_head_id'] = $query_output[0]['advance_head_id'];
$data['description'] = $expData['expenseToNote'];
$data['personal_expense_flag'] = 1;
$data['expense_of_user_id'] = $query_output[0]['user_id'];
$data['expense_of_employee_id'] = $query_output[0]['employee_id'];
}
}
$new_ei = Accounts::CreateExpenseInvoiceFromAddExpense(
$this->getDoctrine()->getManager(),
$data,
'',
$expBillType,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
0,
0,
0,
$expData['ccId'],
$expData['isChildInvoice'],
$primaryInvoiceId
);
//now add Approval info
}
//for purchase
if ($expData['expenseType'] == 1) {
$expBillType = 1;
$po_data = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\PurchaseOrder')
->findOneBy(
array(
'purchaseOrderId' => $expData['docId']
)
);
// $balanceable_advance=$so_data->getBalanceableAdvanceAmount();
$data = array(
'doc_id' => $expData['docId'],
'expense_id' => $expData['expenseId'],
'party_id' => '',
'party_head_id' => $expData['expenseToBePaidTo'],
'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
'invoice_amount' => $expData['expenseAmount'],
'description' => $expData['description'],
'expense_to_note' => $expData['expenseToNote'],
'expense_from_note' => $expData['expenseFromNote'],
'expenseInvocationStrategyOnGrn' => $expData['expenseInvocationStrategyOnGrn'],
'expenseInvocationTypeOnItems' => $expData['expenseInvocationTypeOnItems'],
'date' => $expData['expenseDate'],
'file' => $expData['attachedFile'],
"currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
"currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
"currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
'expense_from' => $expData['expenseFrom'],
'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
);
if ($expData['expenseToBePaidTo'] == '_OWN_' || $expData['expenseToBePaidTo'] == -1) //own expense entry from app
{
$get_kids_sql = "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " . $request->getSession()->get(UserConstants::USER_ID) . " limit 1";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
if (empty($query_output)) {
// $query_output[0] = $data['expense_id'];///// TEMP
return new JsonResponse(array(
"success" => false,
'errorText' => 'You are not listed as Employee',
'errorStr' => 'You are not listed as Employee',
));
} else if ($query_output[0]['accounts_head_id'] == 0 || $query_output[0]['accounts_head_id'] == NULL)
return new JsonResponse(array(
"success" => false,
'errorText' => 'Could not Find Employee Head',
'errorStr' => 'Could not Find Employee Head',
));
else {
$data['party_head_id'] = $query_output[0]['accounts_head_id'];
$data['description'] = $expData['expenseToNote'];
$data['personal_expense_flag'] = 1;
$data['expense_of_user_id'] = $query_output[0]['user_id'];
$data['expense_of_employee_id'] = $query_output[0]['employee_id'];
}
}
if ($expData['expenseToBePaidTo'] == '_OWN_ADVANCE_' || $expData['expenseToBePaidTo'] == -2) //own expense entry from app
{
$get_kids_sql = "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " . $request->getSession()->get(UserConstants::USER_ID) . " limit 1";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
if (empty($query_output)) {
// $query_output[0] = $data['expense_id'];///// TEMP
return new JsonResponse(array(
"success" => false,
'errorText' => 'You are not listed as Employee',
'errorStr' => 'You are not listed as Employee',
));
} else if ($query_output[0]['advance_head_id'] == 0 || $query_output[0]['advance_head_id'] == NULL)
return new JsonResponse(array(
"success" => false,
'errorText' => 'Could not Find Employee Advance Head',
'errorStr' => 'Could not Find Employee Advance Head',
));
else {
$data['party_head_id'] = $query_output[0]['advance_head_id'];
$data['description'] = $expData['expenseToNote'];
$data['personal_expense_flag'] = 1;
$data['expense_of_user_id'] = $query_output[0]['user_id'];
$data['expense_of_employee_id'] = $query_output[0]['employee_id'];
}
}
$new_ei = Accounts::CreateExpenseInvoiceFromAddExpense(
$this->getDoctrine()->getManager(),
$data,
'',
$expBillType,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
0,
$po_data->getProjectId(),
0,
$expData['ccId'],
$expData['isChildInvoice'],
$primaryInvoiceId
);
//now add Approval info
}
if ($expData['expenseType'] == 2) {
$data = $request->request;
// <option value="1">Against Purchase</option>
// <option value="2">Against Sales</option>
// <option value="3">Against Maintenance</option>
$expBillType = 2;
$so_data = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\SalesOrder')
->findOneBy(
array(
'salesOrderId' => $expData['docId']
)
);
$supplier_data = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccSuppliers')
->findOneBy(
array(
'accountsHeadId' => $expData['expenseToBePaidTo']
)
);
// $balanceable_advance=$so_data->getBalanceableAdvanceAmount();
$data = array(
'doc_id' => $expData['docId'],
'expense_id' => $expData['expenseId'],
'party_id' => $supplier_data ? $supplier_data->getSupplierId() : 0,
'party_head_id' => $expData['expenseToBePaidTo'],
'advance_amount_to_assign' => $expData['previousAdvanceAmount'],
'invoice_amount' => $expData['expenseAmount'],
'description' => $expData['description'],
'expense_to_note' => $expData['expenseToNote'],
'expense_from_note' => $expData['expenseFromNote'],
"currencyId" => isset($expData['currencyId']) ? $expData['currencyId'] : 0,
"currencyMultiply" => isset($expData['currencyMultiply']) ? $expData['currencyMultiply'] : 1,
"currencyMultiplyRate" => isset($expData['currencyMultiplyRate']) ? $expData['currencyMultiplyRate'] : 1,
'expenseInvocationStrategyOnGrn' => $expData['expenseInvocationStrategyOnGrn'],
'expenseInvocationTypeOnItems' => $expData['expenseInvocationTypeOnItems'],
'date' => $expData['expenseDate'],
'file' => $expData['attachedFile'],
'uploadedFile' => isset($expData['uploadedFile']) ? $expData['uploadedFile'] : '',
'expense_from' => $expData['expenseFrom'],
'check_date' => isset($expData['checkDate']) ? $expData['checkDate'] : '',
'check_number' => isset($expData['checkNumber']) ? $expData['checkNumber'] : '',
'check_narration' => isset($expData['checkNarration']) ? $expData['checkNarration'] : '',
'markerHash' => isset($expData['expenseMarkerHash']) ? $expData['expenseMarkerHash'] : 0,
'check_id' => isset($expData['checkId']) ? $expData['checkId'] : 0,
);
if ($expData['expenseToBePaidTo'] == '_OWN_' || $expData['expenseToBePaidTo'] == -1) //own expense entry from app
{
$get_kids_sql = "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " . $request->getSession()->get(UserConstants::USER_ID) . " limit 1";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
if (empty($query_output)) {
// $query_output[0] = $data['expense_id'];///// TEMP
return new JsonResponse(array(
"success" => false,
'errorText' => 'You are not listed as Employee',
'errorStr' => 'You are not listed as Employee',
));
} else if ($query_output[0]['accounts_head_id'] == 0 || $query_output[0]['accounts_head_id'] == NULL)
return new JsonResponse(array(
"success" => false,
'errorText' => 'Could not Find Employee Head',
'errorStr' => 'Could not Find Employee Head',
));
else {
$data['party_head_id'] = $query_output[0]['accounts_head_id'];
$data['description'] = $expData['expenseToNote'];
$data['personal_expense_flag'] = 1;
$data['expense_of_user_id'] = $query_output[0]['user_id'];
$data['expense_of_employee_id'] = $query_output[0]['employee_id'];
}
}
if ($expData['expenseToBePaidTo'] == '_OWN_ADVANCE_' || $expData['expenseToBePaidTo'] == -2) //own expense entry from app
{
$get_kids_sql = "SELECT accounts_head_id, employee_id, user_id FROM employee where user_id = " . $request->getSession()->get(UserConstants::USER_ID) . " limit 1";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
if (empty($query_output)) {
// $query_output[0] = $data['expense_id'];///// TEMP
return new JsonResponse(array(
"success" => false,
'errorText' => 'You are not listed as Employee',
'errorStr' => 'You are not listed as Employee',
));
} else if ($query_output[0]['advance_head_id'] == 0 || $query_output[0]['advance_head_id'] == NULL)
return new JsonResponse(array(
"success" => false,
'errorText' => 'Could not Find Employee Advance Head',
'errorStr' => 'Could not Find Employee Advance Head',
));
else {
$data['party_head_id'] = $query_output[0]['advance_head_id'];
$data['description'] = $expData['expenseToNote'];
$data['personal_expense_flag'] = 1;
$data['expense_of_user_id'] = $query_output[0]['user_id'];
$data['expense_of_employee_id'] = $query_output[0]['employee_id'];
}
}
if ($expData['expenseMarkerHash'] != '') {
$get_kids_sql = "SELECT accounts_head_id FROM acc_accounts_head where marker_hash like '%" . $expData['expenseMarkerHash'] . "%' limit 1";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
if (empty($query_output))
return new JsonResponse(array("success" => false, 'errorText' => 'Could not find relevant Expense Head'));
else
$data['expense_id'] = $query_output[0]['accounts_head_id'];
}
$new_ei = Accounts::CreateExpenseInvoiceFromAddExpense(
$this->getDoctrine()->getManager(),
$data,
'',
$expBillType,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
0,
((int) ($expData['directProjectId'] ?? 0) > 0 ? (int) $expData['directProjectId'] : ($so_data ? $so_data->getProjectId() : 0)),
0,
$expData['ccId'],
$expData['isChildInvoice'],
$primaryInvoiceId
);
}
if ($expData['isChildInvoice'] != 1 && isset($new_ei['ei_id'])) {
$primaryInvoiceId = $new_ei['ei_id'];
}
}
//single end
if ($primaryInvoiceId != 0) {
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
$primaryInvoiceId,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
$primaryInvoiceId,
$loginId,
$request->request->get('approvalRole', 1),
$request->request->get('approvalHash')
);
}
return new JsonResponse(array(
"success" => true,
'docId' => isset($new_ei['ei_id']) ? $new_ei['ei_id'] : '',
'docHash' => isset($new_ei['ei_doc_hash']) ? $new_ei['ei_doc_hash'] : '',
));
}
}
return new JsonResponse(array(
"success" => true,
'docId' => isset($new_ei['ei_id']) ? $new_ei['ei_id'] : '',
'docHash' => isset($new_ei['ei_doc_hash']) ? $new_ei['ei_doc_hash'] : '',
'expenseSubTypes' => $expenseSubTypes
));
//
// return $this->render('@Accounts/pages/input_forms/payment_voucher.html.twig',
// array(
// 'page_title'=>'Create Payment Voucher',
// 'test'=>$details_ids,
// 'supplier_list'=>Accounts::SupplierListForPv($this->getDoctrine()->getManager()),
// 'supplier_list_by_ac_head'=>Accounts::SupplierListByAcHead($this->getDoctrine()->getManager()),
// 'supplier_list_by_advance_head'=>Accounts::SupplierListByAdvanceHead($this->getDoctrine()->getManager())
// )
// );
}
public function GetSalesOrderDocument()
{
$em = $this->getDoctrine()->getManager();
$qb = $em->createQueryBuilder();
$qb->select('s.salesOrderId', 's.documentHash', 'c.clientName')
->from('ApplicationBundle:SalesOrder', 's')
->leftJoin('ApplicationBundle:AccClients', 'c', 'WITH', 's.clientId = c.clientId')
->orderBy('s.salesOrderId', 'DESC');
$results = $qb->getQuery()->getArrayResult();
return new JsonResponse([
'success' => true,
'data' => $results
]);
}
public function GetCostCenter()
{
$em = $this->getDoctrine()->getManager();
$qb = $em->createQueryBuilder();
$qb->select('c.costCentreId', 'c.name')
->from('ApplicationBundle:AccCostCentre', 'c');
$results = $qb->getQuery()->getArrayResult();
return new JsonResponse([
'success' => true,
'data' => $results
]);
}
public function GetExpenseType()
{
$em = $this->getDoctrine()->getManager();
// Fetch Sales Orders
$qb = $em->createQueryBuilder();
$qb->select(
's.salesOrderId',
's.documentHash',
'c.clientName',
'p.projectId',
'p.projectName'
)
->from('ApplicationBundle:SalesOrder', 's')
->leftJoin('ApplicationBundle:AccClients', 'c', 'WITH', 's.clientId = c.clientId')
->leftJoin('ApplicationBundle:Project', 'p', 'WITH', 's.projectId = p.projectId')
->orderBy('s.salesOrderId', 'DESC');
$salesOrders = $qb->getQuery()->getArrayResult();
// Fetch Cost Centres
$qb2 = $em->createQueryBuilder();
$qb2->select('c.costCentreId', 'c.name')
->from('ApplicationBundle:AccCostCentre', 'c');
$costCentres = $qb2->getQuery()->getArrayResult();
// Build Expense Types
$types = [];
foreach (GeneralConstant::$expenseType as $id => $name) {
$types[] = [
'id' => $id,
'name' => $name,
'salesOrders' => $id === 2 ? $salesOrders : [],
'costCentres' => $id === 2 ? $costCentres : []
];
}
return new JsonResponse($types);
}
public function AddPayment(Request $request)
{
$details_ids = [];
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isSignatureOk($em, $loginId, $approveHash)) {
// $this->addFlash(
// 'error',
// 'Sorry Could Not insert Data.'
// );
return new JsonResponse(array(
"success" => false,
'errorText' => 'Approval Hash Mismatch',
'errorStr' => 'Approval Hash Mismatch'
));
} else {
// Generic::debugMessage($_POST);
$payment_type = $request->request->get('payment_type'); //1=supp, 2=employee 3=ac head
$payment_sub_type = $request->request->get('payment_sub_type'); //1=gen, 2=adv 3=loan
$payment_to = $request->request->get('payment_to_' . $payment_type);
$payment_to_note = $request->request->get('payment_to_note_' . $payment_type);
$payment_from = $request->request->get('payment_from');
$payment_from_note = $request->request->get('payment_from_note');
$description = $request->request->get('description');
$payment_amount = $request->request->get('payment_amount');
$invoice_balancing = $request->request->has('auto_balance' . $payment_type) ? $request->request->get('auto_balance' . $payment_type) : 0;
$em = $this->getDoctrine()->getManager();
$pi_list = [];
$po_list = [];
$ei_list = [];
$assignable = $payment_amount;
$general_amount = 0;
$advance_amount = 0;
$TransID = 0;
$check_here = [];
$id_list_for_check = [];
$id_for_check = '';
$details_ids = [];
$head_list = Accounts::HeadList($em);
$balancing_data = [];
$purchase_invoices = [];
// $to_assign=0;
//for supplier
if ($payment_type == 1) {
// $supplier_list = Accounts::SupplierListForPv($em);
$supp = $em->getRepository('ApplicationBundle\\Entity\\AccSuppliers')->findOneBy(array(
'supplierId' => $payment_to,
'status' => GeneralConstant::ACTIVE
));
$supplier_list = [];
$pa = array();
$pa['id'] = $supp->getSupplierId();
$pa['name'] = $supp->getSupplierName();
$pa['supplierShortCode'] = $supp->getSupplierShortCode();
$pa['supplier_head_id'] = $supp->getAccountsHeadId();
$pa['supplier_advance_head_id'] = $supp->getAdvanceHeadId();
$supplier_list[$supp->getSupplierId()] = $pa;
// $supplier_list = Accounts::SupplierListByAcHead($em, [$payment_to]);
$balancing_data = Accounts::GetPurchaseInvoiceBalancingData($em, [], [$supplier_list[$payment_to]['supplier_head_id']]);
$id_for_check = $supplier_list[$payment_to]['supplier_head_id'];
$purchase_invoices = $balancing_data['purchase_invoices'];
if (!empty($purchase_invoices))
foreach ($purchase_invoices[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
$pi_list['id'][] = $entry['purchase_invoice_id'];
$pi_list['aa'][] = $assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable;
$general_amount += ($assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable);
$assignable > $entry['due_amount'] ? ($assignable -= $entry['due_amount']) : ($assignable = 0);
}
$expense_invoices = $balancing_data['expense_invoices'];
if (!empty($expense_invoices))
foreach ($expense_invoices[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
$ei_list['id'][] = $entry['expense_invoice_id'];
$ei_list['ei_head_id'][] = $supplier_list[$payment_to]['supplier_head_id'];
$ei_list['aa'][] = $assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable;
$general_amount += ($assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable);
$assignable > $entry['due_amount'] ? ($assignable -= $entry['due_amount']) : ($assignable = 0);
}
$purchase_orders = $balancing_data['purchase_orders'];
if (!empty($purchase_orders))
foreach ($purchase_orders[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
$po_list['id'][] = $entry['purchase_order_id'];
$po_list['aa'][] = $assignable > $entry['po_amount'] ? $entry['po_amount'] : $assignable;
$advance_amount += ($assignable > $entry['po_amount'] ? $entry['po_amount'] : $assignable);
$assignable > $entry['po_amount'] ? ($assignable -= $entry['po_amount']) : ($assignable = 0);
}
$ledgerHeads = [$supplier_list[$payment_to]['supplier_head_id'], $payment_to];
$notes = [$payment_from_note, $payment_to_note];
$costCenters = [];
$drAmount = $payment_amount;
$crAmount = $payment_amount;
$notes = $request->request->get('trNote');
$check_allowed = 0;
// $provisional=0;
if ($request->request->get('check_id') != '')
$check_allowed = 1;
// if($request->request->has('provisional'))
$provisional = 1;
$TransID = Accounts::CreateNewTransaction(
0,
$this->getDoctrine()->getManager(),
$request->request->get('payment_date'),
$payment_amount,
AccountsConstant::VOUCHER_PAYMENT,
$description,
'DV/GN/1/' . Accounts::GetVNoHash($em, 'dv', 'gn', 1),
'DV',
'GN',
1,
Accounts::GetVNoHash($em, 'dv', 'gn', 1),
$check_allowed,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request),
'',
$provisional
);
$check_here = [];
// $id_list_for_check=[];
// $id_list_for_check[$supplier_list[$payment_to]['supplier_head_id']]=$supplier_list[$payment_to]['supplier_head_id'];
if ($general_amount > 0) {
$details_ids[$supplier_list[$payment_to]['supplier_head_id']] = Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('payment_date'),
$TransID,
Generic::CurrToInt($general_amount),
$supplier_list[$payment_to]['supplier_head_id'],
$payment_to_note,
AccountsConstant::DEBIT,
0,
array($pi_list, $po_list, $ei_list),
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$provisional
);
}
if ($advance_amount > 0) {
// $id_list_for_check[$supplier_list[$payment_to]['supplier_advance_head_id']]=$supplier_list[$payment_to]['supplier_head_id'];
$details_ids[$supplier_list[$payment_to]['supplier_advance_head_id']] = Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('payment_date'),
$TransID,
Generic::CurrToInt($advance_amount),
$supplier_list[$payment_to]['supplier_advance_head_id'],
$payment_to_note . ' As Advance',
AccountsConstant::DEBIT,
0,
array($pi_list, $po_list, $ei_list),
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$provisional
);
}
$details_ids[$payment_from] = Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('payment_date'),
$TransID,
Generic::CurrToInt($payment_amount),
$payment_from,
$payment_from_note,
AccountsConstant::CREDIT,
0,
array($pi_list, $po_list, $ei_list),
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$provisional
);
}
if ($payment_type == 2) {
$id_for_check = $payment_to;
// if(isset($supplier_list[$payment_to])) {
// $balancing_data = Accounts::GetPurchaseInvoiceBalancingData($em, [], [$supplier_list[$payment_to]['supplier_head_id']]);
// $id_for_check = $supplier_list[$payment_to]['supplier_head_id'];
// $purchase_invoices = $balancing_data['purchase_invoices'];
//
// if (!empty($purchase_invoices))
// foreach ($purchase_invoices[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
// $pi_list['id'][] = $entry['purchase_invoice_id'];
// $pi_list['aa'][] = $assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable;
// $general_amount += ($assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable);
// $assignable > $entry['due_amount'] ? ($assignable -= $entry['due_amount']) : ($assignable = 0);
// }
// $expense_invoices = $balancing_data['expense_invoices'];
// if (!empty($expense_invoices))
// foreach ($expense_invoices[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
// $ei_list['id'][] = $entry['expense_invoice_id'];
// $ei_list['ei_head_id'][] = $supplier_list[$payment_to]['supplier_head_id'];
// $ei_list['aa'][] = $assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable;
// $general_amount += ($assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable);
// $assignable > $entry['due_amount'] ? ($assignable -= $entry['due_amount']) : ($assignable = 0);
// }
// $purchase_orders = $balancing_data['purchase_orders'];
// if (!empty($purchase_orders))
// foreach ($purchase_orders[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
// $po_list['id'][] = $entry['purchase_order_id'];
// $po_list['aa'][] = $assignable > $entry['po_amount'] ? $entry['po_amount'] : $assignable;
// $advance_amount += ($assignable > $entry['po_amount'] ? $entry['po_amount'] : $assignable);
// $assignable > $entry['po_amount'] ? ($assignable -= $entry['po_amount']) : ($assignable = 0);
// }
// }
$check_allowed = 0;
// $provisional=0;
if ($request->request->get('check_id') != '')
$check_allowed = 1;
// if($request->request->has('provisional'))
$provisional = 1;
$TransID = Accounts::CreateNewTransaction(
0,
$this->getDoctrine()->getManager(),
$request->request->get('payment_date'),
$payment_amount,
AccountsConstant::VOUCHER_PAYMENT,
$description,
'DV/GN/1/' . Accounts::GetVNoHash($em, 'dv', 'gn', 1),
'DV',
'GN',
1,
Accounts::GetVNoHash($em, 'dv', 'gn', 1),
$check_allowed,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request),
'',
$provisional
);
$check_here = [];
// $id_list_for_check=[];
// $id_list_for_check[$supplier_list[$payment_to]['supplier_head_id']]=$supplier_list[$payment_to]['supplier_head_id'];
$details_ids[$payment_to] = Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('payment_date'),
$TransID,
Generic::CurrToInt($payment_amount),
$payment_to,
$payment_to_note,
AccountsConstant::DEBIT,
0,
array($pi_list, $po_list, $ei_list),
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$provisional
);
$details_ids[$payment_from] = Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('payment_date'),
$TransID,
Generic::CurrToInt($payment_amount),
$payment_from,
$payment_from_note,
AccountsConstant::CREDIT,
0,
array($pi_list, $po_list, $ei_list),
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$provisional
);
}
if ($payment_type == 3) {
$id_for_check = $payment_to;
$supplier_list = Accounts::SupplierListForPv($em);
// if(isset($supplier_list[$payment_to])) {
// $balancing_data = Accounts::GetPurchaseInvoiceBalancingData($em, [], [$supplier_list[$payment_to]['supplier_head_id']]);
// $id_for_check = $supplier_list[$payment_to]['supplier_head_id'];
// $purchase_invoices = $balancing_data['purchase_invoices'];
//
// if (!empty($purchase_invoices))
// foreach ($purchase_invoices[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
// $pi_list['id'][] = $entry['purchase_invoice_id'];
// $pi_list['aa'][] = $assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable;
// $general_amount += ($assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable);
// $assignable > $entry['due_amount'] ? ($assignable -= $entry['due_amount']) : ($assignable = 0);
// }
// $expense_invoices = $balancing_data['expense_invoices'];
// if (!empty($expense_invoices))
// foreach ($expense_invoices[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
// $ei_list['id'][] = $entry['expense_invoice_id'];
// $ei_list['ei_head_id'][] = $supplier_list[$payment_to]['supplier_head_id'];
// $ei_list['aa'][] = $assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable;
// $general_amount += ($assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable);
// $assignable > $entry['due_amount'] ? ($assignable -= $entry['due_amount']) : ($assignable = 0);
// }
// $purchase_orders = $balancing_data['purchase_orders'];
// if (!empty($purchase_orders))
// foreach ($purchase_orders[$supplier_list[$payment_to]['supplier_head_id']] as $entry) {
// $po_list['id'][] = $entry['purchase_order_id'];
// $po_list['aa'][] = $assignable > $entry['po_amount'] ? $entry['po_amount'] : $assignable;
// $advance_amount += ($assignable > $entry['po_amount'] ? $entry['po_amount'] : $assignable);
// $assignable > $entry['po_amount'] ? ($assignable -= $entry['po_amount']) : ($assignable = 0);
// }
// }
$check_allowed = 0;
// $provisional=0;
if ($request->request->get('check_id') != '')
$check_allowed = 1;
// if($request->request->has('provisional'))
$provisional = 1;
$TransID = Accounts::CreateNewTransaction(
0,
$this->getDoctrine()->getManager(),
$request->request->get('payment_date'),
$payment_amount,
AccountsConstant::VOUCHER_PAYMENT,
$description,
'DV/GN/1/' . Accounts::GetVNoHash($em, 'dv', 'gn', 1),
'DV',
'GN',
1,
Accounts::GetVNoHash($em, 'dv', 'gn', 1),
$check_allowed,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request),
'',
$provisional
);
$check_here = [];
// $id_list_for_check=[];
// $id_list_for_check[$supplier_list[$payment_to]['supplier_head_id']]=$supplier_list[$payment_to]['supplier_head_id'];
$details_ids[$payment_to] = Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('payment_date'),
$TransID,
Generic::CurrToInt($payment_amount),
$payment_to,
$payment_to_note,
AccountsConstant::DEBIT,
0,
array($pi_list, $po_list, $ei_list),
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$provisional
);
$details_ids[$payment_from] = Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('payment_date'),
$TransID,
Generic::CurrToInt($payment_amount),
$payment_from,
$payment_from_note,
AccountsConstant::CREDIT,
0,
array($pi_list, $po_list, $ei_list),
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$provisional
);
}
if ($request->request->has('check_id')) {
$check_here = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccCheck')
->findOneBy(
array(
'CheckId' => $request->request->get('check_id')
)
);
if ($check_here) {
$check_here->setRecAccountsHeadId($id_for_check);
$check_here->setRecAccountsHeadIdList(json_encode([$id_for_check]));
$check_here->setCheckNarration(empty($request->request->get('check_narration')) ? $head_list[$id_for_check]['name'] : $request->request->get('check_narration'));
$check_here->setCheckAmount($payment_amount);
$check_here->setCheckDate(new \DateTime($request->request->get('check_date')));
$check_here->setAssigned(1);
$check_here->setVoucherId($TransID);
}
}
//approval system
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
Accounts::UpdatePurchasePayments($em, $pi_list, $po_list, $details_ids, $request->request->get('payment_date'), $payment_to);
Accounts::UpdateExpensePayments($em, $ei_list, $details_ids, $request->request->get('payment_date'));
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
[],
array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
$TransID,
$loginId,
5 //payment voucher
);
System::createEditSignatureHash(
$em,
array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
$TransID,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
// $this->addFlash(
// 'success',
// 'New Transaction Added.'
// );
$url = $this->generateUrl(
'view_voucher'
);
$trans_here = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccTransactions')
->findOneBy(
array(
'transactionId' => $TransID
)
);
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),
"Debit Voucher : " . $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
'pos',
System::getPositionIdsByDepartment($em, GeneralConstant::ACCOUNTS_DEPARTMENT),
'success',
$url . "/" . $TransID,
"Debit Voucher"
);
return new JsonResponse(array(
"success" => true,
'docId' => $TransID,
'docHash' => $trans_here->getDocumentHash(),
));
}
}
return new JsonResponse(array("success" => true));
}
public function AddReceipt(Request $request)
{
$details_ids = [];
$em = $this->getDoctrine()->getManager();
$docId = 0;
$docHash = 0;
$companyId = $this->getLoggedUserCompanyId($request);
if ($request->isMethod('POST')) {
$balancing_data = [];
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isSignatureOk($em, $loginId, $approveHash)) {
// $this->addFlash(
// 'error',
// 'Sorry Could Not insert Data.'
// );
return new JsonResponse(array(
"success" => false,
'errorText' => 'Approval Hash Mismatch',
'errorStr' => 'Approval Hash Mismatch'
));
} else {
// Generic::debugMessage($_POST);
// $em->getRepository('ApplicationBundle\\Entity\\AccService')->findAll();
$receipt_type = $request->request->get('receipt_type'); //1=client, 2=employee 3=ac head
$receipt_sub_type = $request->request->get('receipt_sub_type'); //1=gen, 2=adv 3=loan
$receipt_from = $request->request->get('receipt_from_' . $receipt_type);
$receipt_from_note = $request->request->get('receipt_from_note_' . $receipt_type);
$receipt_to = $request->request->get('receipt_to');
$receipt_to_note = $request->request->get('receipt_to_note');
$description = $request->request->get('description');
$receipt_amount = $request->request->get('receipt_amount');
$receipt_charge_amount = (1 * $request->request->get('receipt_charge_amount'));
$receipt_charge_head = $request->request->get('receipt_charge_head');
$receipt_charge_note = $request->request->get('receipt_charge_note');
$receipt_deposit_amount = (1 * $request->request->get('receipt_deposit_amount'));
// $em->getRepository('ApplicationBundle\\Entity\\AccService')->findAll();
// $receipt_deposit_head = $request->request->get('receipt_deposit_head');
if ($receipt_charge_amount > 0 && $receipt_charge_head == '')
return new JsonResponse(array("success" => false));
if ($receipt_charge_amount + $receipt_deposit_amount != $receipt_amount)
return new JsonResponse(array("success" => false));
$invoice_balancing = $request->request->has('auto_balance' . $receipt_type) ? $request->request->get('auto_balance' . $receipt_type) : 0;
$em = $this->getDoctrine()->getManager();
$si_list = [];
$so_list = [];
$ei_list = [];
$assignable = $receipt_amount;
$general_amount = 0;
$advance_amount = 0;
$TransID = 0;
$check_here = [];
$id_list_for_check = [];
$id_for_check = '';
$details_ids = [];
$head_list = Accounts::HeadList($em);
$client_list = Client::GetExistingClientList($em, $companyId);
// $clnt = $client_list[$receipt_from];
// $to_assign=0;
//for client
if ($receipt_type == 1) {
$clnt = $client_list[$receipt_from];
//now check if special case like came form SO
$balancing_data = Accounts::GetSalesInvoiceBalancingData(
$em,
[],
[$client_list[$receipt_from]['accHeadId']],
$request->request->get('AddReceiptModalSpecialType'),
[$request->request->get('AddReceiptModalSpecialTypeSoDocId')],
[$request->request->get('AddReceiptModalSpecialTypeSiDocId')]
);
$id_for_check = $client_list[$receipt_from]['accHeadId'];
$sales_invoices = $balancing_data['sales_invoices'];
if (!empty($sales_invoices))
foreach ($sales_invoices[$client_list[$receipt_from]['accHeadId']] as $entry) {
$si_list['id'][] = $entry['sales_invoice_id'];
$si_list['aa'][] = $assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable;
$general_amount += ($assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable);
$assignable > $entry['due_amount'] ? ($assignable -= $entry['due_amount']) : ($assignable = 0);
}
$expense_invoices = $balancing_data['expense_invoices'];
if (!empty($expense_invoices))
foreach ($expense_invoices[$client_list[$receipt_from]['accHeadId']] as $entry) {
$ei_list['id'][] = $entry['expense_invoice_id'];
$ei_list['ei_head_id'][] = $client_list[$receipt_from]['accHeadId'];
$ei_list['aa'][] = $assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable;
$general_amount += ($assignable > $entry['due_amount'] ? $entry['due_amount'] : $assignable);
$assignable > $entry['due_amount'] ? ($assignable -= $entry['due_amount']) : ($assignable = 0);
}
$sales_orders = $balancing_data['sales_orders'];
if (!empty($sales_orders))
foreach ($sales_orders[$client_list[$receipt_from]['accHeadId']] as $entry) {
$so_list['id'][] = $entry['sales_order_id'];
$so_list['aa'][] = $assignable > $entry['so_amount'] ? $entry['so_amount'] : $assignable;
$advance_amount += ($assignable > $entry['so_amount'] ? $entry['so_amount'] : $assignable);
$assignable > $entry['so_amount'] ? ($assignable -= $entry['so_amount']) : ($assignable = 0);
}
$ledgerHeads = [$client_list[$receipt_from]['accHeadId'], $receipt_from];
$notes = [$receipt_to_note, $receipt_from_note];
$costCenters = [];
$drAmount = $receipt_amount;
$crAmount = $receipt_amount;
$notes = $request->request->get('trNote');
$check_allowed = 0;
// $provisional=0;
if ($request->request->get('check_id') != '')
$check_allowed = 1;
// if($request->request->has('provisional'))
$provisional = 1;
$TransID = Accounts::CreateNewTransaction(
0,
$this->getDoctrine()->getManager(),
$request->request->get('receipt_date'),
$receipt_amount,
AccountsConstant::VOUCHER_RECEIPT,
$description,
'CV/GN/1/' . Accounts::GetVNoHash($em, 'CV', 'GN', 1),
'CV',
'GN',
1,
Accounts::GetVNoHash($em, 'CV', 'GN', 1),
$check_allowed,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request),
'',
$provisional,
0,
0,
'',
$request->request->get('branchId', 0),
'_UNSET_',
'_UNSET_',
0,
'',
$request->request->get('uploaded_image_path', '')
);
$check_here = [];
// $id_list_for_check=[];
// $id_list_for_check[$client_list[$receipt_from]['supplier_head_id']]=$client_list[$receipt_from]['supplier_head_id'];
if ($general_amount > 0) {
$details_ids[$client_list[$receipt_from]['accHeadId']] = Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('receipt_date'),
$TransID,
Generic::CurrToInt($general_amount),
$client_list[$receipt_from]['accHeadId'],
$receipt_from_note,
AccountsConstant::CREDIT,
0,
array($si_list, $so_list, $ei_list),
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$provisional
);
}
if ($advance_amount > 0) {
// $id_list_for_check[$client_list[$receipt_from]['supplier_advance_head_id']]=$client_list[$receipt_from]['supplier_head_id'];
$details_ids[$client_list[$receipt_from]['advanceHeadId']] = Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('receipt_date'),
$TransID,
Generic::CurrToInt($advance_amount),
$client_list[$receipt_from]['advanceHeadId'],
$receipt_from_note . ' As Advance',
AccountsConstant::CREDIT,
0,
array($si_list, $so_list, $ei_list),
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$provisional
);
}
$details_ids[$receipt_to] = Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('receipt_date'),
$TransID,
Generic::CurrToInt($receipt_deposit_amount),
$receipt_to,
$receipt_to_note,
AccountsConstant::DEBIT,
0,
array($si_list, $so_list, $ei_list),
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$provisional
);
if ($receipt_charge_amount != 0) {
$details_ids[$receipt_to] = Accounts::CreateNewTransactionDetails(
$this->getDoctrine()->getManager(),
$request->request->get('receipt_date'),
$TransID,
Generic::CurrToInt($receipt_charge_amount),
$receipt_charge_head,
$receipt_charge_note,
AccountsConstant::DEBIT,
0,
array($si_list, $so_list, $ei_list),
[],
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$provisional
);
}
}
//now check if the head is bank head if so add a check entry
$bank_settings = $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
'name' => 'bank_parents'
));
$under_bank = 0;
$bank_id_list = [];
if ($bank_settings)
$bank_id_list = json_decode($bank_settings->getData());
$the_head = $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findOneBy(array('accountsHeadId' => $receipt_to));
if ($the_head) {
$path_tree_list = explode('/', $the_head->getPathTree());
foreach ($path_tree_list as $pt) {
if (in_array($pt, $bank_id_list)) {
$under_bank = 1;
}
}
}
if ($under_bank == 1) {
// foreach($request->request->get('check_id') as $k=>$value)
// {
$check_here = new AccCheck();
$check_here->setRecAccountsHeadId($receipt_to);
$check_here->setRecAccountsHeadIdList(json_encode([$receipt_to]));
$check_here->setAccountsHeadId($client_list[$receipt_from]['accHeadId']);
// $check_here->setCheckNarration($request->request->get('check_narration')[$k]);
$check_here->setCheckAmount($receipt_amount);
$check_here->setCheckDate(new \DateTime($request->request->get('receipt_date')));
$check_here->setTransactionDate(new \DateTime($request->request->get('receipt_date')));
// $check_here->setCheckDate(new \DateTime($request->request->get('date')));
$check_here->setAssigned(1);
$check_here->setActive(1);
$check_here->setDetails('');
$check_here->setCheckNumber($request->request->get('receipt_check_number'));
$check_here->setStatus(3);
$check_here->setType(2); //receipt check
$check_here->setVoucherId($TransID);
// }
$em->persist($check_here);
$em->flush();
}
//approval system
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
Accounts::UpdateSalesPayments($em, $si_list, $so_list, $details_ids, $request->request->get('receipt_date'), $receipt_from);
// Accounts::UpdateExpenseReceipts($em,$ei_list,$details_ids, $request->request->get('receipt_date'));
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
[],
array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
$TransID,
$loginId,
6 //receipt voucher
);
System::createEditSignatureHash(
$em,
array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
$TransID,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
// $this->addFlash(
// 'success',
// 'New Transaction Added.'
// );
$url = $this->generateUrl(
'view_voucher'
);
$trans_here = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccTransactions')
->findOneBy(
array(
'transactionId' => $TransID
)
);
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),
"Debit Voucher : " . $trans_here->getDocumentHash() . " Has Been Created And is Under Processing",
'pos',
System::getPositionIdsByDepartment($em, GeneralConstant::ACCOUNTS_DEPARTMENT),
'success',
$url . "/" . $TransID,
"Debit Voucher"
);
return new JsonResponse(array(
'success' => true,
'transactionId' => $TransID,
'docId' => $TransID,
'docHash' => $trans_here->getDocumentHash(),
'balancing_data' => $balancing_data,
'clnt' => $clnt,
'general_amount' => $general_amount,
'advance_amount' => $advance_amount,
'assignable' => $assignable,
));
}
}
return new JsonResponse(array(
'success' => false,
'transactionId' => 0,
'balancing_data' => [],
'clnt' => 0,
'general_amount' => 0,
'advance_amount' => 0,
'assignable' => 0,
));
}
public function GetChildHeadsByMarkerHash(Request $request, $queryStr = '')
{
$em = $this->getDoctrine()->getManager();
$dataList = [];
$data_by_id = [];
$lastChildrenOnly = $request->request->has('lastChildrenOnly') ? $request->request->get('lastChildrenOnly') : 0;
$renderTextFormat = $request->request->has('renderTextFormat') ? $request->request->get('renderTextFormat') : '';
$valueField = $request->request->has('valueField') ? $request->request->get('valueField') : 'accounts_head_id';
$textField = $request->request->has('textField') ? $request->request->get('textField') : 'name';
$parentOnly = $request->request->has('parentOnly') ? $request->request->get('parentOnly') : 0;
$queryText = $request->request->get('query', '_EMPTY_');
$itemLimit = $request->request->get('itemLimit', 25);
$offset = $request->request->get('offset', 0);
$isMultiple = $request->request->get('isMultiple', 0);
$selectorId = $request->request->get('selectorId', '');
$dataId = $request->request->get('dataId', '');
$joinTableData = $request->request->has('joinTableData') ? $request->request->get('joinTableData') : [];
if (is_string($joinTableData)) $joinTableData = json_decode($joinTableData, true);
$setValueArray = [];
$setValue = 0;
$selectedId = 0;
$selectAll = 0;
$table = 'acc_accounts_head';
if (!(strpos($queryText, '#setValue:') === false)) {
$setValueArrayBeforeFilter = explode(',', str_replace('#setValue:', '', $queryText));
foreach ($setValueArrayBeforeFilter as $svf) {
if ($svf == '_ALL_') {
$selectAll = 1;
$setValueArray = [];
continue;
}
if (is_numeric($svf)) {
$setValueArray[] = ($svf * 1);
$setValue = $svf * 1;
}
}
$queryText = '_EMPTY_';
$marker_hash_list = ['_ALL_'];
} else
$marker_hash_list = explode(',', $request->request->get('marker_hash', ''));
if (!empty($marker_hash_list)) {
$markerHashLikeStr = '';
$first_item = 1;
$skipMarkerHash = 0;
foreach ($marker_hash_list as $marker_hash) {
if ($first_item == 0) $markerHashLikeStr .= " or ";
if ($marker_hash == '_ALL_') {
$skipMarkerHash = 1;
continue;
} else
$markerHashLikeStr .= "acc_accounts_head.marker_hash like '%$marker_hash%' ";
$first_item = 0;
}
$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
cross join acc_accounts_head acc_accounts_head_0 on `acc_accounts_head_0`.`accounts_head_id` = `acc_accounts_head`.`parent_id`
";
if ($skipMarkerHash == 1) {
$markerHashQuery = "SELECT acc_accounts_head.* , acc_accounts_head_0.name parent_table_name FROM acc_accounts_head
cross join acc_accounts_head acc_accounts_head_0 on `acc_accounts_head_0`.`accounts_head_id` = `acc_accounts_head`.`parent_id`
";
if ($lastChildrenOnly == 1) {
$markerHashQuery .= "WHERE acc_accounts_head.accounts_head_id not in (select distinct parent_id from acc_accounts_head) ";
} else if ($parentOnly == 1) {
$markerHashQuery .= "WHERE acc_accounts_head.accounts_head_id in (select distinct parent_id from acc_accounts_head) ";
} else
$markerHashQuery .= "WHERE 1=1 ";
// $markerHashQuery .= "WHERE acc_accounts_head.accounts_head_id not in (select distinct parent_id from acc_accounts_head) ";
if ($queryText != '_EMPTY_') {
$markerHashQuery .= " AND (";
if (is_numeric($queryText)) {
$markerHashQuery .= (" acc_accounts_head.accounts_head_id = " . $queryText . " ");
} else {
$queryTextArray = explode(',', $queryText);
$addOn = '';
foreach ($queryTextArray as $dd) {
$markerHashQuery .= ($addOn . " acc_accounts_head.name like '%" . $dd . "%' ");
$addOn = ' or ';
}
}
$markerHashQuery .= " ) ";
}
if (!empty($setValueArray) || $selectAll == 1) {
if (!empty($setValueArray)) {
if ($markerHashQuery != '')
$markerHashQuery .= " and ";
$markerHashQuery .= " acc_accounts_head.accounts_head_id in (" . implode(',', $setValueArray) . ") ";
}
}
if ($itemLimit != '_ALL_')
$markerHashQuery .= " limit $offset, $itemLimit ";
else
$markerHashQuery .= " limit $offset, 18446744073709551615 ";
$markerHashQuery .= " ;";
$stmt = $em->getConnection()->fetchAllAssociative($markerHashQuery);
$markerHashQueryResults = $stmt;
foreach ($markerHashQueryResults as $markerHashQueryResult) {
$markerHashQueryResult['value'] = $markerHashQueryResult['accounts_head_id'];
$markerHashQueryResult['text'] = $markerHashQueryResult['name'];
$markerHashQueryResult['id_value'] = '# ' . $markerHashQueryResult['accounts_head_id'] . ' ' . $markerHashQueryResult['name'];
$renderedText = $renderTextFormat;
$compare_array = [];
if ($renderTextFormat != '') {
$renderedText = $renderTextFormat;
$compare_arrayFull = [];
$compare_array = [];
$toBeReplacedData = array( // 'curr'=>'tobereplaced'
);
preg_match_all("/__\w+__/", $renderedText, $compare_arrayFull);
if (isset($compare_arrayFull[0]))
$compare_array = $compare_arrayFull[0];
// $compare_array= preg_split("/__\w+__/",$renderedText);
foreach ($compare_array as $cmpdt) {
$tbr = str_replace("__", "", $cmpdt);
if ($tbr != '') {
if (isset($markerHashQueryResult[$tbr])) {
if ($markerHashQueryResult[$tbr] == null)
$renderedText = str_replace($cmpdt, '', $renderedText);
else
$renderedText = str_replace($cmpdt, $markerHashQueryResult[$tbr], $renderedText);
} else {
$renderedText = str_replace($cmpdt, '', $renderedText);
}
}
}
}
$markerHashQueryResult['rendered_text'] = $renderedText;
$markerHashQueryResult['text'] = ($textField != '' ? $markerHashQueryResult[$textField] : '');
$dataList[] = $markerHashQueryResult;
if ($valueField != '') {
$data_by_id[$markerHashQueryResult[$valueField]] = $markerHashQueryResult;
$selectedId = $markerHashQueryResult[$valueField];
}
}
} else {
$markerHashQuery .= "WHERE ( $markerHashLikeStr );";
$stmt = $em->getConnection()->fetchAllAssociative($markerHashQuery);
$markerHashQueryResults = $stmt;
$hids = [];
foreach ($markerHashQueryResults as $h) {
$hids[] = $h['accounts_head_id'];
}
$markerHashLikeStr = '';
if (!empty($hids))
$markerHashLikeStr = 'accounts_head_id in (' . implode(',', $hids) . ') ';
foreach ($markerHashQueryResults as $h) {
$markerHashLikeStr .= "OR path_tree LIKE '%/" . $h['accounts_head_id'] . "/%' ";
}
if ($markerHashLikeStr != '') {
$markerHashQuery = "SELECT acc_accounts_head.* FROM acc_accounts_head ";
// $markerHashQuery .= "WHERE acc_accounts_head.accounts_head_id not in (select distinct parent_id from acc_accounts_head) and ( $markerHashLikeStr )";
if ($lastChildrenOnly == 1) {
$markerHashQuery .= "WHERE acc_accounts_head.accounts_head_id not in (select distinct parent_id from acc_accounts_head) and ( $markerHashLikeStr )";
} else if ($parentOnly == 1) {
$markerHashQuery .= "WHERE acc_accounts_head.accounts_head_id in (select distinct parent_id from acc_accounts_head) and ( $markerHashLikeStr )";
} else
$markerHashQuery .= "WHERE ( $markerHashLikeStr )";
if ($queryText != '_EMPTY_') {
$markerHashQuery .= " AND (";
if (is_numeric($queryText)) {
$markerHashQuery .= (" acc_accounts_head.accounts_head_id = " . $queryText . " ");
} else {
$queryTextArray = explode(',', $queryText);
$addOn = '';
foreach ($queryTextArray as $dd) {
$markerHashQuery .= ($addOn . " acc_accounts_head.name like '%" . $dd . "%' ");
$addOn = ' or ';
}
}
$markerHashQuery .= " ) ";
}
if ($itemLimit != '_ALL_')
$markerHashQuery .= " limit $offset, $itemLimit ";
else
$markerHashQuery .= " limit $offset, 18446744073709551615 ";
$markerHashQuery .= " ;";
$stmt = $em->getConnection()->fetchAllAssociative($markerHashQuery);
$markerHashQueryResults = $stmt;
foreach ($markerHashQueryResults as $markerHashQueryResult) {
$markerHashQueryResult['value'] = $markerHashQueryResult['accounts_head_id'];
$markerHashQueryResult['text'] = $markerHashQueryResult['name'];
$markerHashQueryResult['id_value'] = '# ' . $markerHashQueryResult['accounts_head_id'] . ' ' . $markerHashQueryResult['name'];
$renderedText = $renderTextFormat;
$compare_array = [];
if ($renderTextFormat != '') {
$renderedText = $renderTextFormat;
$compare_arrayFull = [];
$compare_array = [];
$toBeReplacedData = array( // 'curr'=>'tobereplaced'
);
preg_match_all("/__\w+__/", $renderedText, $compare_arrayFull);
if (isset($compare_arrayFull[0]))
$compare_array = $compare_arrayFull[0];
// $compare_array= preg_split("/__\w+__/",$renderedText);
foreach ($compare_array as $cmpdt) {
$tbr = str_replace("__", "", $cmpdt);
if ($tbr != '') {
if (isset($markerHashQueryResult[$tbr])) {
if ($markerHashQueryResult[$tbr] == null)
$renderedText = str_replace($cmpdt, '', $renderedText);
else
$renderedText = str_replace($cmpdt, $markerHashQueryResult[$tbr], $renderedText);
} else {
$renderedText = str_replace($cmpdt, '', $renderedText);
}
}
}
}
$markerHashQueryResult['rendered_text'] = $renderedText;
$markerHashQueryResult['text'] = ($textField != '' ? $markerHashQueryResult[$textField] : '');
$dataList[] = $markerHashQueryResult;
if ($valueField != '') {
$data_by_id[$markerHashQueryResult[$valueField]] = $markerHashQueryResult;
$selectedId = $markerHashQueryResult[$valueField];
}
}
}
}
}
return new JsonResponse(array(
'success' => empty($dataList) ? false : true,
'tableName' => $table,
'setValue' => $setValue,
'currentTs' => (new \Datetime())->format('U'),
'dataList' => $dataList,
'data' => $dataList,
'dataById' => $data_by_id,
'isMultiple' => $isMultiple,
'selectorId' => $selectorId,
'setValueArray' => $setValueArray,
'queryStr' => $queryStr,
// 'andStr' => $andString,
// 'andOrStr' => $andOrString,
'selectedId' => $selectedId,
'dataId' => $dataId,
));
}
public function CreatePaymentRequisitionVoucher(Request $request)
{
$em = $this->getDoctrine()->getManager();
$new_cc = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\SalesInvoice')
->findBy(
array(
'approved' => 1,
'voucherIds' => null
)
);
foreach ($new_cc as $d) {
ApprovalFunction::SalesInvoice($em, $d->getSalesInvoiceId());
}
return $this->render(
'@Accounts/pages/input_forms/payment_requisition.html.twig',
array(
'page_title' => 'Create Contra Voucher'
)
);
}
public function ViewBalanceSheet(Request $request)
{
$em = $this->getDoctrine()->getManager();
$company_data = Company::getCompanyData($em, $this->getLoggedUserCompanyId($request));
$start_date = ($request->query->has('start_date')) ? $request->query->get('start_date') : "";
$end_date = ($request->query->has('end_date')) ? $request->query->get('end_date') : "";
// $end_date="";
$em = $this->getDoctrine()->getManager();
// $child_list=Accounts::LedgerDetails($em,2,$start_date, $end_date);
$bs_details = Accounts::GetBsDetails($em, $start_date, $end_date);
$grouped_heads = Accounts::GroupedHeads($em);
// if($mis_start_date!=''&&$mis_start_date!=0)
// $start_date=$mis_start_date;
// if($mis_end_date!=''&&$mis_start_date!=0)
// $end_date=$mis_end_date;
return $this->render(
'@Accounts/pages/views/balance_sheet.html.twig',
array(
'page_title' => 'Balance Sheet',
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'details' => $bs_details
)
);
}
public function FiscalClosing(Request $request)
{
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
//now lets create new fiscal closing
// Accounts::FiscalClosing($em,$request->request->get('start_date'),$request->request->get('end_date'));
$new = new FiscalClosing();
$new->setClosingStartDate(new \DateTime($request->request->get('start_date')));
$new->setClosingEndDate(new \DateTime($request->request->get('end_date')));
$new->setClosingData(json_encode(array(
'heads' => $request->request->get('head_id'),
'balance' => $request->request->get('head_balance'),
'recon_balance' => $request->request->get('head_recon_balance')
)));
$new->setCompanyId($this->getLoggedUserCompanyId($request));
$new->setLedgerHit(0);
$new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
$em->persist($new);
$em->flush();
Accounts::DoFiscalClosing($em, $new->getClosingId());
// $new_cc = $this->getDoctrine()
// ->getRepository('ApplicationBundle\\Entity\\AccSettings')
// ->findOneBy(
// array(
// 'name' => 'accounting_year_start',
// )
// );
// $new_cc->setData($request->request->get('end_date'));
// $em->flush();
}
$company_data = Company::getCompanyData($em, $this->getLoggedUserCompanyId($request));
$new_cc = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccSettings')
->findOneBy(
array(
'name' => 'accounting_year_start',
// 'CompanyId'=>$this->getLoggedUserCompanyId($request)
)
);
$today = new \DateTime();
$start_date = $new_cc ? $new_cc->getData() : "";
// $start_date=($request->query->has('start_date'))?$request->query->get('start_date'):"";
$end_date = ($request->query->has('end_date')) ? $request->query->get('end_date') : $today->format('F d, Y');
// $end_date="";
$em = $this->getDoctrine()->getManager();
$url = $this->generateUrl('view_ledger_head', array(), true);
// $child_list=Accounts::LedgerDetails($em,2,$start_date, $end_date);
$details = Accounts::GetFiscalClosing($em, 1, $start_date, $end_date, $url);
$grouped_heads = Accounts::GroupedHeads($em);
// if($mis_start_date!=''&&$mis_start_date!=0)
// $start_date=$mis_start_date;
// if($mis_end_date!=''&&$mis_start_date!=0)
// $end_date=$mis_end_date;
return $this->render(
'@Application/pages/accounts/settings/fiscal_closing.html.twig',
array(
'page_title' => 'Fiscal Closing',
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'start_date' => $start_date,
'end_date' => $end_date,
'details' => $details
)
);
}
public function ViewTrialBalance(Request $request)
{
$em = $this->getDoctrine()->getManager();
$company_data = Company::getCompanyData($em, $this->getLoggedUserCompanyId($request));
$new_cc = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccSettings')
->findOneBy(
array(
'name' => 'accounting_year_start',
)
);
// $start_date = ($request->query->has('start_date')) ? $request->query->get('start_date') : ($new_cc ? $new_cc->getData() : "");
$start_date = ($request->query->has('start_date')) ? $request->query->get('start_date') : "";
$skip_parent_head = ($request->query->has('skip_parent_head')) ? $request->query->get('skip_parent_head') : 0;
$cur_level = ($request->query->has('level')) ? $request->query->get('level') : 1;
$expand_level = ($request->query->has('expand_level')) ? $request->query->get('expand_level') : 1;
$end_date = ($request->query->has('end_date')) ? $request->query->get('end_date') : (new \DateTime())->format('Y-m-d');
$em = $this->getDoctrine()->getManager();
$url = $this->generateUrl('view_ledger_head', array(), true);
// $child_list=Accounts::LedgerDetails($em,2,$start_date, $end_date);
$bs_details = [];
$get_kids_sql = "SELECT max(head_level) max_level FROM acc_accounts_head where 1 ";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
$max_level = isset($query_output[0]['max_level']) ? $query_output[0]['max_level'] : 1;
$budgetVarianceSettings = [];
$budgetEnabled = 0;
$budgetEnabled = 0;
$budgetVarianceSettings = [];
$allocationSupportData = $this->getAllocationReportSupportData($em, $request);
$allocationFilters = $allocationSupportData['allocation_filters'];
if ($request->query->has('budget_variance_enabled')) {
$budgetVarianceSettings['enabled'] = $request->query->get('budget_variance_enabled');
$budgetEnabled = $request->query->get('budget_variance_enabled');
$budgetVarianceSettings['scale'] = ($request->query->has('scale_variance')) ? $request->query->get('scale_variance') : 1;
$budgetVarianceSettings['budgetId'] = ($request->query->has('budgetId')) ? $request->query->get('budgetId') : 1;
}
$tb_details = Accounts::GetTrialBalance($em, $cur_level, $start_date, $end_date, $url, [], $expand_level, 'view', $skip_parent_head, $budgetVarianceSettings, $request->get('forceShowTrans', 0), $allocationFilters);
// $grouped_heads=Accounts::GroupedHeads($em);
// if($mis_start_date!=''&&$mis_start_date!=0)
// $start_date=$mis_start_date;
// if($mis_end_date!=''&&$mis_start_date!=0)
// $end_date=$mis_end_date
return $this->render(
'@Accounts/pages/views/trial_balance.html.twig',
array(
'page_title' => 'Trial Balance',
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'details' => $bs_details,
'tb_details' => $tb_details,
'skip_parent_head' => $skip_parent_head,
'start_date' => $start_date,
'end_date' => $end_date,
'max_level' => $max_level,
'budget_variance_enabled' => $budgetEnabled,
'currBudgetList' => $em->getRepository('ApplicationBundle\\Entity\\FinancialBudget')->findBy(
array(
// 'budgetId'=>$id, ///material
'CompanyId' => $this->getLoggedUserCompanyId($request), ///material
)
),
'scale_variance' => ($request->query->has('scale_variance')) ? $request->query->get('scale_variance') : 0,
'budgetId' => ($request->query->has('budgetId')) ? $request->query->get('budgetId') : 0,
'expand_level' => $expand_level,
'cur_level' => $cur_level,
'allocation_filters' => $allocationFilters,
'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
'project_list' => $allocationSupportData['project_list'],
'branch_list' => $allocationSupportData['branch_list'],
'cost_centers' => $allocationSupportData['cost_centers'],
// 'end_date'=>new \DateTime(),
)
);
}
public function ViewTrialBalanceForApp(Request $request)
{
$em = $this->getDoctrine()->getManager();
$company_data = Company::getCompanyData($em, $this->getLoggedUserCompanyId($request));
$new_cc = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccSettings')
->findOneBy(
array(
'name' => 'accounting_year_start',
)
);
// $start_date = ($request->query->has('start_date')) ? $request->query->get('start_date') : ($new_cc ? $new_cc->getData() : "");
$start_date = ($request->query->has('start_date')) ? $request->query->get('start_date') : "";
$skip_parent_head = ($request->query->has('skip_parent_head')) ? $request->query->get('skip_parent_head') : 0;
$cur_level = ($request->query->has('level')) ? $request->query->get('level') : 1;
$expand_level = ($request->query->has('expand_level')) ? $request->query->get('expand_level') : 1;
$end_date = ($request->query->has('end_date')) ? $request->query->get('end_date') : (new \DateTime())->format('Y-m-d');
$em = $this->getDoctrine()->getManager();
$url = $this->generateUrl('view_ledger_head', array(), true);
// $child_list=Accounts::LedgerDetails($em,2,$start_date, $end_date);
$bs_details = [];
$get_kids_sql = "SELECT max(head_level) max_level FROM acc_accounts_head where 1 ";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
$max_level = isset($query_output[0]['max_level']) ? $query_output[0]['max_level'] : 1;
$budgetVarianceSettings = [];
$budgetEnabled = 0;
$budgetEnabled = 0;
$budgetVarianceSettings = [];
if ($request->query->has('budget_variance_enabled')) {
$budgetVarianceSettings['enabled'] = $request->query->get('budget_variance_enabled');
$budgetEnabled = $request->query->get('budget_variance_enabled');
$budgetVarianceSettings['scale'] = ($request->query->has('scale_variance')) ? $request->query->get('scale_variance') : 1;
$budgetVarianceSettings['budgetId'] = ($request->query->has('budgetId')) ? $request->query->get('budgetId') : 1;
}
$tb_details = Accounts::GetTrialBalance($em, $cur_level, $start_date, $end_date, $url, [], $expand_level, 'view', $skip_parent_head, $budgetVarianceSettings);
// $grouped_heads=Accounts::GroupedHeads($em);
// if($mis_start_date!=''&&$mis_start_date!=0)
// $start_date=$mis_start_date;
// if($mis_end_date!=''&&$mis_start_date!=0)
// $end_date=$mis_end_date
$heads_0 = isset($tb_details['heads'][0]) ? $tb_details['heads'][0] : [];
$calculated_values = [];
foreach ($heads_0 as $item) {
$name = $item['name'] ?? 'Unknown';
$head_balance = $item['head_data']['head_balance'] ?? 0;
$head_debit = $item['head_data']['head_debit'] ?? 0;
$head_credit = $item['head_data']['head_credit'] ?? 0;
$value = abs($head_debit - $head_credit);
$calculated_values[] = [
'tag' => $name,
'debit_credit' => round($value, 2),
'budget_variance' => 0
];
}
return new JsonResponse([
'page_title' => 'Trial Balance',
'calculated_values' => $calculated_values
]);
}
public function ViewFinancialReport(Request $request)
{
$em = $this->getDoctrine()->getManager();
$company_data = Company::getCompanyData($em, $this->getLoggedUserCompanyId($request));
$new_cc = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccSettings')
->findOneBy(
array(
'name' => 'accounting_year_start',
)
);
$start_date = $new_cc ? $new_cc->getData() : "";
$start_date = ($request->query->has('start_date')) ? $request->query->get('start_date') : ($new_cc ? $new_cc->getData() : "");
$cur_level = ($request->query->has('level')) ? $request->query->get('level') : 1;
$expand_level = ($request->query->has('expand_level')) ? $request->query->get('expand_level') : 3;
$end_date = ($request->query->has('end_date')) ? $request->query->get('end_date') : (new \DateTime())->format('F d, Y');
$em = $this->getDoctrine()->getManager();
$url = $this->generateUrl('view_ledger_head', array(), true);
// $child_list=Accounts::LedgerDetails($em,2,$start_date, $end_date);
$bs_details = [];
$get_kids_sql = "SELECT max(head_level) max_level FROM acc_accounts_head where 1 ";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
$max_level = isset($query_output[0]['max_level']) ? $query_output[0]['max_level'] : 1;
//*************Data generation start here
$report_cats = [1, 2, 3, 4];
$periodic = 0;
$last_entries_count = 1;
// if ($request->query->has('print_all')) {
// if ($request->query->get('print_all') == 1)
// $report_cats = [1, 2, 3, 4];
// } else {
// if ($request->query->has('statement'))
// $report_cats = $request->query->get('statement');
// }
if ($request->query->has('periodic'))
if ($request->query->get('periodic') == 1)
$periodic = 1;
if ($request->query->has('last_entries'))
$last_entries_count = $request->query->get('last_entries');
//lets get prev fiscal closing data
$new_cc_list = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\FiscalClosing')
->findBy(
array(),
array(
'closingId' => 'DESC'
),
$last_entries_count
);
$prev_data_list = array();
$prev_data_amounts = array();
$prev_data_amounts_for_is = array();
$prev_data_amounts_for_cf = array();
if (!empty($new_cc_list)) {
$prev_data = array();
foreach ($new_cc_list as $new_cc) {
$prev_data['closing_start_date'] = $new_cc->getClosingStartDate();
$prev_data['closing_end_date'] = $new_cc->getClosingEndDate();
$prev_data['closing_data'] = array();
$last_f_c_data = json_decode($new_cc->getClosingData(), true);
// foreach ($last_f_c_data['heads'] as $key => $entry) {
// $add_data = array(
// 'head_id' => $entry,
// 'balance' => $last_f_c_data['balance'][$key],
// 'recon_balance' => $last_f_c_data['recon_balance'][$key]
// );
// $prev_data['closing_data'][$entry] = $add_data;
// $prev_data_amounts[$entry][]= $last_f_c_data['balance'][$key];
// }
foreach ($last_f_c_data as $key => $entry) {
$add_data = array(
'head_id' => $key,
'balance' => $entry,
'recon_balance' => $entry
);
$prev_data['closing_data'][$key] = $add_data;
$prev_data_amounts[$key][] = $entry;
}
$prev_data_list[] = $prev_data;
}
}
if (!empty($new_cc_list)) {
$prev_data = array();
foreach ($new_cc_list as $new_cc) {
$prev_data['closing_start_date'] = $new_cc->getClosingStartDate();
$prev_data['closing_end_date'] = $new_cc->getClosingEndDate();
$prev_data['closing_data'] = array();
$last_f_c_data = json_decode($new_cc->getBeforeClosingData(), true);
if ($last_f_c_data == null) $last_f_c_data = [];
// foreach ($last_f_c_data['heads'] as $key => $entry) {
// $add_data = array(
// 'head_id' => $entry,
// 'balance' => $last_f_c_data['balance'][$key],
// 'recon_balance' => $last_f_c_data['recon_balance'][$key]
// );
// $prev_data['closing_data'][$entry] = $add_data;
// $prev_data_amounts[$entry][]= $last_f_c_data['balance'][$key];
// }
foreach ($last_f_c_data as $key => $entry) {
$add_data = array(
'head_id' => $key,
'balance' => $entry,
'recon_balance' => $entry
);
$prev_data['closing_data'][$key] = $add_data;
$prev_data_amounts_for_is[$key][] = $entry;
}
// $prev_data_list[]=$prev_data;
}
}
$balance_sheet_data = [];
$is_data = [];
$cf_data = [];
$oe_data = [];
$wacc_data = [];
$allocationSupportData = $this->getAllocationReportSupportData($em, $request);
$allocationFilters = $allocationSupportData['allocation_filters'];
//now get balance sheet if needed
if (in_array(1, $report_cats)) {
$balance_sheet_data = Accounts::GetBalanceSheet($em, $cur_level, $start_date, $end_date, $url, [], $expand_level, 'view', $periodic, $prev_data_amounts, $allocationFilters);
}
$CurrentRoute = $request->attributes->get('_route');
if ($CurrentRoute == 'app_get_financial_report') {
if (in_array(1, $report_cats)) {
$balance_sheet_data = Accounts::GetBalanceSheetForApp($em, $cur_level, $start_date, $end_date, $url, [], $expand_level, 'view', $periodic, $prev_data_amounts, $allocationFilters);
}
return new JsonResponse([
'success' => true,
'message' => "Financial Report data fetch",
'data' => $balance_sheet_data
]);
}
//now the income statement
// if (in_array(2, $report_cats)) {
// $is_data = Accounts::GetIncomeStatement($em, $cur_level, $start_date, $end_date, $url, [], $expand_level, 'print', $periodic, $prev_data_amounts_for_is);
// }
if (in_array(2, $report_cats)) {
$markerHashes = array_column(AccountsConstant::$incomeConfigData, 'markerHash');
$is_data = Accounts::GetBalanceOnDateByMarkerHash($em, $end_date, [], [AccountsConstant::OPERATING_REVENUE_PARENT, AccountsConstant::COGS_PARENT, AccountsConstant::NONOPERATING_REVENUE_PARENT, AccountsConstant::ADMIN_EXPENSE_PARENT, AccountsConstant::SELLING_EXPENSE_PARENT, AccountsConstant::MARKETING_EXPENSE_PARENT, AccountsConstant::ADVERTISEMENT_EXPENSE_PARENT, AccountsConstant::FINANCIAL_EXPENSE_PARENT, AccountsConstant::TAX_EXPENSE_PARENT, AccountsConstant::OCI_RECLASSIFIABLE_PARENT, AccountsConstant::OCI_NONRECLASSIFIABLE_PARENT], 1, [], $allocationFilters);
$is_data['tree'] = "";
$incomeConfigData = AccountsConstant::$incomeConfigData;
$currBal = 0;
$currBalByClosingDate = array();
$totalBalByClosingDate = array();
$totalBal = 0;
// dump($cf_data[AccountsConstant::INTEREST_RECEIVABLE_PARENT]);
foreach ($is_data['fiscal_years'] as $fiscal_year) {
$currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
$totalBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
}
foreach ($incomeConfigData as $config) {
$row = "<tr style='" . ($config['bold'] == false ? "" : "font-weight:bold;") . "'>
<td style='" . ($config['paddingMultiplier'] == 0 ? "" : ("padding-left:" . (20 * $config['paddingMultiplier']) . "px;")) . "'>" . $config['title'] . "</td>";
if ($config['markerHash'] == '_TITLE_ONLY_') {
$row .= "<td ></td>";
foreach ($is_data['fiscal_years'] as $fiscal_year) {
$row .= "<td style='text-align: right' ></td>";
}
} else if ($config['markerHash'] == '_CURRENT_BALANCE_') {
// $row.="<td >pika$currBal</td>";
if ($currBal >= 0)
$row .= "<td style='text-align: right'>" . number_format(1 * $currBal, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currBal, 2, '.', ',') . ")</td>";
foreach ($is_data['fiscal_years'] as $fiscal_year) {
$currValByFiscalYear = $currBalByClosingDate[$fiscal_year['closing_end_date']];
if ($currValByFiscalYear >= 0)
$row .= "<td style='text-align: right' >" . number_format(1 * $currValByFiscalYear, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currValByFiscalYear, 2, '.', ',') . ")</td>";
}
} else {
$currVal = 0;
$currentMarkerData = null;
if (isset($is_data[$config['markerHash']])) {
$currentMarkerData = $is_data[$config['markerHash']];
$currVal = $currentMarkerData['transCr'] - $currentMarkerData['transDr'];
}
if ($currVal >= 0)
$row .= "<td style='text-align: right' >" . number_format(1 * $currVal, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currVal, 2, '.', ',') . ")</td>";
foreach ($is_data['fiscal_years'] as $fiscal_year) {
if ($currentMarkerData) {
$currFiscalTransVal = $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transCr'] - $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transDr'];
if ($currVal >= 0)
$row .= "<td style='text-align: right' >" . number_format(1 * $currFiscalTransVal, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currFiscalTransVal, 2, '.', ',') . ")</td>";
$currBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
$totalBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
} else {
$row .= "<td style='text-align: right' ></td>";
}
}
$totalBal += 1 * $currVal;
$currBal += 1 * $currVal;
}
$row .= "</tr>";
if (isset($config['resetCurrentBal'])) {
if ($config['resetCurrentBal'] == true)
$currBal = 0;
foreach ($is_data['fiscal_years'] as $fiscal_year) {
$currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
}
}
$is_data['tree'] .= $row;
$is_data['grandTotal'] = $totalBal;
$is_data['grandTotal'] = $totalBal;
$is_data['grandTotalByClosingDate'] = $totalBalByClosingDate;
}
//For Profit loss
$finalProfit = $currBal;
$oe_data['_IS_PROFIT_'] = [
'transDr' => 0,
'transCr' => $finalProfit,
'dataByFiscalClosing' => []
];
}
if ($CurrentRoute == 'app_get_financial_report_by_marker_hash') {
$markerHashes = array_column(AccountsConstant::$incomeConfigData, 'markerHash');
$is_data = Accounts::GetBalanceOnDateByMarkerHash($em, $end_date, [], [
AccountsConstant::OPERATING_REVENUE_PARENT,
AccountsConstant::COGS_PARENT,
AccountsConstant::NONOPERATING_REVENUE_PARENT,
AccountsConstant::ADMIN_EXPENSE_PARENT,
AccountsConstant::SELLING_EXPENSE_PARENT,
AccountsConstant::MARKETING_EXPENSE_PARENT,
AccountsConstant::ADVERTISEMENT_EXPENSE_PARENT,
AccountsConstant::FINANCIAL_EXPENSE_PARENT,
AccountsConstant::TAX_EXPENSE_PARENT,
AccountsConstant::OCI_RECLASSIFIABLE_PARENT,
AccountsConstant::OCI_NONRECLASSIFIABLE_PARENT
], 1);
$incomeConfigData = AccountsConstant::$incomeConfigData;
$currBal = 0;
$currBalByClosingDate = [];
$totalBalByClosingDate = [];
$totalBal = 0;
foreach ($is_data['fiscal_years'] as $fiscal_year) {
$currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
$totalBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
}
$treeArray = [];
foreach ($incomeConfigData as $config) {
$node = [
'title' => $config['title'],
'bold' => $config['bold'],
'paddingMultiplier' => $config['paddingMultiplier'],
'currentValue' => null,
'yearlyValues' => [],
];
if ($config['markerHash'] == '_TITLE_ONLY_') {
$node['currentValue'] = null;
foreach ($is_data['fiscal_years'] as $fiscal_year) {
$node['yearlyValues'][$fiscal_year['closing_end_date']] = null;
}
} else if ($config['markerHash'] == '_CURRENT_BALANCE_') {
$node['currentValue'] = $currBal;
foreach ($is_data['fiscal_years'] as $fiscal_year) {
$node['yearlyValues'][$fiscal_year['closing_end_date']] = $currBalByClosingDate[$fiscal_year['closing_end_date']];
}
} else {
$currVal = 0;
$currentMarkerData = null;
if (isset($is_data[$config['markerHash']])) {
$currentMarkerData = $is_data[$config['markerHash']];
$currVal = $currentMarkerData['transCr'] - $currentMarkerData['transDr'];
}
$node['currentValue'] = $currVal;
foreach ($is_data['fiscal_years'] as $fiscal_year) {
if ($currentMarkerData) {
$fiscalDate = $fiscal_year['closing_end_date'];
$currFiscalTransVal = $currentMarkerData['dataByFiscalClosing'][$fiscalDate]['transCr'] - $currentMarkerData['dataByFiscalClosing'][$fiscalDate]['transDr'];
$node['yearlyValues'][$fiscalDate] = $currFiscalTransVal;
$currBalByClosingDate[$fiscalDate] += $currFiscalTransVal;
$totalBalByClosingDate[$fiscalDate] += $currFiscalTransVal;
} else {
$node['yearlyValues'][$fiscal_year['closing_end_date']] = null;
}
}
$totalBal += $currVal;
$currBal += $currVal;
}
if (isset($config['resetCurrentBal']) && $config['resetCurrentBal'] === true) {
$currBal = 0;
foreach ($is_data['fiscal_years'] as $fiscal_year) {
$currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
}
}
$treeArray[] = $node;
}
// Helper function to build nested tree by paddingMultiplier
function buildNestedTree(array $flatList)
{
$stack = [];
$tree = [];
foreach ($flatList as &$node) {
unset($node['children']); // clear any existing children
// Pop stack while top has equal or greater paddingMultiplier
while (!empty($stack) && end($stack)['paddingMultiplier'] >= $node['paddingMultiplier']) {
array_pop($stack);
}
if (empty($stack)) {
// Root node
$tree[] = &$node;
} else {
// Add as child to last node in stack
$parent = &$stack[count($stack) - 1];
if (!isset($parent['children'])) {
$parent['children'] = [];
}
$parent['children'][] = &$node;
}
$stack[] = &$node;
}
return $tree;
}
$nestedTree = buildNestedTree($treeArray);
$response = [
'tree' => $nestedTree,
'grandTotal' => $totalBal,
'grandTotalByClosingDate' => $totalBalByClosingDate,
'fiscalYears' => $is_data['fiscal_years'],
];
$finalProfit = $currBal;
$oe_data['_IS_PROFIT_'] = [
'transDr' => 0,
'transCr' => $finalProfit,
'dataByFiscalClosing' => []
];
return new JsonResponse($response);
}
//now get cash flow
if (in_array(3, $report_cats)) {
$markerHashes = array_column(AccountsConstant::$cashFlowConfigData, 'markerHash');
$cf_data = Accounts::GetBalanceOnDateByMarkerHash($em, $end_date, [], [AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT, AccountsConstant::CUSTOMER_RECEIVABLE_PARENT, AccountsConstant::SUPPLIER_PAYABLE_PARENT, AccountsConstant::OPERATING_EXPENSE_PARENT, AccountsConstant::GENERAL_EMPLOYEE_PARENT, AccountsConstant::INTEREST_RECEIVABLE_PARENT, AccountsConstant::FINANCIAL_EXPENSE_PARENT, AccountsConstant::TAX_EXPENSE_PARENT, AccountsConstant::FIXED_ASSET_PARENT, AccountsConstant::ASSET_SALE_PARENT, AccountsConstant::INVESTMENT_PARENT, AccountsConstant::NONOPERATING_REVENUE_PARENT, AccountsConstant::LOAN_RECEIVED_PARENT, AccountsConstant::LOAN_REPAYMENT_PARENT, AccountsConstant::DIVIDEND_PAYMENT_PARENT], 1, [AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT], $allocationFilters);
$openingData = Accounts::GetBalanceOnDateByMarkerHash(
$em,
$start_date,
[],
[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT],
1,
[],
$allocationFilters
);
$closingData = Accounts::GetBalanceOnDateByMarkerHash(
$em,
$end_date,
[],
[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT],
1,
[],
$allocationFilters
);
$openingCashBalance = isset($openingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT])
? $openingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['transCr'] - $openingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['transDr']
: 0;
$closingCashBalance = isset($closingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT])
? $closingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['transCr'] - $closingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['transDr']
: 0;
$cf_data['_CASH_OPENING_'] = [
'transDr' => 0,
'transCr' => $openingCashBalance,
'dataByFiscalClosing' => []
];
$cf_data['_CASH_CLOSING_'] = [
'transDr' => 0,
'transCr' => $closingCashBalance,
'dataByFiscalClosing' => []
];
$cf_data['tree'] = "";
$cashFlowConfigData = AccountsConstant::$cashFlowConfigData;
$currBal = 0;
$currBalByClosingDate = array();
$totalBalByClosingDate = array();
$totalBal = 0;
// dump($cf_data[AccountsConstant::INTEREST_RECEIVABLE_PARENT]);
foreach ($cf_data['fiscal_years'] as $fiscal_year) {
$currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
$totalBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
}
foreach ($cashFlowConfigData as $config) {
$row = "<tr style='" . ($config['bold'] == false ? "" : "font-weight:bold;") . "'>
<td style='" . ($config['paddingMultiplier'] == 0 ? "" : ("padding-left:" . (20 * $config['paddingMultiplier']) . "px;")) . "'>" . $config['title'] . "</td>";
if ($config['markerHash'] == '_TITLE_ONLY_') {
$row .= "<td ></td>";
foreach ($cf_data['fiscal_years'] as $fiscal_year) {
$row .= "<td style='text-align: right' ></td>";
}
} else if ($config['markerHash'] == '_CURRENT_BALANCE_') {
// $row.="<td >pika$currBal</td>";
if ($currBal >= 0)
$row .= "<td style='text-align: right'>" . number_format(1 * $currBal, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currBal, 2, '.', ',') . ")</td>";
foreach ($cf_data['fiscal_years'] as $fiscal_year) {
$currValByFiscalYear = $currBalByClosingDate[$fiscal_year['closing_end_date']];
if ($currValByFiscalYear >= 0)
$row .= "<td style='text-align: right' >" . number_format(1 * $currValByFiscalYear, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currValByFiscalYear, 2, '.', ',') . ")</td>";
}
} else {
$currVal = 0;
$currentMarkerData = null;
if (isset($cf_data[$config['markerHash']])) {
$currentMarkerData = $cf_data[$config['markerHash']];
$currVal = $currentMarkerData['transCr'] - $currentMarkerData['transDr'];
}
if ($currVal >= 0)
$row .= "<td style='text-align: right' >" . number_format(1 * $currVal, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currVal, 2, '.', ',') . ")</td>";
foreach ($cf_data['fiscal_years'] as $fiscal_year) {
if ($currentMarkerData) {
$currFiscalTransVal = $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transCr'] - $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transDr'];
if ($currVal >= 0)
$row .= "<td style='text-align: right' >" . number_format(1 * $currFiscalTransVal, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currFiscalTransVal, 2, '.', ',') . ")</td>";
$currBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
$totalBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
} else {
$row .= "<td style='text-align: right' ></td>";
}
}
$totalBal += 1 * $currVal;
$currBal += 1 * $currVal;
}
$row .= "</tr>";
if (isset($config['resetCurrentBal'])) {
if ($config['resetCurrentBal'] == true)
$currBal = 0;
foreach ($cf_data['fiscal_years'] as $fiscal_year) {
$currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
}
}
$cf_data['tree'] .= $row;
$cf_data['grandTotal'] = $totalBal;
$cf_data['grandTotalByClosingDate'] = $totalBalByClosingDate;
}
}
if (in_array(4, $report_cats)) {
$markerHashes = array_column(AccountsConstant::$changesInEquityConfigData, 'markerHash');
$oe_data = Accounts::GetBalanceOnDateByMarkerHash($em, $end_date, [], [AccountsConstant::SHARE_CAPITAL_PARENT, AccountsConstant::RETAINED_EARNING_PARENT, AccountsConstant::REVALUATION_SURPLUS_PARENT, AccountsConstant::DIVIDEND_PAYMENT_PARENT, AccountsConstant::OCI_RECLASSIFIABLE_PARENT, AccountsConstant::OCI_NONRECLASSIFIABLE_PARENT], 1, [], $allocationFilters);
if (isset($is_data['grandTotal'])) {
$finalProfit = $is_data['grandTotal'];
} else {
$finalProfit = 0;
}
$oe_data['_IS_PROFIT_'] = [
'transDr' => 0,
'transCr' => $finalProfit,
'dataByFiscalClosing' => []
];
$oe_data['tree'] = "";
$changesInEquityConfigData = AccountsConstant::$changesInEquityConfigData;
$currBal = 0;
$currBalByClosingDate = array();
$totalBalByClosingDate = array();
$totalBal = 0;
// dump($cf_data[AccountsConstant::INTEREST_RECEIVABLE_PARENT]);
foreach ($oe_data['fiscal_years'] as $fiscal_year) {
$currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
$totalBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
}
foreach ($changesInEquityConfigData as $config) {
$row = "<tr style='" . ($config['bold'] == false ? "" : "font-weight:bold;") . "'>
<td style='" . ($config['paddingMultiplier'] == 0 ? "" : ("padding-left:" . (20 * $config['paddingMultiplier']) . "px;")) . "'>" . $config['title'] . "</td>";
if ($config['markerHash'] == '_TITLE_ONLY_') {
$row .= "<td ></td>";
foreach ($oe_data['fiscal_years'] as $fiscal_year) {
$row .= "<td style='text-align: right' ></td>";
}
} else if ($config['markerHash'] == '_CURRENT_BALANCE_') {
// $row.="<td >pika$currBal</td>";
if ($currBal >= 0)
$row .= "<td style='text-align: right'>" . number_format(1 * $currBal, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currBal, 2, '.', ',') . ")</td>";
foreach ($oe_data['fiscal_years'] as $fiscal_year) {
$currValByFiscalYear = $currBalByClosingDate[$fiscal_year['closing_end_date']];
if ($currValByFiscalYear >= 0)
$row .= "<td style='text-align: right' >" . number_format(1 * $currValByFiscalYear, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currValByFiscalYear, 2, '.', ',') . ")</td>";
}
} else {
$currVal = 0;
$currentMarkerData = null;
if (isset($oe_data[$config['markerHash']])) {
$currentMarkerData = $oe_data[$config['markerHash']];
$currVal = $currentMarkerData['transCr'] - $currentMarkerData['transDr'];
}
if ($currVal >= 0)
$row .= "<td style='text-align: right' >" . number_format(1 * $currVal, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currVal, 2, '.', ',') . ")</td>";
foreach ($oe_data['fiscal_years'] as $fiscal_year) {
if ($currentMarkerData) {
$currFiscalTransVal = $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transCr'] - $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transDr'];
if ($currVal >= 0)
$row .= "<td style='text-align: right' >" . number_format(1 * $currFiscalTransVal, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currFiscalTransVal, 2, '.', ',') . ")</td>";
$currBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
$totalBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
} else {
$row .= "<td style='text-align: right' ></td>";
}
}
$totalBal += 1 * $currVal;
$currBal += 1 * $currVal;
}
$row .= "</tr>";
if (isset($config['resetCurrentBal'])) {
if ($config['resetCurrentBal'] == true)
$currBal = 0;
foreach ($oe_data['fiscal_years'] as $fiscal_year) {
$currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
}
}
$oe_data['tree'] .= $row;
$oe_data['grandTotal'] = $totalBal;
$oe_data['grandTotal'] = $totalBal;
$oe_data['grandTotalByClosingDate'] = $totalBalByClosingDate;
}
}
if (in_array(5, $report_cats)) {
$wacc_data = Accounts::GetWaccStatement($em, $cur_level, $start_date, $end_date, $url, $periodic, $prev_data_amounts_for_cf, $expand_level);
}
//now get prev balance totals
//*******Data generation Ends here
$provisional_option = 1; //include
if ($request->query->has('provisional')) {
$provisional_option = $request->query->get('provisional'); //include
}
// now lets get its tree for the description
// $id_list_for_ledger=[];
// if($request->query->has('id_list') )
// $id_list_for_ledger=explode(',',$request->query->get('id_list'));
// if($id=0&&empty($id_list))
// $id_list_for_ledger=[0];
// $ledger_det=[];
// $head_name_list=[];
// foreach($id_list_for_ledger as $ind_head_id) {
// $ledger_data = Accounts::LedgerDetails($em, $ind_head_id, $start_date, $end_date,$provisional_option);
// $ledger_det[$ind_head_id]=$ledger_data;
// $head_name_list[]=$ledger_data['basic_data']['name'];
// }
// $grouped_heads=Accounts::GroupedHeads($em);
// $grouped_heads=Accounts::GroupedHeads($em);
// if($mis_start_date!=''&&$mis_start_date!=0)
// $start_date=$mis_start_date;
// if($mis_end_date!=''&&$mis_start_date!=0)
// $end_date=$mis_end_date;
// return new JsonResponse($oe_data);
// dump(AccountsConstant::SHARE_CAPITAL_PARENT);
return $this->render(
'@Accounts/pages/report/view_financial_report.html.twig',
array(
'page_title' => 'Financial Statement',
'company_name' => $company_data->getName(),
'company_data' => $company_data,
// 'details'=>$bs_details,
'bs_details' => $balance_sheet_data,
'is_details' => $is_data,
'cf_details' => $cf_data,
'oe_details' => $oe_data,
'prev_data_list' => $prev_data_list,
'report_cats' => $report_cats,
'start_date' => $start_date,
'end_date' => $end_date,
'max_level' => $max_level,
'expand_level' => $expand_level,
'cur_level' => $cur_level,
// 'ledger_data'=>$ledger_det,
'page_header' => 'Ledger',
'document_type' => 'Financial Statement',
'page_header_sub' => 'Add',
'head_list' => Accounts::HeadList($em),
'provisional' => $provisional_option,
// 'type_list'=>$type_list,
// 'child_list'=>$child_list,
// 'trans_data_by_closing'=>$trans_data_by_closing,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'invoice_footer' => $company_data->getInvoiceFooter(),
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'allocation_filters' => $allocationFilters,
'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
'project_list' => $allocationSupportData['project_list'],
'branch_list' => $allocationSupportData['branch_list'],
'cost_centers' => $allocationSupportData['cost_centers'],
// 'p'=>$p
)
);
// return $this->render(
// '@Accounts/pages/report/view_financial_report.html.twig',
// array(
// 'page_title' => 'Financial Statements',
// 'company_name' => $company_data->getName(),
// 'company_data' => $company_data,
// 'details' => $bs_details,
// 'tb_details' => $tb_details,
// 'start_date' => $start_date,
//
// 'end_date' => $end_date,
// 'print_all' => $print_all,
// 'max_level' => $max_level,
// 'expand_level' => $expand_level,
// 'cur_level' => $cur_level,
//
// // 'end_date'=>new \DateTime(),
// )
// );
}
public function TestController(Request $request)
{
$em = $this->getDoctrine()->getManager();
$company_data = Company::getCompanyData($em, $this->getLoggedUserCompanyId($request));
$new_cc = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccSettings')
->findOneBy(
array(
'name' => 'accounting_year_start',
)
);
$start_date = $new_cc ? $new_cc->getData() : "";
$start_date = ($request->query->has('start_date')) ? $request->query->get('start_date') : ($new_cc ? $new_cc->getData() : "");
$cur_level = ($request->query->has('level')) ? $request->query->get('level') : 1;
$expand_level = ($request->query->has('expand_level')) ? $request->query->get('expand_level') : 3;
$end_date = ($request->query->has('end_date')) ? $request->query->get('end_date') : (new \DateTime())->format('Y-m-d');
$em = $this->getDoctrine()->getManager();
$url = $this->generateUrl('view_ledger_head', array(), true);
// $child_list=Accounts::LedgerDetails($em,2,$start_date, $end_date);
$bs_details = [];
$get_kids_sql = "SELECT max(head_level) max_level FROM acc_accounts_head where 1 ";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
$max_level = isset($query_output[0]['max_level']) ? $query_output[0]['max_level'] : 1;
$report_cats = [1, 2, 3, 4];
$periodic = 0;
$last_entries_count = 1;
if ($request->query->has('print_all')) {
if ($request->query->get('print_all') == 1)
$report_cats = [1, 2, 3, 4];
} else {
if ($request->query->has('statement'))
$report_cats = $request->query->get('statement');
}
if ($request->query->has('periodic'))
if ($request->query->get('periodic') == 1)
$periodic = 1;
if ($request->query->has('last_entries'))
$last_entries_count = $request->query->get('last_entries');
//lets get prev fiscal closing data
$new_cc_list = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\FiscalClosing')
->findBy(
array(),
array(
'closingId' => 'DESC'
),
$last_entries_count
);
$prev_data_list = array();
$prev_data_amounts = array();
$prev_data_amounts_for_is = array();
$prev_data_amounts_for_cf = array();
if (!empty($new_cc_list)) {
$prev_data = array();
foreach ($new_cc_list as $new_cc) {
$prev_data['closing_start_date'] = $new_cc->getClosingStartDate();
$prev_data['closing_end_date'] = $new_cc->getClosingEndDate();
$prev_data['closing_data'] = array();
$last_f_c_data = json_decode($new_cc->getClosingData(), true);
// foreach ($last_f_c_data['heads'] as $key => $entry) {
// $add_data = array(
// 'head_id' => $entry,
// 'balance' => $last_f_c_data['balance'][$key],
// 'recon_balance' => $last_f_c_data['recon_balance'][$key]
// );
// $prev_data['closing_data'][$entry] = $add_data;
// $prev_data_amounts[$entry][]= $last_f_c_data['balance'][$key];
// }
foreach ($last_f_c_data as $key => $entry) {
$add_data = array(
'head_id' => $key,
'balance' => $entry,
'recon_balance' => $entry
);
$prev_data['closing_data'][$key] = $add_data;
$prev_data_amounts[$key][] = $entry;
}
$prev_data_list[] = $prev_data;
}
}
if (!empty($new_cc_list)) {
$prev_data = array();
foreach ($new_cc_list as $new_cc) {
$prev_data['closing_start_date'] = $new_cc->getClosingStartDate();
$prev_data['closing_end_date'] = $new_cc->getClosingEndDate();
$prev_data['closing_data'] = array();
$last_f_c_data = json_decode($new_cc->getBeforeClosingData(), true);
if ($last_f_c_data == null) $last_f_c_data = [];
// foreach ($last_f_c_data['heads'] as $key => $entry) {
// $add_data = array(
// 'head_id' => $entry,
// 'balance' => $last_f_c_data['balance'][$key],
// 'recon_balance' => $last_f_c_data['recon_balance'][$key]
// );
// $prev_data['closing_data'][$entry] = $add_data;
// $prev_data_amounts[$entry][]= $last_f_c_data['balance'][$key];
// }
foreach ($last_f_c_data as $key => $entry) {
$add_data = array(
'head_id' => $key,
'balance' => $entry,
'recon_balance' => $entry
);
$prev_data['closing_data'][$key] = $add_data;
$prev_data_amounts_for_is[$key][] = $entry;
}
// $prev_data_list[]=$prev_data;
}
}
$balance_sheet_data = [];
$is_data = [];
$cf_data = [];
$oe_data = [];
$wacc_data = [];
$allocationSupportData = $this->getAllocationReportSupportData($em, $request);
$allocationFilters = $allocationSupportData['allocation_filters'];
//now get balance sheet if needed
if (in_array(1, $report_cats)) {
$balance_sheet_data = Accounts::GetBalanceSheet($em, $cur_level, $start_date, $end_date, $url, [], $expand_level, 'print', $periodic, $prev_data_amounts, $allocationFilters);
}
//now the income statement
if (in_array(2, $report_cats)) {
$is_data = Accounts::GetIncomeStatement($em, $cur_level, $start_date, $end_date, $url, [], $expand_level, 'print', $periodic, $prev_data_amounts_for_is);
}
//now get cash flow
if (in_array(3, $report_cats)) {
$cf_data = Accounts::GetBalanceOnDateByMarkerHash($em, $end_date, [], [], 1, [AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT, AccountsConstant::SALES_REVENUE_PARENT], $allocationFilters);
$cf_data['tree'] = "";
$cashFlowConfigData = AccountsConstant::$cashFlowConfigData;
return new JsonResponse($cashFlowConfigData);
$currBal = 0;
$currBalByClosingDate = array();
$totalBalByClosingDate = array();
$totalBal = 0;
foreach ($cf_data['fiscal_years'] as $fiscal_year) {
$currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
$totalBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
}
foreach ($cashFlowConfigData as $config) {
$row = "<tr style='" . ($config['bold'] == false ? "" : "font-weight:bold;") . "'>
<td style='" . ($config['paddingMultiplier'] == 0 ? "" : ("padding-left:" . (20 * $config['paddingMultiplier']) . "px;")) . "'>" . $config['title'] . "</td>";
if ($config['markerHash'] == '_TITLE_ONLY_') {
$row .= "<td ></td>";
foreach ($cf_data['fiscal_years'] as $fiscal_year) {
$row .= "<td style='text-align: right' ></td>";
}
} else if ($config['markerHash'] == '_CURRENT_BALANCE_') {
// $row.="<td >pika$currBal</td>";
if ($currBal >= 0)
$row .= "<td style='text-align: right'>" . number_format(1 * $currBal, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currBal, 2, '.', ',') . ")</td>";
foreach ($cf_data['fiscal_years'] as $fiscal_year) {
$currValByFiscalYear = $currBalByClosingDate[$fiscal_year['closing_end_date']];
if ($currValByFiscalYear >= 0)
$row .= "<td style='text-align: right' >" . number_format(1 * $currValByFiscalYear, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currValByFiscalYear, 2, '.', ',') . ")</td>";
}
} else {
$currVal = 0;
$currentMarkerData = null;
if (isset($cf_data[$config['markerHash']])) {
$currentMarkerData = $cf_data[$config['markerHash']];
$currVal = $currentMarkerData['transCr'] - $currentMarkerData['transDr'];
}
if ($currVal >= 0)
$row .= "<td style='text-align: right' >" . number_format(1 * $currVal, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currVal, 2, '.', ',') . ")</td>";
foreach ($cf_data['fiscal_years'] as $fiscal_year) {
if ($currentMarkerData) {
$currFiscalTransVal = $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transCr'] - $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transDr'];
if ($currVal >= 0)
$row .= "<td style='text-align: right' >" . number_format(1 * $currFiscalTransVal, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currFiscalTransVal, 2, '.', ',') . ")</td>";
$currBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
$totalBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
} else {
$row .= "<td style='text-align: right' ></td>";
}
}
$totalBal += 1 * $currVal;
$currBal += 1 * $currVal;
}
$row .= "</tr>";
if (isset($config['resetCurrentBal'])) {
if ($config['resetCurrentBal'] == true)
$currBal = 0;
foreach ($cf_data['fiscal_years'] as $fiscal_year) {
$currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
}
}
$cf_data['tree'] .= $row;
$cf_data['grandTotal'] = $totalBal;
$cf_data['grandTotalByClosingDate'] = $totalBalByClosingDate;
}
}
if (in_array(4, $report_cats)) {
$oe_data = Accounts::GetCashFlowStatement($em, $cur_level, $start_date, $end_date, $url, $periodic, $prev_data_amounts_for_cf, $expand_level, $allocationFilters);
}
if (in_array(5, $report_cats)) {
$wacc_data = Accounts::GetWaccStatement($em, $cur_level, $start_date, $end_date, $url, $periodic, $prev_data_amounts_for_cf, $expand_level);
}
}
public function PrintFinancialReport(Request $request)
{
$em = $this->getDoctrine()->getManager();
$company_data = Company::getCompanyData($em, $this->getLoggedUserCompanyId($request));
$new_cc = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccSettings')
->findOneBy(
array(
'name' => 'accounting_year_start',
)
);
$start_date = $new_cc ? $new_cc->getData() : "";
$start_date = ($request->query->has('start_date')) ? $request->query->get('start_date') : ($new_cc ? $new_cc->getData() : "");
$cur_level = ($request->query->has('level')) ? $request->query->get('level') : 1;
$expand_level = ($request->query->has('expand_level')) ? $request->query->get('expand_level') : 3;
$end_date = ($request->query->has('end_date')) ? $request->query->get('end_date') : (new \DateTime())->format('Y-m-d');
$em = $this->getDoctrine()->getManager();
$url = $this->generateUrl('view_ledger_head', array(), true);
$allocationSupportData = $this->getAllocationReportSupportData($em, $request);
$allocationFilters = $allocationSupportData['allocation_filters'];
// $child_list=Accounts::LedgerDetails($em,2,$start_date, $end_date);
$bs_details = [];
$get_kids_sql = "SELECT max(head_level) max_level FROM acc_accounts_head where 1 ";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
$max_level = isset($query_output[0]['max_level']) ? $query_output[0]['max_level'] : 1;
//*************Data generation start here
$report_cats = [1, 2, 3, 4];
$periodic = 0;
$last_entries_count = 1;
if ($request->query->has('print_all')) {
if ($request->query->get('print_all') == 1)
$report_cats = [1, 2, 3, 4];
} else {
if ($request->query->has('statement'))
$report_cats = $request->query->get('statement');
}
if ($request->query->has('periodic'))
if ($request->query->get('periodic') == 1)
$periodic = 1;
if ($request->query->has('last_entries'))
$last_entries_count = $request->query->get('last_entries');
//lets get prev fiscal closing data
$new_cc_list = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\FiscalClosing')
->findBy(
array(),
array(
'closingId' => 'DESC'
),
$last_entries_count
);
$prev_data_list = array();
$prev_data_amounts = array();
$prev_data_amounts_for_is = array();
$prev_data_amounts_for_cf = array();
if (!empty($new_cc_list)) {
$prev_data = array();
foreach ($new_cc_list as $new_cc) {
$prev_data['closing_start_date'] = $new_cc->getClosingStartDate();
$prev_data['closing_end_date'] = $new_cc->getClosingEndDate();
$prev_data['closing_data'] = array();
$last_f_c_data = json_decode($new_cc->getClosingData(), true);
// foreach ($last_f_c_data['heads'] as $key => $entry) {
// $add_data = array(
// 'head_id' => $entry,
// 'balance' => $last_f_c_data['balance'][$key],
// 'recon_balance' => $last_f_c_data['recon_balance'][$key]
// );
// $prev_data['closing_data'][$entry] = $add_data;
// $prev_data_amounts[$entry][]= $last_f_c_data['balance'][$key];
// }
foreach ($last_f_c_data as $key => $entry) {
$add_data = array(
'head_id' => $key,
'balance' => $entry,
'recon_balance' => $entry
);
$prev_data['closing_data'][$key] = $add_data;
$prev_data_amounts[$key][] = $entry;
}
$prev_data_list[] = $prev_data;
}
}
if (!empty($new_cc_list)) {
$prev_data = array();
foreach ($new_cc_list as $new_cc) {
$prev_data['closing_start_date'] = $new_cc->getClosingStartDate();
$prev_data['closing_end_date'] = $new_cc->getClosingEndDate();
$prev_data['closing_data'] = array();
$last_f_c_data = json_decode($new_cc->getBeforeClosingData(), true);
if ($last_f_c_data == null) $last_f_c_data = [];
// foreach ($last_f_c_data['heads'] as $key => $entry) {
// $add_data = array(
// 'head_id' => $entry,
// 'balance' => $last_f_c_data['balance'][$key],
// 'recon_balance' => $last_f_c_data['recon_balance'][$key]
// );
// $prev_data['closing_data'][$entry] = $add_data;
// $prev_data_amounts[$entry][]= $last_f_c_data['balance'][$key];
// }
foreach ($last_f_c_data as $key => $entry) {
$add_data = array(
'head_id' => $key,
'balance' => $entry,
'recon_balance' => $entry
);
$prev_data['closing_data'][$key] = $add_data;
$prev_data_amounts_for_is[$key][] = $entry;
}
// $prev_data_list[]=$prev_data;
}
}
$balance_sheet_data = [];
$is_data = [];
$cf_data = [];
$oe_data = [];
$wacc_data = [];
//now get balance sheet if needed
if (in_array(1, $report_cats)) {
$balance_sheet_data = Accounts::GetBalanceSheet($em, $cur_level, $start_date, $end_date, $url, [], $expand_level, 'print', $periodic, $prev_data_amounts, $allocationFilters);
}
//now the income statement
// if (in_array(2, $report_cats)) {
// $is_data = Accounts::GetIncomeStatement($em, $cur_level, $start_date, $end_date, $url, [], $expand_level, 'print', $periodic, $prev_data_amounts_for_is);
// }
if (in_array(2, $report_cats)) {
$markerHashes = array_column(AccountsConstant::$incomeConfigData, 'markerHash');
$is_data = Accounts::GetBalanceOnDateByMarkerHash($em, $end_date, [], [AccountsConstant::OPERATING_REVENUE_PARENT, AccountsConstant::COGS_PARENT, AccountsConstant::NONOPERATING_REVENUE_PARENT, AccountsConstant::ADMIN_EXPENSE_PARENT, AccountsConstant::SELLING_EXPENSE_PARENT, AccountsConstant::MARKETING_EXPENSE_PARENT, AccountsConstant::ADVERTISEMENT_EXPENSE_PARENT, AccountsConstant::FINANCIAL_EXPENSE_PARENT, AccountsConstant::TAX_EXPENSE_PARENT, AccountsConstant::OCI_RECLASSIFIABLE_PARENT, AccountsConstant::OCI_NONRECLASSIFIABLE_PARENT], 1, [], $allocationFilters);
$is_data['tree'] = "";
$incomeConfigData = AccountsConstant::$incomeConfigData;
$currBal = 0;
$currBalByClosingDate = array();
$totalBalByClosingDate = array();
$totalBal = 0;
// dump($cf_data[AccountsConstant::INTEREST_RECEIVABLE_PARENT]);
foreach ($is_data['fiscal_years'] as $fiscal_year) {
$currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
$totalBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
}
foreach ($incomeConfigData as $config) {
$row = "<tr style='" . ($config['bold'] == false ? "" : "font-weight:bold;") . "'>
<td style='" . ($config['paddingMultiplier'] == 0 ? "" : ("padding-left:" . (20 * $config['paddingMultiplier']) . "px;")) . "'>" . $config['title'] . "</td>";
if ($config['markerHash'] == '_TITLE_ONLY_') {
$row .= "<td ></td>";
foreach ($is_data['fiscal_years'] as $fiscal_year) {
$row .= "<td style='text-align: right' ></td>";
}
} else if ($config['markerHash'] == '_CURRENT_BALANCE_') {
// $row.="<td >pika$currBal</td>";
if ($currBal >= 0)
$row .= "<td style='text-align: right'>" . number_format(1 * $currBal, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currBal, 2, '.', ',') . ")</td>";
foreach ($is_data['fiscal_years'] as $fiscal_year) {
$currValByFiscalYear = $currBalByClosingDate[$fiscal_year['closing_end_date']];
if ($currValByFiscalYear >= 0)
$row .= "<td style='text-align: right' >" . number_format(1 * $currValByFiscalYear, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currValByFiscalYear, 2, '.', ',') . ")</td>";
}
} else {
$currVal = 0;
$currentMarkerData = null;
if (isset($is_data[$config['markerHash']])) {
$currentMarkerData = $is_data[$config['markerHash']];
$currVal = $currentMarkerData['transCr'] - $currentMarkerData['transDr'];
}
if ($currVal >= 0)
$row .= "<td style='text-align: right' >" . number_format(1 * $currVal, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currVal, 2, '.', ',') . ")</td>";
foreach ($is_data['fiscal_years'] as $fiscal_year) {
if ($currentMarkerData) {
$currFiscalTransVal = $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transCr'] - $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transDr'];
if ($currVal >= 0)
$row .= "<td style='text-align: right' >" . number_format(1 * $currFiscalTransVal, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currFiscalTransVal, 2, '.', ',') . ")</td>";
$currBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
$totalBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
} else {
$row .= "<td style='text-align: right' ></td>";
}
}
$totalBal += 1 * $currVal;
$currBal += 1 * $currVal;
}
$row .= "</tr>";
if (isset($config['resetCurrentBal'])) {
if ($config['resetCurrentBal'] == true)
$currBal = 0;
foreach ($is_data['fiscal_years'] as $fiscal_year) {
$currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
}
}
$is_data['tree'] .= $row;
$is_data['grandTotal'] = $totalBal;
$is_data['grandTotal'] = $totalBal;
$is_data['grandTotalByClosingDate'] = $totalBalByClosingDate;
}
//For Profit loss
$finalProfit = $currBal;
$oe_data['_IS_PROFIT_'] = [
'transDr' => 0,
'transCr' => $finalProfit,
'dataByFiscalClosing' => []
];
}
//now get cash flow
if (in_array(3, $report_cats)) {
$markerHashes = array_column(AccountsConstant::$cashFlowConfigData, 'markerHash');
$cf_data = Accounts::GetBalanceOnDateByMarkerHash($em, $end_date, [], [AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT, AccountsConstant::CUSTOMER_RECEIVABLE_PARENT, AccountsConstant::SUPPLIER_PAYABLE_PARENT, AccountsConstant::OPERATING_EXPENSE_PARENT, AccountsConstant::GENERAL_EMPLOYEE_PARENT, AccountsConstant::INTEREST_RECEIVABLE_PARENT, AccountsConstant::FINANCIAL_EXPENSE_PARENT, AccountsConstant::TAX_EXPENSE_PARENT, AccountsConstant::FIXED_ASSET_PARENT, AccountsConstant::ASSET_SALE_PARENT, AccountsConstant::INVESTMENT_PARENT, AccountsConstant::NONOPERATING_REVENUE_PARENT, AccountsConstant::LOAN_RECEIVED_PARENT, AccountsConstant::LOAN_REPAYMENT_PARENT, AccountsConstant::DIVIDEND_PAYMENT_PARENT], 1, [AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT], $allocationFilters);
$openingData = Accounts::GetBalanceOnDateByMarkerHash(
$em,
$start_date,
[],
[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT],
1,
[],
$allocationFilters
);
$closingData = Accounts::GetBalanceOnDateByMarkerHash(
$em,
$end_date,
[],
[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT],
1,
[],
$allocationFilters
);
$openingCashBalance = isset($openingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT])
? $openingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['transCr'] - $openingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['transDr']
: 0;
$closingCashBalance = isset($closingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT])
? $closingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['transCr'] - $closingData[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['transDr']
: 0;
$cf_data['_CASH_OPENING_'] = [
'transDr' => 0,
'transCr' => $openingCashBalance,
'dataByFiscalClosing' => []
];
$cf_data['_CASH_CLOSING_'] = [
'transDr' => 0,
'transCr' => $closingCashBalance,
'dataByFiscalClosing' => []
];
$cf_data['tree'] = "";
$cashFlowConfigData = AccountsConstant::$cashFlowConfigData;
$currBal = 0;
$currBalByClosingDate = array();
$totalBalByClosingDate = array();
$totalBal = 0;
// dump($cf_data[AccountsConstant::INTEREST_RECEIVABLE_PARENT]);
foreach ($cf_data['fiscal_years'] as $fiscal_year) {
$currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
$totalBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
}
foreach ($cashFlowConfigData as $config) {
$row = "<tr style='" . ($config['bold'] == false ? "" : "font-weight:bold;") . "'>
<td style='" . ($config['paddingMultiplier'] == 0 ? "" : ("padding-left:" . (20 * $config['paddingMultiplier']) . "px;")) . "'>" . $config['title'] . "</td>";
if ($config['markerHash'] == '_TITLE_ONLY_') {
$row .= "<td ></td>";
foreach ($cf_data['fiscal_years'] as $fiscal_year) {
$row .= "<td style='text-align: right' ></td>";
}
} else if ($config['markerHash'] == '_CURRENT_BALANCE_') {
// $row.="<td >pika$currBal</td>";
if ($currBal >= 0)
$row .= "<td style='text-align: right'>" . number_format(1 * $currBal, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currBal, 2, '.', ',') . ")</td>";
foreach ($cf_data['fiscal_years'] as $fiscal_year) {
$currValByFiscalYear = $currBalByClosingDate[$fiscal_year['closing_end_date']];
if ($currValByFiscalYear >= 0)
$row .= "<td style='text-align: right' >" . number_format(1 * $currValByFiscalYear, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currValByFiscalYear, 2, '.', ',') . ")</td>";
}
} else {
$currVal = 0;
$currentMarkerData = null;
if (isset($cf_data[$config['markerHash']])) {
$currentMarkerData = $cf_data[$config['markerHash']];
$currVal = $currentMarkerData['transCr'] - $currentMarkerData['transDr'];
}
if ($currVal >= 0)
$row .= "<td style='text-align: right' >" . number_format(1 * $currVal, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currVal, 2, '.', ',') . ")</td>";
foreach ($cf_data['fiscal_years'] as $fiscal_year) {
if ($currentMarkerData) {
$currFiscalTransVal = $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transCr'] - $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transDr'];
if ($currVal >= 0)
$row .= "<td style='text-align: right' >" . number_format(1 * $currFiscalTransVal, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currFiscalTransVal, 2, '.', ',') . ")</td>";
$currBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
$totalBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
} else {
$row .= "<td style='text-align: right' ></td>";
}
}
$totalBal += 1 * $currVal;
$currBal += 1 * $currVal;
}
$row .= "</tr>";
if (isset($config['resetCurrentBal'])) {
if ($config['resetCurrentBal'] == true)
$currBal = 0;
foreach ($cf_data['fiscal_years'] as $fiscal_year) {
$currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
}
}
$cf_data['tree'] .= $row;
$cf_data['grandTotal'] = $totalBal;
$cf_data['grandTotalByClosingDate'] = $totalBalByClosingDate;
}
}
if (in_array(4, $report_cats)) {
$markerHashes = array_column(AccountsConstant::$changesInEquityConfigData, 'markerHash');
$oe_data = Accounts::GetBalanceOnDateByMarkerHash($em, $end_date, [], [AccountsConstant::SHARE_CAPITAL_PARENT, AccountsConstant::RETAINED_EARNING_PARENT, AccountsConstant::REVALUATION_SURPLUS_PARENT, AccountsConstant::DIVIDEND_PAYMENT_PARENT, AccountsConstant::OCI_RECLASSIFIABLE_PARENT, AccountsConstant::OCI_NONRECLASSIFIABLE_PARENT], 1, [], $allocationFilters);
if (isset($is_data['grandTotal'])) {
$finalProfit = $is_data['grandTotal'];
} else {
$finalProfit = 0;
}
$oe_data['_IS_PROFIT_'] = [
'transDr' => 0,
'transCr' => $finalProfit,
'dataByFiscalClosing' => []
];
$oe_data['tree'] = "";
$changesInEquityConfigData = AccountsConstant::$changesInEquityConfigData;
$currBal = 0;
$currBalByClosingDate = array();
$totalBalByClosingDate = array();
$totalBal = 0;
// dump($cf_data[AccountsConstant::INTEREST_RECEIVABLE_PARENT]);
foreach ($oe_data['fiscal_years'] as $fiscal_year) {
$currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
$totalBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
}
foreach ($changesInEquityConfigData as $config) {
$row = "<tr style='" . ($config['bold'] == false ? "" : "font-weight:bold;") . "'>
<td style='" . ($config['paddingMultiplier'] == 0 ? "" : ("padding-left:" . (20 * $config['paddingMultiplier']) . "px;")) . "'>" . $config['title'] . "</td>";
if ($config['markerHash'] == '_TITLE_ONLY_') {
$row .= "<td ></td>";
foreach ($oe_data['fiscal_years'] as $fiscal_year) {
$row .= "<td style='text-align: right' ></td>";
}
} else if ($config['markerHash'] == '_CURRENT_BALANCE_') {
// $row.="<td >pika$currBal</td>";
if ($currBal >= 0)
$row .= "<td style='text-align: right'>" . number_format(1 * $currBal, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currBal, 2, '.', ',') . ")</td>";
foreach ($oe_data['fiscal_years'] as $fiscal_year) {
$currValByFiscalYear = $currBalByClosingDate[$fiscal_year['closing_end_date']];
if ($currValByFiscalYear >= 0)
$row .= "<td style='text-align: right' >" . number_format(1 * $currValByFiscalYear, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currValByFiscalYear, 2, '.', ',') . ")</td>";
}
} else {
$currVal = 0;
$currentMarkerData = null;
if (isset($oe_data[$config['markerHash']])) {
$currentMarkerData = $oe_data[$config['markerHash']];
$currVal = $currentMarkerData['transCr'] - $currentMarkerData['transDr'];
}
if ($currVal >= 0)
$row .= "<td style='text-align: right' >" . number_format(1 * $currVal, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currVal, 2, '.', ',') . ")</td>";
foreach ($oe_data['fiscal_years'] as $fiscal_year) {
if ($currentMarkerData) {
$currFiscalTransVal = $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transCr'] - $currentMarkerData['dataByFiscalClosing'][$fiscal_year['closing_end_date']]['transDr'];
if ($currVal >= 0)
$row .= "<td style='text-align: right' >" . number_format(1 * $currFiscalTransVal, 2, '.', ',') . "</td>";
else
$row .= "<td style='text-align: right' >(" . number_format((-1) * $currFiscalTransVal, 2, '.', ',') . ")</td>";
$currBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
$totalBalByClosingDate[$fiscal_year['closing_end_date']] += $currFiscalTransVal;
} else {
$row .= "<td style='text-align: right' ></td>";
}
}
$totalBal += 1 * $currVal;
$currBal += 1 * $currVal;
}
$row .= "</tr>";
if (isset($config['resetCurrentBal'])) {
if ($config['resetCurrentBal'] == true)
$currBal = 0;
foreach ($oe_data['fiscal_years'] as $fiscal_year) {
$currBalByClosingDate[$fiscal_year['closing_end_date']] = 0;
}
}
$oe_data['tree'] .= $row;
$oe_data['grandTotal'] = $totalBal;
$oe_data['grandTotal'] = $totalBal;
$oe_data['grandTotalByClosingDate'] = $totalBalByClosingDate;
}
}
if (in_array(5, $report_cats)) {
$wacc_data = Accounts::GetWaccStatement($em, $cur_level, $start_date, $end_date, $url, $periodic, $prev_data_amounts_for_cf, $expand_level);
}
//now get prev balance totals
//*******Data generation Ends here
$provisional_option = 1; //include
if ($request->query->has('provisional')) {
$provisional_option = $request->query->get('provisional'); //include
}
// now lets get its tree for the description
// $id_list_for_ledger=[];
// if($request->query->has('id_list') )
// $id_list_for_ledger=explode(',',$request->query->get('id_list'));
// if($id=0&&empty($id_list))
// $id_list_for_ledger=[0];
// $ledger_det=[];
// $head_name_list=[];
// foreach($id_list_for_ledger as $ind_head_id) {
// $ledger_data = Accounts::LedgerDetails($em, $ind_head_id, $start_date, $end_date,$provisional_option);
// $ledger_det[$ind_head_id]=$ledger_data;
// $head_name_list[]=$ledger_data['basic_data']['name'];
// }
// $grouped_heads=Accounts::GroupedHeads($em);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
$html = $this->renderView(
'@Accounts/pages/print/print_financial_report.html.twig',
array(
'pdf' => true,
'page_title' => 'Financial Statement',
'company_name' => $company_data->getName(),
'company_data' => $company_data,
// 'details'=>$bs_details,
'bs_details' => $balance_sheet_data,
'is_details' => $is_data,
'cf_details' => $cf_data,
'oe_details' => $oe_data,
'wacc_details' => $wacc_data,
'prev_data_list' => $prev_data_list,
'report_cats' => $report_cats,
'start_date' => $start_date,
'end_date' => $end_date,
'max_level' => $max_level,
'expand_level' => $expand_level,
'cur_level' => $cur_level,
// 'ledger_data'=>$ledger_det,
'page_header' => 'Ledger',
'document_type' => 'Financial Statement',
'document_mark_image' => $document_mark['original'],
'page_header_sub' => 'Add',
'head_list' => Accounts::HeadList($em),
'provisional' => $provisional_option,
// 'type_list'=>$type_list,
// 'child_list'=>$child_list,
// 'trans_data_by_closing'=>$trans_data_by_closing,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'invoice_footer' => $company_data->getInvoiceFooter(),
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'allocation_filters' => $allocationFilters,
'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
'project_list' => $allocationSupportData['project_list'],
'branch_list' => $allocationSupportData['branch_list'],
'cost_centers' => $allocationSupportData['cost_centers'],
)
);
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
// 'orientation' => 'landscape',
// 'enable-javascript' => false,
// 'javascript-delay' => 1000,
'no-stop-slow-scripts' => true,
'no-background' => false,
'lowquality' => false,
'encoding' => 'utf-8',
// 'images' => true,
// 'cookie' => array(),
'dpi' => 300,
'image-dpi' => 300,
// 'enable-external-links' => true,
// 'enable-internal-links' => true
));
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="Financial_Report.pdf"'
)
);
}
return $this->render(
'@Accounts/pages/print/print_financial_report.html.twig',
array(
'export' => 'all',
'page_title' => 'Financial Statement',
'company_name' => $company_data->getName(),
'company_data' => $company_data,
// 'details'=>$bs_details,
'bs_details' => $balance_sheet_data,
'is_details' => $is_data,
'cf_details' => $cf_data,
'oe_details' => $oe_data,
'prev_data_list' => $prev_data_list,
'report_cats' => $report_cats,
'start_date' => $start_date,
'end_date' => $end_date,
'max_level' => $max_level,
'expand_level' => $expand_level,
'cur_level' => $cur_level,
// 'ledger_data'=>$ledger_det,
'page_header' => 'Ledger',
'document_type' => 'Financial Statement',
'document_mark_image' => $document_mark['original'],
'page_header_sub' => 'Add',
'head_list' => Accounts::HeadList($em),
'provisional' => $provisional_option,
// 'type_list'=>$type_list,
// 'child_list'=>$child_list,
// 'trans_data_by_closing'=>$trans_data_by_closing,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'invoice_footer' => $company_data->getInvoiceFooter(),
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'allocation_filters' => $allocationFilters,
'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
'project_list' => $allocationSupportData['project_list'],
'branch_list' => $allocationSupportData['branch_list'],
'cost_centers' => $allocationSupportData['cost_centers'],
// 'p'=>$p
)
);
}
public function PrintTrialBalance(Request $request)
{
$em = $this->getDoctrine()->getManager();
$company_data = Company::getCompanyData($em, $this->getLoggedUserCompanyId($request));
$start_date = ($request->query->has('start_date')) ? $request->query->get('start_date') : "";
$skip_parent_head = ($request->query->has('skip_parent_head')) ? $request->query->get('skip_parent_head') : 0;
$cur_level = ($request->query->has('level')) ? $request->query->get('level') : 1;
$expand_level = ($request->query->has('expand_level')) ? $request->query->get('expand_level') : 1;
$end_date = ($request->query->has('end_date')) ? $request->query->get('end_date') : (new \DateTime())->format('Y-m-d');
$em = $this->getDoctrine()->getManager();
$url = $this->generateUrl('view_ledger_head', array(), true);
// $child_list=Accounts::LedgerDetails($em,2,$start_date, $end_date);
$bs_details = [];
$get_kids_sql = "SELECT max(head_level) max_level FROM acc_accounts_head where 1 ";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
$max_level = isset($query_output[0]['max_level']) ? $query_output[0]['max_level'] : 1;
$budgetEnabled = 0;
$budgetVarianceSettings = [];
$allocationSupportData = $this->getAllocationReportSupportData($em, $request);
$allocationFilters = $allocationSupportData['allocation_filters'];
if ($request->query->has('budget_variance_enabled')) {
$budgetVarianceSettings['enabled'] = $request->query->get('budget_variance_enabled');
$budgetEnabled = $request->query->get('budget_variance_enabled');
$budgetVarianceSettings['scale'] = ($request->query->has('scale_variance')) ? $request->query->get('scale_variance') : 1;
$budgetVarianceSettings['budgetId'] = ($request->query->has('budgetId')) ? $request->query->get('budgetId') : 1;
}
$tb_details = Accounts::GetTrialBalance($em, $cur_level, $start_date, $end_date, $url, [], $expand_level, 'print', $skip_parent_head, $budgetVarianceSettings, 0, $allocationFilters);
// $tb_details=Accounts::GetTrialBalance($em,$cur_level,$start_date, $end_date,$url,[],$expand_level,'print',$skip_parent_head);
// $grouped_heads=Accounts::GroupedHeads($em);
// if($mis_start_date!=''&&$mis_start_date!=0)
// $start_date=$mis_start_date;
// if($mis_end_date!=''&&$mis_start_date!=0)
// $end_date=$mis_end_date;
$provisional_option = 1; //include
if ($request->query->has('provisional')) {
$provisional_option = $request->query->get('provisional'); //include
}
// now lets get its tree for the description
// $id_list_for_ledger=[];
// if($request->query->has('id_list') )
// $id_list_for_ledger=explode(',',$request->query->get('id_list'));
// if($id=0&&empty($id_list))
// $id_list_for_ledger=[0];
// $ledger_det=[];
// $head_name_list=[];
// foreach($id_list_for_ledger as $ind_head_id) {
// $ledger_data = Accounts::LedgerDetails($em, $ind_head_id, $start_date, $end_date,$provisional_option);
// $ledger_det[$ind_head_id]=$ledger_data;
// $head_name_list[]=$ledger_data['basic_data']['name'];
// }
// $grouped_heads=Accounts::GroupedHeads($em);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
$html = $this->renderView(
'@Accounts/pages/print/trial_balance_print.html.twig',
array(
// 'pdf'=>true,
'page_title' => 'Trial Balance',
'company_name' => $company_data->getName(),
'company_data' => $company_data,
// 'details'=>$bs_details,
'tb_details' => $tb_details,
'start_date' => $start_date,
'end_date' => $end_date,
'max_level' => $max_level,
'expand_level' => $expand_level,
'cur_level' => $cur_level,
// 'ledger_data'=>$ledger_det,
'page_header' => 'Ledger',
'document_type' => 'Trial Balance',
'document_mark_image' => $document_mark['original'],
'page_header_sub' => 'Add',
'budget_variance_enabled' => $budgetEnabled,
'currBudgetList' => $em->getRepository('ApplicationBundle\\Entity\\FinancialBudget')->findBy(
array(
// 'budgetId'=>$id, ///material
'CompanyId' => $this->getLoggedUserCompanyId($request), ///material
)
),
'scale_variance' => ($request->query->has('scale_variance')) ? $request->query->get('scale_variance') : 0,
'budgetId' => ($request->query->has('budgetId')) ? $request->query->get('budgetId') : 0,
'head_list' => Accounts::HeadList($em),
'provisional' => $provisional_option,
// 'type_list'=>$type_list,
// 'child_list'=>$child_list,
// 'trans_data_by_closing'=>$trans_data_by_closing,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'invoice_footer' => $company_data->getInvoiceFooter(),
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'allocation_filters' => $allocationFilters,
'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
'project_list' => $allocationSupportData['project_list'],
'branch_list' => $allocationSupportData['branch_list'],
'cost_centers' => $allocationSupportData['cost_centers'],
)
);
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
// 'orientation' => 'landscape',
// 'enable-javascript' => false,
// 'javascript-delay' => 1000,
'no-stop-slow-scripts' => true,
'no-background' => false,
'lowquality' => false,
'encoding' => 'utf-8',
// 'images' => true,
// 'cookie' => array(),
'dpi' => 300,
'image-dpi' => 300,
// 'enable-external-links' => true,
// 'enable-internal-links' => true
));
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="Trial Balance.pdf"'
)
);
}
return $this->render(
'@Accounts/pages/print/trial_balance_print.html.twig',
array(
'page_title' => 'Trial Balance',
'export' => 'all',
'company_name' => $company_data->getName(),
'company_data' => $company_data,
// 'details'=>$bs_details,
'tb_details' => $tb_details,
'start_date' => $start_date,
'end_date' => $end_date,
'max_level' => $max_level,
'expand_level' => $expand_level,
'cur_level' => $cur_level,
// 'ledger_data'=>$ledger_det,
'page_header' => 'Ledger',
'document_type' => 'Trial Balance',
'document_mark_image' => $document_mark['original'],
'page_header_sub' => 'Add',
'budget_variance_enabled' => $budgetEnabled,
'currBudgetList' => $em->getRepository('ApplicationBundle\\Entity\\FinancialBudget')->findBy(
array(
// 'budgetId'=>$id, ///material
'CompanyId' => $this->getLoggedUserCompanyId($request), ///material
)
),
'scale_variance' => ($request->query->has('scale_variance')) ? $request->query->get('scale_variance') : 0,
'budgetId' => ($request->query->has('budgetId')) ? $request->query->get('budgetId') : 0,
'head_list' => Accounts::HeadList($em),
'provisional' => $provisional_option,
// 'type_list'=>$type_list,
// 'child_list'=>$child_list,
// 'trans_data_by_closing'=>$trans_data_by_closing,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'invoice_footer' => $company_data->getInvoiceFooter(),
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
// 'p'=>$p
)
);
}
public function testSnappy(Request $request)
{
$em = $this->getDoctrine()->getManager();
$company_data = Company::getCompanyData($em, $this->getLoggedUserCompanyId($request));
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
$html = $this->renderView(
'@Accounts/pages/print/test.html.twig',
array(
// 'pdf'=>true,
'page_title' => 'Trial Balance',
'company_name' => $company_data->getName(),
'company_data' => $company_data,
// 'details'=>$bs_details,
// 'ledger_data'=>$ledger_det,
'page_header' => 'Ledger',
'document_type' => 'Trial Balance',
'document_mark_image' => $document_mark['original'],
'page_header_sub' => 'Add',
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'allocation_filters' => $allocationFilters,
'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
'project_list' => $allocationSupportData['project_list'],
'branch_list' => $allocationSupportData['branch_list'],
'cost_centers' => $allocationSupportData['cost_centers'],
)
);
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
// 'orientation' => 'landscape',
// 'enable-javascript' => false,
// 'javascript-delay' => 1000,
// 'no-stop-slow-scripts' => true,
'no-background' => false,
// 'lowquality' => false,
'encoding' => 'utf-8',
// 'images' => true,
// 'cookie' => array(),
'dpi' => 300,
'image-dpi' => 300,
// 'enable-external-links' => true,
// 'enable-internal-links' => true
));
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="TestSnappy.pdf"'
)
);
}
public function CreateLedgerHead(Request $request)
{
$companyId = $this->getLoggedUserCompanyId($request);
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
$devAdmin = $request->getSession()->get('devAdminMode', 0) == 1;
//first lets assume replication is not selected so lets get the parent and check if any head has this parents id as replication id
$head_id = Accounts::CreateNewHead(
$em,
GeneralConstant::OPENING_YEAR,
$request->request->get('parent_id'),
$request->request->get('name'),
$request->request->get('code'),
$request->request->get('opening_balance'),
$request->request->get('cc_enabled'),
$request->request->get('head_nature'),
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$request->request->get('replication_head_id'),
$request->request->has('checkAdvanceParent') ? 1 : 0,
"",
"",
$companyId,
$request->request->has('markerHash') ? $request->request->get('markerHash') : null,
$request->request->has('costCentreTypes') ? $request->request->get('costCentreTypes') : '',
$request->request->has('narrationOnCheck') ? $request->request->get('narrationOnCheck') : '',
$devAdmin && $request->request->has('flag_is_system') ? (bool)$request->request->get('flag_is_system') : false,
$devAdmin && $request->request->has('flag_is_editable') ? (bool)$request->request->get('flag_is_editable') : true,
$devAdmin && $request->request->has('flag_is_deletable') ? (bool)$request->request->get('flag_is_deletable') : true,
$devAdmin && $request->request->has('flag_is_child_allowed') ? (bool)$request->request->get('flag_is_child_allowed') : true
); //blahere
// Optional: attach DATEV mapping if provided during creation
if ($head_id && $request->request->has('datev_code') && $request->request->get('datev_code') != '') {
$newHead = $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
->findOneBy(['accountsHeadId' => $head_id]);
if ($newHead) {
AccountHeadExternalMappingService::setDatevMapping(
$em,
$newHead,
$companyId,
$request->request->get('datev_code'),
$request->request->has('datev_name') ? $request->request->get('datev_name') : null
);
}
}
if ($request->request->get('replication_head_id') == '') {
$replicate_data_qry = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
->findBy(
array(
'replicationHeadId' => $request->request->get('parent_id'),
'replicate' => 1
)
);
//now create replicated heads for all of these
$p = 0;
foreach ($replicate_data_qry as $entry) {
$p++;
$replicated_id = Accounts::CreateNewHead(
$em,
GeneralConstant::OPENING_YEAR,
$entry->getAccountsHeadId(),
$request->request->get('name'),
$request->request->get('code') . $p,
$request->request->get('opening_balance'),
$request->request->get('cc_enabled'),
"",
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$head_id,
$entry->getAdvanceOf() == $request->request->get('parent_id') ? 1 : 0
);
}
} else {
// //creating the re
// $head_id=Accounts::CreateNewHead(
// $em,
// GeneralConstant::OPENING_YEAR,
// $request->request->get('parent_id'),
// $request->request->get('name'),
// $request->request->get('code'),
// $request->request->get('opening_balance'),
// $request->request->get('cc_enabled'),
// $request->request->get('head_nature'),
// $request->getSession()->get(UserConstants::USER_LOGIN_ID,
// $request->request->get('replication_head_id'),
// $request->request->has('checkAdvanceParent')?1:0
// )
// );
}
// $url = $this->generateUrl(
// 'edit_ledger_head'
// );
//
// return $this->redirect($url . "/" . $head_id);
}
return $this->render(
'@Accounts/pages/input_forms/add_ledger_heads.html.twig',
array(
'page_title' => 'Create Ledger Head',
'headMarkers' => AccountsConstant::$HEAD_MARKER_ARRAY,
'costCentreTypesArray' => AccountsConstant::$costCentreTypesArray,
)
);
}
public function CreateLedgerHeadForApp(Request $request)
{
$companyId = $this->getLoggedUserCompanyId($request);
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
//first lets assume replication is not selected so lets get the parent and check if any head has this parents id as replication id
$head_id = Accounts::CreateNewHead(
$em,
GeneralConstant::OPENING_YEAR,
$request->request->get('parent_id'),
$request->request->get('name'),
$request->request->get('code'),
$request->request->get('opening_balance'),
$request->request->get('cc_enabled'),
$request->request->get('head_nature'),
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$request->request->get('replication_head_id'),
$request->request->has('checkAdvanceParent') ? 1 : 0,
"",
"",
$companyId,
$request->request->has('markerHash') ? $request->request->get('markerHash') : null,
$request->request->has('costCentreTypes') ? $request->request->get('costCentreTypes') : '',
$request->request->has('narrationOnCheck') ? $request->request->get('narrationOnCheck') : ''
); //blahere
if ($request->request->get('replication_head_id') == '') {
$replicate_data_qry = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
->findBy(
array(
'replicationHeadId' => $request->request->get('parent_id'),
'replicate' => 1
)
);
//now create replicated heads for all of these
$p = 0;
foreach ($replicate_data_qry as $entry) {
$p++;
$replicated_id = Accounts::CreateNewHead(
$em,
GeneralConstant::OPENING_YEAR,
$entry->getAccountsHeadId(),
$request->request->get('name'),
$request->request->get('code') . $p,
$request->request->get('opening_balance'),
$request->request->get('cc_enabled'),
"",
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$head_id,
$entry->getAdvanceOf() == $request->request->get('parent_id') ? 1 : 0
);
}
} else {
// //creating the re
// $head_id=Accounts::CreateNewHead(
// $em,
// GeneralConstant::OPENING_YEAR,
// $request->request->get('parent_id'),
// $request->request->get('name'),
// $request->request->get('code'),
// $request->request->get('opening_balance'),
// $request->request->get('cc_enabled'),
// $request->request->get('head_nature'),
// $request->getSession()->get(UserConstants::USER_LOGIN_ID,
// $request->request->get('replication_head_id'),
// $request->request->has('checkAdvanceParent')?1:0
// )
// );
}
// $url = $this->generateUrl(
// 'edit_ledger_head'
// );
//
// return $this->redirect($url . "/" . $head_id);
}
return new JsonResponse([
'success' => 'true',
]);
// return $this->render(
// '@Accounts/pages/input_forms/add_ledger_heads.html.twig',
// array(
// 'page_title' => 'Create Ledger Head',
// 'headMarkers' => AccountsConstant::$HEAD_MARKER_ARRAY,
// 'costCentreTypesArray' => AccountsConstant::$costCentreTypesArray,
// )
// );
}
public function ChartOfAccounts(Request $request)
{
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
// if($request->isMethod('POST')) {
//
//
//
// //first lets assume replication is not selected so lets get the parent and check if any head has this parents id as replication id
//
// $head_id=Accounts::CreateNewHead(
// $em,
// GeneralConstant::OPENING_YEAR,
// $request->request->get('parent_id'),
// $request->request->get('name'),
// $request->request->get('code'),
// $request->request->get('opening_balance'),
// $request->request->get('cc_enabled'),
// $request->request->get('head_nature'),
// $request->getSession()->get(UserConstants::USER_LOGIN_ID),
// $request->request->get('replication_head_id'),
// $request->request->has('checkAdvanceParent')?1:0
//
// ); //blahere
// if($request->request->get('replication_head_id')=='')
// {
// $replicate_data_qry= $this->getDoctrine()
// ->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
// ->findBy(
// array(
// 'replicationHeadId' => $request->request->get('parent_id'),
// 'replicate'=>1
// )
// );
//
// //now create replicated heads for all of these
// $p=0;
// foreach($replicate_data_qry as $entry)
// {
// $p++;
//
// $replicated_id=Accounts::CreateNewHead(
// $em,
// GeneralConstant::OPENING_YEAR,
// $entry->getAccountsHeadId(),
// $request->request->get('name'),
// $request->request->get('code').$p,
// $request->request->get('opening_balance'),
// $request->request->get('cc_enabled'),
// "",
// $request->getSession()->get(UserConstants::USER_LOGIN_ID),
// $head_id,
// $entry->getAdvanceOf()==$request->request->get('parent_id')?1:0
//
// );
//
// }
//
// }
// else
// {
//// //creating the re
//// $head_id=Accounts::CreateNewHead(
//// $em,
//// GeneralConstant::OPENING_YEAR,
//// $request->request->get('parent_id'),
//// $request->request->get('name'),
//// $request->request->get('code'),
//// $request->request->get('opening_balance'),
//// $request->request->get('cc_enabled'),
//// $request->request->get('head_nature'),
//// $request->getSession()->get(UserConstants::USER_LOGIN_ID,
//// $request->request->get('replication_head_id'),
//// $request->request->has('checkAdvanceParent')?1:0
//// )
//// );
// }
//// $url = $this->generateUrl(
//// 'edit_ledger_head'
//// );
////
//// return $this->redirect($url . "/" . $head_id);
//
// }
return $this->render(
'@Accounts/pages/report/chart_of_accounts.html.twig',
array(
'page_title' => 'Chart of Accounts',
// 'debug_data'=> Company::getMonthlyDataForDashboard($em, $session->get(UserConstants::USER_COMPANY_ID, 1))
)
);
}
public function EditLedgerHead(Request $request, $id)
{
$headExists = 1;
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
$head_data_qry = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
->findOneBy(
array(
'accountsHeadId' => $id,
// 'lockFlag'=>[0,null]
)
);
$headExists = 1;
if ($request->request->has('transferTransactionsFlag')) {
$query = "update acc_transaction_details set accounts_head_id =" . $request->request->get('transferTransactionTo') . " where accounts_head_id =" . $id . ";";
//transfer any payment checks
$query .= "update acc_check set accounts_head_id =" . $request->request->get('transferTransactionTo') . " where accounts_head_id =" . $id . ";";
$query .= "update acc_check set rec_accounts_head_id =" . $request->request->get('transferTransactionTo') . " where rec_accounts_head_id =" . $id . ";";
$stmt = $em->getConnection()->fetchAllAssociative($query);
//now transfer any received checks
$query = "SELECT * from acc_check where rec_accounts_head_id_list like '%\"" . $id . "\"%' ;";
$stmt = $em->getConnection()->fetchAllAssociative($query);
$results = $stmt;
foreach ($results as $result) {
$query = 'update acc_check set rec_accounts_head_id_list=\''
. str_replace("\"" . $id . "\"", "\"" . $request->request->get('transferTransactionTo') . "\"", $result['rec_accounts_head_id_list']) . '\' '
. 'where check_id=' . $result['check_id'];
$stmt = $em->getConnection()->fetchAllAssociative($query);
}
$this->addFlash(
'success',
'Transferred Transactions '
);
}
if ($request->request->has('deleteHeadFlag')) {
if (!AccountHeadPermissionService::canDelete($head_data_qry)) {
$this->addFlash('error', 'Could not Delete Head. This head is protected and cannot be deleted.');
} else {
$query = "SELECT accounts_head_id from acc_accounts_head where parent_id=" . $id;
$stmt = $em->getConnection()->fetchAllAssociative($query);
$results1 = $stmt;
if (!empty($results1)) {
$this->addFlash(
'error',
'Could not Delete Head. Child Heads Found'
);
} else {
$query = "SELECT * from acc_transaction_details where accounts_head_id =" . $id;
$stmt = $em->getConnection()->fetchAllAssociative($query);
$results2 = $stmt;
if (!empty($results2)) {
$this->addFlash(
'error',
'Could not Delete Head. Transactions Entry Found'
);
} else {
$headExists = 0;
if ($head_data_qry) {
AccountHeadExternalMappingService::deleteMappingsForHead($em, (int)$id);
$em->remove($head_data_qry);
$em->flush();
}
$this->addFlash(
'success',
'Deleted Head'
);
}
}
}
} else {
$devAdmin = $request->getSession()->get('devAdminMode', 0) == 1;
if (!$devAdmin && !AccountHeadPermissionService::canEdit($head_data_qry)) {
$this->addFlash('error', 'Could not Edit Head. This head is protected and cannot be modified.');
} else {
// $change_in_opening= $request->request->get('opening_balance')-$head_data_qry->setOpeningBalance();
$head_data_qry->setParentId($request->request->get('parent_id'));
$head_data_qry->setName($request->request->get('name'));
if ($request->request->has('markerHash') && !$head_data_qry->getIsSystem())
$head_data_qry->setMarkerHash($request->request->get('markerHash'));
if ($request->request->has('costCentreTypes'))
$head_data_qry->setCostCentreTypes($request->request->get('costCentreTypes'));
if ($request->request->has('narrationOnCheck'))
$head_data_qry->setNarrationOnCheck($request->request->get('narrationOnCheck'));
$head_data_qry->setLedgerHeadCode($request->request->get('code'));
$head_data_qry->setOpeningBalance($request->request->get('opening_balance'));
$head_nature = $request->request->get('head_nature');
$parentHead = $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findOneBy(array(
"accountsHeadId" => $request->request->get('parent_id')
));
// if ($head_nature == '' || $head_nature == '0')
if (1) // ovverride ,from now the nature will be asiigned by parent only
{
// $accountsHead->setHeadnature(in_array($TheType, $credit_type) ? AccountsConstant::CREDIT : AccountsConstant::DEBIT);
$head_data_qry->setHeadnature($parentHead->getHeadNature());
} else
$head_data_qry->setHeadNature($head_nature);
$head_data_qry->setCcEnabled($request->request->get('cc_enabled'));
// Dev admin: allow overriding control flags directly from the form
if ($devAdmin) {
if ($request->request->has('flag_is_system'))
$head_data_qry->setIsSystem((bool)$request->request->get('flag_is_system'));
if ($request->request->has('flag_is_editable'))
$head_data_qry->setIsEditable((bool)$request->request->get('flag_is_editable'));
if ($request->request->has('flag_is_deletable'))
$head_data_qry->setIsDeletable((bool)$request->request->get('flag_is_deletable'));
if ($request->request->has('flag_is_child_allowed'))
$head_data_qry->setIsChildAllowed((bool)$request->request->get('flag_is_child_allowed'));
}
// Optional DATEV mapping update
if ($request->request->has('datev_code') && $request->request->get('datev_code') != '') {
AccountHeadExternalMappingService::setDatevMapping(
$em,
$head_data_qry,
$this->getLoggedUserCompanyId($request),
$request->request->get('datev_code'),
$request->request->has('datev_name') ? $request->request->get('datev_name') : null
);
}
// if($head_data_qry->getLockFlag()!=1&&$change_in_opening!=0) {
// $first_closing_date= $em->getRepository('ApplicationBundle\\Entity\\AccClosingBalance')->findOneBy(array(
//// 'date' => new \DateTime($trans_date),
// 'accountsHeadId'=>$id
// ),array('date'=>'ASC'));
// 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);
// 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);
// Accounts::HitLedger($em, $id, $change_in_opening, $head_data_qry->getHeadNature(), $change_in_opening);
// }
Accounts::AddHeadPath($em, $id);
$em->flush();
}
}
}
$head_data = [];
if ($id != '' && $id != 0 && $headExists == 1) {
$head_data_qry = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')
->findOneBy(
array(
'accountsHeadId' => $id,
)
);
$head_data['id'] = $head_data_qry->getAccountsHeadId();
$head_data['name'] = $head_data_qry->getName();
$head_data['narrationOnCheck'] = $head_data_qry->getNarrationOnCheck();
$head_data['parent_id'] = $head_data_qry->getParentId();
$head_data['marker_hash'] = $head_data_qry->getMarkerHash();
$head_data['cost_centre_types'] = $head_data_qry->getCostCentreTypes();
$head_data['head_nature'] = $head_data_qry->getHeadNature();
$head_data['cc_enabled'] = $head_data_qry->getCcEnabled();
$head_data['ledger_head_code'] = $head_data_qry->getLedgerHeadCode();
$head_data['opening_balance'] = $head_data_qry->getOpeningBalance();
$head_data['is_system'] = $head_data_qry->getIsSystem() ? 1 : 0;
$head_data['is_editable'] = $head_data_qry->getIsEditable() ? 1 : 0;
$head_data['is_deletable'] = $head_data_qry->getIsDeletable() ? 1 : 0;
$head_data['is_child_allowed'] = $head_data_qry->getIsChildAllowed() ? 1 : 0;
return $this->render(
'@Accounts/pages/input_forms/edit_ledger_head.html.twig',
array(
'page_title' => 'Edit Ledger Head',
'head_data' => $head_data,
'headMarkers' => AccountsConstant::$HEAD_MARKER_ARRAY,
'costCentreTypesArray' => AccountsConstant::$costCentreTypesArray,
)
);
} else {
return $this->render(
'@Accounts/pages/input_forms/add_ledger_heads.html.twig',
array(
'page_title' => 'Create Ledger Head',
'headMarkers' => AccountsConstant::$HEAD_MARKER_ARRAY,
'costCentreTypesArray' => AccountsConstant::$costCentreTypesArray,
)
);
}
}
public function GetCostCentres(Request $request, $headId = 0, $costCentreTypesStr = '')
{
$cc_id = '';
$cc_name = '';
$cc_type = '';
$cost_centre_types_array_this = [];
$em = $this->getDoctrine()->getManager();
if ($headId != 0) {
$queryStr = "select * from acc_accounts_head where
accounts_head_id=$headId limit 1";
$stmt = $em->getConnection()->fetchAllAssociative($queryStr);
$results = $stmt;
$parentIdList = [];
if (!empty($results)) {
$headData = $results[0];
$parentIdList = array_filter(explode(",", $headData['path_tree']));
$cost_centre_types_array_this = array_filter(explode(",", $headData['cost_centre_types']));
$costCentreTypesStr = $headData['cost_centre_types'];
if ($costCentreTypesStr == "" || $costCentreTypesStr == null) {
$queryStr = "select * from acc_accounts_head where
accounts_head_id in ( " . implode(',', $parentIdList) . " )";
$stmt = $em->getConnection()->fetchAllAssociative($queryStr);
$results = $stmt;
if (!empty($results)) {
foreach ($results as $result) {
$headData = $result;
$cost_centre_types_array_this_only = array_filter(explode(",", $headData['cost_centre_types']));
$cost_centre_types_array_this = array_merge($cost_centre_types_array_this, array_diff($cost_centre_types_array_this, $cost_centre_types_array_this_only));
}
}
}
}
}
if (empty($cost_centre_types_array_this)) {
if ($costCentreTypesStr == "" || $costCentreTypesStr == null) {
} else {
$cost_centre_types_array_this = array_filter(explode(",", $costCentreTypesStr));
}
}
$queryStr = "select * from acc_cost_centre where
company_id=" . $this->getLoggedUserCompanyId($request);
if (empty($cost_centre_types_array_this)) {
foreach ($cost_centre_types_array_this as $typ)
$queryStr .= " and cost_centre_type like '%" . $typ . "%' ";
}
$stmt = $em->getConnection()->fetchAllAssociative($queryStr);
$cc_data = $stmt;
$cc_data_list = [];
foreach ($cc_data as $value) {
$cc_data_list[$value['cost_centre_id']]['id'] = $value['cost_centre_id'];
$cc_data_list[$value['cost_centre_id']]['name'] = $value['name'];
$cc_data_list[$value['cost_centre_id']]['type'] = $value['cost_centre_type'];
}
if (!empty($cc_data_list))
return new JsonResponse(array(
'success' => true,
'data' => $cc_data_list
));
else
return new JsonResponse(array(
'success' => false,
'data' => $cc_data_list
));
}
public function CreateCostCentre(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$cc_id = '';
$cc_name = '';
$cc_type = '';
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
// $submittedToken = $request->request->get('token');
//
// // 'delete-item' is the same value used in the template to generate the token
// if ($this->isCsrfTokenValid('delete-item', $submittedToken)) {
// // ... do something, like deleting an object
// }
// return new Response(1);
if ($request->request->get('cc_id') != '' && $request->request->get('cc_id') != 0) {
$em = $this->getDoctrine()->getManager();
$new_cc = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccCostCentre')
->findOneBy(
array(
'costCentreId' => $id,
)
);
$new_cc->setName($request->request->get('name'));
$new_cc->setCostCentreType($request->request->get('costCentreType'));
$new_cc->setCompanyId($this->getLoggedUserCompanyId($request));
$em->flush();
} else {
$new_cc = new AccCostCentre();
$new_cc->setName($request->request->get('name'));
$new_cc->setCostCentreType($request->request->get('costCentreType'));
$new_cc->setCompanyId($this->getLoggedUserCompanyId($request));
$em->persist($new_cc);
$em->flush();
$new_cc->getCostCentreId();
}
}
$cc_data = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccCostCentre')
->findAll();
$cc_data_list = [];
foreach ($cc_data as $value) {
$cc_data_list[$value->getCostCentreId()]['id'] = $value->getCostCentreId();
$cc_data_list[$value->getCostCentreId()]['name'] = $value->getName();
$cc_data_list[$value->getCostCentreId()]['type'] = $value->getCostCentreType();
if ($value->getCostCentreId() == $id) {
$cc_id = $value->getCostCentreId();
$cc_name = $value->getName();
$cc_type = $value->getCostCentreType();
}
}
return $this->render(
'@Accounts/pages/input_forms/add_cost_centre.html.twig',
array(
'page_title' => 'Cost Centre',
'cc_data' => $cc_data_list,
'cc_id' => $cc_id,
'costCentreTypesArray' => AccountsConstant::$costCentreTypesArray,
'costCentreTypes' => AccountsConstant::$costCentreTypes,
'cc_name' => $cc_name,
'cc_type' => $cc_type
)
);
}
public function index(Request $request)
{
return $this->render(
'@Application/pages/dashboard/index.html.twig',
array(
'page_title' => 'Dashboard'
)
);
}
public function TestPixInvent(Request $request)
{
$em = $this->getDoctrine()->getManager();
$allowed_ids = [];
$companyId = $this->getLoggedUserCompanyId($request);
// return $this->render('ApplicationBundle:pages/dashboard:test_pix_invent.html.twig',
return $this->render(
'@Application/pages/dashboard/codecovers_test.html.twig',
array(
'page_title' => 'Client List',
'data' => SalesOrderM::GetClientList($em, [], $companyId),
'client_types' => Client::GetClientType($em, $companyId),
'region_list' => Client::RegionList($em, $companyId),
'geographical_region_list' => Client::GeographicalRegionList($em, $companyId)
)
);
}
public function GetDocumentHash(Request $request, $t, $p, $a)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$timestamp = $request->request->get('timeStampOfForm', $request->query->get('timeStampOfForm', ''));
$documentId = $request->request->get('documentId', $request->query->get('documentId', 0));
if ($request->query->has('returnJson'))
return new JsonResponse(array(
'success' => true,
'numberHash' => MiscActions::GetNumberHash($em, $t, $p, $a, $timestamp, $documentId, $companyId)
));
else
return new Response(MiscActions::GetNumberHash($em, $t, $p, $a, $timestamp, $documentId, $companyId));
}
public function CreatePrefix(Request $request)
{
if ($request->isMethod('POST')) {
// Generic::debugMessage($_POST);
//
$ledgerHeads = [];
$costCenters = [];
$prefix_name = $request->request->get('pref_name');
$prefix_usages = $request->request->get('pref_usages');
$prefix_entry_types = $request->request->get('entryTypes');
if ($prefix_name != 'GN' || $prefix_name != 'gn') {
$ledgerHeads = $request->request->get('ledgerHeads');
$costCenters = $request->request->get('costCenters');
$prefix_name = $request->request->get('pref_name');
$prefix_usages = $request->request->get('pref_usages');
$prefix_entry_types = $request->request->get('entryTypes');
}
// Form arrays may be absent on a POST (e.g. a GN prefix with no ledger
// heads) → coalesce to arrays so count()/indexing don't fatal (PHP 7.2+).
$ledgerHeads = is_array($ledgerHeads) ? $ledgerHeads : [];
$costCenters = is_array($costCenters) ? $costCenters : [];
$prefix_usages = is_array($prefix_usages) ? $prefix_usages : [];
$prefix_entry_types = is_array($prefix_entry_types) ? $prefix_entry_types : [];
// $crAmount=$request->request->get('crAmount');
$prefix_details = array();
for ($i = 0; $i < count($ledgerHeads); $i++) {
array_push($prefix_details, array(
'head_id' => $ledgerHeads[$i],
'cost_centre' => isset($costCenters[$i]) ? $costCenters[$i] : 0,
'type' => $prefix_entry_types[$i],
));
}
for ($i = 0; $i < count($prefix_usages); $i++) {
Accounts::CreateNewPrefix(
$this->getDoctrine()->getManager(),
$prefix_usages[$i],
$prefix_name,
$prefix_details
);
}
$this->addFlash(
'success',
'New Prefix Added.'
);
}
return $this->render(
'@Accounts/pages/input_forms/add_prefix.html.twig',
array(
'page_title' => 'Prefix'
)
);
}
public function BankRecon(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$bank_settings = $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
'name' => 'bank_parents'
));
$bank_id_list = [];
if ($bank_settings)
$bank_id_list = json_decode($bank_settings->getData());
$head_list = Accounts::HeadListFullPath($em);
$bank_head_list = [];
foreach ($head_list as $k => $v) {
foreach ($bank_id_list as $bid) {
$q_str = '/' . $bid . '/';
$path_string = $v['path'];
$debug_it[] = [$q_str, $path_string, strpos($path_string, $q_str)];
if (strpos($path_string, $q_str) !== false) {
$bank_head_list[$k] = $v;
} else {
}
}
}
// if($request->isMethod('POST')){
// //it will be used on the approval page start
// //it will be used on the approval page start
// }
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['Brs'];
$typeHash = "BRS-" . $request->request->get('bank_head');
$brsDate = new \DateTime($request->request->get('statement_date'));
$prefixHash = $brsDate->format('Y');
$assocHash = $brsDate->format('m');
$numberHash = $brsDate->format('d');
// $dochash=$request->request->get('docHash');
$dochash = $typeHash . '/' . $prefixHash . '/' . $assocHash . '/' . $numberHash;
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole') ? $request->request->get('approvalRole') : 1;
$approveHash = $request->request->has('approvalHash') ? $request->request->get('approvalHash') : '';
$skipApprove = 0;
// if($approveHash=='') {
// $skipApprove = 1;//temp
// }
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash,
$id,
$skipApprove
)) {
$this->addFlash(
'error',
'Sorry Could not insert Data.'
);
} else {
//construct the files
$post_data = $request->request;
$brs = $em
->getRepository('ApplicationBundle\\Entity\\Brs')
->findOneby(array(
'brsId' => $id
));
if ($brs)
$new = $brs;
else
$new = new Brs();
$LoginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$companyId = $this->getLoggedUserCompanyId($request);
$data = array();
$exception_key_list = [
'approvalRole',
'approvalHash',
'assocHash',
'numberHash',
'typeHash',
'prefixHash',
'pending_cn',
'pending_vn',
'cleared_cn',
'cleared_vn',
'pending_check_amount_old',
'pending_check_amount_add_old',
'nsf_cn',
'nsf_vn',
];
$prTypeList = array(
0 => 'Document',
1 => 'Ind. Check',
2 => 'Cons. Check',
3 => 'Adv. Letter',
4 => 'O/L Trans',
);
//adding vn and cn
$pending_cn = [];
$pending_vn = [];
foreach (json_decode($post_data->get('pending_check_id'), true) as $v) {
$check = $em
->getRepository('ApplicationBundle\\Entity\\AccCheck')
->findOneby(array(
'CheckId' => $v
));
if ($check) {
$pending_cn[] = $check->getCheckNumber();
$vchr = $em
->getRepository('ApplicationBundle\\Entity\\AccTransactions')
->findOneby(array(
'transactionId' => $check->getVoucherId()
));
if ($vchr) {
$pending_vn[] = $vchr->getDocumentHash();
} else
$pending_vn[] = '';
} else {
$vid = explode('_', explode('v', $v)[1])[0];
$vchr = $em
->getRepository('ApplicationBundle\\Entity\\AccTransactions')
->findOneby(array(
'transactionId' => $vid
));
if ($vchr) {
$prRef = $vchr->getPrReference();
if ($prRef == '0') {
$prRef = $prTypeList[$vchr->getPrMethod()] . " on " . $vchr->getDocumentHash();
}
if ($vchr->getDocumentType() == 6) {
$prRef = "Cash Received on " . $vchr->getDocumentHash();
}
$pending_cn[] = $prRef;
$pending_vn[] = $vchr->getDocumentHash();
}
}
}
$data['pending_cn'] = $pending_cn;
$data['pending_vn'] = $pending_vn;
$cleared_cn = [];
$cleared_vn = [];
foreach (json_decode($post_data->get('cleared_check_id'), true) as $v) {
$check = $em
->getRepository('ApplicationBundle\\Entity\\AccCheck')
->findOneby(array(
'CheckId' => $v
));
if ($check) {
$cleared_cn[] = $check->getCheckNumber();
$vchr = $em
->getRepository('ApplicationBundle\\Entity\\AccTransactions')
->findOneby(array(
'transactionId' => $check->getVoucherId()
));
if ($vchr) {
$cleared_vn[] = $vchr->getDocumentHash();
} else
$cleared_vn[] = '';
} else {
$vid = explode('_', explode('v', $v)[1])[0];
$vchr = $em
->getRepository('ApplicationBundle\\Entity\\AccTransactions')
->findOneby(array(
'transactionId' => $vid
));
if ($vchr) {
$prRef = $vchr->getPrReference();
if ($prRef == '0') {
$prRef = $prTypeList[$vchr->getPrMethod()] . " on " . $vchr->getDocumentHash();
}
if ($vchr->getDocumentType() == 6) {
$prRef = "Cash Received on " . $vchr->getDocumentHash();
}
$cleared_cn[] = $prRef;
$cleared_vn[] = $vchr->getDocumentHash();
}
}
}
$data['cleared_cn'] = $cleared_cn;
$data['cleared_vn'] = $cleared_vn;
$nsf_cn = [];
$nsf_vn = [];
foreach (json_decode($post_data->get('nsf_check_id'), true) as $v) {
$check = $em
->getRepository('ApplicationBundle\\Entity\\AccCheck')
->findOneby(array(
'CheckId' => $v
));
if ($check) {
$nsf_cn[] = $check->getCheckNumber();
$vchr = $em
->getRepository('ApplicationBundle\\Entity\\AccTransactions')
->findOneby(array(
'transactionId' => $check->getVoucherId()
));
if ($vchr) {
$nsf_vn[] = $vchr->getDocumentHash();
} else
$nsf_vn[] = '';
} else {
$vid = explode('_', explode('v', $v)[1])[0];
$vchr = $em
->getRepository('ApplicationBundle\\Entity\\AccTransactions')
->findOneby(array(
'transactionId' => $vid
));
if ($vchr) {
$prRef = $vchr->getPrReference();
if ($prRef == '0') {
$prRef = $prTypeList[$vchr->getPrMethod()] . " on " . $vchr->getDocumentHash();
}
if ($vchr->getDocumentType() == 6) {
$prRef = "Cash Received on " . $vchr->getDocumentHash();
}
$nsf_cn[] = $prRef;
$nsf_vn[] = $vchr->getDocumentHash();
}
}
}
$data['nsf_cn'] = $nsf_cn;
$data['nsf_vn'] = $nsf_vn;
foreach ($post_data->keys() as $req_key) {
if (!in_array($req_key, $exception_key_list)) {
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'])) {
$data[$req_key] = json_decode($post_data->get($req_key), true);
} else
$data[$req_key] = $post_data->get($req_key);
}
}
$new->setBrsDate($brsDate);
$new->setDocumentHash($dochash);
$new->setTypeHash($typeHash);
$new->setPrefixHash($prefixHash);
$new->setNumberHash($numberHash);
$new->setAssocHash($assocHash);
$new->setAccountsHeadId($request->request->get('bank_head'));
$new->setCompanyId($companyId);
$new->setData(json_encode($data));
$new->setStatus(GeneralConstant::ACTIVE);
// if($auto_created==1)
// $new->setApproved(GeneralConstant::APPROVED);
// else
$new->setApproved(GeneralConstant::APPROVAL_STATUS_PENDING);
$new->setAutoCreated(0);
$new->setEditFlag(0);
$new->setDeleteFlag(0);
$new->setLockFlag(0);
$new->setDisabledFlag(0);
if (!$brs) {
$new->setCreatedLoginId($LoginId);
} else
$new->setEditedLoginId($LoginId);
$em->persist($new);
$em->flush();
$docId = $new->getBrsId();
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole'); //created
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
[],
array_flip(GeneralConstant::$Entity_list)['Brs'],
$docId,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['Brs'],
$docId,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$this->addFlash(
'success',
'Bank Reconciliation Created'
);
$url = $this->generateUrl(
'view_brs'
);
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),
"Bank Reconciliation : " . $dochash . " Has Been Created And is Under Processing",
'pos',
System::getPositionIdsByDepartment($em, GeneralConstant::SALES_DEPARTMENT),
'success',
$url . "/" . $docId,
"BRS"
);
return $this->redirect($url . "/" . $docId);
}
}
$check_query = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccCheck')
->findBy(
array(
'assigned' => 1,
'status' => 3, //pending
'active' => 1,
'destroyed' => [0, null],
'securityCheck' => [0, null],
),
array(
'checkNumber' => 'ASC'
)
);
$check_data = [];
$voucher_list = Accounts::VoucherList($em);
foreach ($check_query as $check_here) {
$new_check_data = array(
'checkId' => $check_here->getCheckId(),
'checkNumber' => $check_here->getCheckNumber(),
'voucherId' => $check_here->getVoucherId(),
'voucherNumber' => isset($voucher_list[$check_here->getVoucherId()]) ? $voucher_list[$check_here->getVoucherId()]['doc_hash'] : '',
'checkDate' => $check_here->getCheckDate() ? $check_here->getCheckDate()->format('Y-m-d') : '',
'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') : ''),
// 'reconDate'=>$recondatestr,
);
$check_data[$check_here->getCheckId()] = $new_check_data;
}
return $this->render(
'@Accounts/pages/input_forms/bank_recon.html.twig',
array(
'page_title' => 'Bank ',
'check_list' => $check_data,
'bank_head_list' => $bank_head_list,
'bank_id_list' => $bank_id_list,
)
);
}
public function CheckRecon(Request $request)
{
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
$check_ids = $request->request->get('check_id');
$recon_dates = $request->request->get('recon_date');
if (!empty($check_ids)) {
foreach ($check_ids as $key => $c) {
$check = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccCheck')
->findOneBy(
array(
'CheckId' => $c
)
);
if ($check) {
$check->setStatus(1); //transaction confirmed
$check->setReconDate(new \DateTime($recon_dates[$key]));
$em->flush();
Accounts::ActionAfterNonProvisionalVoucher($em, $check->getVoucherId());
}
}
}
}
$check_query = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccCheck')
->findBy(
array(
'assigned' => 1,
'status' => 3, //pending
'active' => 1
),
array(
'checkNumber' => 'ASC'
)
);
$check_data = [];
$voucher_list = Accounts::VoucherList($em);
foreach ($check_query as $check_here) {
$new_check_data = array(
'checkId' => $check_here->getCheckId(),
'checkNumber' => $check_here->getCheckNumber(),
'voucherId' => $check_here->getVoucherId(),
'voucherNumber' => $voucher_list[$check_here->getVoucherId()]['doc_hash'],
'checkDate' => $check_here->getCheckDate()->format('Y-m-d'),
'transactionDate' => $voucher_list[$check_here->getVoucherId()]['date']->format('Y-m-d'),
// 'reconDate'=>$recondatestr,
);
$check_data[$check_here->getCheckId()] = $new_check_data;
}
return $this->render(
'@Accounts/pages/input_forms/check_recon.html.twig',
array(
'page_title' => 'Bank Reconciliation',
'check_list' => $check_data
)
);
}
public function ExcelTest(Request $request)
{
// ask the service for a Excel5
$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
$phpExcelObject->getProperties()->setCreator("liuggio")
->setLastModifiedBy("Giulio De Donato")
->setTitle("Office 2005 XLSX Test Document")
->setSubject("Office 2005 XLSX Test Document")
->setDescription("Test document for Office 2005 XLSX, generated using PHP classes.")
->setKeywords("office 2005 openxml php")
->setCategory("Test result file");
$phpExcelObject->setActiveSheetIndex(0)
->setCellValue('A1', 'Hello')
->setCellValue('B2', 'world!');
$phpExcelObject->getActiveSheet()->setTitle('Simple');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$phpExcelObject->setActiveSheetIndex(0);
// create the writer
$writer = $this->get('phpexcel')->createWriter($phpExcelObject, 'Excel5');
// create the response
$response = $this->get('phpexcel')->createStreamedResponse($writer);
// adding headers
$dispositionHeader = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
'stream-file.xls'
);
$response->headers->set('Content-Type', 'text/vnd.ms-excel; charset=utf-8');
$response->headers->set('Pragma', 'public');
$response->headers->set('Cache-Control', 'maxage=1');
$response->headers->set('Content-Disposition', $dispositionHeader);
return $response;
}
public function ImageUpload(Request $request)
{
$post_data = $request->request;
$file = $post_data->get('file');
$fileName = "";
if ($file) {
if ($post_data->has('isBase64')) {
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $file));
$fileName = md5(uniqid()) . '.png';
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ExpenseInvoice/';
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ExpenseInvoice/' . $path;
file_put_contents($upl_dir, $data);
} else {
$fileName = md5(uniqid()) . '.' . $file->guessExtension();
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ExpenseInvoice/';
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
$file = $file->move($upl_dir, $path);
}
}
return new JsonResponse(array('file_name' => $fileName));
}
public function ExportPagePdf(Request $request)
{
// $l= $this->get('knp_snappy.pdf')->generateFromHtml($html
// ,
// $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/myfile.pdf'
// );
// $chk=$this->get('knp_snappy.pdf');
if ($request->getMethod() == 'POST') {
$data = $request->request->has('exportable_data') ? $request->request->get('exportable_data') : '';
$doc_title = $request->request->has('doc_title') ? $request->request->get('doc_title') : 'Exported_data';
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($data, array(
// 'orientation' => 'landscape',
// 'enable-javascript' => true,
// 'javascript-delay' => 1000,
'no-stop-slow-scripts' => true,
'no-background' => false,
'lowquality' => false,
'encoding' => 'utf-8',
// 'images' => true,
// 'cookie' => array(),
'dpi' => 300,
'image-dpi' => 300,
// 'enable-external-links' => true,
// 'enable-internal-links' => true
));
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="' . $doc_title . '.pdf"'
)
);
}
}
public function ExportTableDataExcel(Request $request)
{
// ask the service for a Excel5
$em = $this->getDoctrine()->getManager();
$company_data = Company::getCompanyData($em, $this->getLoggedUserCompanyId($request));
$company_name = $company_data->getName();
$company_address = $company_data->getAddress();
$company_invoice_footer = $company_data->getInvoiceFooter();
$replace_list = array(
'%companyName%' => $company_name,
'%companyAddress%' => $company_address,
);
if ($request->isMethod('POST')) {
// $phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
// $spreadsheet = new Spreadsheet();
//
// $sheet = $spreadsheet->getActiveSheet();
// $sheet->setCellValue('A1', 'Hello World !');
//
// $writer = new Xlsx($spreadsheet);
// $writer->save('hello world.xlsx');
if (version_compare(PHP_VERSION, '7.3.0', '>=')) {
$phpExcelObject = new Spreadsheet();
} else {
$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
}
$phpExcelObject->getProperties()->setCreator("HoneyBee IoT Ltd.")
->setLastModifiedBy("Honeybee Ecosystem")
->setTitle("Office 2005 XLSX Test Document")
->setSubject("Office 2005 XLSX Test Document")
->setDescription("Test document for Office 2005 XLSX, generated using PHP classes.")
->setKeywords("office 2005 openxml php")
->setCategory("Test result file");
$data = $request->request->has('exportable_data') ? json_decode($request->request->get('exportable_data'), true) : [];
$sheet_title_data = $request->request->has('sheet_title') ? json_decode($request->request->get('sheet_title'), true) : [];
$doc_title = $request->request->has('doc_title') ? $request->request->get('doc_title') : 'Exported_data';
$sheet_id = 0;
foreach ($data as $list_index => $sheet) {
$phpExcelObject->createSheet($sheet_id);
$celldata = isset($sheet['data']) ? ($sheet['data']) : [];
$mergedata = isset($sheet['merge_data']) ? ($sheet['merge_data']) : [];
$styleArray = array(
'font' => array(
'bold' => false,
'color' => array('rgb' => '000000'),
'size' => 12,
'name' => 'Verdana',
),
'alignment' => array(
'horizontal' => 'left',
'vertical' => 'middle',
)
);
$phpExcelObject->getDefaultStyle()
->applyFromArray(
$styleArray
);
//
// $phpExcelObject->getDefaultStyle()
// ->getAlignment()
// ->applyFromArray(
// array('horizontal' => 'left',));
foreach ($celldata as $cell_info) {
$cell_text = isset($replace_list[$cell_info['cell_data']]) ? $replace_list[$cell_info['cell_data']] : $cell_info['cell_data'];
$phpExcelObject->setActiveSheetIndex($sheet_id)->setCellValue($cell_info['cell_no'], $cell_text);
// $phpExcelObject->setActiveSheetIndex($sheet_id)->setCellValue($cell_info['cell_no'], json_encode($cell_info));
// $phpExcelObject->getActiveSheet()->getStyle($cell_info['cell_no'])->applyFromArray(array( 'alignment'=>['horizontal='=>$cell_info['align'] ]));
if (isset($cell_info['align']))
$phpExcelObject->getActiveSheet()->getStyle($cell_info['cell_no'])->getAlignment()->applyFromArray(
array('horizontal' => $cell_info['align'], 'vertical' => 'middle',)
);
}
foreach ($mergedata as $merge_info) {
if ($merge_info['enabled'] == 1)
$phpExcelObject->setActiveSheetIndex($sheet_id)->mergeCells($merge_info['merge_str']);
}
//now the sheet title
$sheet_name = $sheet_title_data[$list_index];
$sheet_name = str_ireplace('/', '', $sheet_name);
$sheet_name = str_ireplace(':', ' ', $sheet_name);
// $sheet_name=str_ireplace('\n','',$sheet_name);
$sheet_name = trim(preg_replace('/\s\s+/', ' ', $sheet_name));;
// System::log_it($this->container->getParameter('kernel.root_dir'),$sheet_name,'sheet_test');
if (strlen($sheet_name) > 31) {
//have to truncate
//first find if it has 'of and only take later part'
while (count(explode("of", $sheet_name)) > 1 && strlen($sheet_name) > 31) {
$pieces = explode("of", $sheet_name);
$sheet_name = str_replace($pieces[0], "", $sheet_name);
$sheet_name = str_replace($pieces[0], "", $sheet_name);
}
//now remove 1 word form start until length matches
// while(count(explode(" ", $sheet_name))>1&&strlen($sheet_name)>31) {
// $pieces = explode(" ", $sheet_name);
// if(count($pieces)<=1)
// break;
// $sheet_name=str_replace($pieces[0], "", $sheet_name);
//// str_replace()
//// $sheet_name = str_replace($pieces[0], "", $sheet_name);
// }
if (strlen($sheet_name) > 31) //now just chop
{
$sheet_name = substr($sheet_name, 0, 30);
}
}
$phpExcelObject->getActiveSheet()->setTitle($sheet_name);
$sheet = $phpExcelObject->getActiveSheet();
$cellIterator = $sheet->getRowIterator()->current()->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true);
/** @var PHPExcel_Cell $cell */
foreach ($cellIterator as $cell) {
$sheet->getColumnDimension($cell->getColumn())->setAutoSize(true);
}
$sheet_id++;
}
// Auto size columns for each worksheet
// foreach ($phpExcelObject->getWorksheetIterator() as $worksheet) {
//
// $phpExcelObject->setActiveSheetIndex($phpExcelObject->getIndex($worksheet));
//
// $sheet = $phpExcelObject->getActiveSheet();
// $cellIterator = $sheet->getRowIterator()->current()->getCellIterator();
// $cellIterator->setIterateOnlyExistingCells(true);
// /** @var PHPExcel_Cell $cell */
// foreach ($cellIterator as $cell) {
// $sheet->getColumnDimension($cell->getColumn())->setAutoSize(true);
// }
// }
//
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
if (version_compare(PHP_VERSION, '7.3.0', '>=')) {
$writer = new Xlsx($phpExcelObject);
$response = new StreamedResponse(
function () use ($writer) {
$writer->save('php://output');
}
);
} else {
$writer = $this->get('phpexcel')->createWriter($phpExcelObject, 'Excel5');
// create the response
$response = $this->get('phpexcel')->createStreamedResponse($writer);
}
$phpExcelObject->setActiveSheetIndex(0);
// adding headers
// $writer->save('hello world.xlsx');
// create the writer
// $writer = $this->get('phpexcel')->createWriter($phpExcelObject, 'Excel5');
// create the response
// $response = $this->get('phpexcel')->createStreamedResponse($writer);
// adding headers
$dispositionHeader = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
$doc_title . '.xls'
);
$response->headers->set('Content-Type', 'text/vnd.ms-excel; charset=utf-8');
$response->headers->set('Pragma', 'public');
$response->headers->set('Cache-Control', 'maxage=1');
$response->headers->set('Content-Disposition', $dispositionHeader);
return $response;
} else {
$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
$phpExcelObject->getProperties()->setCreator("liuggio")
->setLastModifiedBy("Giulio De Donato")
->setTitle("Office 2005 XLSX Test Document")
->setSubject("Office 2005 XLSX Test Document")
->setDescription("Test document for Office 2005 XLSX, generated using PHP classes.")
->setKeywords("office 2005 openxml php")
->setCategory("Test result file");
$phpExcelObject->createSheet(0);
$phpExcelObject->setActiveSheetIndex(0);
$phpExcelObject->setActiveSheetIndex(0)->setCellValue('A1', 'Hello');
$phpExcelObject->setActiveSheetIndex(0)->setCellValue('B2', 'world!');
$phpExcelObject->getActiveSheet()->setTitle('Simple');
$phpExcelObject->createSheet(1);
$phpExcelObject->setActiveSheetIndex(1)
->setCellValue('A1', 'Hello')
->setCellValue('B2', 'world!');
$phpExcelObject->getActiveSheet()->setTitle('complex');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$phpExcelObject->setActiveSheetIndex(0);
// create the writer
$writer = $this->get('phpexcel')->createWriter($phpExcelObject, 'Excel5');
// create the response
$response = $this->get('phpexcel')->createStreamedResponse($writer);
// adding headers
$dispositionHeader = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
'stream-file.xls'
);
$response->headers->set('Content-Type', 'text/vnd.ms-excel; charset=utf-8');
$response->headers->set('Pragma', 'public');
$response->headers->set('Cache-Control', 'maxage=1');
$response->headers->set('Content-Disposition', $dispositionHeader);
return $response;
}
}
public function AnalyzeTableDataExcel(Request $request)
{
// ask the service for a Excel5
$em = $this->getDoctrine()->getManager();
$extractedData = array();
if ($request->isMethod('POST')) {
foreach ($request->files as $uploadedFileGG) {
// if($uploadedFile->getImage())
// var_dump($uploadedFile->getFile());
// var_dump($uploadedFile);
$tempD = $uploadedFileGG;
if (!is_array($uploadedFileGG)) {
$uploadedFileGG = array();
$uploadedFileGG[] = $tempD;
}
foreach ($uploadedFileGG as $uploadedFile) {
if ($uploadedFile != null) {
$extension = $uploadedFile->guessExtension();
$size = $uploadedFile->getSize();
$fileName = 'TEMP_FILE_' . (md5(uniqid())) . '.' . $uploadedFile->guessExtension();
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/temp';
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
if (file_exists($upl_dir . '' . $path)) {
chmod($upl_dir . '' . $path, 0755);
unlink($upl_dir . '' . $path);
}
$file = $uploadedFile->move($upl_dir, $path);
if (version_compare(PHP_VERSION, '7.3.0', '>=')) {
$phpExcelObject = new Spreadsheet($upl_dir . '' . $path);
} else {
$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject($upl_dir . '' . $path);
}
$extractedData = $phpExcelObject;
if (file_exists($upl_dir . '' . $path)) {
chmod($upl_dir . '' . $path, 0755);
unlink($upl_dir . '' . $path);
}
}
}
}
// $phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
// $spreadsheet = new Spreadsheet();
//
// $sheet = $spreadsheet->getActiveSheet();
// $sheet->setCellValue('A1', 'Hello World !');
//
// $writer = new Xlsx($spreadsheet);
// $writer->save('hello world.xlsx');
if (version_compare(PHP_VERSION, '7.3.0', '>=')) {
$phpExcelObject = new Spreadsheet();
} else {
$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
}
}
return new JsonResponse($extractedData);
}
public function ViewVoucher(Request $request, $id)
{
$voucher_id = $id;
$em = $this->getDoctrine()->getManager();
$dt = Accounts::GetVoucherDetails($em, $voucher_id);
if ($request->get('returnJson')==1) {
return new \Symfony\Component\HttpFoundation\JsonResponse([
'success' => true,
'data' => $dt
]);
}
return $this->render(
// '@Accounts/pages/views/view_journal_voucher.html.twig',
'@Accounts/pages/views/view_journal_voucher_demo.html.twig',
array(
'page_title' => 'View',
'data' => $dt,
'auto_created' => $dt['auto_created'],
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
$voucher_id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => $dt['auto_created'] == 0 ? System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['AccTransactions'],
$voucher_id,
$dt['created_by'],
$dt['edited_by']
) : []
)
);
}
public function ViewPurchaseInvoice(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = Accounts::GetInvoiceDetails($em, $id);
return $this->render(
// '@Accounts/pages/views/view_purchase_invoice.html.twig',
'@Accounts/pages/views/view_purchase_invoice_demo.html.twig',
array(
'page_title' => 'View Purchase Invoice',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['PurchaseInvoice'],
$id,
$dt['created_by'],
$dt['edited_by']
)
)
);
}
public function PrintPurchaseInvoice(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$invoice_id = $id;
$data = Accounts::GetInvoiceDetails($em, $invoice_id);
$company_data = Company::getCompanyData($em, $this->getLoggedUserCompanyId($request));
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'pending' => '/images/pending.jpg',
'copy' => ''
);
$printTemplate = CountryTemplateResolver::resolve(
$this->get('twig'),
$em,
$this->getLoggedUserCompanyId($request),
'@Accounts/pages/print/pi_print.html.twig'
);
$taxMarkers = TaxMarkerLookup::forCompany($em, $this->getLoggedUserCompanyId($request));
if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
$html = $this->renderView(
$printTemplate,
array(
//full array here
'pdf' => true,
'page_title' => 'Purchase Invoice',
'data' => $data,
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'export' => 'pdf,print',
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'page_header' => 'New Product',
'document_type' => 'Purchase Invoice',
'page_header_sub' => 'Add',
// 'type_list'=>$type_list,
// 'mis_data'=>$mis_data,
// 'mis_print'=>$mis_print,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
'taxMarkers' => $taxMarkers,
)
);
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
// 'orientation' => 'landscape',
// 'enable-javascript' => true,
// 'javascript-delay' => 1000,
'no-stop-slow-scripts' => false,
'no-background' => false,
'lowquality' => false,
'encoding' => 'utf-8',
// 'images' => true,
// 'cookie' => array(),
'dpi' => 300,
'image-dpi' => 300,
// 'enable-external-links' => true,
// 'enable-internal-links' => true
));
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="sales_invoice_' . $id . '.pdf"'
)
);
}
return $this->render(
$printTemplate,
array(
// 'page_title' => 'Purchase Invoice',
// 'data' => $data,
// 'document_mark_image' => $document_mark['original'],
// 'company_name' => $company_data->getName(),
// 'company_data' => $company_data,
// 'company_address' => $company_data->getAddress(),
// 'company_image' => $company_data->getImage(),
// 'invoice_footer' => $company_data->getInvoiceFooter(),
// 'red' => 0
'page_title' => 'Purchase Invoice',
'data' => $data,
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'export' => 'pdf,print',
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'page_header' => 'New Product',
'document_type' => 'Purchase Invoice',
'page_header_sub' => 'Add',
// 'type_list'=>$type_list,
// 'mis_data'=>$mis_data,
// 'mis_print'=>$mis_print,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
'taxMarkers' => $taxMarkers,
)
);
}
public function ExpenseInvoiceList(Request $request)
{
$q = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')
->findBy(
array(
'status' => GeneralConstant::ACTIVE,
),
array(
'expenseInvoiceDate' => 'DESC'
)
);
$stage_list = array(
1 => 'Pending',
2 => 'Complete',
4 => 'Pending Payment',
);
$data = [];
foreach ($q as $entry) {
$data[] = array(
'doc_date' => $entry->getExpenseInvoiceDate(),
'id' => $entry->getExpenseInvoiceId(),
'doc_hash' => $entry->getDocumentHash(),
'invoice_amount' => $entry->getInvoiceAmount(),
'stage' => $stage_list[$entry->getStage()]
);
}
return $this->render(
'@Accounts/pages/list/expense_invoices.html.twig',
array(
'page_title' => 'Expense Invoices',
'data' => $data
)
);
}
public function ExpenseInvoiceApprovalQueue(Request $request)
{
$em = $this->getDoctrine()->getManager();
$expenseInvoiceEntityId = array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'];
if ($request->isMethod('POST')) {
$selectedIds = $request->request->all('selected_ids');
if (!is_array($selectedIds)) {
$selectedIds = [];
}
$selectedIds = array_values(array_filter(array_map('intval', $selectedIds)));
$bulkAction = $request->request->get('bulk_action', '');
if (empty($selectedIds)) {
$this->addFlash('error', 'Please select at least one expense invoice.');
} elseif (!in_array($bulkAction, ['approve', 'decline'], true)) {
$this->addFlash('error', 'Please choose a valid bulk action.');
} else {
$processed = 0;
foreach ($selectedIds as $selectedId) {
if ($bulkAction === 'approve') {
System::takeFullApproveActions(
$em,
$expenseInvoiceEntityId,
$selectedId,
$this->get('mail_module')
);
} else {
System::takeFullDeclineActions(
$em,
$expenseInvoiceEntityId,
$selectedId,
$this->get('mail_module')
);
}
$processed++;
}
$this->addFlash(
'success',
sprintf(
'%d expense invoice%s %s successfully.',
$processed,
$processed === 1 ? '' : 's',
$bulkAction === 'approve' ? 'approved' : 'declined'
)
);
}
$redirectParams = array_filter([
'date_from' => $request->request->get('date_from', ''),
'date_to' => $request->request->get('date_to', ''),
'created_user_id' => $request->request->get('created_user_id', ''),
'approved' => $request->request->get('approved', ''),
'search' => $request->request->get('search', ''),
], static function ($value) {
return $value !== '' && $value !== null;
});
return $this->redirectToRoute('expense_invoice_approval_queue', $redirectParams);
}
$dateFrom = trim((string)$request->query->get('date_from', ''));
$dateTo = trim((string)$request->query->get('date_to', ''));
$createdUserId = trim((string)$request->query->get('created_user_id', ''));
$approved = trim((string)$request->query->get('approved', '3'));
$search = trim((string)$request->query->get('search', ''));
$qb = $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')->createQueryBuilder('ei');
$qb->where('ei.status = :status')
->setParameter('status', GeneralConstant::ACTIVE)
->orderBy('ei.expenseInvoiceDate', 'DESC')
->addOrderBy('ei.expenseInvoiceId', 'DESC');
if ($dateFrom !== '') {
$qb->andWhere('ei.expenseInvoiceDate >= :dateFrom')
->setParameter('dateFrom', new \DateTime($dateFrom . ' 00:00:00'));
}
if ($dateTo !== '') {
$qb->andWhere('ei.expenseInvoiceDate <= :dateTo')
->setParameter('dateTo', new \DateTime($dateTo . ' 23:59:59'));
}
if ($createdUserId !== '') {
$qb->andWhere(
$qb->expr()->orX(
'ei.createdUserId = :createdUserId',
'ei.createdUserId IS NULL AND ei.createdLoginId = :createdUserLoginId'
)
)
->setParameter('createdUserId', (int)$createdUserId)
->setParameter('createdUserLoginId', (int)$createdUserId);
}
if ($approved !== '') {
$qb->andWhere('ei.approved = :approved')
->setParameter('approved', (int)$approved);
}
if ($search !== '') {
$qb->andWhere(
$qb->expr()->orX(
$qb->expr()->like('ei.documentHash', ':searchTerm'),
$qb->expr()->like('ei.description', ':searchTerm')
)
)->setParameter('searchTerm', '%' . $search . '%');
}
$invoices = $qb->getQuery()->getResult();
$currencyList = Inventory::CurrencyList($em);
$approvalStatusMap = [
0 => ['label' => 'Declined', 'class' => 'danger'],
1 => ['label' => 'Approved', 'class' => 'success'],
2 => ['label' => 'Reverted', 'class' => 'warning'],
3 => ['label' => 'Pending', 'class' => 'warning'],
];
$expenseInvoiceTypeList = [
0 => 'General Expense',
1 => 'Against Purchase',
2 => 'Against Project/Sales',
3 => 'Against Lead/Tender',
];
$groupedInvoices = [];
$userOptions = [];
$userCache = [];
$summary = [
'count' => 0,
'approved' => 0,
'pending' => 0,
'declined' => 0,
'reverted' => 0,
'amount_by_currency' => [],
];
foreach ($invoices as $invoice) {
$createdUserIdValue = (int)$invoice->getCreatedUserId();
$loginId = (int)$invoice->getCreatedLoginId();
$cacheKey = $createdUserIdValue > 0 ? $createdUserIdValue : $loginId;
if (!isset($userCache[$cacheKey])) {
if ($createdUserIdValue > 0) {
$userCache[$cacheKey] = Users::getUserInfoByUserId($em, $createdUserIdValue);
} else {
$resolvedUser = Users::getUserInfoByLoginId($em, $loginId);
$userCache[$cacheKey] = $resolvedUser;
if (!empty($resolvedUser['id'])) {
$createdUserIdValue = (int)$resolvedUser['id'];
$cacheKey = $createdUserIdValue;
$userCache[$cacheKey] = $resolvedUser;
}
}
}
$userInfo = $userCache[$cacheKey] ?? [];
$userId = (int)($userInfo['id'] ?? $createdUserIdValue);
$userName = $userInfo['name'] ?? ('User #' . $userId);
$invoiceDate = $invoice->getExpenseInvoiceDate();
$dateKey = $invoiceDate ? $invoiceDate->format('Y-m-d') : 'unknown';
$dateLabel = $invoiceDate ? $invoiceDate->format('M d, Y') : 'Unknown date';
$amount = (float)$invoice->getInvoiceAmount();
$currencyId = $invoice->getCurrency();
$currencyName = isset($currencyList[$currencyId]) ? ($currencyList[$currencyId]['nameOnly'] ?? '') : '';
$approvalState = (int)$invoice->getApproved();
$approvalMeta = $approvalStatusMap[$approvalState] ?? ['label' => 'Unknown', 'class' => 'default'];
$summary['count']++;
if ($approvalState === 1) {
$summary['approved']++;
} elseif ($approvalState === 0) {
$summary['declined']++;
} elseif ($approvalState === 2) {
$summary['reverted']++;
} else {
$summary['pending']++;
}
if (!isset($summary['amount_by_currency'][$currencyId])) {
$summary['amount_by_currency'][$currencyId] = [
'currency' => $currencyName,
'amount' => 0,
];
}
$summary['amount_by_currency'][$currencyId]['amount'] += $amount;
$userOptions[$userId] = $userName;
if (!isset($groupedInvoices[$userId])) {
$groupedInvoices[$userId] = [
'userId' => $userId,
'userName' => $userName,
'totalCount' => 0,
'totalAmount' => 0,
'amountByCurrency' => [],
'dates' => [],
];
}
if (!isset($groupedInvoices[$userId]['amountByCurrency'][$currencyId])) {
$groupedInvoices[$userId]['amountByCurrency'][$currencyId] = [
'currency' => $currencyName,
'amount' => 0,
];
}
$groupedInvoices[$userId]['amountByCurrency'][$currencyId]['amount'] += $amount;
$groupedInvoices[$userId]['totalCount']++;
$groupedInvoices[$userId]['totalAmount'] += $amount;
if (!isset($groupedInvoices[$userId]['dates'][$dateKey])) {
$groupedInvoices[$userId]['dates'][$dateKey] = [
'key' => $dateKey,
'label' => $dateLabel,
'count' => 0,
'amount' => 0,
'rows' => [],
];
}
$groupedInvoices[$userId]['dates'][$dateKey]['count']++;
$groupedInvoices[$userId]['dates'][$dateKey]['amount'] += $amount;
$groupedInvoices[$userId]['dates'][$dateKey]['rows'][] = [
'expenseInvoiceId' => $invoice->getExpenseInvoiceId(),
'documentHash' => $invoice->getDocumentHash(),
'expenseInvoiceDate' => $dateLabel,
'expenseInvoiceTypeId' => $invoice->getExpenseInvoiceTypeId(),
'expenseInvoiceTypeLabel' => $expenseInvoiceTypeList[$invoice->getExpenseInvoiceTypeId()] ?? 'N/A',
'invoiceAmount' => $amount,
'currencyId' => $currencyId,
'currencyName' => $currencyName,
'approved' => $approvalState,
'approvedLabel' => $approvalMeta['label'],
'approvedClass' => $approvalMeta['class'],
'description' => $invoice->getDescription(),
'partyHeadId' => $invoice->getPartyHeadId(),
'expenseTypeId' => $invoice->getExpenseTypeId(),
'createdUserId' => $userId,
'viewUrl' => $this->generateUrl('view_expense_invoice', ['id' => $invoice->getExpenseInvoiceId()]),
'printUrl' => $this->generateUrl('print_expense_invoice', ['id' => $invoice->getExpenseInvoiceId()]),
];
}
krsort($groupedInvoices);
foreach ($groupedInvoices as &$group) {
krsort($group['dates']);
}
unset($group);
$amountBreakdown = [];
foreach ($summary['amount_by_currency'] as $currencyData) {
$amountBreakdown[] = trim(
($currencyData['currency'] !== '' ? $currencyData['currency'] . ' ' : '') .
number_format((float)$currencyData['amount'], 2, '.', ',')
);
}
return $this->render(
'@Accounts/pages/views/view_expense_invoice_approval_queue.html.twig',
[
'page_title' => 'Expense Invoice Approval Queue',
'groupedInvoices' => $groupedInvoices,
'userOptions' => $userOptions,
'summary' => $summary,
'amountBreakdown' => $amountBreakdown,
'filters' => [
'date_from' => $dateFrom,
'date_to' => $dateTo,
'created_user_id' => $createdUserId,
'approved' => $approved,
'search' => $search,
],
'approvalStatusMap' => $approvalStatusMap,
'expenseInvoiceTypeList' => $expenseInvoiceTypeList,
'currencyList' => $currencyList,
]
);
}
public function BrsList(Request $request)
{
$q = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\Brs')
->findBy(
array(
'status' => GeneralConstant::ACTIVE,
),
array(
'brsDate' => 'DESC'
)
);
$stage_list = array(
1 => 'Pending',
2 => 'Complete',
4 => 'Pending Payment',
);
$data = [];
foreach ($q as $entry) {
$data[] = array(
'doc_date' => $entry->getBrsDate(),
'id' => $entry->getBrsId(),
'doc_hash' => $entry->getDocumentHash(),
'accountsHeadId' => $entry->getAccountsHeadId(),
// 'stage'=>$stage_list[$entry->getStage()]
);
}
return $this->render(
'@Accounts/pages/list/brs_list.html.twig',
array(
'page_title' => 'BRS Statements',
'data' => $data,
'head_list' => Accounts::HeadList($this->getDoctrine()->getManager())
)
);
}
public function FinancialBudgetList(Request $request)
{
$q = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\FinancialBudget')
->findBy(
array( // 'status' => GeneralConstant::ACTIVE,
),
array( // 'brsDate'=>'DESC'
)
);
$stage_list = array(
1 => 'Pending',
2 => 'Complete',
4 => 'Pending Payment',
);
$data = [];
foreach ($q as $entry) {
$data[] = array(
'doc_start_date' => $entry->getBudgetStartDate(),
'doc_end_date' => $entry->getBudgetEndDate(),
'id' => $entry->getBudgetId(),
'doc_hash' => $entry->getBudgetTitle(),
// 'accountsHeadId'=>$entry->getAccountsHeadId(),
// 'stage'=>$stage_list[$entry->getStage()]
);
}
return $this->render(
'@Accounts/pages/list/financial_budget_list.html.twig',
array(
'page_title' => 'Financial Budgets',
'data' => $data,
'head_list' => Accounts::HeadList($this->getDoctrine()->getManager())
)
);
}
public function ViewExpenseInvoice(Request $request, $id)
{
$invoice_id = $id;
$em = $this->getDoctrine()->getManager();
$dt = Accounts::GetExpenseInvoiceDetails($em, $invoice_id);
if ($request->get('returnJson')==1) {
$ei = $dt['ei_data'];
return new \Symfony\Component\HttpFoundation\JsonResponse([
'success' => true,
'data' => [
'supplier_data' => $dt['supplier_data'] ? [
'supplierName' => $dt['supplier_data']->getSupplierName(),
'supplierAddress' => $dt['supplier_data']->getSupplierAddress(),
'contactNumber' => $dt['supplier_data']->getContactNumber(),
] : null,
'party_head_data' => isset($dt['party_head_data']) && $dt['party_head_data'] ? [
'name' => $dt['party_head_data']->getName(),
] : null,
'ei_data' => [
'expenseInvoiceId' => $ei->getExpenseInvoiceId(),
'documentHash' => $ei->getDocumentHash(),
'expenseInvoiceDate' => $ei->getExpenseInvoiceDate()
? $ei->getExpenseInvoiceDate()->format('Y-m-d') : null,
'invoiceAmount' => $ei->getInvoiceAmount(),
'advanceAmount' => $ei->getAdvanceAmount(),
'dueAmount' => $ei->getDueAmount(),
'currency' => $ei->getCurrency(),
'currencyMultiplyRate' => $ei->getCurrencyMultiplyRate(),
'expenseInvoiceTypeId' => $ei->getExpenseInvoiceTypeId(),
'expenseTypeId' => $ei->getExpenseTypeId(),
'expenseFromNote' => $ei->getExpenseFromNote(),
'expenseToNote' => $ei->getExpenseToNote(),
'description' => $ei->getDescription(),
'approved' => $ei->getApproved(),
'editFlag' => $ei->getEditFlag(),
],
'supplier_data' => $dt['supplier_data'] ? [
'supplierName' => $dt['supplier_data']->getSupplierName(),
'supplierAddress' => $dt['supplier_data']->getSupplierAddress(),
'contactNumber' => $dt['supplier_data']->getContactNumber(),
] : null,
'currency_list' => $dt['currency_list'],
'head_list' => $dt['head_list'],
'expenseInvoiceTypeList' => $dt['expenseInvoiceTypeList'] ?? [],
'voucher_data' => $dt['voucher_data'],
'probable_transaction_data' => $dt['probable_transaction_data'] ?? [],
]
]);
}
return $this->render(
// '@Accounts/pages/views/view_expense_invoice.html.twig',
'@Accounts/pages/views/view_expense_invoice_demo.html.twig',
array(
'page_title' => 'View Expense Invoice',
'data' => $dt,
'auto_created' => $dt['ei_data']->getAutoCreated(),
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
$invoice_id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
$invoice_id,
$dt['created_by'],
$dt['edited_by']
)
)
);
}
public function PrintExpenseInvoice(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$invoice_id = $id;
$data = Accounts::GetExpenseInvoiceDetails($em, $invoice_id);
$company_data = Company::getCompanyData($em, $this->getLoggedUserCompanyId($request));
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
return $this->render(
'@Accounts/pages/print/ei_print.html.twig',
array(
'page_title' => 'Expense Invoice',
'data' => $data,
'export' => 'pdf,print,sendForward',
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'red' => 0
)
);
}
public function strtohex($x)
{
$s = '';
foreach (str_split($x) as $c) $s .= sprintf("%02X", ord($c));
return ($s);
}
public function PrintVoucher(Request $request, $id, $mis_start_date = '', $mis_end_date = '')
{
$voucher_id = $id;
$p = '';
// if ($this->container->has('profiler')) {
// $this->container->get('profiler')->disable();
// }
$mis_print = 0;
if ($request->query->has('mis_print'))
$mis_print = $request->query->get('mis_print');
$em = $this->getDoctrine()->getManager();
$company_data = Company::getCompanyData($em, $this->getLoggedUserCompanyId($request));
$start_date = "";
$end_date = "";
$em = $this->getDoctrine()->getManager();
if ($mis_start_date != '' && $mis_start_date != 0)
$start_date = $mis_start_date;
if ($mis_end_date != '' && $mis_start_date != 0)
$end_date = $mis_end_date;
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'pending' => '/images/pending.jpg',
'copy' => ''
);
$data = Accounts::GetVoucherDetails($em, $voucher_id);
if (!empty($data))
$mis_data = Accounts::GetVoucherMisDetails($em, $data['head_id_list'], $start_date, $end_date);
$templates = [
'3' => '@Accounts/pages/print/voucher_print.html.twig',
'4' => '@Accounts/pages/print/contra_voucher_print.html.twig',
'5' => '@Accounts/pages/print/payment_voucher_print.html.twig',
'6' => '@Accounts/pages/print/receipt_voucher_print.html.twig',
];
if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
$html = $this->renderView(
$templates[$data['type_id']],
array(
//full array here
'pdf' => true,
'page_title' => 'Voucher ' . $data['doc_hash'],
'data' => $data,
'page_header' => 'New Product',
'document_type' => 'Journal voucher',
'document_mark_image' => $document_mark['original'],
'page_header_sub' => 'Add',
// 'type_list'=>$type_list,
'mis_data' => $mis_data,
'mis_print' => $mis_print,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'invoice_footer' => $company_data->getInvoiceFooter(),
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'p' => $p
)
);
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
// 'orientation' => 'landscape',
// 'enable-javascript' => true,
// 'javascript-delay' => 1000,
'no-stop-slow-scripts' => false,
'no-background' => false,
'lowquality' => false,
'encoding' => 'utf-8',
// 'images' => true,
// 'cookie' => array(),
'dpi' => 300,
'image-dpi' => 300,
// 'enable-external-links' => true,
// 'enable-internal-links' => true
));
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="' . $data['doc_hash'] . '.pdf"'
)
);
}
return $this->render(
$templates[$data['type_id']],
array(
'page_title' => 'Voucher ' . $data['doc_hash'],
'export' => 'pdf,print',
'data' => $data,
'page_header' => 'New Product',
'document_type' => 'Journal voucher',
'document_mark_image' => $document_mark['original'],
'page_header_sub' => 'Add',
// 'type_list'=>$type_list,
'mis_data' => $mis_data,
'mis_print' => $mis_print,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'invoice_footer' => $company_data->getInvoiceFooter(),
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'p' => $p
)
);
}
public function PrintVoucherPdf(Request $request, $voucher_id, $mis_start_date = '', $mis_end_date = '')
{
if ($this->container->has('profiler')) {
$this->container->get('profiler')->disable();
}
$p = '';
$mis_print = 0;
if ($request->query->has('mis_print'))
$mis_print = $request->query->get('mis_print');
$em = $this->getDoctrine()->getManager();
$company_data = Company::getCompanyData($em, $this->getLoggedUserCompanyId($request));
$start_date = "";
$end_date = "";
$em = $this->getDoctrine()->getManager();
if ($mis_start_date != '' && $mis_start_date != 0)
$start_date = $mis_start_date;
if ($mis_end_date != '' && $mis_start_date != 0)
$end_date = $mis_end_date;
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'pending' => '/images/pending.jpg',
'copy' => ''
);
$data = Accounts::GetVoucherDetails($em, $voucher_id);
if (!empty($data))
$mis_data = Accounts::GetVoucherMisDetails($em, $data['head_id_list'], $start_date, $end_date);
$format = $request->get('_format');
$this->get('knp_snappy.pdf');
// $format = 'pdf';
// $response = $this->render(sprintf('ApplicationBundle:pages/accounts/pdf:helloAction.%s.twig', $format), array(
// 'name' => 'Ecobeco',
// ));
//// $response->headers->set('Content-Type', 'application/pdf');
//
// return $response;
$templates = [
'3' => '@Accounts/pages/print/voucher_print.html.twig',
'4' => '@Accounts/pages/print/contra_voucher_print.html.twig',
'5' => '@Accounts/pages/print/payment_voucher_print.html.twig',
];
// return $this->render($templates[$data['type_id']],
$html = $this->renderView(
$templates[$data['type_id']],
array(
'page_title' => 'Voucher ' . $data['doc_hash'],
'data' => $data,
'page_header' => 'New Product',
'document_type' => 'Journal voucher',
'document_mark_image' => $document_mark['original'],
'page_header_sub' => 'Add',
// 'type_list'=>$type_list,
'mis_data' => $mis_data,
'mis_print' => $mis_print,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'invoice_footer' => $company_data->getInvoiceFooter(),
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'p' => $p
)
);
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
// 'orientation' => 'landscape',
// 'enable-javascript' => true,
// 'javascript-delay' => 1000,
'no-stop-slow-scripts' => true,
'no-background' => false,
'lowquality' => false,
'encoding' => 'utf-8',
// 'images' => true,
// 'cookie' => array(),
'dpi' => 300,
'image-dpi' => 300,
// 'enable-external-links' => true,
// 'enable-internal-links' => true
));
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
// 'Content-Disposition' => 'attachment; filename="file.pdf"'
)
);
}
public function VoucherList(Request $request)
{
$em = $this->getDoctrine()->getManager();
// $Transaction = $em->getRepository('ApplicationBundle\\Entity\\AccTransactions')->findAllOrderedByName();
$voucherListData = Accounts::GetVoucherList($em, $request->isMethod('POST') ? 'POST' : 'GET', $request->request);
if ($request->isMethod('POST')) {
if ($request->query->has('dataTableQry')) {
return new JsonResponse(
$voucherListData
);
}
}
return $this->render(
'@Accounts/pages/list/voucher_list.html.twig',
array(
'page_title' => 'Transactions',
'data' => $voucherListData['data']
)
);
}
/**
* @Pdf()
*/
public function TestPdf(Request $request, $slug)
{
$format = $request->get('_format');
// $format = 'pdf';
$response = $this->render(sprintf('@Application/pages/accounts/pdf/helloAction.%s.twig', $format), array(
'name' => 'Ecobeco',
));
// $response->headers->set('Content-Type', 'application/pdf');
return $response;
}
public function ViewLedger(Request $request, $id)
{
// $format = $request->get('_format');
// 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);
$start_date = "";
$end_date = "";
$em = $this->getDoctrine()->getManager();
if ($request->query->has('start_date'))
$start_date = $request->query->get('start_date');
if ($request->query->has('end_date'))
$end_date = $request->query->get('end_date');
$balance_view_method = 0;
$bal_set = $em
->getRepository('ApplicationBundle\\Entity\\AccSettings')
->findOneBy(
array(
'name' => 'ledger_balance_display_method',
)
);
if ($bal_set) {
$balance_view_method = $bal_set->getdata();
}
// now lets get its tree for the description
$id_list_for_ledger = [];
$parent_id_list_for_ledger = [];
if ($request->query->has('HeadId'))
$id_list_for_ledger = $request->query->get('HeadId');
if ($request->query->has('parentHeadId'))
$parent_id_list_for_ledger = $request->query->get('parentHeadId');
$provisional_option = 1; //include
if ($request->query->has('provisional')) {
$provisional_option = $request->query->get('provisional'); //include
}
$allocationSupportData = $this->getAllocationReportSupportData($em, $request);
$allocationFilters = $allocationSupportData['allocation_filters'];
if (empty($id_list_for_ledger))
if ($id != 0)
$id_list_for_ledger = [$id];
$ledger_det = [];
foreach ($id_list_for_ledger as $ind_head_id) {
// $ledger_data = Accounts::LedgerDetails($em, $ind_head_id, $start_date, $end_date,$provisional_option);
$ledger_data = Accounts::LedgerDetailsTransMethod($em, $ind_head_id, $start_date, $end_date, $provisional_option, $allocationFilters);
$ledger_det[$ind_head_id] = $ledger_data;
}
$grouped_heads = Accounts::getLedgerHeadsWithParents($em);
return $this->render(
'@Accounts/pages/views/view_head_ledger.html.twig',
array(
'page_title' => 'Ledger',
'id_list' => $id_list_for_ledger,
'parent_id_list' => $parent_id_list_for_ledger,
// 'products'=>Inventory::ProductList($this->getDoctrine()->getManager()),
// 'categories'=>Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
// 'itemgroup'=>Inventory::ItemGroupList($this->getDoctrine()->getManager()),
// 'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager())
'products' => [],
'provisional' => $provisional_option,
'ledger_data' => $ledger_det,
'balance_view_method' => $balance_view_method,
'categories' => [],
'heads' => $grouped_heads,
'itemgroup' => [],
'data' => [],
'start_date' => $start_date,
'end_date' => $end_date,
'allocation_filters' => $allocationFilters,
'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
'project_list' => $allocationSupportData['project_list'],
'branch_list' => $allocationSupportData['branch_list'],
'cost_centers' => $allocationSupportData['cost_centers'],
// 'desc_head_list'=>$desc_tree_list,
)
);
}
public function ViewLedgerForApp(Request $request, $id = 0)
{
$start_date = "";
$end_date = "";
$em = $this->getDoctrine()->getManager();
if ($request->query->has('start_date'))
$start_date = $request->query->get('start_date');
if ($request->query->has('end_date'))
$end_date = $request->query->get('end_date');
$balance_view_method = 0;
$bal_set = $em
->getRepository('ApplicationBundle\\Entity\\AccSettings')
->findOneBy(['name' => 'ledger_balance_display_method']);
if ($bal_set) {
$balance_view_method = $bal_set->getdata();
}
$id_list_for_ledger = [];
if ($request->query->has('acc_heads_id')) {
$raw_head_id = $request->query->get('acc_heads_id');
if (is_array($raw_head_id)) {
$id_list_for_ledger = $raw_head_id;
} elseif (is_string($raw_head_id)) {
$id_list_for_ledger = array_filter(explode(',', $raw_head_id));
}
}
$parent_id_list_for_ledger = [];
if ($request->query->has('acc_parent_head_id')) {
$parent_id_list_for_ledger = $request->query->get('acc_parent_head_id');
}
$provisional_option = $request->query->get('provisional', 1);
$allocationFilters = $this->getAllocationReportFilters($request);
// ✅ Fallback if HeadId not passed
if (empty($id_list_for_ledger) && $id != 0) {
$id_list_for_ledger = [$id];
}
$ledger_det = [];
foreach ($id_list_for_ledger as $ind_head_id) {
$ledger_data = Accounts::LedgerDetailsTransMethodForApp(
$em,
$ind_head_id,
$start_date,
$end_date,
$provisional_option,
23232323,
0,
'DATE_RANGE',
$allocationFilters
);
if (isset($ledger_data['error']) && $ledger_data['error'] === true) {
continue;
}
$head = $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findOneBy(['accountsHeadId' => $ind_head_id]);
$head_name = $head ? $head->getName() : 'Unknown_' . $ind_head_id;
$ledger_det[$head_name] = Accounts::formatLedgerSummary($ledger_data);
}
$grouped_heads = Accounts::getLedgerHeadsWithParents($em);
return new JsonResponse([
'success' => true,
'response' => $ledger_det,
]);
}
public function ListOfProvisional()
{
return new JsonResponse([
['id' => 0, 'label' => "Don't Include Provisional Transaction"],
['id' => 1, 'label' => 'Include Provisional Transaction'],
['id' => 2, 'label' => 'Only Provisional Transaction'],
]);
}
// public function dashboardCashFlow(Request $request, $id)
// {
// $em = $this->getDoctrine()->getManager();
// $end_date = new \DateTime();
// $end_date = $end_date->format('Y-m-d');
// $start_date = new \DateTime();
// $start_date->modify('-1 month');
// $start_date = $start_date->format('Y-m-d');
// // Get the date for the last 7 days
// $seven_days_ago = new \DateTime();
// $seven_days_ago->modify('-7 days');
// $seven_days_ago = $seven_days_ago->format('Y-m-d');
// $balance_view_method = 0;
// $bal_set = $em
// ->getRepository('ApplicationBundle\\Entity\\AccSettings')
// ->findOneBy(array(
// 'name' => 'ledger_balance_display_method',
// ));
// if ($bal_set) {
// $balance_view_method = $bal_set->getdata();
// }
// // Now lets get its tree for the description
// $id_list_for_ledger = [];
// $parent_id_list_for_ledger = [];
// $candceq = $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
// 'name' => 'cash_and_cash_equivalent_parents'
// ));
// if ($candceq)
// $id_list_for_ledger = json_decode($candceq->getData(), true);
// $provisional_option = 1; //include
// if ($request->query->has('provisional')) {
// $provisional_option = $request->query->get('provisional'); //include
// }
// if (empty($id_list_for_ledger))
// if ($id != 0)
// $id_list_for_ledger = [$id];
// $ledger_det = [];
// foreach ($id_list_for_ledger as $ind_head_id) {
// $ledger_data = Accounts::LedgerDetailsTransMethod($em, $ind_head_id, $start_date, $end_date, $provisional_option);
// $ledger_det[$ind_head_id] = $ledger_data;
// }
// $last_7_days_ledger_det = [];
// foreach ($id_list_for_ledger as $ind_head_id) {
// $ledger_data_7_days = Accounts::LedgerDetailsTransMethod($em, $ind_head_id, $seven_days_ago, $end_date, $provisional_option);
// $last_7_days_ledger_det[$ind_head_id] = $ledger_data_7_days;
// }
// $grouped_heads = Accounts::getLedgerHeadsWithParents($em);
// $debitCreditData = [];
// foreach ($ledger_det as $key => $entry) {
// if (isset($entry['imidiate_child']) && is_array($entry['imidiate_child'])) {
// foreach ($entry['imidiate_child'] as $child) {
// $debitCreditData[] = [
// 'debit' => $child['debit'] ?? 0,
// 'credit' => $child['credit'] ?? 0,
// 'balance' => $child['balance'] ?? 0
// ];
// }
// }
// }
// $total = [
// 'debit' => 0,
// 'credit' => 0,
// 'balance' => 0,
// 'closing_balance_last_7_days' => 0,
// ];
// foreach ($debitCreditData as $entry) {
// $total['debit'] += $entry['debit'];
// $total['credit'] += $entry['credit'];
// $total['balance'] += $entry['balance'];
// }
// $closing_balance_details_last_7_days = [];
// foreach ($last_7_days_ledger_det as $key => $entry) {
// if (isset($entry['closing_data']) && is_array($entry['closing_data'])) {
// foreach ($entry['closing_data'] as $closing_entry) {
// $closing_balance_details_last_7_days[] = [
// 'date' => $closing_entry['date'] ?? null,
// //'opening' => $closing_entry['opening'] ?? 0,
// //'balance' => $closing_entry['balance'] ?? 0,
// 'difference' => ($closing_entry['balance'] ?? 0) - ($closing_entry['opening'] ?? 0) // Calculate balance - opening
// ];
// }
// }
// }
// // Add to total response
// $total['closing_balance_details_last_7_days'] = $closing_balance_details_last_7_days;
// return new JsonResponse($total);
// }
// public function dashboardCashFlow(Request $request, $id)
// {
// $em = $this->getDoctrine()->getManager();
// $end_date = new \DateTime();
// $end_date = $end_date->format('Y-m-d');
// $start_date = new \DateTime();
// $start_date->modify('-1 month');
// $start_date = $start_date->format('Y-m-d');
// $seven_days_ago = new \DateTime();
// $seven_days_ago->modify('-7 days');
// $seven_days_ago = $seven_days_ago->format('Y-m-d');
// $balance_view_method = 0;
// $bal_set = $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(['name' => 'ledger_balance_display_method']);
// if ($bal_set) {
// $balance_view_method = $bal_set->getdata();
// }
// $id_list_for_ledger = [];
// $candceq = $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(['name' => 'cash_and_cash_equivalent_parents']);
// if ($candceq) {
// $id_list_for_ledger = json_decode($candceq->getData(), true);
// }
// $provisional_option = $request->query->get('provisional', 1);
// if (empty($id_list_for_ledger) && $id != 0) {
// $id_list_for_ledger = [$id];
// }
// $ledger_det = [];
// foreach ($id_list_for_ledger as $ind_head_id) {
// $ledger_det[$ind_head_id] = Accounts::LedgerDetailsTransMethod($em, $ind_head_id, $start_date, $end_date, $provisional_option);
// }
// $last_7_days_ledger_det = [];
// foreach ($id_list_for_ledger as $ind_head_id) {
// $last_7_days_ledger_det[$ind_head_id] = Accounts::LedgerDetailsTransMethod($em, $ind_head_id, $seven_days_ago, $end_date, $provisional_option);
// }
// $total = ['debit' => 0, 'credit' => 0, 'balance' => 0, 'past_week' => 0, 'vs_past_period' => 0];
// $first_day_opening_7_days = 0;
// $first_day_opening_30_days = 0;
// $first_day_set_7_days = false;
// $first_day_set_30_days = false;
// foreach ($ledger_det as $entry) {
// if (isset($entry['closing_data']) && is_array($entry['closing_data'])) {
// foreach ($entry['closing_data'] as $closing_entry) {
// if (!$first_day_set_30_days) {
// $first_day_opening_30_days = $closing_entry['opening'] ?? 0;
// $first_day_set_30_days = true;
// }
// }
// }
// }
// foreach ($last_7_days_ledger_det as $entry) {
// if (isset($entry['closing_data']) && is_array($entry['closing_data'])) {
// foreach ($entry['closing_data'] as $closing_entry) {
// if (!$first_day_set_7_days) {
// $first_day_opening_7_days = $closing_entry['opening'] ?? 0;
// $first_day_set_7_days = true;
// }
// }
// }
// }
// foreach ($ledger_det as $entry) {
// if (isset($entry['imidiate_child']) && is_array($entry['imidiate_child'])) {
// foreach ($entry['imidiate_child'] as $child) {
// $total['debit'] += $child['debit'] ?? 0;
// $total['credit'] += $child['credit'] ?? 0;
// $total['balance'] += $child['balance'] ?? 0;
// }
// }
// }
// $closing_balance_details_last_7_days = [];
// foreach ($last_7_days_ledger_det as $key => $entry) {
// if (isset($entry['closing_data']) && is_array($entry['closing_data'])) {
// foreach ($entry['closing_data'] as $closing_entry) {
// $closing_balance_details_last_7_days[] = [
// 'date' => $closing_entry['date'] ?? null,
// //'opening' => $closing_entry['opening'] ?? 0,
// //'balance' => $closing_entry['balance'] ?? 0,
// 'difference' => ($closing_entry['balance'] ?? 0) - ($closing_entry['opening'] ?? 0) // Calculate balance - opening
// ];
// }
// }
// }
// $total['closing_balance_details_last_7_days'] = $closing_balance_details_last_7_days;
// $total['past_week'] = $total['balance'] - $first_day_opening_7_days;
// $total['past_period'] = $total['balance'] - $first_day_opening_30_days;
// $total['vs_past_period'] = ($total['balance'] - $total['past_period'])/100;
// return new JsonResponse($total);
// }
public function dashboardCashFlow(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$end_date = new \DateTime();
$end_date = $end_date->format('Y-m-d');
$start_date = new \DateTime();
$start_date->modify('-1 month');
$start_date = $start_date->format('Y-m-d');
$seven_days_ago = new \DateTime();
$seven_days_ago->modify('-7 days');
$seven_days_ago = $seven_days_ago->format('Y-m-d');
$balance_view_method = 0;
$bal_set = $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(['name' => 'ledger_balance_display_method']);
if ($bal_set) {
$balance_view_method = $bal_set->getdata();
}
$id_list_for_ledger = [];
$candceq = $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(['name' => 'cash_and_cash_equivalent_parents']);
if ($candceq) {
$id_list_for_ledger = json_decode($candceq->getData(), true);
}
$provisional_option = $request->query->get('provisional', 1);
if (empty($id_list_for_ledger) && $id != 0) {
$id_list_for_ledger = [$id];
}
$ledger_det = [];
foreach ($id_list_for_ledger as $ind_head_id) {
$ledger_det[$ind_head_id] = Accounts::LedgerDetailsTransMethod($em, $ind_head_id, $start_date, $end_date, $provisional_option);
}
$last_7_days_ledger_det = [];
foreach ($id_list_for_ledger as $ind_head_id) {
$last_7_days_ledger_det[$ind_head_id] = Accounts::LedgerDetailsTransMethod($em, $ind_head_id, $seven_days_ago, $end_date, $provisional_option);
}
$total = ['debit' => 0, 'credit' => 0, 'balance' => 0, 'closing_balance_last_7_days' => 0, 'past_week' => 0, 'vs_past_period' => 0];
$first_day_opening_7_days = 0;
$first_day_opening_30_days = 0;
$first_day_set_7_days = false;
$first_day_set_30_days = false;
foreach ($ledger_det as $entry) {
if (isset($entry['closing_data']) && is_array($entry['closing_data'])) {
foreach ($entry['closing_data'] as $closing_entry) {
if (!$first_day_set_30_days) {
$first_day_opening_30_days = $closing_entry['opening'] ?? 0;
$first_day_set_30_days = true;
}
}
}
}
foreach ($last_7_days_ledger_det as $entry) {
if (isset($entry['closing_data']) && is_array($entry['closing_data'])) {
foreach ($entry['closing_data'] as $closing_entry) {
if (!$first_day_set_7_days) {
$first_day_opening_7_days = $closing_entry['opening'] ?? 0;
$first_day_set_7_days = true;
}
}
}
}
foreach ($ledger_det as $entry) {
if (isset($entry['imidiate_child']) && is_array($entry['imidiate_child'])) {
foreach ($entry['imidiate_child'] as $child) {
$total['debit'] += $child['debit'] ?? 0;
$total['credit'] += $child['credit'] ?? 0;
$total['balance'] += $child['balance'] ?? 0;
}
}
}
$closing_balance_details_last_7_days = [];
$closing_balance_last_7_days_total = 0;
foreach ($last_7_days_ledger_det as $key => $entry) {
if (isset($entry['closing_data']) && is_array($entry['closing_data'])) {
foreach ($entry['closing_data'] as $closing_entry) {
$difference = ($closing_entry['balance'] ?? 0) - ($closing_entry['opening'] ?? 0);
$closing_balance_details_last_7_days[] = [
'date' => $closing_entry['date'] ?? null,
'difference' => $difference
];
$closing_balance_last_7_days_total += $difference;
}
}
}
$total['closing_balance_details_last_7_days'] = $closing_balance_details_last_7_days;
$total['closing_balance_last_7_days'] = $closing_balance_last_7_days_total;
$total['past_week'] = $total['balance'] - $first_day_opening_7_days;
$total['past_period'] = $total['balance'] - $first_day_opening_30_days;
$total['vs_past_period'] = ($total['balance'] - $total['past_period']) / 100;
return new JsonResponse($total);
}
public function LedgerReportForApp(Request $request, $id)
{
// $format = $request->get('_format');
// 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);
$start_date = "";
$end_date = "";
$em = $this->getDoctrine()->getManager();
$start_date = $request->request->get('start_date', $request->query->get('start_date', ''));
$end_date = $request->request->get('end_date', $request->query->get('end_date', ''));
$limit = $request->request->get('limit', $request->query->get('limit', 2511165651));
$offset = $request->request->get('offset', $request->query->get('offset', 0));
$indexType = $request->request->get('indexType', $request->query->get('indexType', 'DATE_RANGE'));
$balance_view_method = 0;
$bal_set = $em
->getRepository('ApplicationBundle\\Entity\\AccSettings')
->findOneBy(
array(
'name' => 'ledger_balance_display_method',
)
);
if ($bal_set) {
$balance_view_method = $bal_set->getdata();
}
// now lets get its tree for the description
$id_list_for_ledger = [];
$parent_id_list_for_ledger = [];
$id_list_for_ledger = $request->request->get('HeadId', $request->query->get('HeadId', []));
if (is_string($id_list_for_ledger))
$id_list_for_ledger = json_decode($id_list_for_ledger, true);
if ($id_list_for_ledger == null)
$id_list_for_ledger = [];
$parent_id_list_for_ledger = $request->request->get('parentHeadId', $request->query->get('parentHeadId', []));
$provisional_option = 1; //include
$provisional_option = $request->request->get('provisional', $request->query->get('provisional', 1));
$allocationSupportData = $this->getAllocationReportSupportData($em, $request);
$allocationFilters = $allocationSupportData['allocation_filters'];
if (empty($id_list_for_ledger))
if ($id != 0)
$id_list_for_ledger = [$id];
$ledger_det = [];
foreach ($id_list_for_ledger as $ind_head_id) {
// $ledger_data = Accounts::LedgerDetails($em, $ind_head_id, $start_date, $end_date,$provisional_option);
$ledger_data = Accounts::LedgerDetailsTransMethodForApp($em, $ind_head_id, $start_date, $end_date, $provisional_option, $limit, $offset, $indexType, $allocationFilters);
// $ledger_det[$ind_head_id] = $ledger_data;
$ledger_det = $ledger_data;
}
$grouped_heads = Accounts::getLedgerHeadsWithParents($em);
if (!empty($ledger_det)) {
return new JsonResponse(
array(
'success' => true,
// 'id_list' => $id_list_for_ledger,
// 'parent_id_list' => $parent_id_list_for_ledger,
// 'products' => [],
// 'provisional' => $provisional_option,
'ledger_data' => $ledger_det,
// 'balance_view_method' => $balance_view_method,
// 'categories' => [],
// 'heads' => $grouped_heads,
'itemgroup' => [],
'data' => [],
'start_date' => $start_date,
'end_date' => $end_date,
)
);
} else {
return new JsonResponse(
array(
'message' => "data not found"
)
);
}
}
public function PrintLedger(Request $request, $id)
{
$start_date = "";
$end_date = "";
$em = $this->getDoctrine()->getManager();
$company_data = Company::getCompanyData($em, $this->getLoggedUserCompanyId($request));
if ($request->query->has('start_date'))
$start_date = $request->query->get('start_date');
if ($request->query->has('end_date'))
$end_date = $request->query->get('end_date');
$provisional_option = 1; //include
if ($request->query->has('provisional')) {
$provisional_option = $request->query->get('provisional'); //include
}
$balance_view_method = 0;
$bal_set = $em
->getRepository('ApplicationBundle\\Entity\\AccSettings')
->findOneBy(
array(
'name' => 'ledger_balance_display_method',
)
);
if ($bal_set) {
$balance_view_method = $bal_set->getdata();
}
// now lets get its tree for the description
$id_list_for_ledger = [];
if ($request->query->has('id_list'))
$id_list_for_ledger = explode(',', $request->query->get('id_list'));
if ($id = 0 && empty($id_list))
$id_list_for_ledger = [0];
$ledger_det = [];
$head_name_list = [];
// Build the allocation filters (tag/project/branch/cost-center) from the request — same as the
// ledger view; the print URL carries these query params and LedgerDetailsTransMethod requires them.
$allocationSupportData = $this->getAllocationReportSupportData($em, $request);
$allocationFilters = $allocationSupportData['allocation_filters'];
foreach ($id_list_for_ledger as $ind_head_id) {
$ledger_data = Accounts::LedgerDetailsTransMethod($em, $ind_head_id, $start_date, $end_date, $provisional_option, $allocationFilters);
$ledger_det[$ind_head_id] = $ledger_data;
$head_name_list[] = $ledger_data['basic_data']['name'];
}
$grouped_heads = Accounts::GroupedHeads($em);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
$html = "";
if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
$html = $this->renderView(
'@Accounts/pages/print/ledger_print.html.twig',
array(
'pdf' => true,
'page_title' => 'Ledger ',
'ledger_data' => $ledger_det,
'balance_view_method' => $balance_view_method,
'page_header' => 'Ledger',
'document_type' => implode(', ', $head_name_list),
'document_mark_image' => $document_mark['original'],
'page_header_sub' => 'Add',
'start_date' => $start_date,
'end_date' => $end_date,
'head_list' => Accounts::HeadListFullPath($em),
'provisional' => $provisional_option,
// 'type_list'=>$type_list,
// 'child_list'=>$child_list,
// 'trans_data_by_closing'=>$trans_data_by_closing,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'invoice_footer' => $company_data->getInvoiceFooter(),
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
// 'desc_head_list'=>$desc_tree_list,
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
// 'p'=>$p
)
);
if ($request->query->has('sendMail')) {
if ($request->query->get('sendMail') == 1) {
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf';
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
'no-stop-slow-scripts' => true,
'no-background' => false,
'lowquality' => false,
'encoding' => 'utf-8',
'dpi' => 300,
'image-dpi' => 300,
));
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'attachment' => $pdf_response
));
return $this->render(
'@Accounts/pages/print/ledger_print.html.twig',
array(
'page_title' => 'Ledger ',
'ledger_data' => $ledger_det,
'page_header' => 'Ledger',
'document_type' => implode(', ', $head_name_list),
'document_mark_image' => $document_mark['original'],
'page_header_sub' => 'Add',
'start_date' => $start_date,
'end_date' => $end_date,
'head_list' => Accounts::HeadListFullPath($em),
'provisional' => $provisional_option,
'balance_view_method' => $balance_view_method,
// 'type_list'=>$type_list,
// 'child_list'=>$child_list,
// 'trans_data_by_closing'=>$trans_data_by_closing,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'invoice_footer' => $company_data->getInvoiceFooter(),
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
// 'desc_head_list'=>$desc_tree_list,
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'allocation_filters' => $allocationFilters,
'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
'project_list' => $allocationSupportData['project_list'],
'branch_list' => $allocationSupportData['branch_list'],
'cost_centers' => $allocationSupportData['cost_centers'],
'export' => 'all'
// 'p'=>$p
)
);
}
} else {
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
'no-stop-slow-scripts' => true,
'no-background' => false,
'lowquality' => false,
'encoding' => 'utf-8',
'dpi' => 300,
'image-dpi' => 300,
));
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="Ledger.pdf"'
)
);
}
}
return $this->render(
'@Accounts/pages/print/ledger_print.html.twig',
array(
'page_title' => 'Ledger ',
'ledger_data' => $ledger_det,
'page_header' => 'Ledger',
'document_type' => implode(', ', $head_name_list),
'document_mark_image' => $document_mark['original'],
'page_header_sub' => 'Add',
'start_date' => $start_date,
'end_date' => $end_date,
'head_list' => Accounts::HeadListFullPath($em),
'provisional' => $provisional_option,
'balance_view_method' => $balance_view_method,
// 'type_list'=>$type_list,
// 'child_list'=>$child_list,
// 'trans_data_by_closing'=>$trans_data_by_closing,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'invoice_footer' => $company_data->getInvoiceFooter(),
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
// 'desc_head_list'=>$desc_tree_list,
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'export' => 'all'
// 'p'=>$p
)
);
}
public function PrintLedgerPdf(Request $request, $id)
{
$start_date = "";
$end_date = "";
if ($this->container->has('profiler')) {
$this->container->get('profiler')->disable();
}
$em = $this->getDoctrine()->getManager();
$company_data = Company::getCompanyData($em, $this->getLoggedUserCompanyId($request));
if ($request->query->has('start_date'))
$start_date = $request->query->get('start_date');
if ($request->query->has('end_date'))
$end_date = $request->query->get('end_date');
$provisional_option = 1; //include
if ($request->query->has('provisional')) {
$provisional_option = $request->query->get('provisional'); //include
}
// now lets get its tree for the description
$id_list_for_ledger = [];
if ($request->query->has('id_list'))
$id_list_for_ledger = explode(',', $request->query->get('id_list'));
if ($id = 0 && empty($id_list))
$id_list_for_ledger = [0];
$ledger_det = [];
$head_name_list = [];
foreach ($id_list_for_ledger as $ind_head_id) {
$ledger_data = Accounts::LedgerDetailsTransMethod($em, $ind_head_id, $start_date, $end_date, $provisional_option);
$ledger_det[$ind_head_id] = $ledger_data;
$head_name_list[] = $ledger_data['basic_data']['name'];
}
$grouped_heads = Accounts::GroupedHeads($em);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
// now lets get its tree for the description
// $id_list=explode('/',$em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findOneBy(array(
// 'accountsHeadId'=>$id
// ))->getPathTree());
// $desc_tree_list=$em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findBy(array(
// 'accountsHeadId'=>$id_list
// ),
// array(
// 'accountsHeadId'=>'ASC',
// ));
//
// //now assigning transactions to closing_data_list
// $trans_data_by_closing=[];
//
// foreach($child_list['transaction_list'] as $g=>$entry)
// {
// $my_time = strtotime($entry['transaction_date']);
// $tr_date = date("m/d/Y", $my_time);
//// if($entry['transaction_date'] instanceof \DateTime)
// $trans_data_by_closing[$tr_date][]=$entry;
// }
$html = $this->renderView(
'@Accounts/pages/print/ledger_print.html.twig',
array(
'page_title' => 'Ledger ',
'ledger_data' => $ledger_det,
'page_header' => 'Ledger',
'document_type' => implode(', ', $head_name_list),
'document_mark_image' => $document_mark['original'],
'page_header_sub' => 'Add',
'start_date' => $start_date,
'end_date' => $end_date,
'provisional' => $provisional_option,
'head_list' => Accounts::HeadList($em),
// 'type_list'=>$type_list,
// 'child_list'=>$child_list,
// 'trans_data_by_closing'=>$trans_data_by_closing,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'invoice_footer' => $company_data->getInvoiceFooter(),
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
// 'desc_head_list'=>$desc_tree_list,
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'allocation_filters' => $allocationFilters,
'allocation_tag_types' => $allocationSupportData['allocation_tag_types'],
'allocation_tag_values_by_type' => $allocationSupportData['allocation_tag_values_by_type'],
'project_list' => $allocationSupportData['project_list'],
'branch_list' => $allocationSupportData['branch_list'],
'cost_centers' => $allocationSupportData['cost_centers'],
// 'p'=>$p
)
);
// $l= $this->get('knp_snappy.pdf')->generateFromHtml($html
// ,
// $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/myfile.pdf'
// );
// $chk=$this->get('knp_snappy.pdf');
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
// 'orientation' => 'landscape',
'enable-javascript' => true,
'javascript-delay' => 1000,
'no-stop-slow-scripts' => true,
'no-background' => false,
// 'lowquality' => false,
'encoding' => 'utf-8',
'images' => true,
'cookie' => array(),
'dpi' => 300,
'image-dpi' => 300,
// 'page-height' => '29.7cm',
// 'page-width' => '21cm'
// 'enable-external-links' => true,
// 'enable-internal-links' => true
));
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
// 'Content-Disposition' => 'attachment; filename="file.pdf"'
)
);
}
public function AccountsSettings(Request $request)
{
$id = 0;
$cc_id = '';
$cc_name = '';
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
foreach ($request->request->keys() as $req_key) {
//first check if it exists so we can update
$new_cc = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccSettings')
->findOneBy(
array(
'name' => $req_key,
)
);
if (empty($new_cc)) //doesnot exists make new
{
$new = new AccSettings();
$new->setName($req_key);
if ($req_key == 'accounting_year_start' || $req_key == 'accounting_year_end')
$new->setData($request->request->get($req_key)); //might look as array so setting as string
else if (is_array($request->request->get($req_key)))
$new->setData(json_encode($request->request->get($req_key)));
else
$new->setData($request->request->get($req_key));
$new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
$em->persist($new);
$em->flush();
} else {
if ($req_key == 'accounting_year_start' || $req_key == 'accounting_year_end')
$new_cc->setData($request->request->get($req_key));
else if (is_array($request->request->get($req_key)))
$new_cc->setData(json_encode($request->request->get($req_key)));
else
$new_cc->setData($request->request->get($req_key));
$new_cc->setEditLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
}
}
$em->flush();
}
$data = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\AccSettings')
->findAll();
$supplier_type_data = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\SupplierType')
->findAll();
$client_type_data = $this->getDoctrine()
->getRepository('ApplicationBundle\\Entity\\ClientType')
->findAll();
$action_type_data = [
1 => 'general',
2 => 'advance',
];
$settings_list = [];
$supplier_type_data_list = [];
$client_type_data_list = [];
foreach ($supplier_type_data as $value) {
$supplier_type_data_list[$value->getSupplierTypeId()]['id'] = $value->getSupplierTypeId();
$supplier_type_data_list[$value->getSupplierTypeId()]['name'] = $value->getName();
}
foreach ($client_type_data as $value) {
$client_type_data_list[$value->getClientTypeId()]['id'] = $value->getClientTypeId();
$client_type_data_list[$value->getClientTypeId()]['name'] = $value->getName();
}
foreach ($data as $value) {
$settings_list[$value->getName()]['id'] = $value->getId();
$settings_list[$value->getName()]['name'] = $value->getName();
$settings_list[$value->getName()]['value'] = $value->getData();
if ($value->getName() == 'accounting_year_start' || $value->getName() == 'accounting_year_end')
$settings_list[$value->getName()]['value'] = $value->getData();
else if (is_array(json_decode($value->getData())))
$settings_list[$value->getName()]['value'] = json_decode($value->getData());
else
$settings_list[$value->getName()]['value'] = $value->getData();
}
$warehouse_action_list = Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), '');
$warehouse_action_list_array = Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), 'array');;
return $this->render(
'@Application/pages/accounts/settings/acc_settings.html.twig',
array(
'page_title' => 'Settings',
'settings_data' => $settings_list,
'client_type_list' => $client_type_data_list,
'sales_type_list' => array(1 => 'Package', 2 => 'Project', 3 => 'Item/Spare'),
'sales_sub_type_list' => array(1 => 'Cash Sales', 2 => 'Credit Sale'),
'supplier_type_list' => $supplier_type_data_list,
'payment_action_type_list' => $action_type_data,
'warehouse_action_list' => $warehouse_action_list,
'head_list' => Accounts::HeadListFullPath($em),
'expense_list' => InventoryConstant::$Expense_list_details,
'payroll_segregation_settings' => HumanResourceConstant::$segregationSettings
)
);
}
public function BankAccount(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$AccounDetails = $em->getRepository(BankAccounts::class)->findAll();
$childAccount = Accounts::getChildLedgerHeads($em, "", "");
$accountType = AccountsConstant::$AccountType;
$interestCategory = AccountsConstant::$InterestCategory;
$bankLists = $em->getRepository(BankList::class)->findAll();
$bankAccount = $id ? $em->getRepository(BankAccounts::class)->find($id) : new BankAccounts();
$availableHeads = $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->findAll();
if ($id && !$bankAccount) {
return new JsonResponse(['success' => false, 'message' => 'Bank account not found'], 404);
}
if ($request->isMethod('POST')) {
$accountHolderName = $request->request->get('account_holder_name');
$accountNumber = $request->request->get('account_number');
$accountTypeVal = $request->request->get('account_type');
$interestRate = $request->request->get('interest_rate');
$bankName = $request->request->get('bank_name');
$branchName = $request->request->get('branch_name');
$swiftCode = $request->request->get('swift_code');
$routingNumber = $request->request->get('routing_number');
$numlength = strlen((string)$accountNumber);
if ($numlength < 8 || $accountNumber <= 0) {
return new JsonResponse(['message' => 'Account number must be at least 8 digits and positive!']);
}
if (!$accountHolderName || !$accountNumber || !$accountTypeVal || $interestRate <= 0) {
return new JsonResponse(['message' => 'Missing or invalid required fields.']);
}
// Save main bank
$bank = $em->getRepository(BankList::class)->findOneBy(['name' => $bankName, 'type' => 0]);
if (!$bank) {
$bank = new BankList();
$bank->setName($bankName);
$bank->setType(0); // Type 0 for Bank
$bank->setSwiftCode($swiftCode);
$bank->setRoutingNumber($routingNumber);
$em->persist($bank);
$em->flush();
}
// Save or find branch under this bank
$branch = $em->getRepository(BankList::class)->findOneBy([
'name' => $branchName,
'type' => 2,
'parentId' => $bank->getBankId()
]);
if (!$branch) {
$branch = new BankList();
$branch->setName($branchName);
$branch->setType(2);
$branch->setParentId($bank->getBankId());
$branch->setBank($bankName);
$branch->setSwiftCode($swiftCode);
$branch->setRoutingNumber($routingNumber);
$em->persist($branch);
$em->flush();
}
// Set BankAccount info
$bankAccount->setAccountHolderName($accountHolderName);
$bankAccount->setAccountNumber($accountNumber);
$bankAccount->setAccountType($accountTypeVal);
$bankAccount->setInterestRate($interestRate);
$bankAccount->setInterestCategory($request->request->get('interest_category'));
$bankAccount->setSwiftCode($swiftCode);
$bankAccount->setRoutingNumber($routingNumber);
$bankAccount->setBranchName($branchName);
$accountsHeadId = $request->request->get('accounts_head_id');
if (!$accountsHeadId) {
$branchBankParentData = $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(['name' => 'branch_bank_parent']);
if (!$branchBankParentData) {
return new JsonResponse(['success' => false, 'message' => 'Parent not found']);
}
$branchBankParent = $branchBankParentData->getData();
$accHead = Accounts::CreateNewHead(
$em,
GeneralConstant::OPENING_YEAR,
$branchBankParent,
$bankAccount->getAccountHolderName() . ' # ' . $bankAccount->getAccountNumber(),
'',
0,
0,
'dr',
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
$em->flush();
$bankAccount->setAccountsHeadId($accHead);
} else {
$bankAccount->setAccountsHeadId($accountsHeadId);
}
$em->persist($bankAccount);
$em->flush();
return new JsonResponse(['success' => true]);
}
return $this->render('@Accounts/pages/input_forms/bank_account.html.twig', [
'page_title' => $id ? 'Update Bank Account' : 'Bank Account',
'account_type' => $accountType,
'childAccounts' => $childAccount,
'interestCategory' => $interestCategory,
'bankLists' => $bankLists,
'bankaccount' => $bankAccount,
'AccounDetails' => $AccounDetails,
'available_heads' => $availableHeads,
'id' => $id
]);
}
public function DeleteBankAccount(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$account = $em->getRepository('ApplicationBundle\\Entity\\BankAccounts')->find($id);
if (!$account) {
return new JsonResponse(['success' => false, 'message' => 'Bank account not found'], 404);
}
$currentHeadId = $account->getAccountsHeadId();
$currentHead = $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->find($currentHeadId);
if ($request->isXmlHttpRequest() && $request->isMethod('POST')) {
$newHeadId = $request->request->get('new_head');
if (!$newHeadId) {
return new JsonResponse(['success' => false, 'message' => 'Please select a new head before deletion'], 400);
}
$transactions = $em->getRepository('ApplicationBundle\\Entity\\AccTransactionDetails')
->findBy(['accountsHeadId' => $account->getAccountsHeadId()]);
$newHead = $em->getRepository('ApplicationBundle\\Entity\\AccAccountsHead')->find($newHeadId);
if ($newHead) {
foreach ($transactions as $transaction) {
$transaction->setAccountsHead($newHead);
$em->persist($transaction);
}
$em->flush();
}
$accountId = $account->getId();
$em->remove($account);
$em->flush();
if ($currentHead) {
$em->remove($currentHead);
$em->flush();
}
return new JsonResponse([
'success' => true,
'message' => 'Bank account deleted successfully',
'accountId' => $accountId
]);
}
return new JsonResponse(['success' => false, 'message' => 'Invalid request'], 400);
}
public function BankAccountList()
{
$em = $this->getDoctrine()->getManager();
$AccounDetails = $em->getRepository(BankAccounts::class)->findAll();
$childAccount = Accounts:: getChildLedgerHeads($em, $doc_type = "", $Type = "");
$accountType = AccountsConstant::$AccountType;
return $this->render('@Accounts/pages/list/bank_account_list.html.twig', array(
'page_title' => 'Bank Account List',
'AccounDetails' => $AccounDetails,
'childAccounts' => $childAccount,
'accountType' => $accountType,
));
}
public function createBank(Request $request)
{
$em = $this->getDoctrine()->getManager();
$BankList = $em->getRepository('ApplicationBundle\\Entity\\BankList')->findAll();
if ($request->isMethod('POST')) {
$bank = new BankList();
$name = $request->request->get('name');
$branchName = $request->request->get('branch_name');
$swiftCode = $request->request->get('swift_code');
$routingNumber = $request->request->get('routing_number');
$address = $request->request->get('address');
$mapPosition = $request->request->get('map_position');
$countryId = $request->request->get('country_id');
$type = $request->request->get('type');
$parentId = $request->request->get('parent_id');
$status = $request->request->get('status');
$createdLoginId = $request->getSession()->get('user_login_id');
$bank->setName($name);
$bank->setBranchName($branchName);
$bank->setSwiftCode($swiftCode);
$bank->setRoutingNumber($routingNumber);
$bank->setAddress($address);
$bank->setMapPosition($mapPosition);
$bank->setCountryId($countryId);
$bank->setType($type);
$bank->setParentId($parentId);
$bank->setStatus($status);
$bank->setCreatedLoginId($createdLoginId);
$bank->setCreatedAt(new \DateTime());
$em->persist($bank);
$em->flush();
// return new JsonResponse(['success' => true, 'message' => 'Bank created successfully']);
return $this->redirectToRoute('create_bank_account');
}
return $this->render('@Accounts/pages/input_forms/create_bank.html.twig', [
'page_title' => 'Create Bank Account',
'bankList' => $BankList
]);
}
public function ViewAccountDetail($id)
{
$em = $this->getDoctrine()->getManager();
$AccounDetails = $em->getRepository(BankAccounts::class)->find($id);
$bankLists = $em->getRepository(BankList::class)->findAll();
$childAccount = Accounts::getChildLedgerHeads($em, $doc_type = "", $Type = "");
$accountType = AccountsConstant::$AccountType;
$interestCategory = AccountsConstant::$InterestCategory;
return $this->render('@Accounts/pages/views/view_bank_account_details.html.twig', array(
'page_title' => ' View Bank Account Details',
'AccounDetails' => $AccounDetails,
'childAccounts' => $childAccount,
'account_Type' => $accountType,
'bankLists' => $bankLists,
'interestCategory' => $interestCategory,
'id' => $id,
));
}
public function PrintBankAccount(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$company_data = Company::getCompanyData($em, 1);
$AccounDetails = $em->getRepository(BankAccounts::class)->find($id);
$bankLists = $em->getRepository(BankList::class)->findAll();
$childAccount = Accounts::getChildLedgerHeads($em, $doc_type = "", $Type = "");
$accountType = AccountsConstant::$AccountType;
$interestCategory = AccountsConstant::$InterestCategory;
return $this->render('@Accounts/pages/print/bank_account_print.html.twig', array(
'page_title' => ' Print Bank Account Details',
'AccounDetails' => $AccounDetails,
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'bankLists' => $bankLists,
'childAccounts' => $childAccount,
'account_Type' => $accountType,
'interestCategory' => $interestCategory,
));
}
public function SingleBank($id)
{
$em = $this->getDoctrine()->getManager();
$bankLists = $em->getRepository(BankList::class)->find($id);
return new JsonResponse(
array(
'success' => true,
'routing_code' => $bankLists->getRoutingNumber(),
'swift_code' => $bankLists->getSwiftCode(),
)
);
}
public function createTaxConfig(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$taxConfig = null;
if ($request->isMethod('POST')) {
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
if ($id != 0)
$taxConfig = $em->getRepository(TaxConfig::class)->find($id);
if (!$taxConfig)
$taxConfig = new TaxConfig();
$taxConfig->setName($request->request->get('name'));
$taxConfig->setAmount($request->request->get('amount'));
$taxConfig->setAmountType($request->request->get('amountType'));
$taxConfig->setInvocationType($request->request->get('invocationType'));
$taxConfig->setMinimumAmountToinvoke($request->request->get('minimumInvokeAmount'));
$taxConfig->setOutgoingHeadId($request->request->get('outgoingHeadId'));
$taxConfig->setIncomingHeadId($request->request->get('incomingHeadId'));
$taxConfig->setPayableHeadId($request->request->get('payableHeadId'));
$taxConfig->setCurrency($request->request->get('currency'));
$markerPost = $request->request->get('marker', null);
$markerNorm = ($markerPost === null) ? null : trim((string) $markerPost);
$taxConfig->setMarker(($markerNorm === '' || $markerNorm === null) ? null : $markerNorm);
$taxConfig->setStatus(1);
$em->persist($taxConfig);
$em->flush();
$this->addFlash(
'success',
'Data added successfully'
);
}
$taxConfigDetails = $em->getRepository(TaxConfig::class)->findAll();
$taxConfigData = [];
if ($id != 0)
$taxConfigData = $em->getRepository(TaxConfig::class)->find($id);
return $this->render('@Accounts/pages/input_forms/create_tax_config.html.twig', array(
'page_title' => 'Tax Config ',
'taxconfigDetails' => $taxConfigDetails,
'data' => $taxConfigData
));
}
public function expenseCategory()
{
$expenseCategory = GeneralConstant::$expenseCategory;
return new JsonResponse($expenseCategory);
}
public function packageDetails()
{
$packageDetails = GeneralConstant::$packageDetails;
return new JsonResponse($packageDetails);
}
public function employeerange()
{
$employeerange = GeneralConstant::$employeerange;
return new JsonResponse($employeerange);
}
// public function getExpenseByCurrentDate(Request $request)
// {
// $em = $this->getDoctrine()->getManager();
// $session = $request->getSession();
// $currentTime = new \Datetime();
// $currDate = $currentTime->format('Y-m-d');
// $partyId = 1313;
//
//
//
// $absoluteUrl = $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
//
//
// $expDetails = $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')->createQueryBuilder('E')
// ->leftJoin('ApplicationBundle:Currencies', 'C', 'WITH', 'E.currency = C.currencyId')
// ->select('E, C.code as currencyName') // Selecting currency name
// ->where('E.partyHeadId = :partyId')
// ->andWhere('E.createdAt >= :currentDate')
// ->setParameter('currentDate', $currDate)
// ->setParameter('partyId', $partyId)
// ->getQuery()
// ->getResult();
//
//
// $expenseCategories = GeneralConstant::$expenseCategory;
//
// function getExpenseCategoryByMarker($markerHash, $categories)
// {
// foreach ($categories as $category) {
// if ($category['markerHash'] === $markerHash) {
// return $category; // Return full category array
// }
// }
// return null;
// }
//
// function getSubcategoryName($category, $subcategoryId)
// {
// if (!$category || !isset($category['expenseSubcategory'])) {
// return null;
// }
//
// foreach ($category['expenseSubcategory'] as $subcategory) {
// if ($subcategory['id'] == $subcategoryId) {
// return $subcategory;
// }
// }
// return null;
// }
//
// function getSubcategoryOptionName($subcategory, $optionId)
// {
// if (!$subcategory || !isset($subcategory['option'])) {
// return null;
// }
//
// foreach ($subcategory['option'] as $option) {
// if ($option['id'] == $optionId) {
// return $option;
// }
// }
// return null;
// }
//
// $expList = [];
//
// foreach ($expDetails as $data) {
// $expenseCategory = getExpenseCategoryByMarker($data[0]->getMarkerHash(), $expenseCategories);
// $subcategory = getSubcategoryName($expenseCategory, $data[0]->getExpenseSubCategory());
// $subcategoryOption = getSubcategoryOptionName($subcategory, $data[0]->getExpenseSubCategoryOption());
//
// $list = [
// 'id' => $data[0]->getExpenseInvoiceId(),
// 'amount' => $data[0]->getInvoiceAmount(),
// 'editFlag' => $data[0]->getEditFlag(),
// 'deleteFlag' => $data[0]->getDeleteFlag(),
// 'markerHash' => $data[0]->getMarkerHash(),
// 'expenseDate' => 1 * $data[0]->getExpenseInvoiceDate()->format('U'),
// 'expenseDescription' => $data[0]->getDescription(),
// 'currency' => $data[0]->getCurrency(),
// 'currencyName' => $data['currencyName'] ?? "Unknown Currency", // Fetching currency name
// 'currencyMultiplyRate' => $data[0]->getCurrencyMultiply(),
// 'file' => $absoluteUrl.''.'uploads/ExpenseInvoice/'.$data[0]->getFiles(),
// 'expenseName' => $expenseCategory ? $expenseCategory['name'] : "Unknown Expense",
// 'child' => [
// 'expenseSubCategoryId' => $data[0]->getExpenseSubCategory(),
// 'expenseSubcategoryName' => $subcategory ? $subcategory['name'] : "Unknown Subcategory",
// 'option' => [
// 'expenseSubCategoryOptionId' => $data[0]->getExpenseSubCategoryOption(),
// 'expenseSubcategoryOptionName' => $subcategoryOption ? $subcategoryOption['name'] : "Unknown Option"
// ]
// ]
// ];
// $expList[] = $list;
// }
//
// return new JsonResponse($expList);
// }
public function getExpenseByCurrentDate(Request $request)
{
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$currentTime = new \Datetime();
$currDate = $currentTime->format('Y-m-d');
$employeeId = $session->get(UserConstants::USER_EMPLOYEE_ID);
$employeeDetails = $em->getRepository('ApplicationBundle\\Entity\\Employee')->createQueryBuilder('E')
->select('E.employeeId, E.accountsHeadId') // Selecting currency name
->where('E.employeeId = :employeeId')
->setParameter('employeeId', $employeeId)
->getQuery()
->getResult();
// $partyId = 1313;
$partyId = $employeeDetails[0]['accountsHeadId'];
$absoluteUrl = $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
$expDetails = $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')->createQueryBuilder('E')
->leftJoin('ApplicationBundle:Currencies', 'C', 'WITH', 'E.currency = C.currencyId')
->select('E, C.code as currencyName') // Selecting currency name
->where('E.partyHeadId = :partyId')
->andWhere('E.createdAt >= :currentDate')
->setParameter('currentDate', $currDate)
->setParameter('partyId', $partyId)
->getQuery()
->getResult();
$expenseCategories = GeneralConstant::$expenseCategory;
function getExpenseCategoryByMarker($markerHash, $categories)
{
foreach ($categories as $category) {
if ($category['markerHash'] === $markerHash) {
return $category;
}
}
return null;
}
function getSubcategoryName($category, $subcategoryId)
{
if (!$category || !isset($category['expenseSubcategory'])) {
return null;
}
foreach ($category['expenseSubcategory'] as $subcategory) {
if ($subcategory['id'] == $subcategoryId) {
return $subcategory;
}
}
return null;
}
function getSubcategoryOptionName($subcategory, $optionId)
{
if (!$subcategory || !isset($subcategory['option'])) {
return null;
}
foreach ($subcategory['option'] as $option) {
if ($option['id'] == $optionId) {
return $option;
}
}
return null;
}
$expList = [];
$totalAmount = 0;
foreach ($expDetails as $data) {
$expenseCategory = getExpenseCategoryByMarker($data[0]->getMarkerHash(), $expenseCategories);
$subcategory = getSubcategoryName($expenseCategory, $data[0]->getExpenseSubCategory());
$subcategoryOption = getSubcategoryOptionName($subcategory, $data[0]->getExpenseSubCategoryOption());
$amount = floatval($data[0]->getInvoiceAmount());
$totalAmount += $amount;
$list = [
'id' => $data[0]->getExpenseInvoiceId(),
'amount' => number_format($amount, 2, '.', ''),
'editFlag' => $data[0]->getEditFlag(),
'deleteFlag' => $data[0]->getDeleteFlag(),
'markerHash' => $data[0]->getMarkerHash(),
'expenseDate' => 1 * $data[0]->getExpenseInvoiceDate()->format('U'),
'expenseDescription' => $data[0]->getDescription(),
'currency' => $data[0]->getCurrency(),
'currencyName' => $data['currencyName'] ?? "Unknown Currency",
'currencyMultiplyRate' => $data[0]->getCurrencyMultiply(),
'filePath' => $absoluteUrl . '' . 'uploads/ExpenseInvoice/' . $data[0]->getFiles(),
'file' => $data[0]->getFiles(),
'expenseName' => $expenseCategory ? $expenseCategory['name'] : "Unknown Expense",
'child' => [
'expenseSubCategoryId' => $data[0]->getExpenseSubCategory(),
'expenseSubcategoryName' => $subcategory ? $subcategory['name'] : "Unknown Subcategory",
'option' => [
'expenseSubCategoryOptionId' => $data[0]->getExpenseSubCategoryOption(),
'expenseSubcategoryOptionName' => $subcategoryOption ? $subcategoryOption['name'] : "Unknown Option"
]
]
];
$expList[] = $list;
}
$response = [
'totalAmount' => number_format($totalAmount, 2, '.', ''),
'expenses' => $expList
// $employeeId,$partyId
// $employeeDetails[0]['accountsHeadId']
];
return new JsonResponse($response);
}
public function currentBalance(Request $request)
{
$em = $this->getDoctrine()->getManager();
$ind_head_id = [];
$start_date = $request->query->get('start_date', "");
$end_date = $request->query->get('end_date', "");
if($end_date=='')
$end_date=(new \DateTime())->format('Y-m-d');
// return new JsonResponse( Accounts::GetBalanceOnDateByMarkerHash($em,$end_date,[],[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT],1));
$dataType = '_OWN_';
// $dataType='_COMPANY_';//_OWN_
$session = $request->getSession();
$userId=$session->get(UserConstants::USER_TYPE);
if ($session->get(UserConstants::USER_TYPE) == UserConstants::USER_TYPE_SYSTEM)
$dataType = '_COMPANY_';
$allowedCards=[];
if($dataType=='_OWN_')
{
$allowedCards=[1,2,3];
$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";
$stmt = $em->getConnection()->fetchAllAssociative($get_kids_sql);
$query_output = $stmt;
if (empty($query_output)) {
$ind_head_id=[0];
} else if ($query_output[0]['accounts_head_id'] == 0 || $query_output[0]['accounts_head_id'] == NULL)
$ind_head_id=[0];
else {
if($query_output[0]['accounts_head_id'] !='' && $query_output[0]['accounts_head_id'] != 0 && $query_output[0]['accounts_head_id'] !=null)$ind_head_id[] = $query_output[0]['accounts_head_id'];
if($query_output[0]['advance_head_id'] !='' && $query_output[0]['advance_head_id'] != 0 && $query_output[0]['advance_head_id'] !=null)$ind_head_id[] = $query_output[0]['advance_head_id'];
if($query_output[0]['advance_wages_head_id'] !='' && $query_output[0]['advance_wages_head_id'] != 0 && $query_output[0]['advance_wages_head_id'] !=null)$ind_head_id[] = $query_output[0]['advance_wages_head_id'];
}
}
else
{
$setting_qry = $em->getRepository('ApplicationBundle\\Entity\\AccSettings')->findOneBy(array(
'name' => 'cash_and_cash_equivalent_parents'
));
$cace_parents=[];
if ($setting_qry)
$cace_parents = json_decode($setting_qry->getData(), true);
$ind_head_id=$cace_parents;
}
$query_head_balance=0;
if($dataType=='_COMPANY_')
{
$ledger_data=Accounts::GetBalanceOnDateByMarkerHash($em,$end_date,[],[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT],1);
$query_head_balance += $ledger_data[AccountsConstant::CASH_AND_CASH_EQUIVALENT_PARENT]['closingBalance'] ?? 0;
}
else {
foreach ($ind_head_id as $ind_head) {
$ledger_data = Accounts::LedgerDetailsTransMethod($em, $ind_head, $start_date, $end_date);
$mult = $ledger_data['basic_data']['head_nature'] ? ($ledger_data['basic_data']['head_nature'] == 'cr' ? 1 : -1) : 0;
$query_head_balance += ($mult * $ledger_data['query_head_balance'] ?? 0);
}
}
$today_date = new \DateTime();
$today_date = $today_date->format('Y-m-d');
$s_date_obj = \DateTime::createFromFormat('Y-m-d', $today_date);
$start_of_month = $s_date_obj->format('Y-m-01'); // First day of the month
$end_of_month = $s_date_obj->format('Y-m-t'); // Last day of the month
$expense_date = $today_date;
$start_of_day = new \DateTime($expense_date . ' 00:00:00');
$end_of_day = new \DateTime($expense_date . ' 23:59:59');
$query = $em->createQueryBuilder()
->select('b.accountsHeadId', 'a.current_balance')
->from('ApplicationBundle:BankAccounts', 'b')
->join('ApplicationBundle:AccAccountsHead', 'a', 'WITH', 'b.accountsHeadId = a.accountsHeadId')
->getQuery();
$results = $query->getResult();
$acc_account_head_data = [];
foreach ($results as $result) {
$acc_account_head_data[] = [
'current_balance' => $result['current_balance'],
];
}
$monthly_summary_data = $em->getRepository('ApplicationBundle\\Entity\\MonthlySummary')
->createQueryBuilder('m')
->where('m.date >= :start_of_month')
->andWhere('m.date <= :end_of_month')
->setParameter('start_of_month', $start_of_month)
->setParameter('end_of_month', $end_of_month)
->orderBy('m.date', 'ASC')
->getQuery()
->getResult();
$monthly_summary = [];
foreach ($monthly_summary_data as $summary) {
if ($summary instanceof \ApplicationBundle\Entity\MonthlySummary) {
$monthly_summary[] = [
'date' => $summary->getDate()->format('Y-m-d'),
'cash' => $summary->getCash(),
'revenue' => $summary->getRevenue(),
'expense' => $summary->getExpense(),
'receivable' => $summary->getReceivable(),
'payable' => $summary->getPayable(),
'asset' => $summary->getAsset(),
'liability' => $summary->getLiability()
];
}
}
$qb = $em->createQueryBuilder()
->select('SUM(e.invoiceAmount)')
->from('ApplicationBundle:ExpenseInvoice', 'e')
->where('e.createdAt BETWEEN :start_of_day AND :end_of_day')
->setParameter('start_of_day', $start_of_day)
->setParameter('end_of_day', $end_of_day);
if($dataType=='_OWN_')
$qb->andWhere("e.createdUserId = $userId");
$total_invoice_amount = $qb->getQuery()->getSingleScalarResult();
$total_invoice_amount = $total_invoice_amount !== null ? (float)$total_invoice_amount : 0.00;
$acc_account_head_data = isset($acc_account_head_data[0]['current_balance'])
? $acc_account_head_data[0]['current_balance'] : 0.00;
$response = [
'query_head_balance' => $query_head_balance,
'total_today_expense_amount' => number_format($total_invoice_amount, 2, '.', ''),
'primary_account_balance' => $acc_account_head_data,
'allowed_cards' => $allowedCards
];
if (!empty($monthly_summary)) {
$response = array_merge($response, $monthly_summary[0]);
}
return new JsonResponse($response);
}
public function editExpense(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$expenseInvoice = $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')->find($id);
if (!$expenseInvoice) {
return new JsonResponse(['success' => false, 'message' => 'Expense invoice not found'], 404);
}
if ($request->isMethod('POST')) {
$expenseInvoice->setExpenseInvoiceDate(new \DateTime($request->request->get('expense_date')));
$expenseInvoice->setInvoiceAmount($request->request->get('expense_amount'));
$expenseInvoice->setPartyId(1313);
$expenseInvoice->setExpenseInvoiceTypeId($request->request->get('expense_type'));
$expenseInvoice->setMarkerHash($request->request->get('markerHash'));
$expenseInvoice->setCurrency($request->request->get('expense_currency_id'));
$expenseInvoice->setCurrencyMultiply($request->request->get('expense_currency_multiply'));
$expenseInvoice->setExpenseSubcategory($request->request->get('expense_sub_category'));
$expenseInvoice->setExpenseSubcategoryOption($request->request->get('expense_sub_category_option'));
$expenseInvoice->setWbsCode($request->request->get('wbsCode', ''));
$expenseInvoice->setWbsActivityName($request->request->get('wbsActivityName', ''));
if (!empty($request->files->get('file'))) {
$file = $request->files->get('file');
$fileName = md5(uniqid()) . '.' . $file->guessExtension();
$path = $fileName;
$upl_dir = $_SERVER["DOCUMENT_ROOT"] . '/../web/uploads/ExpenseInvoice/';
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
$file = $file->move($upl_dir, $path);
$expenseInvoice->setFiles($fileName);
} else {
}
$expenseInvoice->setDescription($request->request->get('description'));
$em->flush(); //
return new JsonResponse(['success' => true]);
}
return new JsonResponse(['success' => false, 'message' => 'Invalid request'], 400);
}
public function deleteExpenseInvoice(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
// $id = $request->query->get('id');
$expenseInvoice = $em->getRepository('ApplicationBundle\\Entity\\ExpenseInvoice')->find($id);
if (!$expenseInvoice) {
return new JsonResponse(['message' => 'Expense invoice not found'], 404);
}
$em->remove($expenseInvoice);
$em->flush();
return new JsonResponse(['message' => 'Expense invoice deleted successfully'], 200);
}
// public function getChequeListForApp(Request $request)
// {
// $em = $this->getDoctrine()->getManager();
//
//
// $qb = $em->getRepository('ApplicationBundle\\Entity\\AccCheck')->createQueryBuilder('C')
// ->select(
// 'c.checkDate',
// 'c.checkNumber',
// 'c.checkAmount',
// 'c.CheckId',
// 't.documentHash',
// 't.transactionDate'
//// 'a.name AS accountsHeadName'
// )
// ->from('ApplicationBundle:AccCheck', 'c')
// ->leftJoin('ApplicationBundle:AccTransactions', 't', 'WITH', 'c.voucherId = t.transactionId')
// ->leftJoin('ApplicationBundle:AccTransactionDetails', 'd', 'WITH', 'd.transactionId = c.voucherId')
// ->leftJoin('ApplicationBundle:AccAccountsHead', 'a', 'WITH', 'a.accountsHeadId = d.accountsHeadId');
//
//
// $inventoryData = $qb->getQuery()->getResult();
//
// return $this->json([
//
// 'data' => $inventoryData,
// ]);
// }
public function getChequeListForApp(Request $request)
{
$em = $this->getDoctrine()->getManager();
$accountsHeadId = $request->query->get('accountsHeadId');
if (!$accountsHeadId) {
return new JsonResponse(['error' => 'accountsHeadId parameter is required'], 400);
}
$page = (int)$request->query->get('page', 1);
$limit = (int)$request->query->get('limit', 10);
$offset = ($page - 1) * $limit;
$qb = $em->createQueryBuilder();
$qb->select(
'c.checkDate',
'c.checkNumber',
'c.checkAmount',
'c.CheckId',
't.documentHash',
't.transactionDate',
'a.name AS accountsHeadName'
)
->from('ApplicationBundle:AccCheck', 'c')
->leftJoin('ApplicationBundle:AccTransactions', 't', 'WITH', 'c.voucherId = t.transactionId')
->leftJoin('ApplicationBundle:AccTransactionDetails', 'd', 'WITH', 'd.transactionId = c.voucherId')
->leftJoin('ApplicationBundle:AccAccountsHead', 'a', 'WITH', 'a.accountsHeadId = d.accountsHeadId')
->where('c.accountsHeadId = :accountsHeadId')
->setParameter('accountsHeadId', $accountsHeadId)
->setFirstResult($offset)
->setMaxResults($limit);
$results = $qb->getQuery()->getArrayResult();
// Get total count
$countQb = $em->createQueryBuilder();
$countQb->select('COUNT(c.CheckId)')
->from('ApplicationBundle:AccCheck', 'c')
->where('c.accountsHeadId = :accountsHeadId')
->setParameter('accountsHeadId', $accountsHeadId);
$total = $countQb->getQuery()->getSingleScalarResult();
// Format dates as timestamp
foreach ($results as &$row) {
$row['checkDate'] = isset($row['checkDate']) && $row['checkDate'] instanceof \DateTime
? $row['checkDate']->getTimestamp()
: '';
$row['transactionDate'] = isset($row['transactionDate']) && $row['transactionDate'] instanceof \DateTime
? $row['transactionDate']->getTimestamp()
: '';
$row['checkNumber'] = $row['checkNumber'] ?? '';
$row['checkAmount'] = $row['checkAmount'] ?? '';
$row['CheckId'] = $row['CheckId'] ?? '';
$row['documentHash'] = !empty($row['documentHash']) ? $row['documentHash'] : '';
$row['accountsHeadName'] = !empty($row['accountsHeadName']) ? $row['accountsHeadName'] : '';
}
return new JsonResponse([
'currentPage' => $page,
'limit' => $limit,
'total' => (int)$total,
'data' => $results,
]);
}
public function MarkerHashCostCenterData()
{
$data = AccountsConstant::$COMBINED_ARRAY;
return new JsonResponse([
'markerHash' => $data['markerHash'],
'costCenter' => $data['costCenter'],
]);
}
public function agingReportApi(Request $request)
{
$em = $this->getDoctrine()->getManager();
$entity = 18;
$projectCategories = $em->getRepository('ApplicationBundle\\Entity\\ProjectCategory')
->findBy(['status' => GeneralConstant::ACTIVE]);
$categoryDetails = [];
foreach ($projectCategories as $category) {
$categoryDetails[] = [
'categoryName' => $category->getCategoryName(),
'categoryId' => $category->getProjectCategoryId(),
];
}
$reportData = [];
$periodType = 1;
$divide = 1;
$categoryIds = [];
if ($request->isMethod('POST')) {
$categoryInput = $request->request->get('projectCategoryId');
if ($categoryInput) {
$categoryIds = is_array($categoryInput) ? $categoryInput : explode(',', $categoryInput);
$categoryIds = array_map('intval', $categoryIds);
}
$periodType = (int)$request->request->get('period_type', 1);
$divide = (int)$request->request->get('divide', 1);
}
$monthsPerInterval = ($periodType * 12) / $divide;
$intervals = [];
$startMonth = 1;
for ($i = 0; $i < $divide; $i++) {
$endMonth = $startMonth + $monthsPerInterval - 1;
$intervals[] = [
'label' => "$startMonth-$endMonth month",
'start' => $startMonth,
'end' => $endMonth
];
$startMonth += $monthsPerInterval;
}
foreach ($intervals as $interval) {
$reportData[$interval['label']] = [];
}
if ($request->isMethod('POST')) {
$qb = $em->createQueryBuilder()
->select([
'cf.entity',
'cf.entityId',
'cf.cashFlowAmount',
'cf.cashFlowDate',
'si.salesInvoiceNumber',
'so.salesOrderId',
'so.salesOrderNumber',
'p.projectId',
'p.projectName',
'pc.projectCategoryId',
'pc.categoryName',
'c.clientName',
'c.clientShortCode',
// 'e.name',
// 'ed.lastname',
])
->from('ApplicationBundle:CashFlowProjection', 'cf')
->innerJoin('ApplicationBundle:SalesInvoice', 'si', 'WITH', 'si.salesInvoiceId = cf.entityId')
->innerJoin('ApplicationBundle:SalesOrder', 'so', 'WITH', 'so.salesOrderId = si.salesOrderId')
->innerJoin('ApplicationBundle:Project', 'p', 'WITH', 'p.projectId = so.projectId')
->innerJoin('ApplicationBundle:ProjectCategory', 'pc', 'WITH', 'pc.projectCategoryId = p.projectCategoryId')
->innerJoin('ApplicationBundle:AccClients', 'c', 'WITH', 'c.clientId = so.clientId')
// ->innerJoin('ApplicationBundle:Employee', 'e', 'WITH', 'e.employeeId = so.salesPersonId')
->where('cf.entity = :entity')
->setParameter('entity', $entity);
if (!empty($categoryIds)) {
$qb->andWhere('pc.projectCategoryId IN (:categoryIds)')
->setParameter('categoryIds', $categoryIds);
}
$results = $qb->getQuery()->getArrayResult();
foreach ($results as $item) {
$month = (int)$item['cashFlowDate']->format('m');
// Find the interval label
$intervalLabel = null;
foreach ($intervals as $interval) {
if ($month >= $interval['start'] && $month <= $interval['end']) {
$intervalLabel = $interval['label'];
break;
}
}
if (!$intervalLabel) continue;
$projectId = $item['projectId'];
$salesOrderId = $item['salesOrderId'];
if (!isset($reportData[$intervalLabel][$projectId])) {
$reportData[$intervalLabel][$projectId] = [
'projectName' => $item['projectName'],
'projectCategory' => $item['projectCategoryId'],
'projectCategoryName' => $item['categoryName'],
'TotalAmount' => 0,
'salesOrders' => []
];
}
if (!isset($reportData[$intervalLabel][$projectId]['salesOrders'][$salesOrderId])) {
$reportData[$intervalLabel][$projectId]['salesOrders'][$salesOrderId] = [
'salesOrderNumber' => $item['salesOrderNumber'],
'clientName' => $item['clientName'],
'clientShortCode' => $item['clientShortCode'],
// 'firstName' => $item['name'],
// 'lastName' => $item['lastname'],
'TotalAmount' => 0,
'invoices' => []
];
}
$invoice = [
'entity' => $item['entity'],
'entityId' => $item['entityId'],
'amount' => $item['cashFlowAmount'],
'date' => $item['cashFlowDate'] ? $item['cashFlowDate']->format('Y-m-d') : null,
'salesInvoiceNumber' => $item['salesInvoiceNumber']
];
$reportData[$intervalLabel][$projectId]['salesOrders'][$salesOrderId]['invoices'][] = $invoice;
$reportData[$intervalLabel][$projectId]['salesOrders'][$salesOrderId]['TotalAmount'] += $item['cashFlowAmount'];
$reportData[$intervalLabel][$projectId]['TotalAmount'] += $item['cashFlowAmount'];
}
}
// return new JsonResponse([
// 'reportData' => $reportData,
//
// ]);
return $this->render('@Accounts/pages/report/aging_report.html.twig', [
'page_title' => 'Aging Report',
'reportData' => $reportData,
'periodType' => $periodType,
'divide' => $divide,
'selectedCategoryIds' => $categoryIds,
'category' => $categoryDetails,
]);
}
public function getParentHead(Request $request)
{
$em = $this->getDoctrine()->getManager();
$response = Accounts::getParentLedgerHeadsForApi($request, $em);
if (!$response) {
return new JsonResponse([
'status' => 'False',
'message' => 'Something went wrong'
], 500);
}
return new JsonResponse($response, 200);
}
public function getChildHead(Request $request)
{
$em = $this->getDoctrine()->getManager();
$parentId = $request->query->get('parent_id');
if (!$parentId) {
return new JsonResponse([
'status' => 'error',
'message' => 'parent_id is required'
], 400);
}
$response = Accounts::getChildHeadData($em, $parentId);
if (!$response) {
return new JsonResponse([
'status' => 'False',
'message' => 'Something went wrong'
], 500);
}
return new JsonResponse($response, 200);
}
// public function getSalesInvoiceDetails(Request $request, $id)
// {
// $em = $this->getDoctrine()->getManager();
//
// $salesInvoiceDetails = $em
// ->getRepository('ApplicationBundle\\Entity\\SalesInvoice')
// ->find($id);
//
// if (!$salesInvoiceDetails) {
// return new JsonResponse(['data' => null], 200);
// }
// $salesInvoiceItems = $em
// ->getRepository('ApplicationBundle\\Entity\\SalesInvoiceItem')
// ->findBy([
// 'salesInvoiceId' => $salesInvoiceDetails->getSalesInvoiceId()
// ]);
// $items = [];
//
// foreach ($salesInvoiceItems as $item) {
//
// $product = $em
// ->getRepository('ApplicationBundle\\Entity\\InvProducts')
// ->findOneBy([
// 'id' => $item->getProductId()
// ]);
// $service = $em
// ->getRepository('ApplicationBundle\\Entity\\AccService')
// ->findOneBy([
// 'serviceId' => $item->getServiceid()
// ]);
//
// $items[] = [
// 'productId' => $item->getProductId(),
// 'productName' => $product ? $product->getName() : '',
// 'serviceId' => $item->getServiceId(),
// 'servceName' => $service ? $service->getServiceName() : '',
// 'qty' => $item->getQty(),
// 'unitPrice' => $item->getAmount(),
// 'total' => $item->getPrice()
// ];
// }
//
// $accClient = $em
// ->getRepository('ApplicationBundle\\Entity\\AccClients')
// ->findOneBy([
// 'clientId' => $salesInvoiceDetails->getClientId()
// ]);
//
// $currency = $em
// ->getRepository('ApplicationBundle\\Entity\\Currencies')
// ->findOneBy([
// 'currencyId' => $salesInvoiceDetails->getCurrency()
// ]);
//
// $data = [
// 'invoiceNumber' => $salesInvoiceDetails->getSalesInvoiceId(),
// 'documentNumber' => $salesInvoiceDetails->getDocumentHash(),
// 'date' => $salesInvoiceDetails->getSalesInvoiceDate()
// ? $salesInvoiceDetails->getSalesInvoiceDate()->format('Y-m-d')
// : null,
// 'currencyName' => $currency ? $currency->getName() : null,
// 'clientName' => $accClient ? $accClient->getClientName() : null,
// 'clientAddress' => $accClient ? $accClient->getAddressContact() : null,
// 'taxAmount' => $salesInvoiceDetails ? $salesInvoiceDetails->getTaxDeductionAmount() : 0,
// 'items' => $items
// ];
//
// return new JsonResponse(['data' => $data]);
// }
public function getSalesInvoiceDetails(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$salesInvoice = $em
->getRepository('ApplicationBundle\\Entity\\SalesInvoice')
->find($id);
if (!$salesInvoice) {
return new Response('Invoice not found', 404);
}
$accClient = $em->getRepository('ApplicationBundle\\Entity\\AccClients')
->findOneBy(['clientId' => $salesInvoice->getClientId()]);
$currency = $em->getRepository('ApplicationBundle\\Entity\\Currencies')
->findOneBy(['currencyId' => $salesInvoice->getCurrency()]);
$itemsData = $em->getRepository('ApplicationBundle\\Entity\\SalesInvoiceItem')
->findBy(['salesInvoiceId' => $salesInvoice->getSalesInvoiceId()]);
$xml = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><Invoice></Invoice>');
$xml->addChild('ID', $salesInvoice->getSalesInvoiceId());
$xml->addChild('IssueDate', $salesInvoice->getSalesInvoiceDate()->format('Y-m-d'));
$xml->addChild('DocumentNumber', $salesInvoice->getDocumentHash());
$clientNode = $xml->addChild('Customer');
$clientNode->addChild('Name', $accClient ? $accClient->getClientName() : '');
$clientNode->addChild('Address', $accClient ? $accClient->getAddressContact() : '');
$xml->addChild('TaxAmount', $salesInvoice->getTaxDeductionAmount() ?? 0);
$itemsNode = $xml->addChild('Items');
foreach ($itemsData as $item) {
$product = $em->getRepository('ApplicationBundle\\Entity\\InvProducts')
->find($item->getProductId());
$itemNode = $itemsNode->addChild('Item');
$itemNode->addChild('ProductName', $product ? $product->getName() : '');
$itemNode->addChild('Quantity', $item->getQty());
$itemNode->addChild('UnitPrice', $item->getAmount());
$itemNode->addChild('Total', $item->getPrice());
}
$xmlContent = $xml->asXML();
$response = new Response($xmlContent);
$response->headers->set('Content-Type', 'application/xml');
$response->headers->set(
'Content-Disposition',
'attachment; filename="invoice_'.$salesInvoice->getSalesInvoiceId().'.xml"'
);
return $response;
}
private function validateAddExpenseRequest(Request $request)
{
$expenseType = (int) $request->request->get('expense_type', 0);
$expenseAmount = (float) $request->request->get('expense_amount', 0);
$previousAdvanceAmount = (float) $request->request->get('prev_advance_amount', 0);
$expenseId = (int) $request->request->get('expense_id', 0);
$expenseToBePaidTo = $request->request->get('expense_to_be_paid_to', '');
$checkId = (int) $request->request->get('check_id', 0);
$expenseDate = $this->parseAddExpenseDate($request->request->get('expense_date', ''));
$supportedExpenseTypes = array(0, 1, 2, 3, 5);
if (!in_array($expenseType, $supportedExpenseTypes, true)) {
return 'Invalid expense type selected.';
}
if (!$expenseDate) {
return 'Please select a valid expense date.';
}
if ($expenseId <= 0) {
return 'Please select expense name/head.';
}
if ($expenseToBePaidTo === '' || (string) $expenseToBePaidTo === '0') {
return 'Please select balance against head.';
}
if ($expenseAmount <= 0) {
return 'Expense amount must be greater than zero.';
}
if ($previousAdvanceAmount < 0) {
return 'Advance amount cannot be negative.';
}
if ($previousAdvanceAmount > $expenseAmount) {
return 'Advance amount cannot be greater than expense amount.';
}
if ($expenseType === 1 && (int) $request->request->get('poId', 0) <= 0) {
return 'Please select a purchase order.';
}
if ($expenseType === 2 && (int) $request->request->get('soId', 0) <= 0) {
return 'Please select a sales order/project.';
}
if ($expenseType === 3 && (int) $request->request->get('opportunityId', $request->request->get('leadId', 0)) <= 0) {
return 'Please select a lead/bid.';
}
if ($expenseType === 5 && (int) $request->request->get('tour_id', 0) <= 0) {
return 'Please select a tour.';
}
if ($checkId > 0 && !$this->parseAddExpenseDate($request->request->get('check_date', ''))) {
return 'Please select a valid cheque date.';
}
if ((int) $request->request->get('exp_check_expense_distribution_on_product', 0) === 1) {
if ($expenseType !== 1) {
return 'Product cost distribution is only available for purchase expenses.';
}
$distributionPoItemIds = $request->request->get('exp_distribution_poitemId', array());
$distributionAmounts = $request->request->get('exp_distribution_amount', array());
if (empty($distributionPoItemIds) || empty($distributionAmounts)) {
return 'No purchase items found for product cost distribution.';
}
$distributedAmount = 0;
foreach ($distributionAmounts as $distributionAmount) {
$distributedAmount += (float) $distributionAmount;
}
if (abs($distributedAmount - $expenseAmount) > 0.01) {
return 'Distributed product cost must equal the expense amount.';
}
}
$fileValidationError = $this->validateAddExpenseFiles($request->files->get('file', array()));
if ($fileValidationError !== null) {
return $fileValidationError;
}
return null;
}
private function parseAddExpenseDate($value)
{
$value = trim((string) $value);
if ($value === '') {
return null;
}
$formats = array('F d, Y', 'Y-m-d', 'd-m-Y');
foreach ($formats as $format) {
$date = \DateTime::createFromFormat($format, $value);
$errors = \DateTime::getLastErrors();
if ($date instanceof \DateTime && ($errors === false || ($errors['warning_count'] === 0 && $errors['error_count'] === 0))) {
$date->setTime(0, 0, 0);
return $date;
}
}
return null;
}
private function validateAddExpenseFiles($files)
{
$allowedExtensions = array('pdf', 'jpg', 'jpeg', 'png', 'doc', 'docx');
$maxFileSize = 5 * 1024 * 1024;
if (!is_array($files)) {
$files = $files ? array($files) : array();
}
foreach ($files as $file) {
if ($file === null) {
continue;
}
$extension = strtolower((string) $file->guessExtension());
if ($extension === '') {
$extension = strtolower((string) $file->getClientOriginalExtension());
}
if (!in_array($extension, $allowedExtensions, true)) {
return 'Only PDF, JPG, JPEG, PNG, DOC, and DOCX files are allowed.';
}
if ((int) $file->getSize() > $maxFileSize) {
return 'Each attachment must be 5 MB or smaller.';
}
}
return null;
}
public function exportDxso(Request $request): Response
{
$data = json_decode($request->getContent(), true);
$formattedDate = (new \DateTime($data['date']))->format('Ymd');
$csvContent = Accounts::generateDxsoCsv($data,$formattedDate);
return new Response(
$csvContent,
Response::HTTP_OK,
[
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="dxso_file.csv"',
]
);
}
// =========================================================================
// S2.6 — Invoice Variant Print Action
// =========================================================================
/**
* Print a specific invoice variant (commercial / customs / lc / import / credit_note).
*
* Loads the same invoice data as PrintSalesInvoice but renders the
* variant-specific template and registers in DocumentRegistry.
*
* Routes: print_invoice_commercial, print_invoice_customs, print_invoice_lc,
* print_invoice_import, print_credit_note
*/
public function PrintInvoiceVariantAction(Request $request, $id = 0, $invoiceVariant = 'commercial')
{
$em = $this->getDoctrine()->getManager();
$data = SalesOrderM::GetSalesInvoiceDetails($em, $id);
// Ensure variant is valid
$validVariants = ['commercial', 'customs', 'lc', 'import', 'credit_note'];
if (!in_array($invoiceVariant, $validVariants)) {
$invoiceVariant = 'commercial';
}
// Register in DocumentRegistry (S2.3) — non-blocking
if (!empty($data['si_data'])) {
try {
DocumentRegistry::register($em, $invoiceVariant, 'SalesInvoice', (int)$id, [
'tenantId' => $data['si_data']->getCompanyId(),
'customerId' => $data['si_data']->getClientId(),
'projectId' => $data['si_data']->getProjectId(),
'documentNumber' => isset($data['doc_hash']) ? $data['doc_hash'] : null,
'currency' => $data['si_data']->getCurrency(),
'documentVariant'=> $invoiceVariant,
'createdBy' => $request->getSession()->get(UserConstants::USER_LOGIN_ID),
]);
} catch (\Exception $e) { /* non-blocking */ }
}
$company_data = Company::getCompanyData($em, $data['si_data']->getCompanyId());
// Variant labels for print header
$variantLabels = [
'commercial' => 'Commercial Invoice',
'customs' => 'Customs Invoice',
'lc' => 'Letter of Credit Invoice',
'import' => 'Import Invoice',
'credit_note'=> 'Credit Note',
];
return $this->render('@Accounts/pages/print/print_invoice_variant.html.twig', [
'page_title' => $variantLabels[$invoiceVariant] . ' — ' . (isset($data['doc_hash']) ? $data['doc_hash'] : ''),
'data' => $data,
'invoice_variant' => $invoiceVariant,
'variant_label' => $variantLabels[$invoiceVariant],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'export' => 'pdf,print',
]);
}
}