<?php
namespace ApplicationBundle\Controller;
use ApplicationBundle\Constants\GeneralConstant;
use ApplicationBundle\Entity\DashboardWidget;
use ApplicationBundle\Modules\User\Position;
use CompanyGroupBundle\Entity\EntityItemGroup;
use CompanyGroupBundle\Entity\EntityProductCategories;
use CompanyGroupBundle\Entity\EntityProductSubCategories;
use CompanyGroupBundle\Entity\EntityProductSpecifications;
use CompanyGroupBundle\Entity\EntityBrandCompany;
use CompanyGroupBundle\Entity\EntityUnitType;
use CompanyGroupBundle\Entity\EntityProducts;
use ApplicationBundle\Helper\Generic;
use ApplicationBundle\Interfaces\SessionCheckInterface;
use ApplicationBundle\Constants\UserConstants;
use ApplicationBundle\Modules\Accounts\Accounts;
use ApplicationBundle\Modules\System\MiscActions;
use ApplicationBundle\Modules\System\System;
use ApplicationBundle\Modules\User\Users;
use ApplicationBundle\Modules\Purchase\Supplier;
use ApplicationBundle\Modules\Inventory\Inventory;
use CompanyGroupBundle\Entity\EntityUser;
use Symfony\Component\BrowserKit\Client as BrowserClientKit;
use ApplicationBundle\Modules\Sales\Client;
use ApplicationBundle\Modules\User\Company;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Loader\ExistsLoaderInterface;
use Twig\Loader\SourceContextLoaderInterface;
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',
'BrandCompany',
'InvItemGroup',
'InvProductCategories',
'InvProductSubCategories',
'InvProductSpecifications',
'InvSpecificationTypes',
'InvProducts'
];
$entity_wise_entities = [
'EntityCurrencies',
'EntityUnitType',
'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',
'BrandCompany',
'InvItemGroup',
'InvProductCategories',
'InvProductSubCategories',
'InvProductSpecifications',
'InvSpecificationTypes',
'InvProducts'
];
$entity_wise_entities = [
'EntityCurrencies',
'EntityUnitType',
'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('ApplicationBundle:pages/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 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('ApplicationBundle:pages/system/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)
{
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$twig_file = 'ApplicationBundle:pages/login:applicant_login.html.twig';
$session = $request->getSession();
return $this->render(
'ApplicationBundle:pages/dashboard:index_central_landing.html.twig',
array(
'page_title' => 'Central Landing'
)
);
}
public function HummanResourceAction()
{
return $this->render(
'ApplicationBundle:pages/dashboard:humanResource.html.twig',
array(
'page_title' => 'Human Resource Dashboard'
)
);
}
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'
)
);
}
}