<?php
namespace ApplicationBundle\Controller;
use ApplicationBundle\Constants\GeneralConstant;
use ApplicationBundle\Entity\DashboardWidget;
use ApplicationBundle\Entity\Employee;
use ApplicationBundle\Entity\EmployeeDetails;
use ApplicationBundle\Entity\SysUser;
use ApplicationBundle\Interfaces\SessionCheckInterface;
use ApplicationBundle\Modules\Accounts\Accounts;
use ApplicationBundle\Modules\Authentication\Constants\UserConstants;
use ApplicationBundle\Modules\HumanResource\HumanResource;
use ApplicationBundle\Modules\Inventory\Inventory;
use ApplicationBundle\Modules\Purchase\Supplier;
use ApplicationBundle\Modules\Sales\Client;
use ApplicationBundle\Modules\System\MiscActions;
use ApplicationBundle\Modules\System\System;
use ApplicationBundle\Modules\User\Company;
use ApplicationBundle\Modules\User\Position;
use ApplicationBundle\Modules\User\Users;
use CompanyGroupBundle\Entity\CompanyGroup;
use CompanyGroupBundle\Entity\EntityApplicantDetails;
use Symfony\Component\BrowserKit\Client as BrowserClientKit;
use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
use Symfony\Component\Routing\Generator\UrlGenerator;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class DashboardController extends GenericController implements SessionCheckInterface
{
public function doLoginAsAction(Request $request)
{
$session = $request->getSession();
if ($request->isMethod('POST')) {
$session->set(UserConstants::USER_CURRENT_POSITION, $request->request->get('position'));
$curr_position_id = $request->request->get('position');
if ($session->get(UserConstants::USER_LOGIN_ID) != 0) {
$loginID = $this->get('user_module')->addUserLoginLog(
$session->get(UserConstants::USER_ID),
$request->server->get("REMOTE_ADDR"),
$request->request->get('position'),
'',
'',
'',
$session->get(UserConstants::USER_LOGIN_ID)
);
} else $loginID = $this->get('user_module')->addUserLoginLog(
$session->get(UserConstants::USER_ID),
$request->server->get("REMOTE_ADDR"),
$request->request->get('position'),
'',
'',
'',
0
);
if ($session->get(UserConstants::ALL_MODULE_ACCESS_FLAG) == 1)
$prohibit_list_array = [];
else if ($curr_position_id != 0)
$prohibit_list_array = Position::getUserProhibitRouteArray($this->getDoctrine()->getManager(), $curr_position_id, $session->get(UserConstants::USER_ID));
$session->set(UserConstants::USER_LOGIN_ID, $loginID);
$session->set(UserConstants::USER_PROHIBIT_LIST, json_encode($prohibit_list_array));
$session->set(UserConstants::USER_ROUTE_LIST, json_encode(Position::getUserRouteArray($this->getDoctrine()->getManager(), $request->request->get('position'), $session->get(UserConstants::USER_ID))));
return $this->redirectToRoute("dashboard");
}
$message = "";
$PositionList = array();
$PL = json_decode($session->get(UserConstants::USER_POSITION_LIST), true);
foreach ($PL as &$positionID) {
$PositionList[$positionID] = Position::getPositionName($this->getDoctrine()->getManager(), $positionID);
}
return $this->render(
'ApplicationBundle:pages/login:login_position.html.twig',
array(
"message" => $message,
'page_title' => 'Users',
'position_list' => $PositionList
)
);
}
// protected $twig;
// protected $debug;
//
// /**
// * @param bool $debug Show error (false) or exception (true) pages by default
// */
// public function __construct(Environment $twig, $debug)
// {
// $this->twig = $twig;
// $this->debug = $debug;
// }
public function TestSmsAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$em = $this->getDoctrine()->getManager();
$userAppId = $session->get('userAppId');
$companyId = $session->get('userCompanyId');
if (GeneralConstant::SMS_ENABLED == 1) {
$company = $em->getRepository('ApplicationBundle:Company')->findOneBy(
array(
'id' => $companyId, ///material
)
);
if ($company->getSmsNotificationEnabled() == 1) {
$smsData = [];
$smsSettings = json_decode($company->getSmsSettings(), true);
if ($smsSettings != null && !empty($smsSettings)) {
$method = isset($smsSettings['method']) ? $smsSettings['method'] : 'GET';
$destination_url = isset($smsSettings['destination_url']) ? $smsSettings['destination_url'] : 'http://172.105.70.96:1234';
$user_name = isset($smsSettings['user_name']) ? $smsSettings['user_name'] : 'test';
$user_name_var = isset($smsSettings['user_name_var']) ? $smsSettings['user_name_var'] : 'Username';
$password_var = isset($smsSettings['password_var']) ? $smsSettings['password_var'] : 'Password';
$password = isset($smsSettings['password']) ? $smsSettings['password'] : '';
$from_number_var = isset($smsSettings['from_number_var']) ? $smsSettings['from_number_var'] : 'From';
$from_number = isset($smsSettings['from_number']) ? $smsSettings['from_number'] : '';
$to_number_var = isset($smsSettings['to_number_var']) ? $smsSettings['to_number_var'] : 'To';
$to_number = $request->query->has('To') ? $request->query->get('To') : '01911706483';
$text_var = isset($smsSettings['text_var']) ? $smsSettings['text_var'] : 'Message';
$text = $request->query->has('Message') ? $request->query->get('Message') : 'Test message';
return new JsonResponse(System::sendSms(
1,
$method,
$destination_url,
$user_name_var,
$user_name,
$password_var,
$password,
$from_number_var,
$from_number,
$to_number_var,
$to_number,
$text_var,
$text,
$viewlink = ""
));
}
}
return new JsonResponse(
[
'companyId' => $companyId,
'companyName' => $company->getName(),
'enabled' => $company->getSmsNotificationEnabled(),
// 'smsSettings'=>$smsSettings
]
);
}
return new JsonResponse(
[
'success' => false
]
);
}
public function SyncCompanyProductToEntityProductAction(Request $request)
{
$gocId = $request->query->has('gocId') ? $request->query->get('gocId') : 0;
$companyId = $request->query->has('companyId') ? $request->query->get('companyId') : 1;
$genQueryArray = [];
$em_goc = $this->getDoctrine()->getManager('company_group');
$em_goc->getConnection()->connect();
$em = $this->getDoctrine()->getManager();
if ($request->query->has('forceRefresh')) {
$genQueryArray = [];
$query = "
TRUNCATE `entity_brand_company`;
TRUNCATE `entity_item_group`;
TRUNCATE `entity_products`;
TRUNCATE `entity_product_categories`;
TRUNCATE `entity_product_specifications`;
TRUNCATE `entity_product_sub_categories`;
TRUNCATE `entity_specification_types`;
TRUNCATE `entity_unit_type`;
SELECT * from `entity_unit_type`;";
$stmt = $em_goc->getConnection()->prepare($query);
$stmt->execute();
// $Transactions = $stmt->fetchAll();
$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()->prepare($get_kids_sql);
$stmt->execute();
$query = $stmt->fetchAll();
} else
$genQueryArray = ['globalId' => [0, null]];
//1st step get all company item ids and then check for global id null if its null then the
// item group is not present in entity so add it
$company_wise_entities = [
'Currencies',
'UnitType',
'SpecType',
'BrandCompany',
'InvItemGroup',
'InvProductCategories',
'InvProductSubCategories',
'InvProductSpecifications',
'InvSpecificationTypes',
'InvProducts'
];
$entity_wise_entities = [
'EntityCurrencies',
'EntityUnitType',
'EntitySpecType',
'EntityBrandCompany',
'EntityItemGroup',
'EntityProductCategories',
'EntityProductSubCategories',
'EntityProductSpecifications',
'EntitySpecificationTypes',
'EntityProducts'
];
////ITEMGROUPS
foreach ($company_wise_entities as $k => $cwa) {
$dataOnCompany = $em
->getRepository("ApplicationBundle:" . $cwa)
->findBy(
$genQueryArray
);
$match_cid_gid_itemgroup = []; //[cid=>gid]
$match_cid_gid_itemgroup = []; //[cid=>gid]
foreach ($dataOnCompany as $data) {
$newClass = "\\CompanyGroupBundle\\Entity\\" . $entity_wise_entities[$k];
$new = new $newClass();
// $new = new \CompanyGroupBundle\Entity\EntityItemGroup();
$getters = array_filter(get_class_methods($data), function ($method) {
return 'get' === substr($method, 0, 3);
});
foreach ($getters as $getter) {
if ($getter == 'getGlobalId')
continue;
// if ($getter == 'getId')
// continue;
$setMethod = str_replace('get', 'set', $getter);
if (method_exists($new, $setMethod))
$new->{$setMethod}($data->{$getter}()); // `foo!`
}
$em_goc->persist($new);
$em_goc->flush();
if ($cwa == 'Currencies') {
$data->setGlobalId($new->getCurrencyId());
$new->setGlobalId($new->getCurrencyId());
} else {
$data->setGlobalId($new->getId());
$new->setGlobalId($new->getId());
}
$em->flush();
$em_goc->flush();
// $match_cid_gid_itemgroup[$data->getId()] = $new->getId();
}
}
return new JsonResponse(
array(
'data' => $entity_wise_entities
)
);
}
public function SyncEntityProductToCompanyProductAction(Request $request)
{
$gocId = $request->query->has('gocId') ? $request->query->get('gocId') : 0;
$companyId = $request->query->has('companyId') ? $request->query->get('companyId') : 1;
$genQueryArray = [];
$em_goc = $this->getDoctrine()->getManager('company_group');
$em_goc->getConnection()->connect();
$em = $this->getDoctrine()->getManager();
if ($request->query->has('forceRefresh')) {
$genQueryArray = [];
$query = "
TRUNCATE `brand_company`;
TRUNCATE `inv_item_group`;
TRUNCATE `inv_products`;
TRUNCATE `inv_product_categories`;
TRUNCATE `inv_product_specifications`;
TRUNCATE `inv_product_sub_categories`;
TRUNCATE `inv_specification_types`;
TRUNCATE `unit_type`;
SELECT * from `unit_type`;";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
// $Transactions = $stmt->fetchAll();
$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()->prepare($get_kids_sql);
$stmt->execute();
$query = $stmt->fetchAll();
} else {
// $genQueryArray = ['globalId' => [0, null]];
}
//1st step get all company item ids and then check for global id null if its null then the
// item group is not present in entity so add it
$company_wise_entities = [
'Currencies',
'UnitType',
'SpecType',
'BrandCompany',
'InvItemGroup',
'InvProductCategories',
'InvProductSubCategories',
'InvProductSpecifications',
'InvSpecificationTypes',
'InvProducts'
];
$entity_wise_entities = [
'EntityCurrencies',
'EntityUnitType',
'EntitySpecType',
'EntityBrandCompany',
'EntityItemGroup',
'EntityProductCategories',
'EntityProductSubCategories',
'EntityProductSpecifications',
'EntitySpecificationTypes',
'EntityProducts'
];
foreach ($entity_wise_entities as $k => $ewa) {
$dataOnEntity = $em_goc
->getRepository("CompanyGroupBundle:" . $ewa)
->findBy(
$genQueryArray
);
$match_cid_gid_itemgroup = []; //[cid=>gid]
$match_cid_gid_itemgroup = []; //[cid=>gid]
foreach ($dataOnEntity as $data) {
$newClass = "\\ApplicationBundle\\Entity\\" . $company_wise_entities[$k];
$rec_exists = 0;
$new = $em
->getRepository("ApplicationBundle:" . $company_wise_entities[$k])
->findOneBy(
array(
'globalId' => $data->getGlobalId()
)
);
if ($new) {
$rec_exists = 1;
} else
$new = new $newClass();
// $new = new \CompanyGroupBundle\Entity\EntityItemGroup();
$getters = array_filter(get_class_methods($data), function ($method) {
return 'get' === substr($method, 0, 3);
});
foreach ($getters as $getter) {
if ($getter == 'getId')
continue;
$setMethod = str_replace('get', 'set', $getter);
if (method_exists($new, $setMethod)) {
if ($ewa == 'EntityProducts') {
if ($rec_exists == 1) {
if (in_array($setMethod, [
'setPurchasePrice',
'setPurchasePriceWoExpense',
'setQty',
'setReorderLevel',
'setBookingQty',
'setNonSalesInvoicedQty',
'setNonSalesReturnReceivedQty',
'setBookingQty',
'setPhysicalQty',
])) {
continue;
}
}
}
$new->{$setMethod}($data->{$getter}()); // `foo!`
}
}
if ($rec_exists == 0)
$em->persist($new);
$em->flush();
if ($ewa == 'EntityCurrencies') {
$new->setGlobalId($data->getCurrencyId());
} else {
$new->setGlobalId($data->getId());
}
$em->flush();
// $match_cid_gid_itemgroup[$data->getId()] = $new->getId();
}
}
return new JsonResponse(
array(
'data' => $company_wise_entities
)
);
}
public function getAppGeneralDashboardDataAction(Request $request)
{
$dataFor = 'client';
$personId = 0;
if ($request->query->has('dataFor'))
$dataFor = $request->query->get('dataFor');
if ($request->request->has('dataFor'))
$dataFor = $request->request->get('dataFor');
if ($request->query->has('personId'))
$personId = $request->query->get('personId');
if ($request->request->has('personId'))
$personId = $request->request->get('personId');
if ($personId == 0)
return new JsonResponse(
array(
'success' => false,
'data' => [],
)
);
$session = $request->getSession();
$em = $this->getDoctrine()->getManager();
$userAppId = $session->get('userAppId');
$companyId = $session->get('userCompanyId');
$dataToConnectList = [];
$appIdList = $session->get('appIdList');
$companyIdListByAppId = $session->get('companyIdListByAppId');
$companyNameListByAppId = $session->get('companyNameListByAppId');
$companyImageListByAppId = $session->get('companyImageListByAppId');
$gocEnabled = 0;
if ($this->container->hasParameter('entity_group_enabled'))
$gocEnabled = $this->container->getParameter('entity_group_enabled');
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$session->get('gocDbName'),
$session->get('gocDbUser'),
$session->get('gocDbPass'),
$session->get('gocDbHost'),
$reset = true
);
$em = $this->getDoctrine()->getManager();
$data = [];
if ($dataFor == 'client') {
//get order_count, order_amount,bill_count, bill_amount, collection_amount, due_amount
$data = [
'order_count' => 0,
'order_amount' => 0,
'invoice_count' => 0,
'invoice_amount' => 0,
'collection_amount' => 0,
'due_amount' => 0,
'client_count' => 1,
];
$clientIds = [$personId];
//order count and amount
$get_sql = "SELECT count(sales_order_id) order_count, sum(so_amount) order_amount
FROM sales_order WHERE approved=1 and sales_order.company_id=" . $companyId . " and sales_order.client_id in (" . implode(',', $clientIds) . ");";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
if (!empty($entries)) {
$data['order_count'] = 1 * $entries[0]['order_count'];
$data['order_amount'] = 1 * $entries[0]['order_amount'];
}
//invoice
$get_sql = "SELECT count(sales_invoice_id) invoice_count, sum(invoice_amount) invoice_amount
FROM sales_invoice WHERE approved=1 and sales_invoice.company_id=" . $companyId . " and sales_invoice.client_id in (" . implode(',', $clientIds) . ");";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
if (!empty($entries)) {
$data['invoice_count'] = 1 * $entries[0]['invoice_count'];
$data['invoice_amount'] = 1 * $entries[0]['invoice_amount'];
}
//now collection
$get_sql = "SELECT SUM(CASE WHEN position = 'cr' THEN amount ELSE 0 END) positive_amount,
SUM(CASE WHEN position = 'dr' THEN amount ELSE 0 END) negative_amount,client_type.client_type_id, client_type.name, acc_clients.client_id, acc_clients.type, acc_clients.client_due, acc_clients.client_id
FROM acc_transaction_details
join acc_clients on acc_clients.accounts_head_id=acc_transaction_details.accounts_head_id or acc_clients.advance_head_id=acc_transaction_details.accounts_head_id
join client_type on acc_clients.type=client_type.client_type_id
WHERE acc_transaction_details.ledger_hit=1 AND acc_transaction_details.transaction_id in (select distinct transaction_id from acc_transactions where acc_transactions.document_type=6) and acc_clients.client_id in (" . implode(',', $clientIds) . ") ";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
$clientTypes = [];
$clientTypeNames = [];
$alreadyCids = [];
foreach ($entries as $entry) {
$data['collection_amount'] += (1 * ($entry['positive_amount'] - $entry['negative_amount']));
if (!in_array($entry['client_id'], $alreadyCids)) {
$data['due_amount'] += ($entry['client_due']);
$alreadyCids[] = $entry['client_id'];
}
}
}
if ($dataFor == 'sales_user') {
//get order_count, order_amount,bill_count, bill_amount, collection_amount, due_amount
$data = [
'order_count' => 0,
'order_amount' => 0,
'invoice_count' => 0,
'invoice_amount' => 0,
'collection_amount' => 0,
'due_amount' => 0,
'client_count' => 0,
];
$clientIds = [];
$salesPersonIds = [];
$allSalespersonFlag = 1; //temp
if ($allSalespersonFlag != 1) {
$query = $em->getRepository('ApplicationBundle:Employee')->findOneBy(
array(
'userId' => $personId
)
);
if ($query)
$salesPersonIds[] = $query->getEmployeeId();
}
//Client count
$get_sql = "SELECT client_id
FROM acc_clients WHERE acc_clients.company_id=" . $companyId . " ";
if ($allSalespersonFlag != 1)
$get_sql .= " and acc_clients.sales_person_id in (" . implode(',', $salesPersonIds) . ");";
else
$get_sql .= " ;";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
if (!empty($entries)) {
foreach ($entries as $entry) {
$data['client_count'] += 1;
$clientIds[] = $entry['client_id'];
}
}
//order count and amount
if (!empty($clientIds)) {
$get_sql = "SELECT count(sales_order_id) order_count, sum(so_amount) order_amount
FROM sales_order WHERE approved=1 and sales_order.company_id=" . $companyId . " and sales_order.client_id in (" . implode(',', $clientIds) . ");";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
if (!empty($entries)) {
$data['order_count'] = 1 * $entries[0]['order_count'];
$data['order_amount'] = 1 * $entries[0]['order_amount'];
}
//invoice
$get_sql = "SELECT count(sales_invoice_id) invoice_count, sum(invoice_amount) invoice_amount
FROM sales_invoice WHERE approved=1 and sales_invoice.company_id=" . $companyId . " and sales_invoice.client_id in (" . implode(',', $clientIds) . ");";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
if (!empty($entries)) {
$data['invoice_count'] = 1 * $entries[0]['invoice_count'];
$data['invoice_amount'] = 1 * $entries[0]['invoice_amount'];
}
//now collection
$get_sql = "SELECT SUM(CASE WHEN position = 'cr' THEN amount ELSE 0 END) positive_amount,
SUM(CASE WHEN position = 'dr' THEN amount ELSE 0 END) negative_amount,client_type.client_type_id, client_type.name, acc_clients.client_id, acc_clients.type, acc_clients.client_due, acc_clients.client_id
FROM acc_transaction_details
join acc_clients on acc_clients.accounts_head_id=acc_transaction_details.accounts_head_id or acc_clients.advance_head_id=acc_transaction_details.accounts_head_id
join client_type on acc_clients.type=client_type.client_type_id
WHERE acc_transaction_details.ledger_hit=1 AND acc_transaction_details.transaction_id in (select distinct transaction_id from acc_transactions where acc_transactions.document_type=6) and acc_clients.client_id in (" . implode(',', $clientIds) . ") ";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
$clientTypes = [];
$clientTypeNames = [];
$alreadyCids = [];
foreach ($entries as $entry) {
$data['collection_amount'] += (1 * ($entry['positive_amount'] - $entry['negative_amount']));
if (!in_array($entry['client_id'], $alreadyCids)) {
$data['due_amount'] += ($entry['client_due']);
$alreadyCids[] = $entry['client_id'];
}
}
}
}
if ($dataFor == 'user') {
//get order_count, payment_amount,
}
return new JsonResponse(
array(
'success' => true,
'data' => $data,
'dataFor' => $dataFor,
'personId' => $personId,
)
);
}
public function getManagementDashboardDataAction(Request $request)
{
$session = $request->getSession();
$data = array(
'cash_and_bank_position' => [],
'order_and_client_count' => [],
'expense_vs_revenue' => [],
'receivable_position' => [],
'payable_position' => [],
'expense_position' => [],
'inventory_position' => [],
'production_position' => [],
'sales_position' => [],
'collection_position' => [],
'market_return_position' => [],
'top_selling_item_position' => [],
'top_selling_client_position' => [],
);
$em = $this->getDoctrine()->getManager();
$reportsToGet = [
'cash_and_bank_position',
'order_and_client_count',
'expense_vs_revenue',
'receivable_position',
'payable_position',
'expense_position',
'inventory_position',
'production_position',
'sales_position',
'collection_position',
'market_return_position',
'top_selling_item_position',
'top_selling_client_position',
];
// $periodType='day'; //day,month,week,year,quarter etc
$periodType = 'month'; //day,month,week,year,quarter etc
if ($request->request->has('reportsToGet')) {
if ($request->request->get('reportsToGet') != 'all' && !in_array('all', $request->request->get('reportsToGet'))) {
$reportsToGet = $request->request->get('reportsToGet');
}
}
if ($request->request->has('periodType')) {
$periodType = $request->request->get('periodType');
}
$userAppId = $session->get('userAppId');
$dataToConnectList = [];
$appIdList = $session->get('appIdList');
$companyIdListByAppId = $session->get('companyIdListByAppId');
$companyNameListByAppId = $session->get('companyNameListByAppId');
$companyImageListByAppId = $session->get('companyImageListByAppId');
$gocEnabled = 0;
if ($this->container->hasParameter('entity_group_enabled'))
$gocEnabled = $this->container->getParameter('entity_group_enabled');
$thisPeriodStartDate = '';
$lastPeriodStartDate = '';
$thisPeriodEndDate = '';
$lastPeriodEndDate = '';
$today = new \DateTime();
if ($periodType == 'month') {
$thisPeriodEndDate = $today->format('Y-m-d');
$thisPeriodStartDate = $today->format('Y-m-') . '01';
$currDate = new \DateTime($thisPeriodStartDate);
$currDate->modify('-1 day');
$lastPeriodEndDate = $currDate->format('Y-m-d');
$lastPeriodStartDate = $currDate->format('Y-m-') . '01';
} else if ($periodType == 'week') {
$thisPeriodEndDate = $today->format('Y-m-d');
$thisWeekStartDate = date("Y-m-d", strtotime("previous saturday"));
$thisPeriodStartDate = date("Y-m-d", strtotime("previous saturday"));
$currDate = new \DateTime($thisPeriodStartDate);
$currDate->modify('-1 day');
$lastPeriodEndDate = $currDate->format('Y-m-d');
$currDate->modify('-6 day');
$lastPeriodStartDate = $currDate->format('Y-m-d');
} else if ($periodType == 'quarter') {
$thisPeriodEndDate = $today->format('Y-m-d');
$thisWeekStartDate = date("Y-m-d", strtotime("previous saturday"));
$thisPeriodStartDate = date("Y-m-d", strtotime("previous saturday"));
$currDate = new \DateTime($thisPeriodStartDate);
$currDate->modify('-1 day');
$lastPeriodEndDate = $currDate->format('Y-m-d');
$currDate->modify('-6 day');
$lastPeriodStartDate = $currDate->format('Y-m-d');
} else if ($periodType == 'year') {
$thisPeriodEndDate = $today->format('Y-m-d');
// $thisWeekStartDate = date("Y-m-d", strtotime("previous saturday"));
$thisPeriodStartDate = ($today->format('Y')) . '-01-01';
$currDate = new \DateTime($thisPeriodStartDate);
$currDate->modify('-1 day');
$lastPeriodEndDate = $currDate->format('Y-m-d');
$lastPeriodStartDate = ($currDate->format('Y')) . '-01-01';;
}
$companyListData = [];
foreach ($appIdList as $appId) {
//queryonly if mor ethan one app id
$skip = 0;
if ($appId == $userAppId) {
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$session->get('gocDbName'),
$session->get('gocDbUser'),
$session->get('gocDbPass'),
$session->get('gocDbHost'),
$reset = true
);
$em = $this->getDoctrine()->getManager();
} else {
$dataToConnect = System::changeDoctrineManagerByAppId($this->getDoctrine()->getManager('company_group'), $gocEnabled, $appId);
$dataToConnectList[] = $dataToConnect;
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 {
$skip = 1;
}
}
if ($skip == 1)
continue;
// $companyListData[] = Company::getCompanyListWithImage($em);
// $get_sql = "SELECT * FROM company ";
// $stmt = $em->getConnection()->prepare($get_sql);
// $stmt->execute();
// $entries = $stmt->fetchAll();
// $companyListData[] = $entries;
// foreach ($companyIdListByAppId as $app_company_index)
if (isset($companyIdListByAppId[$appId])) {
foreach ($companyIdListByAppId[$appId] as $app_company_index) {
//exp vs rev
if (in_array('expense_vs_revenue', $reportsToGet)) {
$acHeadList = [];
$companyId = explode('_', $app_company_index)[1];
$acHeadDataById = [];
$thisBalanceDataByAcHead = [];
$lastBalanceDataByAcHead = [];
$mon_names = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
$limit = 12;
$get_kids_sql = "SELECT expense, revenue, `date` summ_date
FROM monthly_summary
where monthly_summary.company_id=$companyId
AND ( monthly_summary.branch_id=0 or monthly_summary.branch_id is null) ";
// GROUP BY monthly_summary.`date`
$get_kids_sql .= " ORDER BY monthly_summary.`date` DESC limit " . $limit;
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$pl = $stmt->fetchAll();
$curr_date = new \DateTime();
$curr_mon = (1 * $curr_date->format('m'));
$curr_year = (1 * $curr_date->format('Y'));
$object_list = [];
$debug_list = [];
$list = [];
$timeStampList = [];
// $first
foreach ($pl as $key => $entry) {
$qryDate = new \DateTime($entry['summ_date']);
$qrMon = 1 * $qryDate->format('m');;
$qrYr = 1 * $qryDate->format('Y');;
$object_list[$qrYr . '_' . $qrMon] = $entry;
}
for ($k = 0; $k < 11; $k++) {
$debug_list[$k] = $curr_year . '_' . $curr_mon;
$currTimeStamp = strtotime($curr_year . "-" . $curr_mon . '-1');
$currTimeStampMili = $currTimeStamp * 1000;
$cashAddition = 0;
$bankAddition = 0;
if (isset($object_list[$curr_year . '_' . $curr_mon])) {
$entry = $object_list[$curr_year . '_' . $curr_mon];
$list['monthList'][] = $mon_names[$curr_mon];
$list['revenue'][] = round($entry['revenue']);
$list['tsCommaRevenue'][] = [$currTimeStampMili, round($entry['revenue'])];
$list['expense'][] = round($entry['expense']);
$list['tsCommaExpense'][] = [$currTimeStampMili, round($entry['expense'])];
} else {
$list['monthList'][] = $mon_names[($curr_mon)];
$list['revenue'][] = 0;
$list['expense'][] = 0;
$list['tsCommaRevenue'][] = [$currTimeStampMili, 0];
$list['tsCommaExpense'][] = [$currTimeStampMili, 0];
}
$curr_mon--;
if ($curr_mon <= 0) {
$curr_mon = 12;
$curr_year--;
}
//new end
}
$data['expense_vs_revenue'][$app_company_index] = $list;
}
//cash and bank position
if (in_array('cash_and_bank_position', $reportsToGet)) {
$acHeadList = [];
$companyId = explode('_', $app_company_index)[1];
$acHeadDataById = [];
$thisBalanceDataByAcHead = [];
$lastBalanceDataByAcHead = [];
$bank_settings = $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
'name' => 'bank_parents',
// 'CompanyId'=>$companyId
));
$bank_id_list = [];
if ($bank_settings)
$bank_id_list = json_decode($bank_settings->getData());
$bank_child_id_list = [];
$likeQuery = '';
foreach ($bank_id_list as $p) {
$likeQuery .= "OR path_tree like '%/" . $p . "%/' ";
}
$get_sql = "SELECT * FROM acc_accounts_head WHERE acc_accounts_head.company_id=" . $companyId . " AND accounts_head_id not in (select distinct parent_id from acc_accounts_head)and (1=0 " . $likeQuery . ") ";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
foreach ($entries as $entry) {
$has_payments = 1;
$bank_child_id_list[] = $entry['accounts_head_id'];
$acHeadList[] = $entry['accounts_head_id'];
$acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
}
$cash_settings = $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
'name' => 'cash_parents'
// 'CompanyId'=>$companyId
));
$cash_id_list = [];
if ($cash_settings)
$cash_id_list = json_decode($cash_settings->getData());
$cash_child_id_list = [];
$likeQuery = '';
foreach ($cash_id_list as $p) {
$likeQuery .= "OR path_tree like '%/" . $p . "%/' ";
}
$get_sql = "SELECT * FROM acc_accounts_head WHERE acc_accounts_head.company_id=" . $companyId . " AND accounts_head_id not in (select distinct parent_id from acc_accounts_head)and (1=0 " . $likeQuery . ") ";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
foreach ($entries as $entry) {
$has_payments = 1;
$cash_child_id_list[] = $entry['accounts_head_id'];
$acHeadList[] = $entry['accounts_head_id'];
$acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
}
$thisBalance_data = Accounts::GetBalanceOnDate($em, $thisPeriodEndDate, []);
$lastBalance_data = Accounts::GetBalanceOnDate($em, $lastPeriodEndDate, []);
foreach ($acHeadList as $acHead) {
$thisBalanceDataByAcHead[$acHead]['balance'] = $thisBalance_data[$acHead]['end_balance']['balance'];
$lastBalanceDataByAcHead[$acHead]['balance'] = $lastBalance_data[$acHead]['end_balance']['balance'];
}
$thisReportData = array(
'accountsHeadList' => $acHeadList,
'acHeadDataById' => $acHeadDataById,
'cash_child_id_list' => $cash_child_id_list,
'bank_child_id_list' => $bank_child_id_list,
'thisBalanceDataByAcHead' => $thisBalanceDataByAcHead,
'lastBalanceDataByAcHead' => $lastBalanceDataByAcHead,
);
$data['cash_and_bank_position'][$app_company_index] = $thisReportData;
// $companyListData[] = Company::getCompanyListWithImage($em);
}
//Expense Position
if (in_array('expense_position', $reportsToGet)) {
$acHeadList = [];
$companyId = explode('_', $app_company_index)[1];
$acHeadDataById = [];
$thisBalanceDataByAcHead = [];
$lastBalanceDataByAcHead = [];
$get_sql = "SELECT * FROM acc_accounts_head WHERE acc_accounts_head.company_id=" . $companyId . "
AND acc_accounts_head.head_level= 2 ";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
foreach ($entries as $entry) {
$has_payments = 1;
$cash_child_id_list[] = $entry['accounts_head_id'];
$acHeadList[] = $entry['accounts_head_id'];
$acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
}
$thisBalance_data = Accounts::GetPeriodicDataByType($em, $type = 'exp', $level_to_group_by = 1, $parent_id_list = [], $expand_level = 1, $thisPeriodStartDate, $thisPeriodEndDate, '_during_', [], [], [], false);
$lastBalance_data = Accounts::GetPeriodicDataByType($em, $type = 'exp', $level_to_group_by = 1, $parent_id_list = [], $expand_level = 1, $lastPeriodStartDate, $lastPeriodEndDate, '_during_', [], [], [], false);
$skipHeadIds = [];
foreach ($thisBalance_data as $parentHead => $balanceData) {
foreach ($balanceData['data'] as $acHead => $headData) {
if (!in_array($acHead, $acHeadList))
continue;
$thisBalanceDataByAcHead[$acHead]['balance'] = $headData['head_balance'];
if (isset($lastBalance_data[$parentHead])) {
if (isset($lastBalance_data[$parentHead]['data'][$acHead]))
$lastBalanceDataByAcHead[$acHead]['balance'] = $lastBalance_data[$parentHead]['data'][$acHead]['head_balance'];
else
$lastBalanceDataByAcHead[$acHead]['balance'] = 0;
} else
$lastBalanceDataByAcHead[$acHead]['balance'] = 0;
$skipHeadIds[] = $acHead;
}
}
foreach ($lastBalance_data as $parentHead => $balanceData) {
foreach ($balanceData['data'] as $acHead => $headData) {
if (in_array($acHead, $skipHeadIds))
continue;
if (!in_array($acHead, $acHeadList))
continue;
$lastBalanceDataByAcHead[$acHead]['balance'] = $headData['head_balance'];
if (isset($thisBalance_data[$parentHead])) {
if (isset($thisBalance_data[$parentHead]['data'][$acHead]))
$thisBalanceDataByAcHead[$acHead]['balance'] = $thisBalance_data[$parentHead]['data'][$acHead]['head_balance'];
else
$thisBalanceDataByAcHead[$acHead]['balance'] = 0;
} else
$thisBalanceDataByAcHead[$acHead]['balance'] = 0;
$skipHeadIds[] = $acHead;
}
}
$thisReportData = array(
'accountsHeadList' => $acHeadList,
// 'thisBalance_data' => $thisBalance_data,
'confirmedHeadList' => $skipHeadIds,
'acHeadDataById' => $acHeadDataById,
'thisBalanceDataByAcHead' => $thisBalanceDataByAcHead,
'lastBalanceDataByAcHead' => $lastBalanceDataByAcHead,
);
$data['expense_position'][$app_company_index] = $thisReportData;
// $companyListData[] = Company::getCompanyListWithImage($em);
}
//Payable Position
if (in_array('payable_position', $reportsToGet)) {
$acHeadList = [];
$companyId = explode('_', $app_company_index)[1];
$acHeadDataById = [];
$thisBalanceDataByAcHead = [];
$lastBalanceDataByAcHead = [];
$filter_settings = $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
'name' => 'payable_parents',
// 'CompanyId'=>$companyId
));
$filter_head_parents_id_list = [];
if ($filter_settings)
$filter_head_parents_id_list = json_decode($filter_settings->getData());
$likeQuery = '';
foreach ($filter_head_parents_id_list as $p) {
$likeQuery .= "OR path_tree like '%/" . $p . "%/' ";
}
$get_sql = "SELECT * FROM acc_accounts_head WHERE acc_accounts_head.company_id=" . $companyId . "
and (1=0 " . $likeQuery . ") ";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
foreach ($entries as $entry) {
$has_payments = 1;
$acHeadList[] = $entry['accounts_head_id'];
$acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
}
// $get_sql = "SELECT * FROM acc_accounts_head WHERE acc_accounts_head.company_id=" . $companyId . "
// AND acc_accounts_head.head_level= 2 and acc_accounts_head.type='lib'";
//
// $stmt = $em->getConnection()->prepare($get_sql);
// $stmt->execute();
// $entries = $stmt->fetchAll();
//
// foreach ($entries as $entry) {
// $has_payments = 1;
// $cash_child_id_list[] = $entry['accounts_head_id'];
// $acHeadList[] = $entry['accounts_head_id'];
// $acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
// }
$thisBalance_data = Accounts::GetPeriodicDataByType($em, $type = 'lib', $level_to_group_by = 2, $parent_id_list = [], $expand_level = 1, $thisPeriodStartDate, $thisPeriodEndDate, '_during_', [], [], [], false);
$lastBalance_data = Accounts::GetPeriodicDataByType($em, $type = 'lib', $level_to_group_by = 2, $parent_id_list = [], $expand_level = 1, $lastPeriodStartDate, $lastPeriodEndDate, '_during_', [], [], [], false);
$skipHeadIds = [];
foreach ($thisBalance_data as $parentHead => $balanceData) {
foreach ($balanceData['data'] as $acHead => $headData) {
if (!(in_array($acHead, $acHeadList)))
continue;
if ($headData['head_level'] > 4)
continue;
// $thisBalanceDataByAcHead[$acHead]['balance'] = $headData['head_balance'];
$thisBalanceDataByAcHead[$acHead]['balance'] = $headData['end_balance']['balance'];
if (isset($lastBalance_data[$parentHead])) {
if (isset($lastBalance_data[$parentHead]['data'][$acHead]))
// $lastBalanceDataByAcHead[$acHead]['balance'] = $lastBalance_data[$parentHead]['data'][$acHead]['head_balance'];
$lastBalanceDataByAcHead[$acHead]['balance'] = $lastBalance_data[$parentHead]['data'][$acHead]['end_balance']['balance'];
else
$lastBalanceDataByAcHead[$acHead]['balance'] = 0;
} else
$lastBalanceDataByAcHead[$acHead]['balance'] = 0;
$skipHeadIds[] = $acHead;
}
}
foreach ($lastBalance_data as $parentHead => $balanceData) {
foreach ($balanceData['data'] as $acHead => $headData) {
if (in_array($acHead, $skipHeadIds))
continue;
if (!in_array($acHead, $acHeadList))
continue;
if ($headData['head_level'] > 4)
continue;
$lastBalanceDataByAcHead[$acHead]['balance'] = $headData['end_balance']['balance'];
if (isset($thisBalance_data[$parentHead])) {
if (isset($thisBalance_data[$parentHead]['data'][$acHead]))
$thisBalanceDataByAcHead[$acHead]['balance'] = $thisBalance_data[$parentHead]['data'][$acHead]['end_balance']['balance'];
else
$thisBalanceDataByAcHead[$acHead]['balance'] = 0;
} else
$thisBalanceDataByAcHead[$acHead]['balance'] = 0;
$skipHeadIds[] = $acHead;
}
}
$thisReportData = array(
'accountsHeadList' => $acHeadList,
// 'thisBalance_data' => $thisBalance_data,
'confirmedHeadList' => $skipHeadIds,
'acHeadDataById' => $acHeadDataById,
'thisBalanceDataByAcHead' => $thisBalanceDataByAcHead,
'lastBalanceDataByAcHead' => $lastBalanceDataByAcHead,
);
$data['payable_position'][$app_company_index] = $thisReportData;
// $companyListData[] = Company::getCompanyListWithImage($em);
}
//Receivable Position
if (in_array('receivable_position', $reportsToGet)) {
$acHeadList = [];
$companyId = explode('_', $app_company_index)[1];
$acHeadDataById = [];
$thisBalanceDataByAcHead = [];
$lastBalanceDataByAcHead = [];
// $filter_settings = $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
// 'name' => 'receivable_parents',
//// 'CompanyId'=>$companyId
// ));
// $filter_head_parents_id_list = [];
// if ($filter_settings)
// $filter_head_parents_id_list = json_decode($filter_settings->getData());
// $likeQuery = '';
// foreach ($filter_head_parents_id_list as $p) {
// $likeQuery .= "OR path_tree like '%/" . $p . "%/' ";
// }
// $get_sql = "SELECT * FROM acc_accounts_head WHERE acc_accounts_head.company_id=" . $companyId . "
// and (1=0 " . $likeQuery . ") ";
$get_sql = "SELECT acc_accounts_head.* FROM acc_accounts_head
WHERE acc_accounts_head.company_id=" . $companyId . "
and ( acc_accounts_head.accounts_head_id in (select distinct accounts_head_id from acc_clients)
OR acc_accounts_head.accounts_head_id in (select distinct advance_head_id from acc_clients)
) ";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
$account_head_ids_by_client_type = [];
foreach ($entries as $entry) {
$has_payments = 1;
$acHeadList[] = $entry['accounts_head_id'];
$acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
}
$get_sql = "SELECT acc_clients.* FROM acc_clients
WHERE acc_clients.company_id=" . $companyId;
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
$clientTypeListArray = Client::ClientTypeList($em, [$companyId], true);
$clientTypesOfHeads = [];
foreach ($entries as $entry) {
if (!isset($account_head_ids_by_client_type[$entry['type']]))
$account_head_ids_by_client_type[$entry['type']] = [];
$account_head_ids_by_client_type[$entry['type']][] = $entry['accounts_head_id'];
$clientTypesOfHeads[$entry['accounts_head_id']] = $entry['type'];
if ($entry['accounts_head_id'] != $entry['advance_head_id']) {
$account_head_ids_by_client_type[$entry['type']][] = $entry['advance_head_id'];
$clientTypesOfHeads[$entry['advance_head_id']] = $entry['type'];
}
}
// $get_sql = "SELECT * FROM acc_accounts_head WHERE acc_accounts_head.company_id=" . $companyId . "
// AND acc_accounts_head.head_level= 2 and acc_accounts_head.type='lib'";
//
// $stmt = $em->getConnection()->prepare($get_sql);
// $stmt->execute();
// $entries = $stmt->fetchAll();
//
// foreach ($entries as $entry) {
// $has_payments = 1;
// $cash_child_id_list[] = $entry['accounts_head_id'];
// $acHeadList[] = $entry['accounts_head_id'];
// $acHeadDataById[$entry['accounts_head_id']]['name'] = $entry['name'];
// }
$thisBalance_data = Accounts::GetPeriodicDataByType($em, $type = 'ast', $level_to_group_by = 2, $parent_id_list = [], $expand_level = 1, $thisPeriodStartDate, $thisPeriodEndDate, '_during_', [], [], [], true);
$lastBalance_data = Accounts::GetPeriodicDataByType($em, $type = 'ast', $level_to_group_by = 2, $parent_id_list = [], $expand_level = 1, $lastPeriodStartDate, $lastPeriodEndDate, '_during_', [], [], [], true);
$skipHeadIds = [];
$thisBalanceDataByClientType = [];
$lastBalanceDataByClientType = [];
foreach ($clientTypeListArray as $ct) {
$thisBalanceDataByClientType[$ct['id']] = 0;
$lastBalanceDataByClientType[$ct['id']] = 0;
}
foreach ($thisBalance_data as $parentHead => $balanceData) {
foreach ($balanceData['data'] as $acHead => $headData) {
if (!(in_array($acHead, $acHeadList)))
continue;
// if ($headData['head_level'] > 4)
// continue;
$thisBalanceDataByAcHead[$acHead]['balance'] = $headData['end_balance']['balance'];
if (isset($lastBalance_data[$parentHead])) {
if (isset($lastBalance_data[$parentHead]['data'][$acHead]))
$lastBalanceDataByAcHead[$acHead]['balance'] = $lastBalance_data[$parentHead]['data'][$acHead]['end_balance']['balance'];
else
$lastBalanceDataByAcHead[$acHead]['balance'] = 0;
} else
$lastBalanceDataByAcHead[$acHead]['balance'] = 0;
if (!isset($thisBalanceDataByClientType[$clientTypesOfHeads[$acHead]]))
$thisBalanceDataByClientType[$clientTypesOfHeads[$acHead]] = $headData['end_balance']['balance'];
else
$thisBalanceDataByClientType[$clientTypesOfHeads[$acHead]] += $headData['end_balance']['balance'];
if (!isset($lastBalanceDataByClientType[$clientTypesOfHeads[$acHead]]))
$lastBalanceDataByClientType[$clientTypesOfHeads[$acHead]] = 0;
else
$lastBalanceDataByClientType[$clientTypesOfHeads[$acHead]] += $lastBalance_data[$parentHead]['data'][$acHead]['end_balance']['balance'];
$skipHeadIds[] = $acHead;
}
}
foreach ($lastBalance_data as $parentHead => $balanceData) {
foreach ($balanceData['data'] as $acHead => $headData) {
if (in_array($acHead, $skipHeadIds))
continue;
if (!in_array($acHead, $acHeadList))
continue;
// if ($headData['head_level'] > 4)
// continue;
$lastBalanceDataByAcHead[$acHead]['balance'] = $headData['end_balance']['balance'];
if (isset($thisBalance_data[$parentHead])) {
if (isset($thisBalance_data[$parentHead]['data'][$acHead]))
$thisBalanceDataByAcHead[$acHead]['balance'] = $thisBalance_data[$parentHead]['data'][$acHead]['end_balance']['balance'];
else
$thisBalanceDataByAcHead[$acHead]['balance'] = 0;
} else
$thisBalanceDataByAcHead[$acHead]['balance'] = 0;
if (!isset($lastBalanceDataByClientType[$clientTypesOfHeads[$acHead]]))
$lastBalanceDataByClientType[$clientTypesOfHeads[$acHead]] = $headData['end_balance']['balance'];
else
$lastBalanceDataByClientType[$clientTypesOfHeads[$acHead]] += $headData['end_balance']['balance'];
if (!isset($thisBalanceDataByClientType[$clientTypesOfHeads[$acHead]]))
$thisBalanceDataByClientType[$clientTypesOfHeads[$acHead]] = 0;
$skipHeadIds[] = $acHead;
}
}
$thisReportData = array(
// 'accountsHeadList' => $acHeadList,
// 'thisBalance_data' => $thisBalance_data,
// 'confirmedHeadList' => $skipHeadIds,
// 'acHeadDataById' => $acHeadDataById,
'thisBalance_data' => $thisBalance_data,
'lastBalance_data' => $lastBalance_data,
'thisBalanceDataByAcHead' => $thisBalanceDataByAcHead,
'lastBalanceDataByAcHead' => $lastBalanceDataByAcHead,
'clientTypeListArray' => $clientTypeListArray,
'thisBalanceDataByClientType' => $thisBalanceDataByClientType,
'lastBalanceDataByClientType' => $lastBalanceDataByClientType,
);
$data['receivable_position'][$app_company_index] = $thisReportData;
// $companyListData[] = Company::getCompanyListWithImage($em);
}
//Sales Position
if (in_array('sales_position', $reportsToGet)) {
$acHeadList = [];
$companyId = explode('_', $app_company_index)[1];
$acHeadDataById = [];
$thisBalanceDataByClientType = [];
$lastBalanceDataByClientType = [];
$get_sql = "SELECT sum(sales_invoice.invoice_amount) sales_amount,client_type.client_type_id, client_type.name, acc_clients.client_id, acc_clients.type
FROM sales_invoice
join acc_clients on acc_clients.client_id=sales_invoice.client_id
join client_type on acc_clients.type=client_type.client_type_id
WHERE sales_invoice.company_id=" . $companyId . " AND sales_invoice.approved=1
AND sales_invoice_date between '" . $thisPeriodStartDate . " 00:00:00' and '" . $thisPeriodEndDate . " 23:59:59.999'
GROUP BY client_type.client_type_id
";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
$clientTypes = [];
$clientTypeNames = [];
$get_sql_1 = $get_sql;
foreach ($entries as $entry) {
$has_payments = 1;
$thisBalanceDataByClientType[$entry['client_type_id']] = $entry;
$lastBalanceDataByClientType[$entry['client_type_id']]['sales_amount'] = 0; //just for the lulz
if (!in_array($entry['client_type_id'], $clientTypes)) {
$clientTypes[] = $entry['client_type_id'];
$clientTypeNames[$entry['client_type_id']] = $entry['name'];
}
}
$get_sql = "SELECT sum(sales_invoice.invoice_amount) sales_amount,client_type.client_type_id, client_type.name, acc_clients.client_id, acc_clients.type
FROM sales_invoice
join acc_clients on acc_clients.client_id=sales_invoice.client_id
join client_type on acc_clients.type=client_type.client_type_id
WHERE sales_invoice.company_id=" . $companyId . " AND sales_invoice.approved=1
AND sales_invoice_date between '" . $lastPeriodStartDate . " 00:00:00' and '" . $lastPeriodEndDate . " 23:59:59.999'
GROUP BY client_type.client_type_id
";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
foreach ($entries as $entry) {
$has_payments = 1;
$lastBalanceDataByClientType[$entry['client_type_id']] = $entry;
if (!isset($thisBalanceDataByClientType[$entry['client_type_id']]))
$thisBalanceDataByClientType[$entry['client_type_id']]['sales_amount'] = 0; //just for the lulz
if (!in_array($entry['client_type_id'], $clientTypes)) {
$clientTypes[] = $entry['client_type_id'];
$clientTypeNames[$entry['client_type_id']] = $entry['name'];
}
}
$skipHeadIds = [];
$thisReportData = array(
'clientTypes' => $clientTypes,
// 'get_sql_1' => $get_sql_1,
// 'get_sql' => $get_sql,
'clientTypeNames' => $clientTypeNames,
'thisBalanceDataByClientType' => $thisBalanceDataByClientType,
'lastBalanceDataByClientType' => $lastBalanceDataByClientType,
);
$data['sales_position'][$app_company_index] = $thisReportData;
// $companyListData[] = Company::getCompanyListWithImage($em);
}
//Collection Position
if (in_array('collection_position', $reportsToGet)) {
$acHeadList = [];
$companyId = explode('_', $app_company_index)[1];
$acHeadDataById = [];
$thisBalanceDataByClientType = [];
$lastBalanceDataByClientType = [];
$get_sql = "SELECT SUM(CASE WHEN position = 'cr' THEN amount ELSE 0 END) positive_amount,
SUM(CASE WHEN position = 'dr' THEN amount ELSE 0 END) negative_amount,client_type.client_type_id, client_type.name, acc_clients.client_id, acc_clients.type
FROM acc_transaction_details
join acc_clients on acc_clients.accounts_head_id=acc_transaction_details.accounts_head_id or acc_clients.advance_head_id=acc_transaction_details.accounts_head_id
join client_type on acc_clients.type=client_type.client_type_id
WHERE acc_transaction_details.ledger_hit=1 AND acc_transaction_details.transaction_id in (select distinct transaction_id from acc_transactions where acc_transactions.document_type=6) AND ledger_hit_date between '" . $thisPeriodStartDate . " 00:00:00' and '" . $thisPeriodEndDate . " 23:59:59.999'
GROUP BY client_type.client_type_id";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
$clientTypes = [];
$clientTypeNames = [];
foreach ($entries as $entry) {
$has_payments = 1;
$thisBalanceDataByClientType[$entry['client_type_id']] = $entry;
$lastBalanceDataByClientType[$entry['client_type_id']]['collection_amount'] = 0; //just for the lulz
$thisBalanceDataByClientType[$entry['client_type_id']]['collection_amount'] = $entry['positive_amount'] - $entry['negative_amount'];
if (!in_array($entry['client_type_id'], $clientTypes)) {
$clientTypes[] = $entry['client_type_id'];
$clientTypeNames[$entry['client_type_id']] = $entry['name'];
}
}
$get_sql = "SELECT SUM(CASE WHEN position = 'cr' THEN amount ELSE 0 END) positive_amount,
SUM(CASE WHEN position = 'dr' THEN amount ELSE 0 END) negative_amount,client_type.client_type_id, client_type.name, acc_clients.client_id, acc_clients.type
FROM acc_transaction_details
join acc_clients on acc_clients.accounts_head_id=acc_transaction_details.accounts_head_id or acc_clients.advance_head_id=acc_transaction_details.accounts_head_id
join client_type on acc_clients.type=client_type.client_type_id
WHERE acc_transaction_details.ledger_hit=1 AND acc_transaction_details.transaction_id in (select distinct transaction_id from acc_transactions where acc_transactions.document_type=6) AND ledger_hit_date between '" . $lastPeriodStartDate . " 00:00:00' and '" . $lastPeriodEndDate . " 23:59:59.999'
GROUP BY client_type.client_type_id";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
foreach ($entries as $entry) {
$has_payments = 1;
$lastBalanceDataByClientType[$entry['client_type_id']] = $entry;
$lastBalanceDataByClientType[$entry['client_type_id']]['collection_amount'] = $entry['positive_amount'] - $entry['negative_amount'];
if (!isset($thisBalanceDataByClientType[$entry['client_type_id']]))
$thisBalanceDataByClientType[$entry['client_type_id']]['collection_amount'] = 0; //just for the lulz
if (!in_array($entry['client_type_id'], $clientTypes)) {
$clientTypes[] = $entry['client_type_id'];
$clientTypeNames[$entry['client_type_id']] = $entry['name'];
}
}
$skipHeadIds = [];
$thisReportData = array(
'clientTypes' => $clientTypes,
'clientTypeNames' => $clientTypeNames,
'thisBalanceDataByClientType' => $thisBalanceDataByClientType,
'lastBalanceDataByClientType' => $lastBalanceDataByClientType,
);
$data['collection_position'][$app_company_index] = $thisReportData;
// $companyListData[] = Company::getCompanyListWithImage($em);
}
//Return Position
if (in_array('market_return_position', $reportsToGet)) {
$acHeadList = [];
$companyId = explode('_', $app_company_index)[1];
$acHeadDataById = [];
$thisBalanceDataByClientType = [];
$lastBalanceDataByClientType = [];
$get_sql = "SELECT sum(irr_item.received_total_sales_price) return_amount,client_type.client_type_id, client_type.name, acc_clients.client_id, acc_clients.type
FROM irr_item
join item_received_replacement on item_received_replacement.irr_id=irr_item.irr_id
join acc_clients on acc_clients.client_id=item_received_replacement.client_id
join client_type on acc_clients.type=client_type.client_type_id
WHERE item_received_replacement.company_id=" . $companyId . " AND item_received_replacement.approved=1
AND item_received_replacement.irr_date between '" . $thisPeriodStartDate . " 00:00:00' and '" . $thisPeriodEndDate . " 23:59:59.999'
GROUP BY client_type.client_type_id
";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
$clientTypes = [];
$clientTypeNames = [];
$get_sql_1 = $get_sql;
foreach ($entries as $entry) {
$has_payments = 1;
$thisBalanceDataByClientType[$entry['client_type_id']] = $entry;
$lastBalanceDataByClientType[$entry['client_type_id']]['return_amount'] = 0; //just for the lulz
if (!in_array($entry['client_type_id'], $clientTypes)) {
$clientTypes[] = $entry['client_type_id'];
$clientTypeNames[$entry['client_type_id']] = $entry['name'];
}
}
$get_sql = "SELECT sum(irr_item.received_total_sales_price) return_amount,client_type.client_type_id, client_type.name, acc_clients.client_id, acc_clients.type
FROM irr_item
join item_received_replacement on item_received_replacement.irr_id=irr_item.irr_id
join acc_clients on acc_clients.client_id=item_received_replacement.client_id
join client_type on acc_clients.type=client_type.client_type_id
WHERE item_received_replacement.company_id=" . $companyId . " AND item_received_replacement.approved=1
AND item_received_replacement.irr_date between '" . $lastPeriodStartDate . " 00:00:00' and '" . $lastPeriodEndDate . " 23:59:59.999'
GROUP BY client_type.client_type_id
";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
foreach ($entries as $entry) {
$has_payments = 1;
$lastBalanceDataByClientType[$entry['client_type_id']] = $entry;
if (!isset($thisBalanceDataByClientType[$entry['client_type_id']]))
$thisBalanceDataByClientType[$entry['client_type_id']]['return_amount'] = 0; //just for the lulz
if (!in_array($entry['client_type_id'], $clientTypes)) {
$clientTypes[] = $entry['client_type_id'];
$clientTypeNames[$entry['client_type_id']] = $entry['name'];
}
}
$skipHeadIds = [];
$thisReportData = array(
'clientTypes' => $clientTypes,
// 'get_sql_1' => $get_sql_1,
// 'get_sql' => $get_sql,
'clientTypeNames' => $clientTypeNames,
'thisBalanceDataByClientType' => $thisBalanceDataByClientType,
'lastBalanceDataByClientType' => $lastBalanceDataByClientType,
);
$data['market_return_position'][$app_company_index] = $thisReportData;
// $companyListData[] = Company::getCompanyListWithImage($em);
}
//order and client count
if (in_array('order_and_client_count', $reportsToGet)) {
$acHeadList = [];
$companyId = explode('_', $app_company_index)[1];
$acHeadDataById = [];
$thisBalanceDataByAcHead = [];
$lastBalanceDataByAcHead = [];
$today = new \DateTime();
$get_sql = "SELECT count(sales_order_id) total_so_count, sum(so_amount) total_so_amount, sum(invoice_amount) total_invoice_amount FROM sales_order WHERE sales_order.company_id=" . $companyId . " and sales_order.sales_order_date between '" . $thisPeriodStartDate . " 00:00:00' and '" . $thisPeriodEndDate . " 23:59:59.999' ";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries1 = $stmt->fetchAll();
$get_sql = "SELECT count(client_id) total_clients FROM acc_clients WHERE acc_clients.company_id=" . $companyId;
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries2 = $stmt->fetchAll();
$currCompanyData = Company::getCompanyData($em, $session->get(UserConstants::USER_COMPANY_ID, $companyId));
$get_sql = "SELECT SUM(CASE WHEN position = 'cr' THEN amount ELSE ((-1)*amount) END) total_collection_amount, acc_transactions.document_hash FROM acc_transaction_details
join acc_transactions on acc_transactions.transaction_id=acc_transaction_details.transaction_id
WHERE acc_transaction_details.ledger_hit=1 AND acc_transactions.document_type=6
AND (
accounts_head_id in(select distinct accounts_head_id from acc_clients WHERE acc_clients.company_id=" . $companyId . ")
or accounts_head_id in(select distinct advance_head_id from acc_clients WHERE acc_clients.company_id=" . $companyId . ") )
AND acc_transactions.company_id=" . $companyId . " AND acc_transactions.approved=1 AND acc_transaction_details.ledger_hit_date between '" . $thisPeriodStartDate . " 00:00:00' and '" . $thisPeriodEndDate . " 23:59:59.999' ";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries3 = $stmt->fetchAll();
//
// $get_sql = "SELECT (select c.balance last_balance from inv_closing_balance c
//where c.product_id=a.product_id and c.warehouse_id=a.warehouse_id and c.action_tag_id=a.action_tag_id order by date desc limit 1) stock_amount
//from inv_closing_balance a
// where a.warehouse_id in (select distinct id from warehouse
// WHERE warehouse.company_id=" . $companyId . ") and a.date between '" . $thisPeriodStartDate . " 00:00:00' and '" . $thisPeriodEndDate . " 23:59:59.999' ";
$get_sql = "SELECT a.* , (select c.balance last_balance from inv_closing_balance c
where date <='" . $thisPeriodEndDate . " 00:00:00' and c.product_id=a.product_id and c.warehouse_id=a.warehouse_id and c.action_tag_id=a.action_tag_id order by date desc limit 1) last_balance
from inv_closing_balance a
where a.warehouse_id in (select distinct id from warehouse
WHERE warehouse.company_id=" . $companyId . ") ";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries4 = $stmt->fetchAll();
$currCompanyData = Company::getCompanyData($em, $session->get(UserConstants::USER_COMPANY_ID, $companyId));
$total_stock_amount = 0;
foreach ($entries4 as $ent) {
$total_stock_amount += $ent['last_balance'];
}
$thisReportData = array(
// 'total_stock_amount' => empty($entries3) ? 0 : $entries4[0]['total_stock_amount'],
'total_stock_amount' => $total_stock_amount,
'total_collection_amount' => empty($entries3) ? 0 : $entries3[0]['total_collection_amount'],
'total_so_count' => empty($entries1) ? 0 : $entries1[0]['total_so_count'],
'total_so_amount' => empty($entries1) ? 0 : $entries1[0]['total_so_amount'],
'total_invoice_amount' => empty($entries1) ? 0 : $entries1[0]['total_invoice_amount'],
'total_receivable' => $currCompanyData->getReceivable(),
'total_payable' => $currCompanyData->getPayable(),
'total_clients' => empty($entries2) ? 0 : $entries2[0]['total_clients'],
);
$data['order_and_client_count'][$app_company_index] = $thisReportData;
// $companyListData[] = Company::getCompanyListWithImage($em);
}
//Inventory Position
if (in_array('inventory_position', $reportsToGet)) {
$acHeadList = [];
$companyId = explode('_', $app_company_index)[1];
$acHeadDataById = [];
$thisBalanceDataByActionTag = [];
$lastBalanceDataByActionTag = [];
$warehouseList = Inventory::warehouse_action_list($em, $companyId, $method = 'object');
$get_sql = "SELECT a.* , (select c.balance last_balance from inv_closing_balance c
where date <='" . $thisPeriodEndDate . " 00:00:00' and c.product_id=a.product_id and c.warehouse_id=a.warehouse_id and c.action_tag_id=a.action_tag_id order by date desc limit 1) last_balance
from inv_closing_balance a
where a.warehouse_id in (select distinct id from warehouse
WHERE warehouse.company_id=" . $companyId . ") ";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
$confirmed_action_ids = [];
$confirmed_action_names = [];
$get_sql_1 = $get_sql;
foreach ($entries as $entry) {
$has_payments = 1;
if (isset($thisBalanceDataByActionTag[$entry['action_tag_id']]))
$thisBalanceDataByActionTag[$entry['action_tag_id']]['inventory_amount'] += $entry['last_balance'];
else
$thisBalanceDataByActionTag[$entry['action_tag_id']]['inventory_amount'] = $entry['last_balance'];
if (!isset($lastBalanceDataByActionTag[$entry['action_tag_id']]))
$lastBalanceDataByActionTag[$entry['action_tag_id']]['inventory_amount'] = 0;
if (!in_array($entry['action_tag_id'], $confirmed_action_ids)) {
$confirmed_action_ids[] = $entry['action_tag_id'];
$confirmed_action_names[$entry['action_tag_id']] = $warehouseList[$entry['action_tag_id']]['name'];
}
}
$get_sql = "SELECT a.* , (select c.balance last_balance from inv_closing_balance c
where date <='" . $lastPeriodEndDate . " 00:00:00' and c.product_id=a.product_id and c.warehouse_id=a.warehouse_id and c.action_tag_id=a.action_tag_id order by date desc limit 1) last_balance
from inv_closing_balance a
where a.warehouse_id in (select distinct id from warehouse
WHERE warehouse.company_id=" . $companyId . ") ";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
foreach ($entries as $entry) {
$has_payments = 1;
if (isset($lastBalanceDataByActionTag[$entry['action_tag_id']]))
$lastBalanceDataByActionTag[$entry['action_tag_id']]['inventory_amount'] += $entry['last_balance'];
else
$lastBalanceDataByActionTag[$entry['action_tag_id']]['inventory_amount'] = $entry['last_balance'];
if (!isset($thisBalanceDataByActionTag[$entry['action_tag_id']]))
$thisBalanceDataByActionTag[$entry['action_tag_id']]['inventory_amount'] = 0;
if (!in_array($entry['action_tag_id'], $confirmed_action_ids)) {
$confirmed_action_ids[] = $entry['action_tag_id'];
$confirmed_action_names[$entry['action_tag_id']] = $warehouseList[$entry['action_tag_id']]['name'];
}
}
$skipHeadIds = [];
$thisReportData = array(
// 'clientTypes' => $clientTypes,
// 'get_sql_1' => $get_sql_1,
// 'get_sql' => $get_sql,
'confirmed_action_ids' => $confirmed_action_ids,
'confirmed_action_names' => $confirmed_action_names,
'thisBalanceDataByActionTag' => $thisBalanceDataByActionTag,
'lastBalanceDataByActionTag' => $lastBalanceDataByActionTag,
);
$data['inventory_position'][$app_company_index] = $thisReportData;
// $companyListData[] = Company::getCompanyListWithImage($em);
}
//Production Position
if (in_array('production_position', $reportsToGet)) {
$acHeadList = [];
$companyId = explode('_', $app_company_index)[1];
$acHeadDataById = [];
$thisBalanceDataByIgId = [];
$lastBalanceDataByIgId = [];
$itemGroups = [];
$itemGroupNames = [];
$get_sql = "SELECT sum((case WHEN inv_products.curr_sales_price!=0 then inv_products.curr_sales_price else inv_products.curr_purchase_price END )*production_entry_item.produced_qty) production_amount,inv_item_group.id item_group_id ,inv_item_group.name item_group_name ,inv_products.id product_id
FROM production_entry_item
join production on production_entry_item.production_id=production.production_id
join inv_products on production_entry_item.product_id=inv_products.id
join inv_item_group on inv_item_group.id=inv_products.ig_id
WHERE production.company_id=" . $companyId . " AND production.approved=1
AND production.production_date between '" . $thisPeriodStartDate . " 00:00:00' and '" . $thisPeriodEndDate . " 23:59:59.999'
GROUP BY inv_item_group.id
";
// $get_sql = "SELECT sum(product_mrp.average_price*production_entry_item.produced_qty) production_amount,inv_item_group.id item_group_id ,inv_item_group.name item_group_name ,inv_products.id product_id
// FROM production_entry_item
// join production on production_entry_item.production_id=production.production_id
// join inv_products on production_entry_item.product_id=inv_products.id
// join product_mrp on production_entry_item.product_id=product_mrp.product_id
// join inv_item_group on inv_item_group.id=inv_products.ig_id
// WHERE production.company_id=" . $companyId . " AND production.approved=1
// AND production.production_date between '" . $thisPeriodStartDate . " 00:00:00' and '" . $thisPeriodEndDate . " 23:59:59.999'
// GROUP BY inv_item_group.id
// ";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
$get_sql_1 = $get_sql;
foreach ($entries as $entry) {
$has_payments = 1;
$thisBalanceDataByIgId[$entry['item_group_id']] = $entry;
$lastBalanceDataByIgId[$entry['item_group_id']]['production_amount'] = 0; //just for the lulz
if (!in_array($entry['item_group_id'], $clientTypes)) {
$itemGroups[] = $entry['item_group_id'];
$itemGroupNames[$entry['item_group_id']] = $entry['item_group_name'];
}
}
$get_sql = "SELECT sum(production_entry_item.price*production_entry_item.produced_qty) production_amount,inv_item_group.id item_group_id ,inv_item_group.name item_group_name ,inv_products.id product_id
FROM production_entry_item
join production on production_entry_item.production_id=production.production_id
join inv_products on production_entry_item.product_id=inv_products.id
join inv_item_group on inv_item_group.id=inv_products.ig_id
WHERE production.company_id=" . $companyId . " AND production.approved=1
AND production.production_date between '" . $lastPeriodStartDate . " 00:00:00' and '" . $lastPeriodEndDate . " 23:59:59.999'
GROUP BY inv_item_group.id
";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
foreach ($entries as $entry) {
$has_payments = 1;
$lastBalanceDataByIgId[$entry['item_group_id']] = $entry;
if (!isset($thisBalanceDataByIgId[$entry['item_group_id']]))
$thisBalanceDataByIgId[$entry['item_group_id']]['production_amount'] = 0; //just for the lulz
if (!in_array($entry['item_group_id'], $clientTypes)) {
$itemGroups[] = $entry['item_group_id'];
$itemGroupNames[$entry['item_group_id']] = $entry['item_group_name'];
}
}
$skipHeadIds = [];
$thisReportData = array(
'itemGroups' => $itemGroups,
// 'get_sql_1' => $get_sql_1,
// 'get_sql' => $get_sql,
'itemGroupNames' => $itemGroupNames,
'thisBalanceDataByIgId' => $thisBalanceDataByIgId,
'lastBalanceDataByIgId' => $lastBalanceDataByIgId,
);
$data['production_position'][$app_company_index] = $thisReportData;
// $companyListData[] = Company::getCompanyListWithImage($em);
}
//Top Products
if (in_array('top_selling_item_position', $reportsToGet)) {
$acHeadList = [];
$companyId = explode('_', $app_company_index)[1];
$acHeadDataById = [];
$thisBalanceDataByRelId = [];
$lastBalanceDataByRelId = [];
$clientIds = [];
$clientNames = [];
$productIds = [];
$productNames = [];
$get_sql = "SELECT sum(sales_invoice_item.qty*sales_invoice_item.current_purchase_price) sales_amount, inv_products.id product_id, inv_products.name product_name, acc_clients.client_id, acc_clients.type
FROM sales_invoice_item
join sales_invoice on sales_invoice_item.sales_invoice_id=sales_invoice.sales_invoice_id
join inv_products on sales_invoice_item.product_id=inv_products.id
join acc_clients on acc_clients.client_id=sales_invoice.client_id
WHERE sales_invoice.company_id=" . $companyId . " AND sales_invoice.approved=1
AND sales_invoice_date between '" . $thisPeriodStartDate . " 00:00:00' and '" . $thisPeriodEndDate . " 23:59:59.999'
GROUP BY sales_invoice_item.product_id
ORDER BY sales_amount DESC
LIMIT 10
";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
$get_sql_1 = $get_sql;
for ($k = 0; $k < 10; $k++) {
$has_payments = 1;
if (!isset($entries[$k]))
$entries[$k] = array(
'sales_amount' => '',
'product_name' => '',
'client_name' => '',
);
$has_payments = 1;
$thisBalanceDataByRelId[$k] = $entries[$k];
}
$get_sql = "SELECT sum(sales_invoice_item.qty*sales_invoice_item.current_purchase_price) sales_amount, inv_products.id product_id, inv_products.name product_name, acc_clients.client_id, acc_clients.type
FROM sales_invoice_item
join sales_invoice on sales_invoice_item.sales_invoice_id=sales_invoice.sales_invoice_id
join inv_products on sales_invoice_item.product_id=inv_products.id
join acc_clients on acc_clients.client_id=sales_invoice.client_id
WHERE sales_invoice.company_id=" . $companyId . " AND sales_invoice.approved=1
AND sales_invoice_date between '" . $lastPeriodStartDate . " 00:00:00' and '" . $lastPeriodEndDate . " 23:59:59.999'
GROUP BY sales_invoice_item.product_id
ORDER BY sales_amount DESC
LIMIT 10
";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
for ($k = 0; $k < 10; $k++) {
$has_payments = 1;
if (!isset($entries[$k]))
$entries[$k] = array(
'sales_amount' => '',
'product_name' => '',
'client_name' => '',
);
$lastBalanceDataByRelId[$k] = $entries[$k];
}
$skipHeadIds = [];
$thisReportData = array(
// 'clientTypes' => $clientTypes,
//// 'get_sql_1' => $get_sql_1,
//// 'get_sql' => $get_sql,
// 'clientTypeNames' => $clientTypeNames,
'thisBalanceDataByRelId' => $thisBalanceDataByRelId,
'lastBalanceDataByRelId' => $lastBalanceDataByRelId,
);
$data['top_selling_item_position'][$app_company_index] = $thisReportData;
// $companyListData[] = Company::getCompanyListWithImage($em);
}
//Top Products
if (in_array('top_selling_client_position', $reportsToGet)) {
$acHeadList = [];
$companyId = explode('_', $app_company_index)[1];
$acHeadDataById = [];
$thisBalanceDataByRelId = [];
$lastBalanceDataByRelId = [];
$clientIds = [];
$clientNames = [];
$productIds = [];
$productNames = [];
$get_sql = "SELECT sum(sales_invoice.invoice_amount) sales_amount, acc_clients.client_id, acc_clients.client_name client_name
FROM sales_invoice
join acc_clients on acc_clients.client_id=sales_invoice.client_id
WHERE sales_invoice.company_id=" . $companyId . " AND sales_invoice.approved=1
AND sales_invoice_date between '" . $thisPeriodStartDate . " 00:00:00' and '" . $thisPeriodEndDate . " 23:59:59.999'
GROUP BY sales_invoice.client_id
ORDER BY sales_amount DESC
LIMIT 10
";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
$get_sql_1 = $get_sql;
for ($k = 0; $k < 10; $k++) {
$has_payments = 1;
if (!isset($entries[$k]))
$entries[$k] = array(
'sales_amount' => '',
'product_name' => '',
'client_name' => '',
);
$has_payments = 1;
$thisBalanceDataByRelId[$k] = $entries[$k];
}
$get_sql = "SELECT sum(sales_invoice.invoice_amount) sales_amount, acc_clients.client_id, acc_clients.client_name client_name
FROM sales_invoice
join acc_clients on acc_clients.client_id=sales_invoice.client_id
WHERE sales_invoice.company_id=" . $companyId . " AND sales_invoice.approved=1
AND sales_invoice_date between '" . $lastPeriodStartDate . " 00:00:00' and '" . $lastPeriodEndDate . " 23:59:59.999'
GROUP BY sales_invoice.client_id
ORDER BY sales_amount DESC
LIMIT 10
";
$stmt = $em->getConnection()->prepare($get_sql);
$stmt->execute();
$entries = $stmt->fetchAll();
for ($k = 0; $k < 10; $k++) {
$has_payments = 1;
if (!isset($entries[$k]))
$entries[$k] = array(
'sales_amount' => '',
'product_name' => '',
'client_name' => '',
);
$lastBalanceDataByRelId[$k] = $entries[$k];
}
$skipHeadIds = [];
$thisReportData = array(
// 'clientTypes' => $clientTypes,
//// 'get_sql_1' => $get_sql_1,
//// 'get_sql' => $get_sql,
// 'clientTypeNames' => $clientTypeNames,
'thisBalanceDataByRelId' => $thisBalanceDataByRelId,
'lastBalanceDataByRelId' => $lastBalanceDataByRelId,
);
$data['top_selling_client_position'][$app_company_index] = $thisReportData;
// $companyListData[] = Company::getCompanyListWithImage($em);
}
}
}
}
return new JsonResponse(
array(
'success' => true,
'data' => $data,
'companyListData' => $companyListData,
'dataToConnectList' => $dataToConnectList,
'periodType' => $periodType,
'queriedReportsToGet' => $request->request->get('reportsToGet'),
'reportsToGet' => $reportsToGet,
'thisPeriodStartDate' => $thisPeriodStartDate,
'thisPeriodEndDate' => $thisPeriodEndDate,
'lastPeriodStartDate' => $lastPeriodStartDate,
'lastPeriodEndDate' => $lastPeriodEndDate,
'companyIdListByAppId' => $companyIdListByAppId,
'companyNameListByAppId' => $companyNameListByAppId,
'companyImageListByAppId' => $companyImageListByAppId,
'appIdList' => $appIdList,
)
);
}
public function indexAction(Request $request, $cgHash = '')
{
$session = $request->getSession();
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
if ($systemType == '_ERP_') {
//do nothing its default to dashboard index
} else if ($systemType == '_BUDDYBEE_') {
if ($cgHash != '')
$session->set('codeHash', $cgHash);
}
// Generic::debugMessage($session);
$ROUTE_LIST = json_decode($session->get(UserConstants::USER_ROUTE_LIST), true);
if ($ROUTE_LIST == null)
$ROUTE_LIST = [];
$CurrentRoute = $request->attributes->get('_route');
if ($session->get(UserConstants::USER_ROUTE_LIST) == 1 || in_array('management_dashboard', $ROUTE_LIST)) {
// User is not authorized. send him to dashboard
// $controller->addFlash(
// 'error',
// 'Sorry Couldnot insert Data.'
// );
// return $this->render('ApplicationBundle:pages/dashboard:advanced_management_dashboard.html.twig',
if ($session->has('isMobile'))
if ($session->get('isMobile') == true) {
return $this->render(
'ApplicationBundle:pages/dashboard:index_finance_mobile.html.twig',
array(
'page_title' => 'Finance Dashboard',
'dashboardDataForUser' => []
)
);
}
return $this->render(
'ApplicationBundle:pages/dashboard:advanced_management_dashboard.html.twig',
array(
'page_title' => 'Dashboard'
)
);
}
if ($session->has('isMobile'))
if ($session->get('isMobile') == true) {
if ($systemType == '_CENTRAL_') {
$defaultRoute = 'central_landing';
return $this->redirectToRoute($defaultRoute);
} else
return $this->render(
'ApplicationBundle:pages/dashboard:index_finance_mobile.html.twig',
array(
'page_title' => 'Finance Dashboard',
'dashboardDataForUser' => []
)
);
} else {
//check if user has a default route if yes redirect to it
if ($session->get(UserConstants::USER_TYPE) == UserConstants::USER_TYPE_SUPPLIER)
$defaultRoute = 'supplier_dashboard';
else if ($session->get(UserConstants::USER_TYPE) == UserConstants::USER_TYPE_CLIENT)
$defaultRoute = 'client_dashboard';
else if ($session->get(UserConstants::USER_TYPE) == UserConstants::USER_TYPE_APPLICANT) {
if ($systemType == '_CENTRAL_') {
$defaultRoute = 'central_landing';
} else
$defaultRoute = 'applicant_dashboard';
} else
$defaultRoute = $session->get(UserConstants::USER_DEFAULT_ROUTE);
// if(in_array($defaultRoute, $ROUTE_LIST))
if ($defaultRoute != '' && $defaultRoute != null)
return $this->redirectToRoute($defaultRoute);
else
return $this->render(
'ApplicationBundle:pages/dashboard:index.html.twig',
array(
'page_title' => 'Dashboard'
)
);
}
}
public function indexSupplierAction(Request $request)
{
$session = $request->getSession();
$supplierId = 3;
if ($request->query->has('supplierId')) //for debug now
{
$session->set('supplierId', $request->query->get('supplierId'));
}
$supplierId = $session->get('supplierId'); //////////////////////LATER
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$userId = $request->getSession()->get(UserConstants::USER_ID);
$SD = Supplier::GetSupplierProfileDetails($em, $supplierId, 'SI');
$dashboardDataForUser = [];
return $this->render(
'ApplicationBundle:pages/dashboard:index_supplier.html.twig',
array(
'page_title' => 'Supplier Dashboard',
'dashboardDataForUser' => $dashboardDataForUser,
'data' => $SD,
'igList' => Inventory::ItemGroupList($em, $companyId)
)
);
}
public function indexClientAction(Request $request)
{
$session = $request->getSession();
$clientId = 3;
if ($request->query->has('clientId')) //for debug now
{
$session->set('clientId', $request->query->get('clientId'));
}
$clientId = $session->get('clientId'); //////////////////////LATER
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$userId = $request->getSession()->get(UserConstants::USER_ID);
$SD = Client::GetClientProfileDetails($em, $clientId, 'CI');
$dashboardDataForUser = [];
return $this->render(
'ApplicationBundle:pages/dashboard:index_client.html.twig',
array(
'page_title' => 'Client Dashboard',
'dashboardDataForUser' => $dashboardDataForUser,
'data' => $SD,
'igList' => Inventory::ItemGroupList($em, $companyId)
)
);
}
public function indexFinanceAction(Request $request)
{
$session = $request->getSession();
$dashboardDataForUser = [];
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$userId = $request->getSession()->get(UserConstants::USER_ID);
$dbQuery = $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
array(
'CompanyId' => $companyId,
'userId' => $userId,
'status' => GeneralConstant::ACTIVE
),
array(
'sequence' => 'ASC'
)
);
if (empty($dbQuery)) ///now get the defaults
$dbQuery = $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
array(
'CompanyId' => $companyId,
// 'userId'=>$userId,
'defaultBoxFlag' => 1,
'status' => GeneralConstant::ACTIVE
),
array(
'sequence' => 'ASC'
)
);
foreach ($dbQuery as $entry) {
$dashboardDataForUser[] = array(
'id' => $entry->getId(),
'widgetId' => $entry->getId(),
'widgetSequence' => $entry->getSequence(),
'widgetStatus' => $entry->getStatus(),
'widgetData' => json_decode($entry->getData(), true),
'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
'widgetSizeTiny' => $entry->getSizeTiny(),
'widgetSizeSmall' => $entry->getSizeSmall(),
'widgetSizeMedium' => $entry->getSizeMedium(),
'widgetSizeLarge' => $entry->getSizeLarge(),
'refreshInterval' => $entry->getRefreshInterval(),
);
}
if ($session->has('isMobile')) {
if ($session->get('isMobile') == true) {
return $this->render(
'ApplicationBundle:pages/dashboard:index_finance_mobile.html.twig',
array(
'page_title' => 'Finance Dashboard',
'dashboardDataForUser' => $dashboardDataForUser
)
);
} else {
}
}
return $this->render(
'ApplicationBundle:pages/dashboard:index_finance.html.twig',
array(
'page_title' => 'Finance Dashboard',
'dashboardDataForUser' => $dashboardDataForUser
)
);
}
public function indexSalesAction(Request $request)
{
$session = $request->getSession();
$dashboardDataForUser = [];
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$userId = $request->getSession()->get(UserConstants::USER_ID);
$dbQuery = $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
array(
'CompanyId' => $companyId,
'userId' => $userId,
'status' => GeneralConstant::ACTIVE
),
array(
'sequence' => 'ASC'
)
);
if (empty($dbQuery)) ///now get the defaults
$dbQuery = $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
array(
'CompanyId' => $companyId,
// 'userId'=>$userId,
'defaultBoxFlag' => 1,
'status' => GeneralConstant::ACTIVE
),
array(
'sequence' => 'ASC'
)
);
foreach ($dbQuery as $entry) {
$dashboardDataForUser[] = array(
'id' => $entry->getId(),
'widgetId' => $entry->getId(),
'widgetSequence' => $entry->getSequence(),
'widgetStatus' => $entry->getStatus(),
'widgetData' => json_decode($entry->getData(), true),
'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
'widgetSizeTiny' => $entry->getSizeTiny(),
'widgetSizeSmall' => $entry->getSizeSmall(),
'widgetSizeMedium' => $entry->getSizeMedium(),
'widgetSizeLarge' => $entry->getSizeLarge(),
'refreshInterval' => $entry->getRefreshInterval(),
);
}
if ($session->has('isMobile')) {
if ($session->get('isMobile') == true) {
return $this->render(
'ApplicationBundle:pages/dashboard:index_finance_mobile.html.twig',
array(
'page_title' => 'Finance Dashboard',
'dashboardDataForUser' => $dashboardDataForUser
)
);
} else {
}
}
return $this->render(
'ApplicationBundle:pages/dashboard:index_sales.html.twig',
array(
'page_title' => 'Sales Dashboard',
'dashboardDataForUser' => $dashboardDataForUser
)
);
}
public function indexPurchaseAction(Request $request)
{
$session = $request->getSession();
$dashboardDataForUser = [];
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$userId = $request->getSession()->get(UserConstants::USER_ID);
$dbQuery = $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
array(
'CompanyId' => $companyId,
'userId' => $userId,
'status' => GeneralConstant::ACTIVE
),
array(
'sequence' => 'ASC'
)
);
if (empty($dbQuery)) ///now get the defaults
$dbQuery = $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
array(
'CompanyId' => $companyId,
// 'userId'=>$userId,
'defaultBoxFlag' => 1,
'status' => GeneralConstant::ACTIVE
),
array(
'sequence' => 'ASC'
)
);
foreach ($dbQuery as $entry) {
$dashboardDataForUser[] = array(
'id' => $entry->getId(),
'widgetId' => $entry->getId(),
'widgetSequence' => $entry->getSequence(),
'widgetStatus' => $entry->getStatus(),
'widgetData' => json_decode($entry->getData(), true),
'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
'widgetSizeTiny' => $entry->getSizeTiny(),
'widgetSizeSmall' => $entry->getSizeSmall(),
'widgetSizeMedium' => $entry->getSizeMedium(),
'widgetSizeLarge' => $entry->getSizeLarge(),
'refreshInterval' => $entry->getRefreshInterval(),
);
}
return $this->render(
'ApplicationBundle:pages/dashboard:index_sales.html.twig',
array(
'page_title' => 'Sales Dashboard',
'dashboardDataForUser' => $dashboardDataForUser
)
);
}
public function indexDistributionAction(Request $request)
{
$session = $request->getSession();
$dashboardDataForUser = [];
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$userId = $request->getSession()->get(UserConstants::USER_ID);
$dbQuery = $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
array(
'CompanyId' => $companyId,
'userId' => $userId,
'status' => GeneralConstant::ACTIVE
),
array(
'sequence' => 'ASC'
)
);
if (empty($dbQuery)) ///now get the defaults
$dbQuery = $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
array(
'CompanyId' => $companyId,
// 'userId'=>$userId,
'defaultBoxFlag' => 1,
'status' => GeneralConstant::ACTIVE
),
array(
'sequence' => 'ASC'
)
);
foreach ($dbQuery as $entry) {
$dashboardDataForUser[] = array(
'id' => $entry->getId(),
'widgetId' => $entry->getId(),
'widgetSequence' => $entry->getSequence(),
'widgetStatus' => $entry->getStatus(),
'widgetData' => json_decode($entry->getData(), true),
'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
'widgetSizeTiny' => $entry->getSizeTiny(),
'widgetSizeSmall' => $entry->getSizeSmall(),
'widgetSizeMedium' => $entry->getSizeMedium(),
'widgetSizeLarge' => $entry->getSizeLarge(),
'refreshInterval' => $entry->getRefreshInterval(),
);
}
return $this->render(
'ApplicationBundle:pages/dashboard:index_sales.html.twig',
array(
'page_title' => 'Sales Dashboard',
'dashboardDataForUser' => $dashboardDataForUser
)
);
}
public function indexProductionAction(Request $request)
{
$session = $request->getSession();
$dashboardDataForUser = [];
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$userId = $request->getSession()->get(UserConstants::USER_ID);
$dbQuery = $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
array(
'CompanyId' => $companyId,
'userId' => $userId,
'status' => GeneralConstant::ACTIVE
),
array(
'sequence' => 'ASC'
)
);
if (empty($dbQuery)) ///now get the defaults
$dbQuery = $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
array(
'CompanyId' => $companyId,
// 'userId'=>$userId,
'defaultBoxFlag' => 1,
'status' => GeneralConstant::ACTIVE
),
array(
'sequence' => 'ASC'
)
);
foreach ($dbQuery as $entry) {
$dashboardDataForUser[] = array(
'id' => $entry->getId(),
'widgetId' => $entry->getId(),
'widgetSequence' => $entry->getSequence(),
'widgetStatus' => $entry->getStatus(),
'widgetData' => json_decode($entry->getData(), true),
'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
'widgetSizeTiny' => $entry->getSizeTiny(),
'widgetSizeSmall' => $entry->getSizeSmall(),
'widgetSizeMedium' => $entry->getSizeMedium(),
'widgetSizeLarge' => $entry->getSizeLarge(),
'refreshInterval' => $entry->getRefreshInterval(),
);
}
return $this->render(
'ApplicationBundle:pages/dashboard:index_sales.html.twig',
array(
'page_title' => 'Sales Dashboard',
'dashboardDataForUser' => $dashboardDataForUser
)
);
}
public function indexInventoryAction(Request $request)
{
$session = $request->getSession();
$dashboardDataForUser = [];
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$userId = $request->getSession()->get(UserConstants::USER_ID);
$dbQuery = $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
array(
'CompanyId' => $companyId,
'userId' => $userId,
'status' => GeneralConstant::ACTIVE
),
array(
'sequence' => 'ASC'
)
);
if (empty($dbQuery)) ///now get the defaults
$dbQuery = $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
array(
'CompanyId' => $companyId,
// 'userId'=>$userId,
'defaultBoxFlag' => 1,
'status' => GeneralConstant::ACTIVE
),
array(
'sequence' => 'ASC'
)
);
foreach ($dbQuery as $entry) {
$dashboardDataForUser[] = array(
'id' => $entry->getId(),
'widgetId' => $entry->getId(),
'widgetSequence' => $entry->getSequence(),
'widgetStatus' => $entry->getStatus(),
'widgetData' => json_decode($entry->getData(), true),
'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
'widgetSizeTiny' => $entry->getSizeTiny(),
'widgetSizeSmall' => $entry->getSizeSmall(),
'widgetSizeMedium' => $entry->getSizeMedium(),
'widgetSizeLarge' => $entry->getSizeLarge(),
'refreshInterval' => $entry->getRefreshInterval(),
);
}
return $this->render(
'ApplicationBundle:pages/dashboard:index_sales.html.twig',
array(
'page_title' => 'Sales Dashboard',
'dashboardDataForUser' => $dashboardDataForUser
)
);
}
public function indexServiceAction(Request $request)
{
$session = $request->getSession();
$dashboardDataForUser = [];
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$userId = $request->getSession()->get(UserConstants::USER_ID);
$dbQuery = $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
array(
'CompanyId' => $companyId,
'userId' => $userId,
'status' => GeneralConstant::ACTIVE
),
array(
'sequence' => 'ASC'
)
);
if (empty($dbQuery)) ///now get the defaults
$dbQuery = $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
array(
'CompanyId' => $companyId,
// 'userId'=>$userId,
'defaultBoxFlag' => 1,
'status' => GeneralConstant::ACTIVE
),
array(
'sequence' => 'ASC'
)
);
foreach ($dbQuery as $entry) {
$dashboardDataForUser[] = array(
'id' => $entry->getId(),
'widgetId' => $entry->getId(),
'widgetSequence' => $entry->getSequence(),
'widgetStatus' => $entry->getStatus(),
'widgetData' => json_decode($entry->getData(), true),
'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
'widgetSizeTiny' => $entry->getSizeTiny(),
'widgetSizeSmall' => $entry->getSizeSmall(),
'widgetSizeMedium' => $entry->getSizeMedium(),
'widgetSizeLarge' => $entry->getSizeLarge(),
'refreshInterval' => $entry->getRefreshInterval(),
);
}
return $this->render(
'ApplicationBundle:pages/dashboard:index_sales.html.twig',
array(
'page_title' => 'Sales Dashboard',
'dashboardDataForUser' => $dashboardDataForUser
)
);
}
public function modifyDashboardAction(Request $request)
{
$session = $request->getSession();
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$userId = $request->getSession()->get(UserConstants::USER_ID);
if ($request->isMethod('post')) {
//update dashboard data
if ($request->request->has('widgetId')) {
foreach ($request->request->get('widgetId') as $k => $v) {
if ($v != 0) {
//exists sso edit
$widget = $em->getRepository("ApplicationBundle:DashboardWidget")->findOneBy(
array(
'id' => $v,
)
);
} else
$widget = new DashboardWidget();
$widget->setData($request->request->get('widgetData')[$k]);
$widget->setSequence($request->request->get('widgetSequence')[$k]);
$widget->setStatus($request->request->has('widgetStatus') ? $request->request->get('widgetStatus')[$k] : GeneralConstant::ACTIVE);
$widget->setUserId($userId);
$widget->setCompanyId($companyId);
$widget->setDefaultBoxFlag($request->request->has('defaultBoxFlag') ? $request->request->get('defaultBoxFlag')[$k] : 0);
if ($v == 0)
$em->persist($widget);
$em->flush();
}
}
}
$dashboardDataForUser = [];
$dbQuery = $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
array(
'CompanyId' => $companyId,
'userId' => $userId,
'status' => GeneralConstant::ACTIVE
)
);
if (empty($dbQuery)) ///now get the defaults
$dbQuery = $em->getRepository("ApplicationBundle:DashboardWidget")->findBy(
array(
'CompanyId' => $companyId,
// 'userId'=>$userId,
'defaultBoxFlag' => 1,
'status' => GeneralConstant::ACTIVE
)
);
foreach ($dbQuery as $entry) {
$dashboardDataForUser[] = array(
'id' => $entry->getId(),
'widgetId' => $entry->getId(),
'widgetSequence' => $entry->getSequence(),
'widgetStatus' => $entry->getStatus(),
'widgetData' => $entry->getData(),
'defaultBoxFlag' => $entry->getDefaultBoxFlag(),
'widgetSizeTiny' => $entry->getSizeTiny(),
'widgetSizeSmall' => $entry->getSizeSmall(),
'widgetSizeMedium' => $entry->getSizeMedium(),
'widgetSizeLarge' => $entry->getSizeLarge(),
'refreshInterval' => $entry->getRefreshInterval(),
);
}
//1st try to see if any exists
return $this->render(
'ApplicationBundle:pages/dashboard:index_sales.html.twig',
array(
'page_title' => 'Modify Dashboard'
)
);
}
public function ChangeCompanyDashboardAction(Request $request, $id = 1)
{
$session = $request->getSession();
if ($request->query->has('sys_admin_panel'))
return $this->redirectToRoute('system_admin_dashboard');
else {
$session->set(UserConstants::USER_COMPANY_ID, $id);
return $this->redirectToRoute('dashboard');
}
}
public function ChangeLeftPanelDisplayStatusAction(Request $request)
{
$session = $request->getSession();
$curr_status = 1;
if ($session->has('HIDE_LEFT_PANEL'))
$curr_status = $session->get('HIDE_LEFT_PANEL');
if ($curr_status == 1)
$curr_status = 0;
else
$curr_status = 1;
$session->set('HIDE_LEFT_PANEL', $curr_status);
// return $this->redirectToRoute('dashboard');
return new Response($curr_status);
}
public function PermissionDeniedAction(Request $request)
{
$session = $request->getSession();
// Generic::debugMessage($session);
return $this->render(
'@System/pages/permission_denied.html.twig',
array(
'page_title' => 'Permission Denied'
)
);
}
public function MyDocumentsAction(Request $request)
{
$session = $request->getSession();
$em = $this->getDoctrine()->getManager();
$data = MiscActions::getDocumentsByUserId($em, $session->get(UserConstants::USER_ID));
// Generic::debugMessage($session);
return $this->render(
'ApplicationBundle:pages/dashboard:my_documents.html.twig',
array(
'page_title' => 'My Documents',
'data' => $data
)
);
}
// public function MyDocumentsListForAppAction(Request $request)
// {
// $session = $request->getSession();
// $em = $this->getDoctrine()->getManager();
// $absoluteUrlList = [];
// foreach (GeneralConstant::$Entity_list_details as $e => $d) {
// if (isset($d['entity_print_route_path_name']))
// $absoluteUrlList[$e] = $this->generateUrl($d['entity_print_route_path_name'], [], UrlGenerator::ABSOLUTE_URL);
// }
// $data = MiscActions::getDocumentsByUserIdForApp($em, $session->get(UserConstants::USER_ID), 1, $absoluteUrlList);
// // Generic::debugMessage($session);
// return new JsonResponse(array(
// 'data' => $data
// ));
// // return $this->render('ApplicationBundle:pages/dashboard:my_documents.html.twig',
// // array(
// // 'page_title' => 'My Documents',
// // 'data' => $data
// // )
// // );
// }
public function MyDocumentsListForAppAction(Request $request)
{
$session = $request->getSession();
$em = $this->getDoctrine()->getManager();
// Build absolute URL list
$absoluteUrlList = [];
foreach (GeneralConstant::$Entity_list_details as $e => $d) {
if (isset($d['entity_print_route_path_name'])) {
$absoluteUrlList[$e] = $this->generateUrl($d['entity_print_route_path_name'], [], UrlGenerator::ABSOLUTE_URL);
}
}
// Extract pagination parameters from the request
$page = $request->query->get('page', '_UNSET_');
$offset = $request->query->get('offset', 0);
$limit = $request->query->get('limit', 10); // default limit is 10
// Call the document list method with pagination
return new JsonResponse(
MiscActions::getDocumentsByUserIdForApp(
$em,
$session->get(UserConstants::USER_ID),
1,
$absoluteUrlList,
$page,
$offset,
$limit
)
);
}
public function ShowExceptionAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null)
{
$session = $request->getSession();
$em = $this->getDoctrine()->getManager();
// Generic::debugMessage($session);
// $currentContent = $this->getAndCleanOutputBuffering($request->headers->get('X-Php-Ob-Level', -1));
// $showException = $request->attributes->get('showException', $this->debug); // As opposed to an additional parameter, this maintains BC
$code = $exception->getStatusCode();
// $data = MiscActions::getDocumentsByUserId($em, $session->get(UserConstants::USER_ID));
return $this->render(
'ApplicationBundle:pages/error:error_' . $code . '.html.twig',
array(
'page_title' => 'Sorry',
// 'data' => $data
)
);
}
public function NotificationAction(Request $request)
{
$session = $request->getSession();
//'error', 'success', 'alert', 'information', 'warning', 'confirm'
$themes = array(
'error' => 'bg-red',
'success' => 'bg-green',
'alert' => 'bg-purple',
'information' => 'bg-grey',
'warning' => 'bg-orange',
'confirm' => 'bg-blue',
);
$fa = array(
'error' => 'fa fa-ban',
'success' => 'fa fa-check',
'alert' => 'fa fa-envelope',
'information' => 'fa fa-comments',
'warning' => 'fa fa-warning',
'confirm' => 'fa fa-crosshairs',
);
// Generic::debugMessage($session);
return $this->render(
'ApplicationBundle:pages/dashboard:notification.html.twig',
array(
'page_title' => 'Notifications',
'dt' => json_decode(System::GetAllNotification(
$this->container->getParameter('notification_enabled'),
$this->container->getParameter('notification_server'),
$request->getSession()->get(UserConstants::USER_ID),
$request->getSession()->get(UserConstants::USER_APP_ID),
$request->getSession()->get(UserConstants::USER_COMPANY_ID)
), true),
// 'dt'=>System::GetAllNotification(
// $this->container->getParameter('notification_enabled'),
// $request->getSession()->get(UserConstants::USER_ID),
// $request->getSession()->get(UserConstants::USER_APP_ID),
// $request->getSession()->get(UserConstants::USER_COMPANY_ID)
// ),
'themes' => $themes,
'fa' => $fa,
't' => curl_init()
)
);
}
public function EditAccountAction(Request $request)
{
$session = $request->getSession();
//'error', 'success', 'alert', 'information', 'warning', 'confirm'
$themes = array(
'error' => 'bg-red',
'success' => 'bg-green',
'alert' => 'bg-purple',
'information' => 'bg-aqua',
'warning' => 'bg-orange',
'confirm' => 'bg-blue',
);
$fa = array(
'error' => 'fa fa-ban',
'success' => 'fa fa-check',
'alert' => 'fa fa-envelope',
'information' => 'fa fa-comments',
'warning' => 'fa fa-warning',
'confirm' => 'fa fa-crosshairs',
);
$em = $this->getDoctrine()->getManager();
$g_path = '';
if ($request->isMethod('POST')) {
$post = $request->request;
$path = "";
foreach ($request->files as $uploadedFile) {
if ($uploadedFile != null) {
$fileName = md5(uniqid()) . '.' . $uploadedFile->guessExtension();
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' . $request->request->get('userId') . '/';
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
$file = $uploadedFile->move($upl_dir, $path);
}
}
if ($path != "")
$file_path = 'uploads/FileUploads/' . $request->request->get('userId') . '/' . $path;
$g_path = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' . $request->request->get('userId') . '/' . $path;
// $img_file = file_get_contents($g_path);
// $image_data=base64_encode($img_file);
// $encoded_data=System::encryptSignature($image_data,$request->request->get('approvalHash'));
$query_here = $this->getDoctrine()
->getRepository('ApplicationBundle:SysUser')
->findOneBy(
array('userId' => $request->request->get('userId'))
);
if ($query_here) {
$new = $query_here;
if ($path != "") {
if ($request->request->has('check_pp')) {
$new->setImage($file_path);
$session->set(UserConstants::USER_IMAGE, $new->getImage());
} else
$new->setImage('');
}
$new->setName($request->request->get('name'));
$session->set(UserConstants::USER_NAME, $request->request->get('name'));
//now password
if ($request->request->get('oldPass') != '') {
//1st check if old pass valid
if (!$this->container->get('sha256salted_encoder')->isPasswordValid($new->getPassword(), $request->request->get('oldPass'), $new->getSalt())) {
$this->addFlash(
'error',
'Your Old Password Was Wrong'
);
} else {
//old pass valid so now check if neww passes matches
if ($request->request->get('newPass') == $request->request->get('newPassAgain')) {
$new->setSalt(uniqid(mt_rand()));
$password = $this->container->get('sha256salted_encoder')->encodePassword($request->request->get('newPass'), $new->getSalt());
$new->setPassword($password);
$em->flush();
} else {
$this->addFlash(
'error',
'Passwords Did not Match'
);
}
}
}
} else {
// $new=new EncryptedSignature();
// $new->setData($encoded_data);
// $new->setUserId($request->request->get('userId'));
// $em->persist($new);
}
$em->flush();
// now deleting the file
}
$user_data = Users::getUserInfoByLoginId($em, $this->getLoggedUserLoginId($request));
// Generic::debugMessage($session);
return $this->render(
'@System/pages/settings/edit_account.html.twig',
array(
'page_title' => 'Edit Account',
'user_data' => $user_data,
// 'dt'=>json_decode(System::GetAllNotification($request->getSession()->get(UserConstants::USER_ID)),true),
'themes' => $themes,
'fa' => $fa,
)
);
}
public function indexApplicantAction(Request $request)
{
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$twig_file = 'ApplicationBundle:pages/login:applicant_login.html.twig';
$session = $request->getSession();
if ($systemType == '_BUDDYBEE_') {
if ($session->get('buddybeeAdminLevel', 0) > 1)
return $this->redirectToRoute("buddybee_admin_dashboard", []);
elseif ($session->get('isConsultant') == 1)
return $this->redirectToRoute("consultant_dashboard", []);
else
return $this->redirectToRoute("student_dashboard", []);
} elseif ($systemType == '_CENTRAL_') {
return $this->render(
'ApplicationBundle:pages/dashboard:index_applicant.html.twig',
array(
'page_title' => 'Applicant Dashboard'
)
);
} else
return $this->render(
'ApplicationBundle:pages/dashboard:consultant_dashboard.html.twig',
array(
'page_title' => 'Applicant Dashboard'
)
);
}
public function indexCentralLandingAction(Request $request)
{
$session = $request->getSession();
$userAccessList = $session->get('userAccessList', []);
$companyNames = array_map(function ($company) {
return $company['companyName'];
}, $userAccessList);
if ($request->isMethod('POST')) {
$employeeId = $request->request->get('employee_id');
$companyName = $request->request->get('company_name');
if ($employeeId && $companyName) {
return new JsonResponse([
'status' => 'success',
'message' => 'Data received successfully',
'employee_id' => $employeeId,
'company_name' => $companyName,
]);
} else {
return new JsonResponse([
'status' => 'error',
'message' => 'Employee ID or Company Name is missing',
]);
}
}
// If the request is not a POST request, render the normal page
return $this->render(
'ApplicationBundle:pages/dashboard:index_central_landing.html.twig',
[
'page_title' => 'Central Landing',
'companyNames' => $companyNames
]
);
}
public function HummanResourceAction()
{
return $this->render(
'ApplicationBundle:pages/dashboard:humanResource.html.twig',
array(
'page_title' => 'Human Resource Dashboard'
)
);
}
public function projectCashFlowReportAction()
{
return $this->render(
'ApplicationBundle:pages/dashboard:cash_flow_report.html.twig',
array(
'page_title' => 'Cash Flow Report'
)
);
}
public function PerformanceReviewDashboardAction()
{
return $this->render(
'ApplicationBundle:pages/dashboard:performance_review_dashboard.html.twig',
array(
'page_title' => 'Performance Review Dashboard'
)
);
}
public function RecruitmentDashboardAction()
{
return $this->render(
'ApplicationBundle:pages/dashboard:recruitment_dashboard.html.twig',
array(
'page_title' => 'Recruitment Dashboard'
)
);
}
public function TalentManagementDashboardAction()
{
return $this->render(
'ApplicationBundle:pages/dashboard:talent_management_dashboard.html.twig',
array(
'page_title' => 'Talent Management Dashboard'
)
);
}
public function CreateCompanyAction(Request $request)
{
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$appId = $request->get('app_id', 0);
$post = $request;
$session = $request->getSession();
if ($request->isMethod('POST')) {
if ($systemType == '_CENTRAL_') {
$em_goc = $this->getDoctrine()->getManager('company_group');
$em_goc->getConnection()->connect();
$connected = $em_goc->getConnection()->isConnected();
$gocDataList = [];
if ($connected) {
$goc = null;
$serverList = GeneralConstant::$serverListById;
$companyGroupHash = $post->get('company_short_code', '');
$defaultUsageDate = new \DateTime();
$defaultUsageDate->modify('+1 year');
$usageValidUpto = new \DateTime($post->get('usage_valid_upto_dt_str', $defaultUsageDate->format('Y-m-d')));
$companyGroupServerId = $post->get('server_id', 1);
$companyGroupServerAddress = $serverList[$companyGroupServerId]['absoluteUrl'];
$companyGroupServerPort = $serverList[$companyGroupServerId]['port'];
$companyGroupServerHash = $serverList[$companyGroupServerId]['serverMarker'];
// $dbUser=
if ($appId != 0)
$goc = $this->getDoctrine()->getManager('company_group')
->getRepository("CompanyGroupBundle:CompanyGroup")
->findOneBy(array(
'appId' => $appId
));
if (!$goc)
$goc = new CompanyGroup();
if ($appId == 0) {
$biggestAppIdCg = $this->getDoctrine()->getManager('company_group')
->getRepository("CompanyGroupBundle:CompanyGroup")
->findOneBy(array( // 'appId' => $appId
), array(
'appId' => 'desc'
));
if ($biggestAppIdCg)
$appId = 1 + $biggestAppIdCg->getAppId();
}
$goc->setName($post->get('company_name'));
$goc->setCompanyGroupHash($companyGroupHash);
$goc->setAppId($appId);
$goc->setActive(1);
$goc->setAddress($post->get('address'));
$goc->setShippingAddress($post->get('s_address'));
$goc->setBillingAddress($post->get('b_address'));
$goc->setMotto($post->get('motto'));
$goc->setInitiateFlag($post->get('initiate_flag', 2));
$goc->setInvoiceFooter($post->get('i_footer'));
$goc->setGeneralFooter($post->get('g_footer'));
$goc->setCompanyReg($post->get('company_reg', ''));
$goc->setCompanyTin($post->get('company_tin', ''));
$goc->setCompanyBin($post->get('company_bin', ''));
$goc->setCompanyTl($post->get('company_tl', ''));
$goc->setCompanyType($post->get('company_type', ''));
$goc->setCurrentSubscriptionPackageId($post->get('package', ''));
$goc->setUsageValidUptoDate($usageValidUpto);
$goc->setUsageValidUptoDateTs($usageValidUpto->format('U'));
// $goc->setCu($post->get('package', ''));
$goc->setAdminUserAllowed($post->get('number_of_admin_user', 1));
$goc->setUserAllowed($post->get('number_of_user', 2));
$goc->setSubscriptionMonth($post->get('subscription_month', 1));
$goc->setCompanyDescription($post->get('company_description', ''));
$goc->setDbUser($post->get('db_user'));
$goc->setDbPass($post->get('db_pass'));
$goc->setDbHost($post->get('db_host'));
$goc->setCompanyGroupServerId($companyGroupServerId);
$goc->setCompanyGroupServerAddress($companyGroupServerAddress);
$goc->setCompanyGroupServerPort($companyGroupServerPort);
$goc->setCompanyGroupServerHash($companyGroupServerHash);
foreach ($request->files as $uploadedFile) {
if ($uploadedFile != null) {
$fileName = 'company_image' . $appId . '.' . $uploadedFile->guessExtension();
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/CompanyImage/';
if ($goc->getImage() != null && $goc->getImage() != '' && file_exists($this->container->getParameter('kernel.root_dir') . '/../web' . $goc->getImage())) {
unlink($this->container->getParameter('kernel.root_dir') . '/../web' . $goc->getImage());
}
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
$file = $uploadedFile->move($upl_dir, $path);
if ($path != "")
$goc->setImage('/uploads/CompanyImage/' . $path);
}
}
$em_goc->persist($goc);
$em_goc->flush();
$goc->setDbName('cg_' . $appId . '_' . $companyGroupHash);
$goc->setDbUser($serverList[$companyGroupServerId]['dbUser']);
$goc->setDbPass($serverList[$companyGroupServerId]['dbPass']);
$goc->setDbHost('localhost');
$em_goc->flush();
$centralUser = $this->getDoctrine()->getManager('company_group')
->getRepository("CompanyGroupBundle:EntityApplicantDetails")
->findOneBy(array(
'applicantId' => $session->get(UserConstants::USER_ID, 0)
));
if ($centralUser) {
$userAppIds = json_decode($centralUser->getUserAppIds(), true);
$userTypesByAppIds = json_decode($centralUser->getUserTypesByAppIds(), true);
if ($userAppIds == null) $userAppIds = [];
if ($userTypesByAppIds == null) $userTypesByAppIds = [];
$userAppIds = array_merge($userAppIds, array_diff([$appId], $userAppIds));
if (!isset($userTypesByAppIds[$appId])) {
$userTypesByAppIds[$appId] = [];
}
$userTypesByAppIds[$appId] = array_merge($userTypesByAppIds[$appId], array_diff([UserConstants::USER_TYPE_SYSTEM], $userTypesByAppIds[$appId]));
$centralUser->setUserAppIds(json_encode($userAppIds));
$centralUser->setUserTypesByAppIds(json_encode($userTypesByAppIds));
$em_goc->flush();
}
$accessList = $session->get('userAccessList', []);
$d = array(
'userType' => UserConstants::USER_TYPE_SYSTEM,
'globalId' => $session->get(UserConstants::USER_ID, 0),
'serverId' => $companyGroupServerId,
'serverUrl' => $companyGroupServerAddress,
'serverPort' => $companyGroupServerPort,
'systemType' => '_ERP_',
'companyId' => 1,
'appId' => $appId,
'companyLogoUrl' => $goc->getImage(),
'companyName' => $goc->getName(),
'authenticationStr' => $this->get('url_encryptor')->encrypt(
json_encode(
array(
'globalId' => $session->get(UserConstants::USER_ID, 0),
'appId' => $appId,
'authenticate' => 1,
'userType' => UserConstants::USER_TYPE_SYSTEM
)
)
),
'userCompanyList' => []
);
$accessList[] = $d;
$session->set('userAccessList', $accessList);
}
return new JsonResponse(array(
'user_access_data' => $d,
'app_id' => $appId
));
}
}
return $this->render('@HoneybeeWeb/pages/create_company.html.twig', array(
'page_title' => 'Company',
'serverList' => GeneralConstant::$serverListById
));
}
public function GetSessionDataForAppAction(
Request $request,
$remoteVerify = 0,
$version = 'latest',
$identifier = '_default_',
$refRoute = '',
$apiKey = '_ignore_'
)
{
$message = "";
$gocList = [];
$session = $request->getSession();
if ($request->request->has('token')) {
$em_goc = $this->getDoctrine()->getManager('company_group');
$to_set_session_data = MiscActions::GetSessionDataFromToken($em_goc, $request->request->get('token'))['sessionData'];
if ($to_set_session_data != null) {
foreach ($to_set_session_data as $k => $d) {
//check if mobile
$session->set($k, $d);
}
}
}
if ($request->request->has('sessionData')) {
$to_set_session_data = $request->request->get('sessionData');
foreach ($to_set_session_data as $k => $d) {
//check if mobile
$session->set($k, $d);
}
}
if ($version !== 'latest') {
$session_data = array(
'oAuthToken' => $session->get('oAuthToken'),
'locale' => $session->get('locale'),
'firebaseToken' => $session->get('firebaseToken'),
'token' => $session->get('token'),
UserConstants::USER_EMPLOYEE_ID => $session->get(UserConstants::USER_EMPLOYEE_ID),
UserConstants::USER_ID => $session->get(UserConstants::USER_ID),
UserConstants::LAST_SETTINGS_UPDATED_TS => $session->get(UserConstants::LAST_SETTINGS_UPDATED_TS),
UserConstants::USER_LOGIN_ID => $session->get(UserConstants::USER_LOGIN_ID),
UserConstants::USER_EMAIL => $session->get(UserConstants::USER_EMAIL),
UserConstants::USER_TYPE => $session->get(UserConstants::USER_TYPE),
UserConstants::USER_IMAGE => $session->get(UserConstants::USER_IMAGE),
UserConstants::USER_DEFAULT_ROUTE => $session->get(UserConstants::USER_DEFAULT_ROUTE),
UserConstants::USER_NAME => $session->get(UserConstants::USER_NAME),
UserConstants::USER_COMPANY_ID => $session->get(UserConstants::USER_COMPANY_ID),
UserConstants::USER_COMPANY_ID_LIST => $session->get(UserConstants::USER_COMPANY_ID_LIST),
UserConstants::USER_COMPANY_NAME_LIST => $session->get(UserConstants::USER_COMPANY_NAME_LIST),
UserConstants::USER_COMPANY_IMAGE_LIST => $session->get(UserConstants::USER_COMPANY_IMAGE_LIST),
UserConstants::USER_APP_ID => $session->get(UserConstants::USER_APP_ID),
UserConstants::USER_POSITION_LIST => $session->get(UserConstants::USER_POSITION_LIST),
UserConstants::USER_CURRENT_POSITION => $session->get(UserConstants::USER_CURRENT_POSITION),
UserConstants::ALL_MODULE_ACCESS_FLAG => $session->get(UserConstants::ALL_MODULE_ACCESS_FLAG),
UserConstants::USER_GOC_ID => $session->get(UserConstants::USER_GOC_ID),
UserConstants::USER_NOTIFICATION_ENABLED => GeneralConstant::NOTIFICATION_ENABLED == 1 ? ($this->getParameter('notification_enabled') == 1 ? 1 : 0) : 0,
UserConstants::USER_NOTIFICATION_SERVER => $this->getParameter('notification_server'),
UserConstants::PRODUCT_NAME_DISPLAY_TYPE => $session->get(UserConstants::PRODUCT_NAME_DISPLAY_TYPE),
UserConstants::APPLICATION_SECRET => $session->get(UserConstants::APPLICATION_SECRET),
//new addition
'appIdList' => $session->get('appIdList'),
'branchIdList' => $session->get('branchIdList', null),
'branchId' => $session->get('branchId', null),
'companyIdListByAppId' => $session->get('companyIdListByAppId'),
'companyNameListByAppId' => $session->get('companyNameListByAppId'),
'companyImageListByAppId' => $session->get('companyImageListByAppId'),
'userAccessList' => $session->get('userAccessList'),
'csToken' => $session->get('csToken'),
);
} else {
$session_data = array(
'oAuthToken' => $session->get('oAuthToken'),
'locale' => $session->get('locale'),
'firebaseToken' => $session->get('firebaseToken'),
'token' => $session->get('token'),
UserConstants::USER_EMPLOYEE_ID => $session->get(UserConstants::USER_EMPLOYEE_ID),
UserConstants::USER_ID => $session->get(UserConstants::USER_ID),
UserConstants::LAST_SETTINGS_UPDATED_TS => $session->get(UserConstants::LAST_SETTINGS_UPDATED_TS),
UserConstants::USER_LOGIN_ID => $session->get(UserConstants::USER_LOGIN_ID),
UserConstants::USER_EMAIL => $session->get(UserConstants::USER_EMAIL),
UserConstants::USER_TYPE => $session->get(UserConstants::USER_TYPE),
UserConstants::USER_IMAGE => $session->get(UserConstants::USER_IMAGE),
UserConstants::USER_DEFAULT_ROUTE => $session->get(UserConstants::USER_DEFAULT_ROUTE),
UserConstants::USER_NAME => $session->get(UserConstants::USER_NAME),
UserConstants::USER_COMPANY_ID => $session->get(UserConstants::USER_COMPANY_ID),
UserConstants::USER_COMPANY_ID_LIST => $session->get(UserConstants::USER_COMPANY_ID_LIST),
UserConstants::USER_COMPANY_NAME_LIST => $session->get(UserConstants::USER_COMPANY_NAME_LIST),
UserConstants::USER_COMPANY_IMAGE_LIST => $session->get(UserConstants::USER_COMPANY_IMAGE_LIST),
UserConstants::USER_APP_ID => $session->get(UserConstants::USER_APP_ID),
UserConstants::USER_POSITION_LIST => $session->get(UserConstants::USER_POSITION_LIST),
UserConstants::USER_CURRENT_POSITION => $session->get(UserConstants::USER_CURRENT_POSITION),
UserConstants::ALL_MODULE_ACCESS_FLAG => $session->get(UserConstants::ALL_MODULE_ACCESS_FLAG),
UserConstants::USER_GOC_ID => $session->get(UserConstants::USER_GOC_ID),
UserConstants::USER_DB_NAME => $session->get(UserConstants::USER_DB_NAME),
UserConstants::USER_DB_USER => $session->get(UserConstants::USER_DB_USER),
UserConstants::USER_DB_HOST => $session->get(UserConstants::USER_DB_HOST),
UserConstants::USER_DB_PASS => $session->get(UserConstants::USER_DB_PASS),
UserConstants::USER_NOTIFICATION_ENABLED => GeneralConstant::NOTIFICATION_ENABLED == 1 ? ($this->getParameter('notification_enabled') == 1 ? 1 : 0) : 0,
UserConstants::USER_NOTIFICATION_SERVER => $this->getParameter('notification_server'),
UserConstants::PRODUCT_NAME_DISPLAY_TYPE => $session->get(UserConstants::PRODUCT_NAME_DISPLAY_TYPE),
UserConstants::APPLICATION_SECRET => $session->get(UserConstants::APPLICATION_SECRET),
//new addition
'appIdList' => $session->get('appIdList'),
'branchIdList' => $session->get('branchIdList', null),
'branchId' => $session->get('branchId', null),
'companyIdListByAppId' => $session->get('companyIdListByAppId'),
'companyNameListByAppId' => $session->get('companyNameListByAppId'),
'companyImageListByAppId' => $session->get('companyImageListByAppId'),
'userAccessList' => $session->get('userAccessList'),
'csToken' => $session->get('csToken'),
);
}
$response = new JsonResponse(array(
"success" => empty($session->get(UserConstants::USER_ID)) ? false : true,
// 'session'=>$request->getSession(),
'session_data' => $session_data,
// 'session2'=>$_SESSION,
));
$response->headers->set('Access-Control-Allow-Origin', '*, null');
$response->headers->set('Access-Control-Allow-Methods', 'POST');
// $response->setCallback('FUNCTION_CALLBACK_NAME');
return $response;
}
public function EmployeeAddUsingQrCodeCentralAction(Request $request)
{
if ($request->isMethod('post')) {
$em_goc = $this->getDoctrine()->getManager('company_group');
$entityApplicant = $em_goc->getRepository("CompanyGroupBundle:EntityApplicantDetails")
->findOneBy(
array(
'applicantId' => $request->request->get('userId'),
)
);
$app = $em_goc->getRepository("CompanyGroupBundle:CompanyGroup")
->findOneBy(
array(
'appId' => $request->request->get('appId'),
)
);
$userType = $request->request->get('userType');
$currAccessData = json_decode($entityApplicant->getUserTypesByAppIds(), true);
if ($currAccessData == null) $currAccessData = [];
if (!isset($currAccessData[$request->request->get('appId')]))
$currAccessData[$request->request->get('appId')] = [];
$currAccessData[$request->request->get('appId')] = array_merge($currAccessData[$request->request->get('appId')], array_diff([$request->request->get('userType', $userType)], $currAccessData[$request->request->get('appId')]));
$entityApplicant->setUserTypesByAppIds(json_encode($currAccessData));
$em_goc->flush();
$postData = [];
$postData['globalId'] = $entityApplicant->getApplicantId();
$postData['username'] = $entityApplicant->getUsername();
$postData['email'] = $entityApplicant->getEmail();
$postData['firstname'] = $entityApplicant->getFirstname();
$postData['lastname'] = $entityApplicant->getLastname();
$postData['appId'] = $request->request->get('appId');
$postData['companyId'] = $request->request->get('companyId');
$postData['userType'] = $userType;
$urlToCall = $app->getCompanyGroupServerAddress() . '/add_employee_by_qr_erp';
$userFiles = $postData;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $urlToCall,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_HTTPHEADER => array( // "Accept: multipart/form-data",
),
// ),
CURLOPT_POSTFIELDS => $userFiles
));
$retData = curl_exec($curl);
$errData = curl_error($curl);
curl_close($curl);
$retDataObj = json_decode($retData, true);
} else {
$company = $request->get('company');
return new JsonResponse(array(
"success" => false,
));
}
return new JsonResponse([
'status' => 'success',
'message' => 'User successfully added to company or already joined.'
]);
}
public function EmployeeAddUsingQrCodeErpServerAction(Request $request)
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$app = $em_goc->getRepository("CompanyGroupBundle:CompanyGroup")
->findOneBy(
array(
'appId' => $request->request->get('appId'),
)
);
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$app->getDbName(),
$app->getDbUser(),
$app->getDbPass(),
$app->getDbHost(),
true
);
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('ApplicationBundle:SysUser')
->findOneBy(
array(
'globalId' => $request->request->get('globalId'),
)
);
if (!$user)
$user = new SysUser();
$user->setGlobalId($request->request->get('globalId'));
$user->setUsername($request->request->get('username'));
$user->setEmail($request->request->get('email'));
$user->setName($request->request->get('firstname'));
$user->setUserType($request->request->get('userType'));
$user->setUserAppId($request->request->get('appId'));
$user->setUserCompanyId(1);
$user->setStatus(1);
$user->setDefaultRoute('sales_dashboard');
$em->persist($user);
$em->flush();
$employee = $em->getRepository('ApplicationBundle:Employee')
->findOneBy(
array(
'userId' => $user->getUserId(),
)
);
if (!$employee) {
$employee = new Employee();
if ($request->request->get('email') && $request->request->get('firstname') && $request->request->get('lastname')) {
$employee->setEmail($request->request->get('email'));
$employee->setFirstName($request->request->get('firstname'));
$employee->setLastName($request->request->get('lastname'));
$employee->setCompanyId($request->request->get('companyId'));
$employee->setStatus(1);
$employee->setUserId($user->getUserId());
$em->persist($employee);
$em->flush();
} else {
return new JsonResponse([
'status' => 'error',
'message' => 'Missing employee data',
]);
}
}
$employeeDetails = $em->getRepository('ApplicationBundle:EmployeeDetails')
->findOneBy(
array(
'userId' => $user->getUserId(),
)
);
if (!$employeeDetails) {
$employeeDetails = new EmployeeDetails();
if ($request->request->get('email') && $request->request->get('firstname') && $request->request->get('lastname')) {
$employeeDetails->setId($employee->getEmployeeId());
$employeeDetails->setEmail($request->request->get('email'));
$employeeDetails->setFirstName($request->request->get('firstname'));
$employeeDetails->setLastName($request->request->get('lastname'));
$employeeDetails->setUsername($request->request->get('username'));
$employeeDetails->setUserId($employee->getUserId());
$employeeDetails->setEmpStatus(1);
$em->persist($employeeDetails);
$em->flush();
} else {
return new JsonResponse([
'status' => 'error',
'message' => 'Missing employee data',
]);
}
}
return $this->render(
'ApplicationBundle:pages/dashboard:index_central_landing.html.twig',
[
'page_title' => 'Central Landing',
]
);
}
public function EmployeeAddUsingQrCodeAction(Request $request)
{
$post = $request;
$em = $this->getDoctrine()->getManager('company_group');
$appid = $request->query->get('appid', $request->request->get('appid', null));
$session = $request->getSession();
$CurrentRoute = $request->attributes->get('_route');
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
if ($request->isMethod('POST')) {
$userId = $request->request->get('userId', null);
if ($userId === null) {
$companyId = $request->request->get('company');
$email = $request->request->get('email');
$qrImage = $request->files->get('qr_image');
if (!$email) {
return new JsonResponse(['status' => 'error', 'message' => 'Invalid request'], 400);
}
if ($qrImage) {
$uploadsDir = $this->getParameter('kernel.project_dir') . '/public/uploads/';
$fileName = 'qr_' . $companyId . '_' . time() . '.png';
$qrImage->move($uploadsDir, $fileName);
$qrImagePath = $uploadsDir . $fileName;
$bodyTemplate = 'ApplicationBundle:email/user:applicant_confirm.html.twig';
$bodyData = [
'name' => $email,
'companyData' => $companyId,
'companyName' => $request->request->get('company'),
'userType' => 2,
'appId' => $appid,
// 'qr_code_url' => '/uploads/' . $fileName
];
$userAccessList = $session->get('userAccessList', []);
$companyName = array_map(function ($company) {
return $company['companyName'];
}, $userAccessList);
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail([
'senderHash' => '_CUSTOM_',
'forwardToMailAddress' => $email,
'fromAddress' => 'no-reply@ourhoneybee.eu',
'userName' => 'no-reply@ourhoneybee.eu',
'password' => 'Honeybee@0112',
'smtpServer' => 'smtp.hostinger.com',
'smtpPort' => 465,
'subject' => 'User Registration on HoneyBee Ecosystem under Entity ',
'toAddress' => $email,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'companyId' => $companyId,
]);
return $this->render(
'ApplicationBundle:pages/dashboard:index_central_landing.html.twig',
[
'page_title' => 'Central Landing',
'companyNames' => $companyName
]
);
} else {
$userAccessList = $session->get('userAccessList', []);
$companyName = array_map(function ($company) {
return $company['companyName'];
}, $userAccessList);
return $this->render(
'ApplicationBundle:pages/dashboard:index_central_landing.html.twig',
[
'page_title' => 'Central Landing',
'companyNames' => $companyName
]
);
}
} else {
if ($systemType == '_CENTRAL_') {
$userAccessList = $session->get('userAccessList', []);
$companyName = array_map(function ($company) {
return $company['companyName'];
}, $userAccessList);
$modifiedRequest = $request->duplicate(
null,
array_merge($request->request->all(), ['appId' => $request->request->get('appid')])
);
$response = $this->EmployeeAddUsingQrCodeCentralAction($modifiedRequest);
if ($CurrentRoute == 'employee_add_by_qr_api') {
return $response;
}
return $this->render(
'ApplicationBundle:pages/dashboard:index_central_landing.html.twig',
[
'page_title' => 'Central Landing',
'companyNames' => $companyName
]
);
}
}
} else {
$company = $request->get('company');
return $this->render(
'ApplicationBundle:pages/dashboard:employee_add_by_qr.html.twig',
[
'page_title' => 'Central Landing',
'companyNames' => $company
]
);
}
}
public function EmployeeOnboardUsingQrAction(Request $request)
{
$email = $request->get('email');
$isAjax = $request->isXmlHttpRequest();
$currentRoute = $request->attributes->get('_route');
if (!$email) {
if ($isAjax) {
return new JsonResponse(['status' => 'error', 'message' => 'Email is required.']);
} else {
throw $this->createNotFoundException("Email is missing.");
}
}
$em_goc = $this->getDoctrine()->getManager('company_group');
$user = $em_goc->getRepository("CompanyGroupBundle:EntityApplicantDetails")->findOneBy(['email' => $email]);
if (!$user) {
if ($isAjax) {
return new JsonResponse(['status' => 'error', 'message' => 'Applicant not found.']);
} else {
throw $this->createNotFoundException("Applicant not found.");
}
}
$payloadUrl = $this->generateUrl('employee_onboard_by_qr_api', [
'email' => $user->getEmail(),
'applicantId' => $user->getApplicantId(),
'employeeQr'=>1
], UrlGeneratorInterface::ABSOLUTE_URL);
if ($currentRoute === 'employee_onboard') {
return new JsonResponse([
'status' => 'success',
'data' => [
'applicantId' => $user->getApplicantId(),
'username' => $user->getUsername(),
'email' => $user->getEmail(),
'firstName'=> $user->getFirstname(),
'lastName' => $user->getLastname(),
'link' => $payloadUrl
]
]);
}
if ($isAjax) {
return new JsonResponse([
'status' => 'success',
'data' => [
'id' => $user->getApplicantId(),
'email' => $user->getEmail(),
'name' => $user->getFirstname() . ' ' . $user->getLastname(),
'dob' => $user->getDob() ? $user->getDob()->format('Y-m-d') : null,
]
]);
}
$companies = $request->getSession()->get('userAccessList', []);
return $this->render('ApplicationBundle:pages/dashboard:qr_onboard_result.html.twig', [
'page_title' => 'Onboarding',
'applicant' => $user,
'companies' => $companies
]);
}
public function OnboardUserToCompanyAction(Request $request)
{
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$currentRoute = $request->attributes->get('_route');
if ($systemType !== '_CENTRAL_') {
throw new \Exception("This action must be called from CENTRAL system.");
}
$email = $request->request->get('email');
$applicantId = $request->request->get('applicant_id');
$appId = $request->request->get('company_id');
$userType = $request->request->get('user_type');
if (!$email || !$appId || !$userType) {
$this->addFlash('error', 'Missing required fields.');
return new JsonResponse(['status' => 'error', 'message' => 'Missing required fields.']);
}
$em = $this->getDoctrine()->getManager('company_group');
$applicant = $em->getRepository("CompanyGroupBundle:EntityApplicantDetails")->findOneBy(['email' => $email]);
if (!$applicant) {
$this->addFlash('error', 'Applicant not found.');
return $this->redirectToRoute('central_landing');
}
$userAppIds = json_decode($applicant->getUserAppIds(), true);
if (!is_array($userAppIds)) {
$userAppIds = [];
}
if (!in_array($appId, $userAppIds)) {
$userAppIds[] = $appId;
$applicant->setUserAppIds(json_encode($userAppIds));
}
$userTypesByAppIds = json_decode($applicant->getUserTypesByAppIds(), true) ?: [];
$userTypesByAppIds[$appId] = array((int) $userType);
$applicant->setUserTypesByAppIds(json_encode($userTypesByAppIds));
$em->persist($applicant);
$em->flush();
$companyRepo = $this->getDoctrine()->getManager('company_group')->getRepository("CompanyGroupBundle:CompanyGroup");
$targetCompany = $companyRepo->findOneBy(['appId' => $appId]);
if (!$targetCompany) {
$this->addFlash('error', 'Target company not found.');
return $this->redirectToRoute('central_landing');
}
$serverList = GeneralConstant::$serverListById;
$serverId = $targetCompany->getCompanyGroupServerId();
$appId = $targetCompany->getAppId();
if (!isset($serverList[$serverId])) {
$this->addFlash('error', 'Server configuration not found.');
return $this->redirectToRoute('central_landing');
}
// Find correct companyId from session userAccessList using appId
$session = $request->getSession();
$userAccessList = $session->get('userAccessList', []);
$resolvedCompanyId = null;
foreach ($userAccessList as $access) {
if (isset($access['appId']) && $access['appId'] == $appId) {
$resolvedCompanyId = $access['companyId'];
break;
}
}
if (!$resolvedCompanyId) {
$this->addFlash('error', 'Could not resolve companyId from session for the given appId.');
return $this->redirectToRoute('central_landing');
}
$imagePath = $this->container->getParameter('kernel.root_dir') . '/../web/' . $applicant->getImage();
$imageFile = null;
if ($applicant->getImage() && file_exists($imagePath)) {
$mime = mime_content_type($imagePath);
$name = pathinfo($imagePath, PATHINFO_BASENAME);
$imageFile = new \CURLFile($imagePath, $mime, $name);
}
// Prepare userData
$userData = [];
$getters = array_filter(get_class_methods($applicant), function ($method) {
return strpos($method, 'get') === 0;
});
foreach ($getters as $getter) {
if (in_array($getter, ['getCreatedAt', 'getUpdatedAt', 'getImage'])) continue;
$value = $applicant->$getter();
$userData[$getter] = $value instanceof \DateTime ? $value->format('Y-m-d') : $value;
}
$userData['getUserAppIds'] = json_encode($userAppIds);
$userData['getUserTypesByAppIds'] = json_encode($userTypesByAppIds);
$postFields = [
'userData' => json_encode([$userData]),
'appIds' => $appId,
'userIds' => $applicantId,
'companyId' => $resolvedCompanyId,
'userType' => $userType,
'imageFile' => $imageFile
];
if ($imageFile) {
$postFields['file_' . $applicant->getApplicantId()] = $imageFile;
}
$url = $serverList[$serverId]['absoluteUrl'] . '/OnBoardCentralUserToErp';
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $url,
CURLOPT_POSTFIELDS => $postFields,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
]);
$response = curl_exec($curl);
$curlError = curl_error($curl);
curl_close($curl);
$responseObj = json_decode($response, true);
if ($currentRoute === 'employee_onboard_api') {
return new JsonResponse(
$responseObj
);
}
if (!empty($responseObj['success'])) {
$this->addFlash('success', 'Applicant onboarded and synced to ERP.');
} else {
$this->addFlash('warning', 'Onboarded, but ERP sync may have failed. Check logs.');
}
return $this->redirectToRoute('central_landing');
}
public function OnBoardCentralUserToErpAction(Request $request)
{
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
if ($systemType === '_CENTRAL_') {
return new JsonResponse(['success' => false, 'message' => 'Invalid system type.']);
}
$userDataJson = $request->get('userData');
$userDataList = json_decode($userDataJson, true);
if (!$userDataList || !is_array($userDataList)) {
return new JsonResponse(['success' => false, 'message' => 'Invalid or missing userData.']);
}
$userData = $userDataList[0] ?? null;
if (!$userData || empty($userData['getApplicantId'])) {
return new JsonResponse(['success' => false, 'message' => 'Missing applicant ID.']);
}
$em_goc = $this->getDoctrine()->getManager('company_group');
$globalId = $userData['getApplicantId'];
$appIds = $request->get('appIds');
$userIds = $request->get('userIds');
$companyId = $request->get('companyId');
$company = $em_goc->getRepository("CompanyGroupBundle:CompanyGroup")->findOneBy(['appId' => $appIds]);
if (!$company) {
return new JsonResponse(['success' => false, 'message' => 'Target company not found.']);
}
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$company->getDbName(),
$company->getDbUser(),
$company->getDbPass(),
$company->getDbHost(),
true
);
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('ApplicationBundle:SysUser')->findOneBy([
'globalId' => $globalId
]);
if (!$user) {
$user = new \ApplicationBundle\Entity\SysUser();
$user->setGlobalId($globalId);
}
$setterMap = [
'getUsername' => 'setUserName',
'getEmail' => 'setEmail',
'getPassword' => 'setPassword',
'getDeviceId' => 'setDeviceId',
'getDeviceIdLockedFlag' => 'setDeviceIdLockedFlag',
'getLockDeviceIdOnNextLoginFlag' => 'setLockDeviceIdOnNextLoginFlag',
'getOAuthUniqueId' => 'setOAuthUniqueId',
'getOAuthEmail' => 'setOAuthEmail',
'getSyncFlag' => 'setSyncFlag',
'getFirstname' => 'setName',
];
$user->setUserAppId($appIds);
$user->setUserAppIdList(json_encode([$appIds]));
$user->setStatus(1);
foreach ($setterMap as $getter => $setter) {
if (isset($userData[$getter]) && method_exists($user, $setter)) {
$user->$setter($userData[$getter]);
}
}
$fullName = trim(($userData['getFirstname'] ?? '') . ' ' . ($userData['getLastname'] ?? ''));
if (!empty($fullName)) {
$user->setName($fullName);
}
$imagePathToSet = '';
$uploadedFile = $request->files->get('file_' . $globalId);
if ($uploadedFile) {
$uploadDir = $this->getParameter('kernel.project_dir') . '/web/uploads/UserImage/';
if (!file_exists($uploadDir)) {
mkdir($uploadDir, 0777, true);
}
$filename = 'user_' . $globalId . '.' . $uploadedFile->guessExtension();
$uploadedFile->move($uploadDir, $filename);
$imagePathToSet = 'uploads/UserImage/' . $filename;
$user->setImage($imagePathToSet);
}
$user->setUserType(1);
$em->persist($user);
$em->flush();
$employee = $em->getRepository('ApplicationBundle:Employee')->findOneBy([
'userId' => $user->getUserId()
]);
if (!$employee) {
$employee = new \ApplicationBundle\Entity\Employee();
$employee->setUserId($user->getUserId());
$employee->setDateOfAddition(new \DateTime());
}
$employee->setFirstName($userData['getFirstname'] ?? null);
$employee->setLastName($userData['getLastname'] ?? null);
$employee->setName(trim(($userData['getFirstname'] ?? '') . ' ' . ($userData['getLastname'] ?? '')));
$employee->setEmail($userData['getEmail'] ?? null);
$employee->setEmmContact($userData['getEmmContact'] ?? null);
$employee->setCurrentAddress($userData['getCurrAddr'] ?? null);
$employee->setPermanentAddress($userData['getPermAddr'] ?? null);
$employee->setCompanyId((int) $companyId);
$employee->setDepartmentId($userData['getDept'] ?? null);
$employee->setBranchId($userData['getBranch'] ?? null);
$employee->setPositionId($userData['getDesg'] ?? null);
$employee->setSupervisorId($userData['getSupervisor'] ?? null);
if (!empty($imagePathToSet)) {
$employee->setImage($imagePathToSet);
}
$employee->setStatus("1");
$employee->setLastModifiedDate(new \DateTime());
$em->persist($employee);
$em->flush();
$employeeDetails = $em->getRepository('ApplicationBundle:EmployeeDetails')
->findOneBy(['userId' => $user->getUserId()]);
if (!$employeeDetails) {
$employeeDetails = new \ApplicationBundle\Entity\EmployeeDetails();
$employeeDetails->setUserId($user->getUserId());
}
$employeeDetails->setId($employee->getEmployeeId());
$employeeDetails->setFirstname($userData['getFirstname'] ?? null);
$employeeDetails->setLastname($userData['getLastname'] ?? null);
$employeeDetails->setUsername($userData['getUsername'] ?? null);
$employeeDetails->setEmail($userData['getEmail'] ?? null);
$employeeDetails->setPassword($userData['getPassword'] ?? null);
$employeeDetails->setNid($userData['getNid'] ?? null);
$employeeDetails->setSex($userData['getSex'] ?? null);
$employeeDetails->setFather($userData['getFather'] ?? null);
$employeeDetails->setMother($userData['getMother'] ?? null);
$employeeDetails->setSpouse($userData['getSpouse'] ?? null);
$employeeDetails->setChild1($userData['getChild1'] ?? null);
$employeeDetails->setChild2($userData['getChild2'] ?? null);
$employeeDetails->setPhone($userData['getPhone'] ?? null);
$employeeDetails->setOfficialPhone($userData['getOfficailPhone'] ?? null);
$employeeDetails->setCurrAddr($userData['getCurrAddr'] ?? null);
$employeeDetails->setPermAddr($userData['getPermAddr'] ?? null);
$employeeDetails->setEmmContact($userData['getEmmContact'] ?? null);
if (!empty($userData['getDob'])) {
$employeeDetails->setDob(new \DateTime($userData['getDob']));
}
if (!empty($userData['getJoiningDate'])) {
$employeeDetails->setJoiningDate(new \DateTime($userData['getJoiningDate']));
}
if (!empty($userData['getEmpValidTill'])) {
$employeeDetails->setEmpValidTill(new \DateTime($userData['getEmpValidTill']));
}
if (!empty($userData['getTinValidTill'])) {
$employeeDetails->setTinValidTill(new \DateTime($userData['getTinValidTill']));
}
if (!empty($userData['getMedInsValidTill'])) {
$employeeDetails->setMedInsValidTill(new \DateTime($userData['getMedInsValidTill']));
}
$employeeDetails->setEmpType($userData['getEmpType'] ?? null);
$employeeDetails->setEmpCode($userData['getEmpCode'] ?? null);
$employeeDetails->setEmployeeLevel($userData['getEmployeeLevel'] ?? null);
$employeeDetails->setTin($userData['getTin'] ?? null);
$employeeDetails->setSkill($userData['getSkill'] ?? null);
$employeeDetails->setEducationData($userData['getEducationData'] ?? null);
$employeeDetails->setWorkExperienceData($userData['getWorkExperienceData'] ?? null);
$employeeDetails->setApplicationText($userData['getApplicationText'] ?? null);
$employeeDetails->setCurrentEmployment($userData['getCurrentEmployment'] ?? null);
$employeeDetails->setEmergencyContactNumber($userData['getEmergencyContactNumber'] ?? null);
$employeeDetails->setPostalCode($userData['getPostalCode'] ?? null);
$employeeDetails->setCountry($userData['getCountry'] ?? null);
if (!empty($imagePathToSet)) {
$employeeDetails->setImage($imagePathToSet);
}
$em->persist($employeeDetails);
$em->flush();
$uploadedFile = $request->files->get('file_' . $globalId);
return new JsonResponse([
'success' => true,
'globalId' => $globalId,
'appIds' => $appIds,
'userIds' => $userIds,
'hasFile' => $uploadedFile !== null,
]);
}
public function getIndustryListForAppAction()
{
$industryList = GeneralConstant::$industryList;
return new JsonResponse($industryList);
}
public function getFeatureListAction()
{
$featureList = GeneralConstant::$featureList;
return new JsonResponse($featureList);
}
public function chooseYourPlanAction()
{
$plan = GeneralConstant::$chooseYourPlan;
return new JsonResponse($plan);
}
// public function getLogindataFromTokenAction(Request $request)
// {
// $em_goc = $this->getDoctrine()->getManager('company_group');
// $sessionData = MiscActions::GetSessionDataFromToken($em_goc, $request->query->get('hbeeSessionToken'))['sessionData'];
// return new JsonResponse($sessionData);
// $sessionDataa = MiscActions::GetSessionDataFromToken($em_goc, $request->query->get('hbeeSessionToken'))['sessionData'];
// return new JsonResponse($sessionDataa);
// }
public function getLogindataFromTokenAction(Request $request)
{
$em_goc = $this->getDoctrine()->getManager('company_group');
$token = $request->query->get('hbeeSessionToken');
if (!$token) {
return new JsonResponse(['error' => 'Missing session token'], 400);
}
$sessionResult = MiscActions::GetSessionDataFromToken($em_goc, $token);
if (!$sessionResult || !isset($sessionResult['sessionData'])) {
return new JsonResponse(['error' => 'Invalid session token or session not found'], 401);
}
$sessionData = $sessionResult['sessionData'];
return new JsonResponse($sessionData);
}
public function packageDetailsAction()
{
$packageDetails = GeneralConstant::$packageDetails;
return new JsonResponse($packageDetails);
}
public function employeeRangeAction()
{
$employeeRangeForApp = GeneralConstant::$employeeRange;
return new JsonResponse($employeeRangeForApp);
}
public function paymentMethodAction()
{
$paymentMethod = GeneralConstant::$paymentMethod;
return new JsonResponse($paymentMethod);
}
}