<?php
namespace ApplicationBundle\Controller;
use ApplicationBundle\Constants\GeneralConstant;
use ApplicationBundle\Constants\NotificationEventCatalogue;
use ApplicationBundle\Entity\EncryptedSignature;
use ApplicationBundle\Interfaces\SessionCheckInterface;
use ApplicationBundle\Modules\Authentication\Constants\UserConstants;
use ApplicationBundle\Modules\Api\Constants\ApiConstants;
use ApplicationBundle\Modules\System\DocValidation;
use ApplicationBundle\Modules\System\MiscActions;
use ApplicationBundle\Modules\System\System;
use ApplicationBundle\Modules\User\Users;
use ApplicationBundle\Notification\NotificationEvent;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGenerator;
class ApprovalController extends GenericController implements SessionCheckInterface
{
public function ApproveDocumentAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
if (isset(GeneralConstant::$Entity_list_details[$request->request->get('approvalEntity')]['entity_view_route_path_name']))
$url = $this->generateUrl(
GeneralConstant::$Entity_list_details[$request->request->get('approvalEntity')]['entity_view_route_path_name']
);
else {
$url = '';
}
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
// 'appId'=>$request->getSession()->get(UserConstants::USER_APP_ID),
// 'url'=>$this->generateUrl(
// GeneralConstant::$Entity_list_details[$request->request->get('approvalEntity')]['entity_view_route_path_name']
// )
);
if ($request->request->has('approvalAction')) {
$message = System::approveDocument(
$em,
$options,
$request->request->get('approvalEntity'),
$request->request->get('approvalEntityId'),
$request->request->get('approvalId'),
$this->getLoggedUserLoginId($request),
$request->request->get('approvalAction'),
$request->request->get('approvalNote'),
$request->request->get('approvalHash'),
$url,
$request->request->get('forwardTo'),
$this->get('mail_module'),
$request->request->get('approvedAmount') // partial approval (expense): reduce to this if < current
);
// ── Notify the next approver(s) in line ──────────────────────
// approveDocument() returns userIdList = next pending approvers.
// We notify them that a document is now waiting for their approval.
if ($message['success'] == true && !empty($message['userIdList'])) {
$entityAlias = GeneralConstant::$Entity_list_details[$request->request->get('approvalEntity')]['entity_alias'] ?? 'Document';
/** @var \ApplicationBundle\Service\NotificationDispatcher $dispatcher */
$dispatcher = $this->get('app.notification_dispatcher');
$dispatcher->dispatchDirect(
\ApplicationBundle\Notification\NotificationEvent::make(
\ApplicationBundle\Constants\NotificationEventCatalogue::DOC_AWAITING_MY_APPROVAL,
(int) $request->getSession()->get(UserConstants::USER_COMPANY_ID),
(int) $request->getSession()->get(UserConstants::USER_APP_ID),
[
'entityType' => $entityAlias,
'documentHash' => $message['docHash'] ?? '',
'targetRoute' => GeneralConstant::$Entity_list_details[$request->request->get('approvalEntity')]['entity_view_route_path_name'] ?? '',
'targetId' => $request->request->get('approvalEntityId'),
'actorUserId' => (int) $request->getSession()->get(UserConstants::USER_ID),
]
),
array_map('intval', $message['userIdList'])
);
}
// $this->addFlash(
// $message[0],
// $message[1]
// );
if ($message['success'] == true)
return new JsonResponse(array("success" => true,
'message' => $message,
'approvalEntity' => $request->request->get('approvalEntity'),
'approvalEntityId' => $request->request->get('approvalEntityId'),
'approvalId' => $request->request->get('approvalId'),
'approvalAction' => $request->request->get('approvalAction'),
)
);
else
return new JsonResponse(array("success" => false, 'message' => $message,
'approvalEntity' => $request->request->get('approvalEntity'),
'approvalEntityId' => $request->request->get('approvalEntityId'),
'approvalId' => $request->request->get('approvalId'),
'approvalAction' => $request->request->get('approvalAction'),
)
);
}
return new JsonResponse(array("success" => false));
}
// $userList=$this->get('user_module')->showUserList();
return new JsonResponse(array("success" => false));
}
public function getPendingApprovalListForUserAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$currentDateTime = new \DateTime();
$currTs = $currentDateTime->format('U');
$tvp = $this->get('url_encryptor')->encrypt(json_encode(
array(
'timeout' => 1 * $currTs + 3600,
'token' => $session->get('token', 0),
)
));
$absoluteUrlList = [];
$filterApprovalEntityId=$request->request->get('entity','_all_');
foreach (GeneralConstant::$Entity_list_details as $e => $d) {
if (isset($d['entity_view_route_path_name']))
$absoluteUrlList[$e] = $this->generateUrl($d['entity_view_route_path_name'], [], UrlGenerator::ABSOLUTE_URL);
}
return new JsonResponse(System::getPendingApprovalListByUserLoginId($em, $this->getLoggedUserLoginId($request), 1, $absoluteUrlList, $tvp,$filterApprovalEntityId));
}
public function getPendingApprovalListForAppAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$absoluteUrlList = [];
$session = $request->getSession();
$currentDateTime = new \DateTime();
$currTs = $currentDateTime->format('U');
$absoluteUrl = $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
$tvp = $this->get('url_encryptor')->encrypt(json_encode(
array(
'timeout' => 1 * $currTs + 3600,
'token' => $session->get('token', 0),
)
));
foreach (GeneralConstant::$Entity_list_details as $e => $d) {
if (isset($d['entity_view_route_path_name']))
$absoluteUrlList[$e] = $this->generateUrl(isset($d['entity_print_route_path_name']) ? $d['entity_print_route_path_name'] : $d['entity_view_route_path_name'], [], UrlGenerator::ABSOLUTE_URL);
}
return new JsonResponse(System::getPendinDocumentListForAppByUserLoginId($em, $this->getLoggedUserLoginId($request), 1, $absoluteUrlList, $tvp,'_all_',
$request->query->get('page', '_UNSET_'),
$request->query->get('offset', 0),
$request->query->get('limit', 999999),
$absoluteUrl
));
// $em = $this->getDoctrine()->getManager();
//
// $absoluteUrlList = [];
// foreach (GeneralConstant::$Entity_list_details as $e => $d) {
// if (isset($d['entity_view_route_path_name']))
// $absoluteUrlList[$e] = $this->generateUrl(isset($d['entity_print_route_path_name']) ? $d['entity_print_route_path_name'] : $d['entity_view_route_path_name'], [], UrlGenerator::ABSOLUTE_URL);
// }
// $session = $request->getSession();
// $currentDateTime = new \DateTime();
// $currTs = $currentDateTime->format('U');
// $tvp = $this->get('url_encryptor')->encrypt(json_encode(
// array(
// 'timeout' => 1 * $currTs + 3600,
// 'token' => $session->get('token', 0),
//
// )
// ));
//
//
// return new JsonResponse(System::getPendinDocumentListForAppByUserLoginId($em, $this->getLoggedUserLoginId($request), 1, $absoluteUrlList,
// $tvp,
// $request->query->get('page', '_UNSET_'),
// $request->query->get('offset', 0),
// $request->query->get('limit', 999999)
// ));
}
public function getMyDocumentListForAppAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$absoluteUrlList = [];
$session = $request->getSession();
$currentDateTime = new \DateTime();
$currTs = $currentDateTime->format('U');
$absoluteUrl = $this->generateUrl('dashboard', [], UrlGenerator::ABSOLUTE_URL);
$tvp = $this->get('url_encryptor')->encrypt(json_encode(
array(
'timeout' => 1 * $currTs + 3600,
'token' => $session->get('token', 0),
)
));
foreach (GeneralConstant::$Entity_list_details as $e => $d) {
if (isset($d['entity_view_route_path_name']))
$absoluteUrlList[$e] = $this->generateUrl(isset($d['entity_print_route_path_name']) ? $d['entity_print_route_path_name'] : $d['entity_view_route_path_name'], [], UrlGenerator::ABSOLUTE_URL);
}
return new JsonResponse(System::getMyDocumentListForAppByUserLoginId($em, $this->getLoggedUserLoginId($request),$absoluteUrl, 1, $absoluteUrlList, $tvp,'_all_',
$request->query->get('page', '_UNSET_'),
$request->query->get('limit', 999999)
));
// $em = $this->getDoctrine()->getManager();
//
// $absoluteUrlList = [];
// foreach (GeneralConstant::$Entity_list_details as $e => $d) {
// if (isset($d['entity_view_route_path_name']))
// $absoluteUrlList[$e] = $this->generateUrl(isset($d['entity_print_route_path_name']) ? $d['entity_print_route_path_name'] : $d['entity_view_route_path_name'], [], UrlGenerator::ABSOLUTE_URL);
// }
// $session = $request->getSession();
// $currentDateTime = new \DateTime();
// $currTs = $currentDateTime->format('U');
// $tvp = $this->get('url_encryptor')->encrypt(json_encode(
// array(
// 'timeout' => 1 * $currTs + 3600,
// 'token' => $session->get('token', 0),
//
// )
// ));
//
//
// return new JsonResponse(System::getPendinDocumentListForAppByUserLoginId($em, $this->getLoggedUserLoginId($request), 1, $absoluteUrlList,
// $tvp,
// $request->query->get('page', '_UNSET_'),
// $request->query->get('offset', 0),
// $request->query->get('limit', 999999)
// ));
}
/**
* First-run guard: does the logged-in user have a usable signature yet?
* Used by the first-login modal so a new user is prompted to set their
* signature + approval hash BEFORE they hit an approval action and get stuck.
* Local-only check (cheap); a central copy is pulled lazily on first verify.
*/
public function SignatureStatusAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$userId = $request->getSession()->get('userId');
$has = false;
if ($userId) {
$rec = $em->getRepository('ApplicationBundle\\Entity\\EncryptedSignature')
->findOneBy(['userId' => $userId]);
$has = ($rec && $rec->getData());
}
return new JsonResponse(['hasSignature' => (bool) $has]);
}
/**
* App: does the logged-in user have an approval signature yet? Lets the
* mobile client route between "enter your existing PIN" and "create a
* new PIN" on first use.
*/
public function SignatureStatusForAppAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$userId = $request->getSession()->get('userId');
$has = false;
if ($userId) {
$rec = $em->getRepository('ApplicationBundle\\Entity\\EncryptedSignature')
->findOneBy(['userId' => $userId]);
$has = ($rec && $rec->getData());
}
return new JsonResponse(array('success' => true, 'hasSignature' => (bool) $has));
}
/**
* App: set or change the approval hash WITHOUT the ERP web. Mirrors
* UpdateSignatureAction, minus the mandatory image upload:
* - first-time set → a simple name-stamp signature image is generated
* server-side and encrypted under the new hash;
* - change → the current hash must verify first, and the existing
* signature image is preserved (re-encrypted under the new hash).
* Synced to CENTRAL exactly like the web flow.
*/
public function SetSignatureForAppAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$session = $request->getSession();
$userId = $session->get('userId');
$companyId = $session->get('userCompanyId');
$loginId = $this->getLoggedUserLoginId($request);
$newHash = trim((string) $request->request->get('newHash', ''));
$oldHash = trim((string) $request->request->get('oldHash', ''));
if ($userId == null || $loginId == null) {
return new JsonResponse(array('success' => false, 'message' => 'Not signed in.'));
}
if (strlen($newHash) < 4) {
return new JsonResponse(array('success' => false, 'message' => 'PIN must be at least 4 characters.'));
}
$repo = $em->getRepository('ApplicationBundle\\Entity\\EncryptedSignature');
$record = $repo->findOneBy(['userId' => $userId]);
if ($record && $record->getData()) {
// Changing an existing hash: the current one must verify, and we
// keep the user's existing signature image.
if ($oldHash === '') {
return new JsonResponse(array('success' => false, 'message' => 'Your current PIN is required to change it.'));
}
$check = DocValidation::isSignatureOk($em, $loginId, $oldHash, 1);
if (!isset($check['success']) || $check['success'] != true) {
return new JsonResponse(array('success' => false, 'message' => 'Current PIN did not match.'));
}
$imageData = $check['data'];
} else {
// First-time set from the app: no drawn signature exists, so
// generate a clean name-stamp image to act as the signature.
$user_data = Users::getUserInfoByLoginId($em, $loginId);
$name = isset($user_data['name']) && $user_data['name'] != '' ? $user_data['name'] : 'Approved';
$img = imagecreatetruecolor(240, 80);
$bg = imagecolorallocate($img, 255, 255, 255);
imagefilledrectangle($img, 0, 0, 240, 80, $bg);
$fg = imagecolorallocate($img, 26, 28, 28);
imagestring($img, 5, 12, 32, substr($name, 0, 26), $fg);
ob_start();
imagepng($img);
$png = ob_get_clean();
imagedestroy($img);
$imageData = base64_encode($png);
}
$encoded = System::encryptSignature($imageData, $newHash);
if ($encoded === false) {
return new JsonResponse(array('success' => false, 'message' => 'Could not secure the signature. Try again.'));
}
if (!$record) {
$record = new \ApplicationBundle\Entity\EncryptedSignature();
$record->setUserId($userId);
$record->setCreatedAt(new \DateTime());
}
$record->setCompanyId($companyId);
$record->setData($encoded);
$record->setSigExists(0);
$record->setLastDecryptedSigId(0);
$record->setUpdatedAt(new \DateTime());
$em->persist($record);
$em->flush();
// Sync to CENTRAL (same contract as the web UpdateSignatureAction).
if ($systemType !== '_CENTRAL_') {
$applicantId = null;
$sysUser = $em->getRepository('ApplicationBundle\\Entity\\SysUser')->findOneBy(['userId' => $userId]);
if ($sysUser) {
$applicantId = $sysUser->getGlobalId();
}
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_URL => GeneralConstant::HONEYBEE_CENTRAL_SERVER . '/SyncSignatureToCentral',
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_HTTPHEADER => [
'Accept: application/json',
'Content-Type: application/json'
],
CURLOPT_POSTFIELDS => json_encode([
'userId' => $userId,
'approvalHash' => $newHash,
'signatureData' => $encoded,
'companyId' => $companyId,
'applicantId' => $applicantId
])
]);
curl_exec($curl);
curl_close($curl);
}
return new JsonResponse(array(
'success' => true,
'hasSignature' => true,
'message' => 'Approval PIN saved.'
));
}
public function UpdateSignatureAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
$session = $request->getSession();
$userId = $session->get('userId');
$companyId = $session->get('userCompanyId');
$appId = $session->get('userAppId');
$user = $em->getRepository('ApplicationBundle\\Entity\\SysUser')->findOneBy(['userId' => $userId]);
$applicantId = $user->getGlobalId();
$user_data = Users::getUserInfoByLoginId($em, $this->getLoggedUserLoginId($request));
$g_path = '';
if ($request->isMethod('POST')) {
$path = "";
$extension_here = '';
foreach ($request->files as $uploadedFile) {
if ($uploadedFile != null) {
$extension_here = $uploadedFile->guessExtension();
$fileName = md5(uniqid()) . '.' . $extension_here;
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/';
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
$file = $uploadedFile->move($upl_dir, $path);
}
}
if ($path != "") {
$file_path = 'uploads/FileUploads/' . $path;
$g_path = $this->container->getParameter('kernel.root_dir') . '/../web/' . $file_path;
list($width, $height) = getimagesize($g_path);
$percent = (200 / $width);
$newwidth = $width * $percent;
$newheight = $height * $percent;
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = ($extension_here == 'png') ? imagecreatefrompng($g_path) : imagecreatefromjpeg($g_path);
imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
$thumbPath = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/th.png';
imagepng($thumb, $thumbPath);
$th_file = file_get_contents($thumbPath);
$image_data = base64_encode($th_file);
$encoded_data = System::encryptSignature($image_data, $request->request->get('approvalHash'));
if ($encoded_data !== false) {
$repo = $em->getRepository('ApplicationBundle\\Entity\\EncryptedSignature');
$record = $repo->findOneBy(['userId' => $userId]);
if (!$record) {
$record = new \ApplicationBundle\Entity\EncryptedSignature();
$record->setUserId($userId);
$record->setCreatedAt(new \DateTime());
}
$record->setCompanyId($companyId);
$record->setData($encoded_data);
$record->setSigExists(0);
$record->setLastDecryptedSigId(0);
$record->setUpdatedAt(new \DateTime());
$em->persist($record);
$em->flush();
// Sync to central server
if ($systemType !== '_CENTRAL_') {
$centralUrl = GeneralConstant::HONEYBEE_CENTRAL_SERVER . '/SyncSignatureToCentral';
$payload = [
'userId' => $userId,
'approvalHash' => $request->request->get('approvalHash'),
'signatureData' => $encoded_data,
'companyId' => $companyId,
'applicantId' => $applicantId
];
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_URL => $centralUrl,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_HTTPHEADER => [
'Accept: application/json',
'Content-Type: application/json'
],
CURLOPT_POSTFIELDS => json_encode($payload)
]);
$retData = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
// return new JsonResponse($retData);
if ($err) {
$this->addFlash('error', 'Signature sent failed: ' . $err);
} else {
$response = json_decode($retData, true);
if (isset($response['success']) && $response['success'] === true) {
$this->addFlash('success', 'Signature synced successfully to CENTRAL.');
} else {
$this->addFlash('error', 'CENTRAL server error: ' . ($response['message'] ?? 'Unknown error.'));
}
}
}
}
// Delete temp files
@unlink($g_path);
@unlink($thumbPath);
}
// First-run modal posts with a redirectTo so the user lands back where
// they were (instead of the settings page) once the signature is set.
$redirectTo = $request->request->get('redirectTo');
if ($redirectTo) {
return $this->redirect($redirectTo);
}
}
return $this->render('@System/pages/settings/update_signature.html.twig', [
'page_title' => 'Update Signature',
'user_data' => $user_data,
'path' => $g_path
]);
}
public function SignatureCheckFromCentralAction(Request $request)
{
$systemType = $this->container->hasParameter('system_type') ? $this->container->getParameter('system_type') : '_ERP_';
if ($systemType !== '_CENTRAL_') {
return new JsonResponse(['success' => false, 'message' => 'Only allowed on CENTRAL server.'], 403);
}
$em = $this->getDoctrine()->getManager('company_group');
$em->getConnection()->connect();
$data = json_decode($request->getContent(), true);
if (
!$data ||
!isset($data['userId']) ||
!isset($data['companyId']) ||
!isset($data['signatureData']) ||
!isset($data['approvalHash']) ||
!isset($data['applicantId'])
) {
return new JsonResponse(['success' => false, 'message' => 'Missing parameters.'], 400);
}
$userId = $data['userId'];
$companyId = $data['companyId'];
$signatureData = $data['signatureData'];
$approvalHash = $data['approvalHash'];
$applicantId = $data['applicantId'];
try {
$centralUser = $em
->getRepository("CompanyGroupBundle\\Entity\\EntityApplicantDetails")
->findOneBy(['applicantId' => $applicantId]);
if (!$centralUser) {
return new JsonResponse(['success' => false, 'message' => 'Central user not found.'], 404);
}
$userAppIds = json_decode($centralUser->getUserAppIds(), true);
if (!is_array($userAppIds)) $userAppIds = [];
$companies = $em->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findBy([
'appId' => $userAppIds
]);
if (count($companies) < 1) {
return new JsonResponse(['success' => false, 'message' => 'No companies found for userAppIds.'], 404);
}
$repo = $em->getRepository('CompanyGroupBundle\\Entity\\EntitySignature');
$record = $repo->findOneBy(['userId' => $userId]);
if (!$record) {
$record = new \CompanyGroupBundle\Entity\EntitySignature();
$record->setUserId($applicantId);
$record->setCreatedAt(new \DateTime());
}
$record->setCompanyId($companyId);
$record->setApplicantId($applicantId);
$record->setData($signatureData);
$record->setSigExists(0);
$record->setLastDecryptedSigId(0);
$record->setUpdatedAt(new \DateTime());
$em->persist($record);
$em->flush();
$dataByServerId = [];
$gocDataListByAppId = [];
foreach ($companies as $entry) {
$gocDataListByAppId[$entry->getAppId()] = [
'dbName' => $entry->getDbName(),
'dbUser' => $entry->getDbUser(),
'dbPass' => $entry->getDbPass(),
'dbHost' => $entry->getDbHost(),
'serverAddress' => $entry->getCompanyGroupServerAddress(),
'port' => $entry->getCompanyGroupServerPort() ?: 80,
'appId' => $entry->getAppId(),
'serverId' => $entry->getCompanyGroupServerId(),
];
if (!isset($dataByServerId[$entry->getCompanyGroupServerId()]))
$dataByServerId[$entry->getCompanyGroupServerId()] = array(
'serverId' => $entry->getCompanyGroupServerId(),
'serverAddress' => $entry->getCompanyGroupServerAddress(),
'port' => $entry->getCompanyGroupServerPort() ?: 80,
'payload' => array(
'globalId' => $applicantId,
'companyId' => $userAppIds,
'signatureData' => $signatureData,
// 'approvalHash' => $approvalHash
)
);
}
$urls = [];
foreach ($dataByServerId as $entry) {
$serverAddress = $entry['serverAddress'];
if (!$serverAddress) continue;
// $connector = $this->container->get('application_connector');
// $connector->resetConnection(
// 'default',
// $entry['dbName'],
// $entry['dbUser'],
// $entry['dbPass'],
// $entry['dbHost'],
// $reset = true
// );
$syncUrl = $serverAddress . '/ReceiveSignatureFromCentral';
$payload = $entry['payload'];
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_URL => $syncUrl,
// CURLOPT_PORT => $entry['port'],
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_HTTPHEADER => [
'Accept: application/json',
'Content-Type: application/json'
],
CURLOPT_POSTFIELDS => json_encode($payload)
]);
$response = curl_exec($curl);
$err = curl_error($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
// if ($err) {
// error_log("ERP Sync Error [AppID $appId]: $err");
// $urls[]=$err;
// } else {
// error_log("ERP Sync Response [AppID $appId] (HTTP $httpCode): $response");
// $res = json_decode($response, true);
// if (!isset($res['success']) || !$res['success']) {
// error_log("❗ ERP Sync error for AppID $appId: " . ($res['message'] ?? 'Unknown'));
// }
//
// $urls[]=$response;
// }
}
return new JsonResponse(['success' => true, 'message' => 'Signature synced successfully.']);
} catch (\Exception $e) {
return new JsonResponse(['success' => false, 'message' => 'DB error: ' . $e->getMessage()], 500);
}
}
public function ReceiveSignatureFromCentralAction(Request $request)
{
$data = json_decode($request->getContent(), true);
if (
!$data ||
!isset($data['globalId']) ||
!isset($data['companyId']) ||
!isset($data['signatureData'])
) {
return new JsonResponse(['success' => false, 'message' => 'Missing required fields'], 400);
}
$em_goc = $this->getDoctrine()->getManager('company_group');
$globalId = $data['globalId'];
$signatureData = $data['signatureData'];
$companyId = $data['companyId'];
$companies = $em_goc->getRepository('CompanyGroupBundle\\Entity\\CompanyGroup')->findBy([
'appId' => $companyId
]);
foreach ($companies as $entry) {
$goc = [
'dbName' => $entry->getDbName(),
'dbUser' => $entry->getDbUser(),
'dbPass' => $entry->getDbPass(),
'dbHost' => $entry->getDbHost(),
'serverAddress' => $entry->getCompanyGroupServerAddress(),
'port' => $entry->getCompanyGroupServerPort() ?: 80,
'appId' => $entry->getAppId(),
// 'serverId' => $entry->getServerId(),
];
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$goc['dbName'],
$goc['dbUser'],
$goc['dbPass'],
$goc['dbHost'],
$reset = true
);
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('ApplicationBundle\\Entity\\SysUser')->findOneBy(['globalId' => $globalId]);
if (!$user) {
return new JsonResponse(['success' => false, 'message' => 'User not found'], 404);
}
$sig = $em->getRepository('ApplicationBundle\\Entity\\EncryptedSignature')->findOneBy(['userId' => $user->getUserId()]);
if (!$sig) {
$sig = new \ApplicationBundle\Entity\EncryptedSignature();
$sig->setUserId($user->getUserId());
$sig->setData($signatureData);
$sig->setCreatedAt(new \DateTime());
}
$sig->setCompanyId($companyId);
$sig->setData($signatureData);
$sig->setSigExists(1);
$sig->setLastDecryptedSigId(0);
$sig->setUpdatedAt(new \DateTime());
$em->persist($sig);
$em->flush();
}
return new JsonResponse(['success' => true, 'message' => 'Signature updated in ERP']);
}
public function CheckSignatureHashAction(Request $request)
{
$details_ids = [];
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveHash = $request->request->get('approvalHash');
//
$retData = DocValidation::isSignatureOk($em, $loginId, $approveHash, 1);
// $this->addFlash(
// 'success',
// 'New Transaction Added.'
// );
return new JsonResponse(array(
"success" => $retData['success'],
"data" => $retData['data'],
));
}
return $this->render('@Application/pages/accounts/input_forms/payment_voucher.html.twig',
array(
'test' => $details_ids,
)
);
}
public function CheckSignatureHashForAppAction(Request $request)
{
$details_ids = [];
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveHash = $request->request->get('approvalHash');
//
$retData = DocValidation::isSignatureOk($em, $loginId, $approveHash, 1);
// $this->addFlash(
// 'success',
// 'New Transaction Added.'
// );
return new JsonResponse(array(
"success" => $retData['success'],
// "data"=>$retData['data'],
));
}
return $this->render('@Application/pages/accounts/input_forms/payment_voucher.html.twig',
array(
'test' => $details_ids,
)
);
}
public function approvalRoleAction()
{
$approvalRole = GeneralConstant::$approvalRoleList;
return new JsonResponse($approvalRole);
}
public function PendingApprovalListAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$login_id = $this->getLoggedUserLoginId($request);
$pending_data = System::getPendingApprovalListByUserLoginId($em, $login_id);
// $user_data=Users::getUserInfoByLoginId($em,$login_id);
//1st get only currently pendings
if ($request->request->has('getSummaryData'))
$pending_data = MiscActions::getSummaryData($em, $pending_data);
$pending_approval_list = $pending_data['pending_approval_list'];
$override_approval_list = $pending_data['override_approval_list'];
if ($request->request->has('returnJson')) {
return new JsonResponse(
array(
'success' => true,
'page_title' => 'View',
'override_approval_list' => $override_approval_list,
'pending_approval_list' => $pending_approval_list
// 'productByCodeData' => $productByCodeData,
// 'productData' => $productData,
// 'currInvList' => $currInvList,
// 'productList' => Inventory::ProductList($em, $companyId),
// 'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
// 'categoryList' => Inventory::ProductCategoryList($em, $companyId),
// 'igList' => Inventory::ItemGroupList($em, $companyId),
// 'unitList' => Inventory::UnitTypeList($em),
// 'brandList' => Inventory::GetBrandList($em, $companyId),
// 'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
// 'warehouseList' => Inventory::WarehouseList($em),
)
);
}
return $this->render('@System/pages/settings/my_pending_list.html.twig',
array(
'page_title' => 'View',
'override_approval_list' => $override_approval_list,
'pending_approval_list' => $pending_approval_list
)
);
}
public function getApprovalLogAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$entityId = $request->query->get('entityId');
$entity = $request->query->get('entity');
$doc = $em->getRepository('ApplicationBundle\\Entity\\' . GeneralConstant::$Entity_list[$entity])
->findOneBy(
array(
GeneralConstant::$Entity_id_field_list[$entity] => $entityId,
)
);
$log_data = [];
$data = [];
$pending_data = [];
$remaining_data = [];
$created_data = [];
$created_data['dt'] = [];
$edited_data = [];
$edited_data['dt'] = [];
if($doc) {
$set = $em->getRepository('ApplicationBundle\\Entity\\Approval')
->findBy(
array(
'entity' => $entity,
'entityId' => $entityId,
)
);
$roleType = GeneralConstant::$approvalRole;
// $approvalRoles=GeneralConstant::$approvalRoleForPrint;
//now add additional roles form dbase
$addRoles = $em->getRepository('ApplicationBundle\\Entity\\ApprovalRole')
->findBy(
array( // 'id' => $v->getSigId()
)
);
foreach ($addRoles as $addRole) {
$roleType[$addRole->getIndexId()] = $addRole->getName();
}
if ($doc->getCreatedLoginId() && $doc->getCreatedLoginId() != 0 && $doc->getCreatedLoginId() != null) {
$usrDT = Users::getUserInfoByLoginId($em, $doc->getCreatedLoginId());
if (isset($usrDT['id'])) {
$gg = Users::getUserInfoByUserId($em, $usrDT['id']);
$gg['action'] = '';
$gg['sequence'] = 0;
$gg['actionId'] = 0;
$gg['role'] = 1;
$gg['roleName'] = GeneralConstant::$approvalRole[1];
$gg['note'] = '';
$gg['current'] = 0;
$gg['loginIp'] = $usrDT['loginIp'];
$gg['dateTs'] = 1 * $doc->getCreatedAt()->format('U');
$data[] = $gg;
}
}
if ($doc->getEditedLoginId() != null && $doc->getEditedLoginId() != 0) {
$usrDT = Users::getUserInfoByLoginId($em, $doc->getEditedLoginId());
if (isset($usrDT['id'])) {
$gg = Users::getUserInfoByUserId($em, $usrDT['id']);
$gg['action'] = '';
$gg['sequence'] = 0;
$gg['actionId'] = 0;
$gg['role'] = 2;
$gg['roleName'] = GeneralConstant::$approvalRole[2];
$gg['note'] = '';
$gg['current'] = 0;
// $gg['date'] = $doc->getUpdatedAt();
$gg['loginIp'] = $usrDT['loginIp'];
$gg['dateTs'] = 1 * $doc->getUpdatedAt()->format('U');
$data[] = $gg;
}
}
// $remaining_data=[];
foreach ($roleType as $key => $value) {
$log_data[$key] = array(
'role_name' => $value,
'dt' => []
);
}
foreach ($set as $entry) {
if ($entry->getAction() == 3) {
foreach (json_decode($entry->getUserIds(), true) as $item)
if ($item != null) {
$gg = Users::getUserInfoByUserId($em, $item);
$gg['action'] = GeneralConstant::$approvalAction[$entry->getAction()];
$gg['sequence'] = 1 * $entry->getSequence();
$gg['actionId'] = 1 * $entry->getAction();
$gg['role'] = 1 * $entry->getRoleType();
$gg['roleName'] = GeneralConstant::$approvalRole[$entry->getRoleType()];
$gg['note'] = $entry->getNote();
$gg['current'] = $entry->getCurrent() == GeneralConstant::CURRENTLY_PENDING_APPROVAL ? 1 : 0;
$gg['dateTs'] = 1 * $doc->getUpdatedAt()->format('U');
$data[] = $gg;
}
} else {
$usrDT = Users::getUserInfoByLoginId($em, $doc->getCreatedLoginId());
if (isset($usrDT['id'])) {
$gg = Users::getUserInfoByUserId($em, $usrDT['id']);
$gg['action'] = GeneralConstant::$approvalAction[$entry->getAction()];
$gg['sequence'] = 1 * $entry->getSequence();
$gg['actionId'] = 1 * $entry->getAction();
$gg['role'] = 1 * $entry->getRoleType();
$gg['roleName'] = GeneralConstant::$approvalRole[$entry->getRoleType()];
$gg['note'] = $entry->getNote();
$gg['current'] = $entry->getCurrent() == GeneralConstant::CURRENTLY_PENDING_APPROVAL ? 1 : 0;
$gg['dateTs'] = 1 * $usrDT['logTime']->format('U');
$gg['loginIp'] = $usrDT['loginIp'];
$data[] = $gg;
}
}
}
}
return new JsonResponse([
"message" => !empty($data) ? "success" : "false",
"data" => empty($data) ? "No data found using the entity" : $data
]);
}
public function getDocumentDataAction(Request $request)
{
$entityListDetails = GeneralConstant::$Entity_list_details;
$entityListForApp = [];
foreach ($entityListDetails as $id => $entity) {
$entityListForApp[] = [
'id' => $id,
'entity_alias' => $entity['entity_alias'],
'imageUrl' => isset($entity['image_url']) ? $entity['image_url'] : 'app_asset/default_document.svg'
];
}
return new JsonResponse($entityListForApp);
}
public function documentSummaryAction(Request $request)
{
// No document context here, so return an empty key-facts list rather than the
// Lorem-Ipsum placeholder (mobile shows a graceful fallback). Real per-document
// rows come from pending_approval_list[i].summary. See APPROVAL_SUMMARY_FIX.md.
return new JsonResponse([]);
}
}