From 078396d5d720ae943585a65d2a3d56c54741b7e3 Mon Sep 17 00:00:00 2001 From: Thilina Hasantha Date: Mon, 8 Feb 2016 04:25:58 +0530 Subject: [PATCH] Upgrade to v15.0.OS --- core-ext/config.base.php | 6 +- core-ext/configureUIManager.php | 10 - .../icehrmdb_upgrade_v14.0.OS_v15.0.OS.sql | 45 + core-ext/login.php | 126 +- core-ext/model/models.base.php | 6 +- core-ext/scripts/icehrm_master_data.sql | 6 + core-ext/scripts/icehrmdb.sql | 13 +- .../attendance/api/AttendanceAdminManager.php | 38 + ext/admin/attendance/dashboard.html | 18 + ext/admin/attendance/meta.json | 1 + .../api/Company_structureAdminManager.php | 8 + ext/admin/company_structure/dashboard.html | 17 + ext/admin/company_structure/lib.js | 4 +- ext/admin/company_structure/meta.json | 27 +- .../dashboard/api/DashboardActionManager.php | 21 +- ext/admin/dashboard/index.php | 260 +-- ext/admin/dashboard/lib.js | 11 +- ext/admin/dashboard/meta.json | 2 +- .../employees/api/EmployeesAdminManager.php | 15 + ext/admin/employees/dashboard.html | 19 + ext/admin/employees/meta.json | 17 +- ext/admin/modules/lib.js | 6 +- ext/admin/payroll/README.txt | 7 + ext/admin/permissions/dashboard.html | 19 + ext/admin/permissions/meta.json | 17 +- .../projects/api/ProjectsAdminManager.php | 13 + ext/admin/projects/dashboard.html | 17 + ext/admin/projects/meta.json | 33 +- ext/admin/reports/dashboard.html | 17 + ext/admin/reports/index.php | 9 +- ext/admin/reports/lib.js | 44 +- ext/admin/reports/meta.json | 18 +- .../reportClasses/ActiveEmployeeReport.php | 2 +- .../EmployeeAttendanceReport.php | 2 +- .../EmployeeLeaveEntitlementReport.php | 53 + .../reportClasses/EmployeeLeavesReport.php | 70 + .../reportClasses/EmployeeTimeSheetData.php | 67 + .../reportClasses/EmployeeTimeTrackReport.php | 2 +- .../reportClasses/EmployeeTimesheetReport.php | 2 +- .../reports/reportClasses/ExpenseReport.php | 68 + .../reportClasses/NewHiresEmployeeReport.php | 2 +- .../reports/reportClasses/ReportBuilder.php | 2 +- .../TerminatedEmployeeReport.php | 2 +- .../reportClasses/TravelRequestReport.php | 69 + ext/admin/settings/dashboard.html | 17 + ext/admin/settings/index.php | 6 + ext/admin/settings/lib.js | 23 +- ext/admin/settings/meta.json | 18 +- ext/admin/travel/dashboard.html | 19 + ext/admin/travel/meta.json | 17 +- ext/admin/users/api/UsersAdminManager.php | 22 + ext/admin/users/dashboard.html | 17 + ext/admin/users/index.php | 11 +- ext/admin/users/lib.js | 44 +- ext/admin/users/meta.json | 17 +- ext/modules/attendance/dashboard.html | 17 + ext/modules/attendance/meta.json | 2 +- .../dashboard/api/DashboardActionManager.php | 119 +- ext/modules/dashboard/index.php | 213 +- ext/modules/dashboard/lib.js | 185 +- ext/modules/projects/dashboard.html | 15 + ext/modules/projects/meta.json | 2 +- .../api/Time_sheetsActionManager.php | 7 + .../api/Time_sheetsModulesManager.php | 68 + ext/modules/time_sheets/dashboard.html | 17 + ext/modules/time_sheets/lib.js | 14 +- ext/modules/time_sheets/meta.json | 1 + ext/modules/travel/dashboard.html | 17 + ext/modules/travel/meta.json | 2 +- src/api/AdapterBase.js | 19 +- src/api/Base.js | 67 +- src/api/FormValidation.js | 13 +- src/classes/AbstractModuleManager.php | 80 +- src/classes/BaseService.php | 1960 +++++++++-------- src/classes/CronUtils.php | 26 +- src/classes/EmailSender.php | 18 +- src/config.base.php | 2 +- src/configureUIManager.php | 9 + src/crons/cronRunner.php | 2 +- src/header.php | 37 +- src/images/icehrm-loader.gif | Bin 0 -> 6413 bytes src/includes.inc.php | 6 + src/js/signature_pad.js | 352 +++ src/login.php | 3 + src/model/models.base.php | 4 + src/modules.php | 19 +- src/server.includes.inc.php | 7 +- src/templates/email/emailBody.html | 2 +- src/templates/fields/signature.html | 9 + src/themecss/AdminLTE.css | 308 +++ src/utils/CalendarTools.php | 8 + 91 files changed, 3332 insertions(+), 1720 deletions(-) delete mode 100644 core-ext/configureUIManager.php create mode 100644 core-ext/db_upgrade/icehrmdb_upgrade_v14.0.OS_v15.0.OS.sql create mode 100644 ext/admin/attendance/dashboard.html create mode 100644 ext/admin/company_structure/dashboard.html create mode 100644 ext/admin/employees/dashboard.html create mode 100644 ext/admin/payroll/README.txt create mode 100644 ext/admin/permissions/dashboard.html create mode 100644 ext/admin/projects/dashboard.html create mode 100644 ext/admin/reports/dashboard.html create mode 100644 ext/admin/reports/reportClasses/EmployeeLeaveEntitlementReport.php create mode 100644 ext/admin/reports/reportClasses/EmployeeLeavesReport.php create mode 100644 ext/admin/reports/reportClasses/EmployeeTimeSheetData.php create mode 100644 ext/admin/reports/reportClasses/ExpenseReport.php create mode 100644 ext/admin/reports/reportClasses/TravelRequestReport.php create mode 100644 ext/admin/settings/dashboard.html create mode 100644 ext/admin/travel/dashboard.html create mode 100644 ext/admin/users/dashboard.html create mode 100644 ext/modules/attendance/dashboard.html create mode 100644 ext/modules/projects/dashboard.html create mode 100644 ext/modules/time_sheets/dashboard.html create mode 100644 ext/modules/travel/dashboard.html create mode 100644 src/images/icehrm-loader.gif create mode 100644 src/js/signature_pad.js create mode 100644 src/templates/fields/signature.html diff --git a/core-ext/config.base.php b/core-ext/config.base.php index 597df782..4a420dac 100644 --- a/core-ext/config.base.php +++ b/core-ext/config.base.php @@ -9,9 +9,9 @@ define('HOME_LINK_ADMIN', CLIENT_BASE_URL."?g=admin&n=dashboard&m=admin_Admin"); define('HOME_LINK_OTHERS', CLIENT_BASE_URL."?g=modules&n=dashboard&m=module_Personal_Information"); //Version -define('VERSION', '14.1.OS'); -define('CACHE_VALUE', '14.1.OS'); -define('VERSION_DATE', '26/12/2015'); +define('VERSION', '15.0.OS'); +define('CACHE_VALUE', '15.0.OS'); +define('VERSION_DATE', '07/02/2016'); if(!defined('CONTACT_EMAIL')){define('CONTACT_EMAIL','icehrm@gamonoid.com');} if(!defined('KEY_PREFIX')){define('KEY_PREFIX','IceHrm');} diff --git a/core-ext/configureUIManager.php b/core-ext/configureUIManager.php deleted file mode 100644 index 7cc7b6a5..00000000 --- a/core-ext/configureUIManager.php +++ /dev/null @@ -1,10 +0,0 @@ -setCurrentUser($user); -UIManager::getInstance()->setProfiles($profileCurrent, $profileSwitched); -UIManager::getInstance()->setHomeLink($homeLink); - -UIManager::getInstance()->addQuickAccessMenuItem("View Employees","fa-users",CLIENT_BASE_URL."?g=admin&n=employees&m=admin_Employees",array("Admin","Manager")); -UIManager::getInstance()->addQuickAccessMenuItem("Add a New Employee","fa-edit",CLIENT_BASE_URL."?g=admin&n=employees&m=admin_Employees&action=new",array("Admin")); -UIManager::getInstance()->addQuickAccessMenuItem("Manage Client/Projects","fa-list-alt",CLIENT_BASE_URL."?g=admin&n=projects&m=admin_Admin",array("Admin","Manager")); -UIManager::getInstance()->addQuickAccessMenuItem("Clocked In Employees","fa-clock-o",CLIENT_BASE_URL."?g=admin&n=attendance&m=admin_Employees#tabAttendanceStatus",array("Admin","Manager")); -UIManager::getInstance()->addQuickAccessMenuItem("Additional Modules","fa-shopping-cart","http://icehrm.com/modules.php",array("Admin")); \ No newline at end of file diff --git a/core-ext/db_upgrade/icehrmdb_upgrade_v14.0.OS_v15.0.OS.sql b/core-ext/db_upgrade/icehrmdb_upgrade_v14.0.OS_v15.0.OS.sql new file mode 100644 index 00000000..312862ae --- /dev/null +++ b/core-ext/db_upgrade/icehrmdb_upgrade_v14.0.OS_v15.0.OS.sql @@ -0,0 +1,45 @@ +ALTER table `Employees` ADD COLUMN `indirect_supervisors` VARCHAR(250) default null after `supervisor`; +ALTER table `Reports` ADD COLUMN `report_group` varchar(500) NULL; + +UPDATE Reports set report_group = 'Employee Information' where name = 'Employee Details Report'; +UPDATE Reports set report_group = 'Time Management' where name = 'Employee Time Entry Report'; +UPDATE Reports set report_group = 'Time Management' where name = 'Employee Attendance Report'; +UPDATE Reports set report_group = 'Time Management' where name = 'Employee Time Tracking Report'; +UPDATE Reports set report_group = 'Employee Information' where name = 'Active Employee Report'; +UPDATE Reports set report_group = 'Employee Information' where name = 'New Hires Employee Report'; +UPDATE Reports set report_group = 'Employee Information' where name = 'Terminated Employee Report'; +UPDATE Reports set report_group = 'Travel and Expense Management' where name = 'Travel Request Report'; +UPDATE Reports set report_group = 'Travel and Expense Management' where name = 'Expense Report'; + +INSERT INTO `Reports` (`name`, `details`, `parameters`, `query`, `paramOrder`, `type`,`report_group`) VALUES + ('Employee Time Sheet Report', 'This report list all employee time sheets by employee and date range', '[\r\n[ "employee", {"label":"Employee","type":"select2multi","allow-null":true,"null-label":"All Employees","remote-source":["Employee","id","first_name+last_name"]}],\r\n[ "date_start", {"label":"Start Date","type":"date"}],\r\n[ "date_end", {"label":"End Date","type":"date"}],\r\n[ "status", {"label":"Status","allow-null":true,"null-label":"All Status","type":"select","source":[["Approved","Approved"],["Pending","Pending"],["Rejected","Rejected"]]}]\r\n]', 'EmployeeTimeSheetData', '["employee","date_start","date_end","status"]', 'Class','Time Management'); + + + +INSERT INTO `Settings` (`name`, `value`, `description`, `meta`) VALUES +('Files: Upload Files to S3', '0', '','["value", {"label":"Value","type":"select","source":[["1","Yes"],["0","No"]]}]'), +('Files: Amazon S3 Key for File Upload', '', 'Please provide S3 Key for uploading files',''), +('Files: Amazone S3 Secret for File Upload', '', 'Please provide S3 Secret for uploading files',''), +('Files: S3 Bucket', '', 'Please provide S3 Bucket name for uploading files',''), +('Files: S3 Web Url', '', 'Please provide Url to the s3 bucket',''); + + +create table `Crons` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `name` varchar(100) NOT NULL, + `class` varchar(100) NOT NULL, + `lastrun` DATETIME default '0000-00-00 00:00:00', + `frequency` int(4) NOT NULL, + `time` varchar(50) NOT NULL, + `type` enum('Minutely','Hourly','Daily','Weekly','Monthly','Yearly') default 'Hourly', + `status` enum('Enabled','Disabled') default 'Enabled', + primary key (`id`), + key `KEY_Crons_frequency` (`frequency`) +) engine=innodb default charset=utf8; + + +INSERT INTO `Crons` (`name`,`class`, `lastrun`, `frequency`, `time`, `type`, `status`) VALUES + ('Email Sender Task', 'EmailSenderTask', NULL, 1, 1, 'Minutely', 'Enabled'), + ('Document Expire Alert', 'DocumentExpiryNotificationTask', NULL, 1, 1, 'Minutely', 'Enabled'); + + diff --git a/core-ext/login.php b/core-ext/login.php index 18925cff..3b26b28e 100644 --- a/core-ext/login.php +++ b/core-ext/login.php @@ -1,54 +1,100 @@ Load("(username = ? or email = ?) and password = ?",array($_REQUEST['username'],$_REQUEST['username'],md5($_REQUEST['password']))); - } - - if($suser->password == md5($_REQUEST['password']) || $ssoUserLoaded){ - $user = $suser; - SessionUtils::saveSessionObject('user', $user); - $suser->last_login = date("Y-m-d H:i:s"); - $suser->Save(); - - if(!$ssoUserLoaded && !empty(BaseService::getInstance()->auditManager)){ - BaseService::getInstance()->auditManager->user = $user; - BaseService::getInstance()->audit(IceConstants::AUDIT_AUTHENTICATION, "User Login"); - } - - if($user->user_level == "Admin"){ - header("Location:".HOME_LINK_ADMIN); - }else{ - header("Location:".HOME_LINK_OTHERS); - } - }else{ - header("Location:".CLIENT_BASE_URL."login.php?f=1"); - } - } + if(!empty($_REQUEST['username']) && !empty($_REQUEST['password'])){ + $suser = null; + $ssoUserLoaded = false; + + if($_REQUEST['username'] != "admin") { + LogManager::getInstance()->debug("LDAP: Enabled :" . SettingsManager::getInstance()->getSetting("LDAP: Enabled")); + if (SettingsManager::getInstance()->getSetting("LDAP: Enabled") == "1") { + $ldapResp = LDAPManager::getInstance()->checkLDAPLogin($_REQUEST['username'], $_REQUEST['password']); + LogManager::getInstance()->debug("LDAP Response :" . json_encode($ldapResp)); + if ($ldapResp->getStatus() == IceResponse::ERROR) { + header("Location:" . CLIENT_BASE_URL . "login.php?f=1"); + exit(); + } else { + $suser = new User(); + $suser->Load("username = ?", array($_REQUEST['username'])); + + if (empty($suser)) { + header("Location:" . CLIENT_BASE_URL . "login.php?f=1"); + exit(); + } + + $ssoUserLoaded = true; + } + } + } + + if(empty($suser)){ + $suser = new User(); + $suser->Load("(username = ? or email = ?) and password = ?",array($_REQUEST['username'],$_REQUEST['username'],md5($_REQUEST['password']))); + } + + if($suser->password == md5($_REQUEST['password']) || $ssoUserLoaded){ + $user = $suser; + SessionUtils::saveSessionObject('user', $user); + $suser->last_login = date("Y-m-d H:i:s"); + $suser->Save(); + + if(!$ssoUserLoaded && !empty(BaseService::getInstance()->auditManager)){ + BaseService::getInstance()->auditManager->user = $user; + BaseService::getInstance()->audit(IceConstants::AUDIT_AUTHENTICATION, "User Login"); + } + + $redirectUrl = SessionUtils::getSessionObject('loginRedirect'); + if(!empty($redirectUrl)){ + header("Location:".$redirectUrl); + }else{ + if($user->user_level == "Admin"){ + header("Location:".HOME_LINK_ADMIN); + }else{ + if(empty($user->default_module)){ + header("Location:".HOME_LINK_OTHERS); + }else{ + $defaultModule = new Module(); + $defaultModule->Load("id = ?",array($user->default_module)); + if($defaultModule->mod_group == "user"){ + $defaultModule->mod_group = "modules"; + } + $homeLink = CLIENT_BASE_URL."?g=".$defaultModule->mod_group."&n=".$defaultModule->name. + "&m=".$defaultModule->mod_group."_".str_replace(" ","_",$defaultModule->menu); + header("Location:".$homeLink); + } + } + } + }else{ + header("Location:".CLIENT_BASE_URL."login.php?f=1"); + } + } }else{ - if($user->user_level == "Admin"){ - header("Location:".HOME_LINK_ADMIN); - }else{ - header("Location:".HOME_LINK_OTHERS); - } - + if($user->user_level == "Admin"){ + header("Location:".HOME_LINK_ADMIN); + }else{ + if(empty($user->default_module)){ + header("Location:".HOME_LINK_OTHERS); + }else{ + $defaultModule = new Module(); + $defaultModule->Load("id = ?",array($user->default_module)); + if($defaultModule->mod_group == "user"){ + $defaultModule->mod_group = "modules"; + } + $homeLink = CLIENT_BASE_URL."?g=".$defaultModule->mod_group."&n=".$defaultModule->name. + "&m=".$defaultModule->mod_group."_".str_replace(" ","_",$defaultModule->menu); + header("Location:".$homeLink); + } + } + } $tuser = SessionUtils::getSessionObject('user'); //check user -$logoFileName = CLIENT_BASE_PATH."data/logo.png"; -$logoFileUrl = CLIENT_BASE_URL."data/logo.png"; -if(!file_exists($logoFileName)){ - $logoFileUrl = BASE_URL."images/logo.png"; -} +$logoFileUrl = UIManager::getInstance()->getCompanyLogoUrl(); ?> diff --git a/core-ext/model/models.base.php b/core-ext/model/models.base.php index 649a3f46..d841ba89 100644 --- a/core-ext/model/models.base.php +++ b/core-ext/model/models.base.php @@ -69,4 +69,8 @@ class ICEHRM_Record extends ADOdb_Active_Record{ return array( ); } -} \ No newline at end of file + + public function allowIndirectMapping(){ + return false; + } +} diff --git a/core-ext/scripts/icehrm_master_data.sql b/core-ext/scripts/icehrm_master_data.sql index 555a1855..526c488e 100644 --- a/core-ext/scripts/icehrm_master_data.sql +++ b/core-ext/scripts/icehrm_master_data.sql @@ -1012,6 +1012,12 @@ INSERT INTO `SalaryComponent` (`id`,`name`, `componentType`) VALUES (2,'Fixed Allowance', 1), (3,'Car Allowance', 2), (4,'Telephone Allowance', 2); + + +INSERT INTO `Crons` (`name`,`class`, `lastrun`, `frequency`, `time`, `type`, `status`) VALUES + ('Email Sender Task', 'EmailSenderTask', NULL, 1, 1, 'Minutely', 'Enabled'), + ('Document Expire Alert', 'DocumentExpiryNotificationTask', NULL, 1, 1, 'Minutely', 'Enabled'); + INSERT INTO `ExpensesPaymentMethods` (`name`) VALUES ('Cash'), ('Check'), diff --git a/core-ext/scripts/icehrmdb.sql b/core-ext/scripts/icehrmdb.sql index 65d8bbf6..6e00bf57 100644 --- a/core-ext/scripts/icehrmdb.sql +++ b/core-ext/scripts/icehrmdb.sql @@ -708,7 +708,18 @@ create table `DeductionRules` ( ) engine=innodb default charset=utf8; - +create table `Crons` ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `name` varchar(100) NOT NULL, + `class` varchar(100) NOT NULL, + `lastrun` DATETIME default '0000-00-00 00:00:00', + `frequency` int(4) NOT NULL, + `time` varchar(50) NOT NULL, + `type` enum('Minutely','Hourly','Daily','Weekly','Monthly','Yearly') default 'Hourly', + `status` enum('Enabled','Disabled') default 'Enabled', + primary key (`id`), + key `KEY_Crons_frequency` (`frequency`) +) engine=innodb default charset=utf8; create table `Emails` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, diff --git a/ext/admin/attendance/api/AttendanceAdminManager.php b/ext/admin/attendance/api/AttendanceAdminManager.php index b4957b87..51ff1893 100644 --- a/ext/admin/attendance/api/AttendanceAdminManager.php +++ b/ext/admin/attendance/api/AttendanceAdminManager.php @@ -19,6 +19,44 @@ if (!class_exists('AttendanceAdminManager')) { $this->addModelClass('Attendance'); } + public function getDashboardItemData(){ + $data = array(); + $attendance = new Attendance(); + $data['numberOfAttendanceLastWeek'] = $attendance->Count("in_time > '".date("Y-m-d H:i:s",strtotime("-1 week"))."'"); + if(empty($data['numberOfAttendanceLastWeek'])){ + $data['numberOfAttendanceLastWeek'] = 0; + } + return $data; + + } + + public function initQuickAccessMenu(){ + UIManager::getInstance()->addQuickAccessMenuItem("Clocked In Employees","fa-clock-o",CLIENT_BASE_URL."?g=admin&n=attendance&m=admin_Employees#tabAttendanceStatus",array("Admin","Manager")); + } + + } +} + +if (!class_exists('AttendanceDashboardManager')) { + + class AttendanceDashboardManager extends AbstractModuleManager{ + + public function initializeUserClasses(){ + + } + + public function initializeFieldMappings(){ + + } + + public function initializeDatabaseErrorMappings(){ + + } + + public function setupModuleClassDefinitions(){ + $this->addModelClass('Attendance'); + } + } } diff --git a/ext/admin/attendance/dashboard.html b/ext/admin/attendance/dashboard.html new file mode 100644 index 00000000..a60691c3 --- /dev/null +++ b/ext/admin/attendance/dashboard.html @@ -0,0 +1,18 @@ +
+
+
+

+ Attendance +

+

+ #_numberOfAttendanceLastWeek_# Entries Last Week +

+
+
+ +
+ + Monitor Attendance + +
+
\ No newline at end of file diff --git a/ext/admin/attendance/meta.json b/ext/admin/attendance/meta.json index aee8d48a..3e6b72b1 100644 --- a/ext/admin/attendance/meta.json +++ b/ext/admin/attendance/meta.json @@ -4,6 +4,7 @@ "order":"8", "icon":"fa-clock-o", "user_levels":["Admin","Manager"], +"dashboardPosition":5, "permissions": {} diff --git a/ext/admin/company_structure/api/Company_structureAdminManager.php b/ext/admin/company_structure/api/Company_structureAdminManager.php index 49ca0744..41cb7ea0 100644 --- a/ext/admin/company_structure/api/Company_structureAdminManager.php +++ b/ext/admin/company_structure/api/Company_structureAdminManager.php @@ -20,6 +20,14 @@ if (!class_exists('Company_structureAdminManager')) { $this->addModelClass('CompanyStructure'); } + + public function getDashboardItemData(){ + $data = array(); + $company = new CompanyStructure(); + $data['numberOfCompanyStuctures'] = $company->Count("1 = 1"); + return $data; + + } } } diff --git a/ext/admin/company_structure/dashboard.html b/ext/admin/company_structure/dashboard.html new file mode 100644 index 00000000..8398f192 --- /dev/null +++ b/ext/admin/company_structure/dashboard.html @@ -0,0 +1,17 @@ +
+ +
+
+

Company

+

+ #_numberOfCompanyStuctures_# Departments +

+
+
+ +
+ + Manage Company + +
+
\ No newline at end of file diff --git a/ext/admin/company_structure/lib.js b/ext/admin/company_structure/lib.js index 03a067f8..f5f81126 100644 --- a/ext/admin/company_structure/lib.js +++ b/ext/admin/company_structure/lib.js @@ -41,8 +41,8 @@ CompanyStructureAdapter.method('getFormFields', function() { [ "description", {"label":"Details","type":"textarea","validation":""}], [ "address", {"label":"Address","type":"textarea","validation":"none"}], [ "type", {"label":"Type","type":"select","source":[["Company","Company"],["Head Office","Head Office"],["Regional Office","Regional Office"],["Department","Department"],["Unit","Unit"],["Sub Unit","Sub Unit"],["Other","Other"]]}], - [ "country", {"label":"Country","type":"select","remote-source":["Country","code","name"]}], - [ "timezone", {"label":"Time Zone","type":"select","allow-null":false,"remote-source":["Timezone","name","details"]}], + [ "country", {"label":"Country","type":"select2","remote-source":["Country","code","name"]}], + [ "timezone", {"label":"Time Zone","type":"select2","allow-null":false,"remote-source":["Timezone","name","details"]}], [ "parent", {"label":"Parent Structure","type":"select","allow-null":true,"remote-source":["CompanyStructure","id","title"]}] ]; }); diff --git a/ext/admin/company_structure/meta.json b/ext/admin/company_structure/meta.json index 7d226ff1..747064a3 100644 --- a/ext/admin/company_structure/meta.json +++ b/ext/admin/company_structure/meta.json @@ -1,16 +1,17 @@ { -"label":"Company Structure", -"menu":"Admin", -"order":"2", -"icon":"fa-building-o", -"user_levels":["Admin","Manager"], + "label":"Company Structure", + "menu":"Admin", + "order":"2", + "icon":"fa-building-o", + "user_levels":["Admin","Manager"], + "dashboardPosition":2, -"permissions": - { - "Manager":{ - "Add Company Structure":"No", - "Edit Company Structure":"No", - "Delete Company Structure":"No" - } - } + "permissions": + { + "Manager":{ + "Add Company Structure":"No", + "Edit Company Structure":"No", + "Delete Company Structure":"No" + } + } } \ No newline at end of file diff --git a/ext/admin/dashboard/api/DashboardActionManager.php b/ext/admin/dashboard/api/DashboardActionManager.php index 755326d5..b4ed2d1e 100644 --- a/ext/admin/dashboard/api/DashboardActionManager.php +++ b/ext/admin/dashboard/api/DashboardActionManager.php @@ -40,13 +40,26 @@ class DashboardActionManager extends SubActionManager{ $attendance = new Attendance(); $data['numberOfAttendanceLastWeek'] = $attendance->Count("in_time > '".date("Y-m-d H:i:s",strtotime("-1 week"))."'"); + if(empty($data['numberOfAttendanceLastWeek'])){ + $data['numberOfAttendanceLastWeek'] = 0; + } - $data['numberOfLeaves'] = 0; + + $empLeave = new EmployeeLeave(); + $data['numberOfLeaves'] = $empLeave->Count("date_start > '".date("Y-m-d")."'"); $timeEntry = new EmployeeTimeEntry(); - $data['numberOfAttendanceLastWeek'] = $attendance->Count("in_time > '".date("Y-m-d H:i:s",strtotime("-1 week"))."'"); - - + $data['numberOfAttendanceLastWeek'] = $timeEntry->Count("in_time > '".date("Y-m-d H:i:s",strtotime("-1 week"))."'"); + + $candidate = new Candidate(); + $data['numberOfCandidates'] = $candidate->Count("1 = 1"); + + $job = new Job(); + $data['numberOfJobs'] = $job->Count("status = 'Active'"); + + $course = new Course(); + $data['numberOfCourses'] = $course->Count("1 = 1"); + return new IceResponse(IceResponse::SUCCESS,$data); } diff --git a/ext/admin/dashboard/index.php b/ext/admin/dashboard/index.php index f4246fb7..1f06e3ef 100644 --- a/ext/admin/dashboard/index.php +++ b/ext/admin/dashboard/index.php @@ -17,7 +17,7 @@ along with iCE Hrm. If not, see . ------------------------------------------------------------------ -Original work Copyright (c) 2012 [Gamonoid Media Pvt. Ltd] +Original work Copyright (c) 2012 [Gamonoid Media Pvt. Ltd] Developer: Thilina Hasantha (thilina.hasantha[at]gmail.com / facebook.com/thilinah) */ @@ -25,242 +25,48 @@ $moduleName = 'dashboard'; define('MODULE_PATH',dirname(__FILE__)); include APP_BASE_PATH.'header.php'; include APP_BASE_PATH.'modulejslibs.inc.php'; + ?>
- -
-
- -
-
-

- People -

-

- .. Employees -

-
-
- -
- - Manage Employees - -
-
-
- -
-
-

..

-

- Company Structures -

-
-
- -
- - Manage Company - -
-
-
- -
-
-

Users

-

- .. Users -

-
-
- -
- - Manage Users - -
-
-
- -
-
-

..

-

- Active Projects -

-
-
- -
- - Update Clients/Projects - -
-
+
+ getModuleManagers(); + $dashBoardList = array(); + foreach($moduleManagers as $moduleManagerObj){ -
- -
-
-

- Attendance -

-

- .. Entries Last Week -

-
-
- -
- - Monitor Attendance - -
-
-
- -
-
-

Reports

-

- View / Download Reports -

-
-
- -
- - Create a Report - -
-
-
- -
-
-

Settings

-

- Configure IceHrm -

-
-
- -
- - Update Settings - -
-
-
- -
-
-

- Travel -

-

- Requests -

-
-
- -
- - Manage Travel - -
-
-
- -
-
-

- Help -

-

- User Guide -

-
-
- -
- - Documentation - -
-
-
- -
-
-

- Purchase -

-

- Additional Modules -

-
-
- -
- - From Icehrm.com - -
-
-
+ //Check if this is not an admin module + if($moduleManagerObj->getModuleType() != 'admin'){ + continue; + } -
-
-

Why not upgrade to IceHrm Pro Version

-

- IceHrm Pro is the feature rich upgrade to IceHrm open source version. It comes with improved modules for - employee management, leave management and number of other features over open source version. - Hit this link to do a full one to one comparison. + $allowed = BaseService::getInstance()->isModuleAllowedForUser($moduleManagerObj); - Also you can learn more about IceHrm Pro here -
-
- Buy IceHrm Pro -

-
+ if(!$allowed){ + continue; + } + + $item = $moduleManagerObj->getDashboardItem(); + if(!empty($item)) { + $index = $moduleManagerObj->getDashboardItemIndex(); + $dashBoardList[$index] = $item; + } + } + + ksort($dashBoardList); + + foreach($dashBoardList as $k=>$v){ + echo $v; + } + ?>
-
- \ No newline at end of file + \ No newline at end of file diff --git a/ext/admin/dashboard/lib.js b/ext/admin/dashboard/lib.js index dedc9f53..c2bc3914 100644 --- a/ext/admin/dashboard/lib.js +++ b/ext/admin/dashboard/lib.js @@ -62,13 +62,16 @@ DashboardAdapter.method('getInitData', function() { DashboardAdapter.method('getInitDataSuccessCallBack', function(data) { $("#numberOfEmployees").html(data['numberOfEmployees']+" Employees"); - $("#numberOfCompanyStuctures").html(data['numberOfCompanyStuctures']); + $("#numberOfCompanyStuctures").html(data['numberOfCompanyStuctures']+" Departments"); $("#numberOfUsers").html(data['numberOfUsers']+" Users"); - $("#numberOfProjects").html(data['numberOfProjects']); + $("#numberOfProjects").html(data['numberOfProjects']+" Active Projects"); $("#numberOfAttendanceLastWeek").html(data['numberOfAttendanceLastWeek']+" Entries Last Week"); - $("#numberOfLeaves").html(data['numberOfLeaves']); + $("#numberOfLeaves").html(data['numberOfLeaves']+" Upcoming"); $("#numberOfTimeEntries").html(data['numberOfTimeEntries']); - + $("#numberOfCandidates").html(data['numberOfCandidates']+" Candidates"); + $("#numberOfJobs").html(data['numberOfJobs']+" Active"); + $("#numberOfCourses").html(data['numberOfCourses']+" Courses"); + }); DashboardAdapter.method('getInitDataFailCallBack', function(callBackData) { diff --git a/ext/admin/dashboard/meta.json b/ext/admin/dashboard/meta.json index 1383aecd..1c0de2e6 100644 --- a/ext/admin/dashboard/meta.json +++ b/ext/admin/dashboard/meta.json @@ -3,7 +3,7 @@ "menu":"Admin", "order":"1", "icon":"fa-desktop", -"user_levels":["Admin"], +"user_levels":["Admin","Other"], "permissions": { diff --git a/ext/admin/employees/api/EmployeesAdminManager.php b/ext/admin/employees/api/EmployeesAdminManager.php index 219156b2..aae3727b 100644 --- a/ext/admin/employees/api/EmployeesAdminManager.php +++ b/ext/admin/employees/api/EmployeesAdminManager.php @@ -20,6 +20,21 @@ if (!class_exists('EmployeesAdminManager')) { $this->addModelClass('EmploymentStatus'); } + public function getDashboardItemData(){ + $data = array(); + $emp = new Employee(); + $data['numberOfEmployees'] = $emp->Count("1 = 1"); + + return $data; + + } + + public function initQuickAccessMenu(){ + UIManager::getInstance()->addQuickAccessMenuItem("View Employees","fa-users",CLIENT_BASE_URL."?g=admin&n=employees&m=admin_Employees",array("Admin","Manager")); + UIManager::getInstance()->addQuickAccessMenuItem("Add a New Employee","fa-edit",CLIENT_BASE_URL."?g=admin&n=employees&m=admin_Employees&action=new",array("Admin")); + + } + } } diff --git a/ext/admin/employees/dashboard.html b/ext/admin/employees/dashboard.html new file mode 100644 index 00000000..74c34b49 --- /dev/null +++ b/ext/admin/employees/dashboard.html @@ -0,0 +1,19 @@ +
+ +
+
+

+ People +

+

+ #_numberOfEmployees_# Employees +

+
+
+ +
+ + Manage Employees + +
+
\ No newline at end of file diff --git a/ext/admin/employees/meta.json b/ext/admin/employees/meta.json index ac5d18ed..f3486434 100644 --- a/ext/admin/employees/meta.json +++ b/ext/admin/employees/meta.json @@ -1,11 +1,12 @@ { -"label":"Employees", -"menu":"Employees", -"order":"1", -"icon":"fa-users", -"user_levels":["Admin"], + "label":"Employees", + "menu":"Employees", + "order":"1", + "icon":"fa-users", + "user_levels":["Admin","Manager"], + "dashboardPosition":1, -"permissions": - { - } + "permissions": + { + } } \ No newline at end of file diff --git a/ext/admin/modules/lib.js b/ext/admin/modules/lib.js index ba70d1e8..a94db521 100644 --- a/ext/admin/modules/lib.js +++ b/ext/admin/modules/lib.js @@ -46,7 +46,8 @@ ModuleAdapter.method('getFormFields', function() { [ "id", {"label":"ID","type":"hidden"}], [ "label", {"label":"Label","type":"text","validation":""}], [ "status", {"label":"Status","type":"select","source":[["Enabled","Enabled"],["Disabled","Disabled"]]}], - [ "user_levels", {"label":"User Levels","type":"select2multi","source":[["Admin","Admin"],["Manager","Manager"],["Employee","Employee"],["Other","Other"]]}] + [ "user_levels", {"label":"User Levels","type":"select2multi","source":[["Admin","Admin"],["Manager","Manager"],["Employee","Employee"],["Other","Other"]]}], + [ "user_roles", {"label":"User Roles","type":"select2multi","remote-source":["UserRole","id","name"]}] ]; }); @@ -65,7 +66,8 @@ ModuleAdapter.method('getActionButtonsHtml', function(id,data) { nonEditableFields["admin_Settings"] = 1; nonEditableFields["admin_Users"] = 1; nonEditableFields["admin_Upgrade"] = 1; - + nonEditableFields["admin_Upgrade"] = 1; + nonEditableFields["user_Basic Information"] = 1; if(nonEditableFields[data[3]+"_"+data[1]] == 1){ diff --git a/ext/admin/payroll/README.txt b/ext/admin/payroll/README.txt new file mode 100644 index 00000000..0bd0cec8 --- /dev/null +++ b/ext/admin/payroll/README.txt @@ -0,0 +1,7 @@ +This module is licensed under IceHrm Commercial License, which can be found in LICENSE.txt. +You are allowed to make any modification required to these module, but only allowed to use +the module in one production server (even with modifications). + +Installation +------------ +Copy this module into /admin/ directory \ No newline at end of file diff --git a/ext/admin/permissions/dashboard.html b/ext/admin/permissions/dashboard.html new file mode 100644 index 00000000..78472904 --- /dev/null +++ b/ext/admin/permissions/dashboard.html @@ -0,0 +1,19 @@ +
+ +
+
+

+ Permission +

+

+ Management +

+
+
+ +
+ + Manage Permissions + +
+
\ No newline at end of file diff --git a/ext/admin/permissions/meta.json b/ext/admin/permissions/meta.json index a33dca1c..80e81d15 100644 --- a/ext/admin/permissions/meta.json +++ b/ext/admin/permissions/meta.json @@ -1,11 +1,12 @@ { -"label":"Manage Permissions", -"menu":"System", -"order":"4", -"icon":"fa-unlock", -"user_levels":["Admin"], + "label":"Manage Permissions", + "menu":"System", + "order":"4", + "icon":"fa-unlock", + "user_levels":["Admin"], + "dashboardPosition":15, -"permissions": - { - } + "permissions": + { + } } \ No newline at end of file diff --git a/ext/admin/projects/api/ProjectsAdminManager.php b/ext/admin/projects/api/ProjectsAdminManager.php index 72dad203..0b821429 100644 --- a/ext/admin/projects/api/ProjectsAdminManager.php +++ b/ext/admin/projects/api/ProjectsAdminManager.php @@ -21,6 +21,19 @@ if (!class_exists('ProjectsAdminManager')) { } + public function getDashboardItemData(){ + $data = array(); + $project = new Project(); + $data['numberOfProjects'] = $project->Count("status = 'Active'"); + return $data; + + } + + public function initQuickAccessMenu(){ + UIManager::getInstance()->addQuickAccessMenuItem("Manage Client/Projects","fa-list-alt",CLIENT_BASE_URL."?g=admin&n=projects&m=admin_Admin",array("Admin","Manager")); + + } + } } diff --git a/ext/admin/projects/dashboard.html b/ext/admin/projects/dashboard.html new file mode 100644 index 00000000..d6afb034 --- /dev/null +++ b/ext/admin/projects/dashboard.html @@ -0,0 +1,17 @@ +
+ +
+
+

Projects

+

+ #_numberOfProjects_# Active Projects +

+
+
+ +
+ + Update Clients/Projects + +
+
\ No newline at end of file diff --git a/ext/admin/projects/meta.json b/ext/admin/projects/meta.json index 3a566411..4405bf8a 100644 --- a/ext/admin/projects/meta.json +++ b/ext/admin/projects/meta.json @@ -1,19 +1,20 @@ { -"label":"Projects/Client Setup", -"menu":"Admin", -"order":"5", -"icon":"fa-list-alt", -"user_levels":["Admin","Manager"], + "label":"Projects/Client Setup", + "menu":"Admin", + "order":"51", + "icon":"fa-list-alt", + "user_levels":["Admin","Manager"], + "dashboardPosition":4, -"permissions": - { - "Manager":{ - "Add Projects":"Yes", - "Edit Projects":"Yes", - "Delete Projects":"No", - "Add Clients":"Yes", - "Edit Clients":"Yes", - "Delete Clients":"No" - } - } + "permissions": + { + "Manager":{ + "Add Projects":"Yes", + "Edit Projects":"Yes", + "Delete Projects":"No", + "Add Clients":"Yes", + "Edit Clients":"Yes", + "Delete Clients":"No" + } + } } \ No newline at end of file diff --git a/ext/admin/reports/dashboard.html b/ext/admin/reports/dashboard.html new file mode 100644 index 00000000..f12546d4 --- /dev/null +++ b/ext/admin/reports/dashboard.html @@ -0,0 +1,17 @@ +
+ +
+
+

Reports

+

+ View / Download Reports +

+
+
+ +
+ + Create a Report + +
+
\ No newline at end of file diff --git a/ext/admin/reports/index.php b/ext/admin/reports/index.php index 20be3dc6..cbba1fa6 100644 --- a/ext/admin/reports/index.php +++ b/ext/admin/reports/index.php @@ -19,14 +19,21 @@ include APP_BASE_PATH.'modulejslibs.inc.php';
+ \ No newline at end of file diff --git a/ext/admin/settings/lib.js b/ext/admin/settings/lib.js index 932ba801..dc649c24 100644 --- a/ext/admin/settings/lib.js +++ b/ext/admin/settings/lib.js @@ -55,6 +55,11 @@ SettingAdapter.method('getMetaFieldForRendering', function(fieldName) { return ""; }); +SettingAdapter.method('edit', function(id) { + this.loadRemoteDataForSettings(); + this.uber('edit',id); +}); + SettingAdapter.method('fillForm', function(object) { this.uber('fillForm',object); @@ -62,6 +67,22 @@ SettingAdapter.method('fillForm', function(object) { }); +SettingAdapter.method('loadRemoteDataForSettings', function () { + var field = ["country", {"label": "Country", "type": "select2", "remote-source": ["Country", "code", "name"]}]; + if (field[1]['remote-source'] != undefined && field[1]['remote-source'] != null) { + var key = field[1]['remote-source'][0] + "_" + field[1]['remote-source'][1] + "_" + field[1]['remote-source'][2]; + this.fieldMasterDataKeys[key] = false; + this.sourceMapping[field[0]] = field[1]['remote-source']; + + var callBackData = {}; + callBackData['callBack'] = 'initFieldMasterDataResponse'; + callBackData['callBackData'] = [key]; + + this.getFieldValues(field[1]['remote-source'], callBackData); + } +}); + + SettingAdapter.method('getHelpLink', function () { return 'http://blog.icehrm.com/docs/settings/'; -}); +}); \ No newline at end of file diff --git a/ext/admin/settings/meta.json b/ext/admin/settings/meta.json index 1cb09f75..f9f96685 100644 --- a/ext/admin/settings/meta.json +++ b/ext/admin/settings/meta.json @@ -1,11 +1,11 @@ { -"label":"Settings", -"menu":"System", -"order":"1", -"icon":"fa-cogs", -"user_levels":["Admin"], - -"permissions": - { - } + "label":"Settings", + "menu":"System", + "order":"1", + "icon":"fa-cogs", + "user_levels":["Admin"], + "dashboardPosition":8, + "permissions": + { + } } \ No newline at end of file diff --git a/ext/admin/travel/dashboard.html b/ext/admin/travel/dashboard.html new file mode 100644 index 00000000..1c14dc56 --- /dev/null +++ b/ext/admin/travel/dashboard.html @@ -0,0 +1,19 @@ +
+ +
+
+

+ Travel +

+

+ Requests +

+
+
+ +
+ + Manage Travel + +
+
\ No newline at end of file diff --git a/ext/admin/travel/meta.json b/ext/admin/travel/meta.json index f6ee9bd2..1ec3631a 100644 --- a/ext/admin/travel/meta.json +++ b/ext/admin/travel/meta.json @@ -1,11 +1,12 @@ { -"label":"Travel Administration", -"menu":"Employees", -"order":"6", -"icon":"fa-plane", -"user_levels":["Admin","Manager"], + "label":"Travel Administration", + "menu":"Employees", + "order":"6", + "icon":"fa-plane", + "user_levels":["Admin","Manager"], + "dashboardPosition":12, -"permissions": - { - } + "permissions": + { + } } \ No newline at end of file diff --git a/ext/admin/users/api/UsersAdminManager.php b/ext/admin/users/api/UsersAdminManager.php index 768df568..1b9a0aec 100644 --- a/ext/admin/users/api/UsersAdminManager.php +++ b/ext/admin/users/api/UsersAdminManager.php @@ -19,6 +19,14 @@ if (!class_exists('UsersAdminManager')) { $this->addModelClass('User'); } + public function getDashboardItemData(){ + $data = array(); + $user = new User(); + $data['numberOfUsers'] = $user->Count("1 = 1"); + return $data; + + } + } } @@ -53,4 +61,18 @@ if (!class_exists('User')) { var $_table = 'Users'; } +} + +if (!class_exists('UserRole')) { + class UserRole extends ICEHRM_Record { + public function getAdminAccess(){ + return array("get","element","save","delete"); + } + + public function getUserAccess(){ + return array(); + } + + var $_table = 'UserRoles'; + } } \ No newline at end of file diff --git a/ext/admin/users/dashboard.html b/ext/admin/users/dashboard.html new file mode 100644 index 00000000..d196df6f --- /dev/null +++ b/ext/admin/users/dashboard.html @@ -0,0 +1,17 @@ +
+ +
+
+

Users

+

+ #_numberOfUsers_# Users +

+
+
+ +
+ + Manage Users + +
+
\ No newline at end of file diff --git a/ext/admin/users/index.php b/ext/admin/users/index.php index 3f6d57bf..1a7e21ac 100644 --- a/ext/admin/users/index.php +++ b/ext/admin/users/index.php @@ -30,6 +30,7 @@ include APP_BASE_PATH.'modulejslibs.inc.php';
@@ -41,6 +42,14 @@ include APP_BASE_PATH.'modulejslibs.inc.php';
+
+
+ +
+ +
@@ -50,7 +59,7 @@ modJsList['tabUser'] = new UserAdapter('User'); modJsList['tabUser'].newInitObject = JSON.parse(Base64.decode('')); - +modJsList['tabUserRole'] = new UserRoleAdapter('UserRole'); var modJs = modJsList['tabUser']; diff --git a/ext/admin/users/lib.js b/ext/admin/users/lib.js index aaa08749..66e09cad 100644 --- a/ext/admin/users/lib.js +++ b/ext/admin/users/lib.js @@ -35,7 +35,9 @@ UserAdapter.method('getFormFields', function() { [ "username", {"label":"User Name","type":"text","validation":"username"}], [ "email", {"label":"Email","type":"text","validation":"email"}], [ "employee", {"label":"Employee","type":"select2","allow-null":true,"remote-source":["Employee","id","first_name+last_name"]}], - [ "user_level", {"label":"User Level","type":"select","source":[["Admin","Admin"],["Manager","Manager"],["Employee","Employee"]]}] + [ "user_level", {"label":"User Level","type":"select","source":[["Admin","Admin"],["Manager","Manager"],["Employee","Employee"],["Other","Other"]]}], + [ "user_roles", {"label":"User Roles","type":"select2multi","remote-source":["UserRole","id","name"]}], + [ "default_module", {"label":"Default Module","type":"select2","null-label":"No Default Module","allow-null":true,"remote-source":["Module","id","menu+label"]}] ]; }); @@ -62,8 +64,8 @@ UserAdapter.method('saveUserFailCallBack', function(callBackData,serverData) { UserAdapter.method('doCustomValidation', function(params) { var msg = null; - if(params['user_level'] != "Admin" && params['employee'] == "NULL"){ - msg = "For non Admin users, you have to assign an employee when adding or editing the user.
"; + if((params['user_level'] != "Admin" && params['user_level'] != "Other") && params['employee'] == "NULL"){ + msg = "For this user type, you have to assign an employee when adding or editing the user.
"; msg += " You may create a new employee through 'Admin'->'Employees' menu"; } return msg; @@ -154,9 +156,39 @@ UserAdapter.method('changePasswordFailCallBack', function(callBackData,serverDat this.showMessage("Error",callBackData); }); -UserAdapter.method('getHelpLink', function () { - return 'http://blog.icehrm.com/?page_id=132'; + + + + +/** + * UserRoleAdapter + */ + +function UserRoleAdapter(endPoint,tab,filter,orderBy) { + this.initAdapter(endPoint,tab,filter,orderBy); +} + +UserRoleAdapter.inherits(AdapterBase); + + + +UserRoleAdapter.method('getDataMapping', function() { + return [ + "id", + "name" + ]; }); +UserRoleAdapter.method('getHeaders', function() { + return [ + { "sTitle": "ID" ,"bVisible":false}, + { "sTitle": "Name"} + ]; +}); - +UserRoleAdapter.method('getFormFields', function() { + return [ + [ "id", {"label":"ID","type":"hidden"}], + [ "name", {"label":"Name","type":"text","validation":""}] + ]; +}); diff --git a/ext/admin/users/meta.json b/ext/admin/users/meta.json index 9d1a901f..e88bf380 100644 --- a/ext/admin/users/meta.json +++ b/ext/admin/users/meta.json @@ -1,11 +1,12 @@ { -"label":"Users", -"menu":"System", -"order":"2", -"icon":"fa-user", -"user_levels":["Admin"], + "label":"Users", + "menu":"System", + "order":"2", + "icon":"fa-user", + "user_levels":["Admin"], + "dashboardPosition":3, -"permissions": - { - } + "permissions": + { + } } \ No newline at end of file diff --git a/ext/modules/attendance/dashboard.html b/ext/modules/attendance/dashboard.html new file mode 100644 index 00000000..3ad0a0fc --- /dev/null +++ b/ext/modules/attendance/dashboard.html @@ -0,0 +1,17 @@ +
+ +
+
+

+ Punch In +

+

or punch out

+
+
+ +
+ + Record Attendance + +
+
\ No newline at end of file diff --git a/ext/modules/attendance/meta.json b/ext/modules/attendance/meta.json index 4f663c67..cf7433b2 100644 --- a/ext/modules/attendance/meta.json +++ b/ext/modules/attendance/meta.json @@ -4,7 +4,7 @@ "order":"2", "icon":"fa-clock-o", "user_levels":["Admin","Manager","Employee"], - + "dashboardPosition":102, "permissions": { } diff --git a/ext/modules/dashboard/api/DashboardActionManager.php b/ext/modules/dashboard/api/DashboardActionManager.php index 1a5fa324..459bb913 100644 --- a/ext/modules/dashboard/api/DashboardActionManager.php +++ b/ext/modules/dashboard/api/DashboardActionManager.php @@ -21,49 +21,82 @@ Original work Copyright (c) 2012 [Gamonoid Media Pvt. Ltd] Developer: Thilina Hasantha (thilina.hasantha[at]gmail.com / facebook.com/thilinah) */ +include (APP_BASE_PATH."modules/leaves/api/LeavesActionManager.php"); class DashboardActionManager extends SubActionManager{ - - public function getPendingLeaves($req){ - - return new IceResponse(IceResponse::SUCCESS,0); - - } - - public function getLastTimeSheetHours($req){ - $timeSheet = new EmployeeTimeSheet(); - $timeSheet->Load("employee = ? order by date_end desc limit 1",array($this->getCurrentProfileId())); - - if(empty($timeSheet->employee)){ - return new IceResponse(IceResponse::SUCCESS,"0:00"); - } - - $timeSheetEntry = new EmployeeTimeEntry(); - $list = $timeSheetEntry->Find("timesheet = ?",array($timeSheet->id)); - - $seconds = 0; - foreach($list as $entry){ - $seconds += (strtotime($entry->date_end) - strtotime($entry->date_start)); - } - - $minutes = (int)($seconds/60); - $rem = $minutes % 60; - $hours = ($minutes - $rem)/60; - if($rem < 10){ - $rem ="0".$rem; - } - return new IceResponse(IceResponse::SUCCESS,$hours.":".$rem); - - } - - public function getEmployeeActiveProjects($req){ - $project = new EmployeeProject(); - $projects = $project->Find("employee = ? and status =?",array($this->getCurrentProfileId(),'Current')); - - - return new IceResponse(IceResponse::SUCCESS,count($projects)); - - } - - + + public function getPendingLeaves($req){ + + $lam = new LeavesActionManager(); + $leavePeriod = $lam->getCurrentLeavePeriod(date("Y-m-d H:i:s"), date("Y-m-d H:i:s")); + + $leave = new EmployeeLeave(); + $pendingLeaves = $leave->Find("status = ? and employee = ?",array("Pending", $this->getCurrentProfileId())); + + return new IceResponse(IceResponse::SUCCESS,count($pendingLeaves)); + + } + + public function getInitData($req){ + $data = array(); + + $emp = new Employee(); + $data['numberOfEmployees'] = $emp->Count("status = 'Active' and supervisor = ?",array($this->getCurrentProfileId())); + + $data['lastTimeSheetHours'] = $this->getLastTimeSheetHours($req)->getData(); + $data['activeProjects'] = $this->getEmployeeActiveProjects($req)->getData(); + $data['pendingLeaves'] = $this->getPendingLeaves($req)->getData(); + $candidate = new Candidate(); + $data['numberOfCandidates'] = $candidate->Count("1 = 1"); + + $job = new Job(); + $data['numberOfJobs'] = $job->Count("status = 'Active'"); + + + $attendance = new Attendance(); + $data['numberOfAttendanceLastWeek'] = $attendance->Count("in_time > '".date("Y-m-d H:i:s",strtotime("-1 week"))."'"); + + $course = new Course(); + $data['numberOfCourses'] = $course->Count("1 = 1"); + + return new IceResponse(IceResponse::SUCCESS,$data); + + } + + public function getLastTimeSheetHours($req){ + $timeSheet = new EmployeeTimeSheet(); + $timeSheet->Load("employee = ? order by date_end desc limit 1",array($this->getCurrentProfileId())); + + if(empty($timeSheet->employee)){ + return new IceResponse(IceResponse::SUCCESS,"0:00"); + } + + $timeSheetEntry = new EmployeeTimeEntry(); + $list = $timeSheetEntry->Find("timesheet = ?",array($timeSheet->id)); + + $seconds = 0; + foreach($list as $entry){ + $seconds += (strtotime($entry->date_end) - strtotime($entry->date_start)); + } + + $minutes = (int)($seconds/60); + $rem = $minutes % 60; + $hours = ($minutes - $rem)/60; + if($rem < 10){ + $rem ="0".$rem; + } + return new IceResponse(IceResponse::SUCCESS,$hours.":".$rem); + + } + + public function getEmployeeActiveProjects($req){ + $project = new EmployeeProject(); + $projects = $project->Find("employee = ? and status =?",array($this->getCurrentProfileId(),'Current')); + + + return new IceResponse(IceResponse::SUCCESS,count($projects)); + + } + + } \ No newline at end of file diff --git a/ext/modules/dashboard/index.php b/ext/modules/dashboard/index.php index 689847bf..b7671f07 100644 --- a/ext/modules/dashboard/index.php +++ b/ext/modules/dashboard/index.php @@ -26,166 +26,41 @@ define('MODULE_PATH',dirname(__FILE__)); include APP_BASE_PATH.'header.php'; include APP_BASE_PATH.'modulejslibs.inc.php'; ?>
- -
-
- -
-
-

- .. -

-

- Waiting for Response.. -

-
-
- -
- - Record Attendance - -
-
-
- -
-
-

..

-

- Hours worked Last Week -

-
-
- -
- - Update Time Sheet - -
-
-
- -
-
-

..

-

- Active Projects -

-
-
- -
- - More info - -
-
-
- -
-
-

- My Travel -

-

- Requests -

-
-
- -
- - Travel Requests - -
-
- -
- -
-
-

- Help -

-

- User Guide -

-
-
- -
- - Documentation - -
-
- - user_level == "Manager" || $user->user_level == "Admin"){?> - -
- -
-
-

- Travel -

-

- Management -

-
-
- -
- - Manage Travel - -
-
+
-
- -
-
-

- Attendance -

-

- Monitor -

-
-
- -
- - View Attendance - -
-
- -
- -
-
-

Reports

-

- View / Download Reports -

-
-
- -
- - Create a Report - -
-
- -
+ getModuleManagers(); + $dashBoardList = array(); + foreach($moduleManagers as $moduleManagerObj){ + + $allowed = BaseService::getInstance()->isModuleAllowedForUser($moduleManagerObj); + + if(!$allowed){ + continue; + } + + $item = $moduleManagerObj->getDashboardItem(); + if(!empty($item)) { + $index = $moduleManagerObj->getDashboardItemIndex(); + $dashBoardList[$index] = $item; + } + } + + ksort($dashBoardList); + + foreach($dashBoardList as $k=>$v){ + echo $v; + } + ?> + + + + +
\ No newline at end of file diff --git a/ext/modules/dashboard/lib.js b/ext/modules/dashboard/lib.js index a14c72d0..6475d148 100644 --- a/ext/modules/dashboard/lib.js +++ b/ext/modules/dashboard/lib.js @@ -1,27 +1,27 @@ /* -This file is part of iCE Hrm. + This file is part of iCE Hrm. -iCE Hrm is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. + iCE Hrm is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. -iCE Hrm is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. + iCE Hrm is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. -You should have received a copy of the GNU General Public License -along with iCE Hrm. If not, see . + You should have received a copy of the GNU General Public License + along with iCE Hrm. If not, see . ------------------------------------------------------------------- + ------------------------------------------------------------------ -Original work Copyright (c) 2012 [Gamonoid Media Pvt. Ltd] -Developer: Thilina Hasantha (thilina.hasantha[at]gmail.com / facebook.com/thilinah) + Original work Copyright (c) 2012 [Gamonoid Media Pvt. Ltd] + Developer: Thilina Hasantha (thilina.hasantha[at]gmail.com / facebook.com/thilinah) */ function DashboardAdapter(endPoint) { - this.initAdapter(endPoint); + this.initAdapter(endPoint); } DashboardAdapter.inherits(AdapterBase); @@ -29,15 +29,15 @@ DashboardAdapter.inherits(AdapterBase); DashboardAdapter.method('getDataMapping', function() { - return []; + return []; }); DashboardAdapter.method('getHeaders', function() { - return []; + return []; }); DashboardAdapter.method('getFormFields', function() { - return []; + return []; }); @@ -46,128 +46,85 @@ DashboardAdapter.method('get', function(callBackData) { DashboardAdapter.method('getPunch', function() { - var that = this; - var object = {}; - - object['date'] = this.getClientDate(new Date()).toISOString().slice(0, 19).replace('T', ' '); - object['offset'] = this.getClientGMTOffset(); - var reqJson = JSON.stringify(object); - var callBackData = []; - callBackData['callBackData'] = []; - callBackData['callBackSuccess'] = 'getPunchSuccessCallBack'; - callBackData['callBackFail'] = 'getPunchFailCallBack'; - - this.customAction('getPunch','modules=attendance',reqJson,callBackData); + var that = this; + var object = {}; + + object['date'] = this.getClientDate(new Date()).toISOString().slice(0, 19).replace('T', ' '); + object['offset'] = this.getClientGMTOffset(); + var reqJson = JSON.stringify(object); + var callBackData = []; + callBackData['callBackData'] = []; + callBackData['callBackSuccess'] = 'getPunchSuccessCallBack'; + callBackData['callBackFail'] = 'getPunchFailCallBack'; + + this.customAction('getPunch','modules=attendance',reqJson,callBackData); }); DashboardAdapter.method('getPunchSuccessCallBack', function(callBackData) { - var punch = callBackData; - if(punch == null){ - $("#lastPunchTime").html("Not"); - $("#punchTimeText").html("Punched In"); - }else{ - $("#lastPunchTime").html(Date.parse(punch.in_time).toString('h:mm tt')); - $("#punchTimeText").html("Punched In"); - } + var punch = callBackData; + if(punch == null){ + $("#lastPunchTime").html("Not"); + $("#punchTimeText").html("Punched In"); + }else{ + $("#lastPunchTime").html(Date.parse(punch.in_time).toString('h:mm tt')); + $("#punchTimeText").html("Punched In"); + } }); DashboardAdapter.method('getPunchFailCallBack', function(callBackData) { - + }); +DashboardAdapter.method('getInitData', function() { + var that = this; + var object = {}; + var reqJson = JSON.stringify(object); + var callBackData = []; + callBackData['callBackData'] = []; + callBackData['callBackSuccess'] = 'getInitDataSuccessCallBack'; + callBackData['callBackFail'] = 'getInitDataFailCallBack'; -DashboardAdapter.method('getPendingLeaves', function() { - var that = this; - var object = {}; - - var reqJson = JSON.stringify(object); - var callBackData = []; - callBackData['callBackData'] = []; - callBackData['callBackSuccess'] = 'getPendingLeavesSuccessCallBack'; - callBackData['callBackFail'] = 'getPendingLeavesFailCallBack'; - - this.customAction('getPendingLeaves','modules=dashboard',reqJson,callBackData); + this.customAction('getInitData','modules=dashboard',reqJson,callBackData); }); -DashboardAdapter.method('getPendingLeavesSuccessCallBack', function(callBackData) { - var leaveCount = callBackData; - $("#pendingLeaveCount").html(leaveCount); +DashboardAdapter.method('getInitDataSuccessCallBack', function(data) { + + $("#timeSheetHoursWorked").html(data['lastTimeSheetHours']); + $("#numberOfProjects").html(data['activeProjects']); + $("#pendingLeaveCount").html(data['pendingLeaves']); + + $("#numberOfEmployees").html(data['numberOfEmployees']+" Subordinates"); + $("#numberOfCandidates").html(data['numberOfCandidates']+" Candidates"); + $("#numberOfJobs").html(data['numberOfJobs']+" Active"); + $("#numberOfCourses").html(data['numberOfCourses']+" Active"); + }); -DashboardAdapter.method('getPendingLeavesFailCallBack', function(callBackData) { - +DashboardAdapter.method('getInitDataFailCallBack', function(callBackData) { + }); -DashboardAdapter.method('getLastTimeSheetHours', function() { - var that = this; - var object = {}; - - var reqJson = JSON.stringify(object); - var callBackData = []; - callBackData['callBackData'] = []; - callBackData['callBackSuccess'] = 'getLastTimeSheetHoursSuccessCallBack'; - callBackData['callBackFail'] = 'getLastTimeSheetHoursFailCallBack'; - - this.customAction('getLastTimeSheetHours','modules=dashboard',reqJson,callBackData); -}); - - - -DashboardAdapter.method('getLastTimeSheetHoursSuccessCallBack', function(callBackData) { - var hours = callBackData; - $("#timeSheetHoursWorked").html(hours); -}); - -DashboardAdapter.method('getLastTimeSheetHoursFailCallBack', function(callBackData) { - -}); - - - -DashboardAdapter.method('getEmployeeActiveProjects', function() { - var that = this; - var object = {}; - - var reqJson = JSON.stringify(object); - var callBackData = []; - callBackData['callBackData'] = []; - callBackData['callBackSuccess'] = 'getEmployeeActiveProjectsSuccessCallBack'; - callBackData['callBackFail'] = 'getEmployeeActiveProjectsFailCallBack'; - - this.customAction('getEmployeeActiveProjects','modules=dashboard',reqJson,callBackData); -}); - - - -DashboardAdapter.method('getEmployeeActiveProjectsSuccessCallBack', function(callBackData) { - var hours = callBackData; - $("#numberOfProjects").html(hours); -}); - -DashboardAdapter.method('getEmployeeActiveProjectsFailCallBack', function(callBackData) { - -}); DashboardAdapter.method('getClientDate', function (date) { - var offset = this.getClientGMTOffset(); + var offset = this.getClientGMTOffset(); var tzDate = date.addMinutes(offset*60); return tzDate; }); DashboardAdapter.method('getClientGMTOffset', function () { - - var rightNow = new Date(); - var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0); - var temp = jan1.toGMTString(); - var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1)); - var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60); - - return std_time_offset; - + + var rightNow = new Date(); + var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0); + var temp = jan1.toGMTString(); + var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1)); + var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60); + + return std_time_offset; + }); diff --git a/ext/modules/projects/dashboard.html b/ext/modules/projects/dashboard.html new file mode 100644 index 00000000..41636087 --- /dev/null +++ b/ext/modules/projects/dashboard.html @@ -0,0 +1,15 @@ +
+ +
+
+

My Projects

+

Projects Assigned

+
+
+ +
+ + More info + +
+
\ No newline at end of file diff --git a/ext/modules/projects/meta.json b/ext/modules/projects/meta.json index 1bc57478..65f88b61 100644 --- a/ext/modules/projects/meta.json +++ b/ext/modules/projects/meta.json @@ -4,7 +4,7 @@ "order":"1", "icon":"fa-pencil-square", "user_levels":["Admin","Manager","Employee"], - + "dashboardPosition":105, "permissions": { "Manager":{ diff --git a/ext/modules/time_sheets/api/Time_sheetsActionManager.php b/ext/modules/time_sheets/api/Time_sheetsActionManager.php index ff66e214..cfb3227b 100644 --- a/ext/modules/time_sheets/api/Time_sheetsActionManager.php +++ b/ext/modules/time_sheets/api/Time_sheetsActionManager.php @@ -64,6 +64,13 @@ class Time_sheetsActionManager extends SubActionManager{ $oldStatus = $timeSheet->status; $timeSheet->status = $req->status; + + + //Auto approve admin timesheets + if($req->status == 'Submitted' && BaseService::getInstance()->getCurrentUser()->user_level == "Admin"){ + $timeSheet->status = 'Approved'; + } + if($oldStatus == $req->status){ return new IceResponse(IceResponse::SUCCESS,""); diff --git a/ext/modules/time_sheets/api/Time_sheetsModulesManager.php b/ext/modules/time_sheets/api/Time_sheetsModulesManager.php index df57ae83..e4424059 100644 --- a/ext/modules/time_sheets/api/Time_sheetsModulesManager.php +++ b/ext/modules/time_sheets/api/Time_sheetsModulesManager.php @@ -23,6 +23,39 @@ if (!class_exists('Time_sheetsModulesManager')) { } + public function getDashboardItemData(){ + $data = array(); + $data['timeSheetHoursWorked'] = $this->getLastTimeSheetHours()->getData(); + return $data; + + } + + private function getLastTimeSheetHours(){ + $timeSheet = new EmployeeTimeSheet(); + $timeSheet->Load("employee = ? order by date_end desc limit 1",array(BaseService::getInstance()->getCurrentProfileId())); + + if(empty($timeSheet->employee)){ + return new IceResponse(IceResponse::SUCCESS,"0:00"); + } + + $timeSheetEntry = new EmployeeTimeEntry(); + $list = $timeSheetEntry->Find("timesheet = ?",array($timeSheet->id)); + + $seconds = 0; + foreach($list as $entry){ + $seconds += (strtotime($entry->date_end) - strtotime($entry->date_start)); + } + + $minutes = (int)($seconds/60); + $rem = $minutes % 60; + $hours = ($minutes - $rem)/60; + if($rem < 10){ + $rem ="0".$rem; + } + return new IceResponse(IceResponse::SUCCESS,$hours.":".$rem); + + } + } } @@ -46,6 +79,41 @@ if (!class_exists('EmployeeTimeSheet')) { public function getUserOnlyMeAccess(){ return array("element","save","delete"); } + + public function getTotalTime() + { + + $start = $this->date_start . " 00:00:00"; + $end = $this->date_end . " 23:59:59"; + + $timeEntry = new EmployeeTimeEntry(); + $list = $timeEntry->Find("employee = ? and ((date_start >= ? and date_start <= ?) or (date_end >= ? and date_end <= ?))", array($this->employee, $start, $end, $start, $end)); + + + $seconds = 0; + + foreach ($list as $entry) { + + $secondsTemp = (strtotime($entry->date_end) - strtotime($entry->date_start)); + if ($secondsTemp < 0) { + $secondsTemp = 0; + } + + + $seconds += $secondsTemp; + } + + $totMinutes = round($seconds / 60); + $minutes = $totMinutes % 60; + $hours = ($totMinutes - $minutes) / 60; + + return CalendarTools::addLeadingZero($hours) . ":" . CalendarTools::addLeadingZero($minutes); + } + + public function postProcessGetData($entry){ + $entry->total_time = $this->getTotalTime(); + return $entry; + } } class EmployeeTimeEntry extends ICEHRM_Record { diff --git a/ext/modules/time_sheets/dashboard.html b/ext/modules/time_sheets/dashboard.html new file mode 100644 index 00000000..43b1d952 --- /dev/null +++ b/ext/modules/time_sheets/dashboard.html @@ -0,0 +1,17 @@ +
+ +
+
+

#_timeSheetHoursWorked_#

+

+ Hours worked Last Week +

+
+
+ +
+ + Update Time Sheet + +
+
\ No newline at end of file diff --git a/ext/modules/time_sheets/lib.js b/ext/modules/time_sheets/lib.js index efae5e5d..78614e06 100644 --- a/ext/modules/time_sheets/lib.js +++ b/ext/modules/time_sheets/lib.js @@ -34,6 +34,7 @@ EmployeeTimeSheetAdapter.method('getDataMapping', function() { "id", "date_start", "date_end", + "total_time", "status" ]; }); @@ -43,6 +44,7 @@ EmployeeTimeSheetAdapter.method('getHeaders', function() { { "sTitle": "ID" ,"bVisible":false}, { "sTitle": "Start Date"}, { "sTitle": "End Date"}, + { "sTitle": "Total Time"}, { "sTitle": "Status"} ]; }); @@ -533,14 +535,16 @@ EmployeeTimeEntryAdapter.method('renderForm', function(object) { //append dates - var dateStart = new Date(this.currentTimesheet.date_start.replace(" ","T")); - var dateStop = new Date(this.currentTimesheet.date_end.replace(" ","T")); + var dateStart = new Date(this.currentTimesheet.date_start); + var dateStop = new Date(this.currentTimesheet.date_end); var datesArray = this.getDates(dateStart, dateStop); var optionList = ""; for(var i=0; i'+datesArray[i].toString("d-MMM-yyyy")+''; + var k = datesArray[i]; + //optionList += ''; + optionList += ''; } @@ -665,8 +669,8 @@ EmployeeTimeEntryAdapter.method('save', function() { }); EmployeeTimeEntryAdapter.method('doCustomValidation', function(params) { - var st = Date.parse(params.date_start.replace(" ","T")); - var et = Date.parse(params.date_end.replace(" ","T")); + var st = Date.parse(params.date_start); + var et = Date.parse(params.date_end); if(st.compareTo(et) != -1){ return "Start time should be less than End time"; } diff --git a/ext/modules/time_sheets/meta.json b/ext/modules/time_sheets/meta.json index e0149e17..ed1b5ebd 100644 --- a/ext/modules/time_sheets/meta.json +++ b/ext/modules/time_sheets/meta.json @@ -4,6 +4,7 @@ "order":"3", "icon":"fa-check-circle-o", "user_levels":["Admin","Manager","Employee"], + "dashboardPosition":104, "permissions": { diff --git a/ext/modules/travel/dashboard.html b/ext/modules/travel/dashboard.html new file mode 100644 index 00000000..1bd1d87f --- /dev/null +++ b/ext/modules/travel/dashboard.html @@ -0,0 +1,17 @@ +
+ +
+
+

My Travel

+

+ Management +

+
+
+ +
+ + Travel Management + +
+
\ No newline at end of file diff --git a/ext/modules/travel/meta.json b/ext/modules/travel/meta.json index 06ea91c2..37069e21 100644 --- a/ext/modules/travel/meta.json +++ b/ext/modules/travel/meta.json @@ -4,7 +4,7 @@ "order":"1", "icon":"fa-plane", "user_levels":["Admin","Manager","Employee"], - + "dashboardPosition":107, "permissions": { "Manager":{ diff --git a/src/api/AdapterBase.js b/src/api/AdapterBase.js index 61e2960e..d00f4acb 100644 --- a/src/api/AdapterBase.js +++ b/src/api/AdapterBase.js @@ -95,13 +95,14 @@ AdapterBase.method('add', function(object,getFunctionCallBackData,callGetFunctio } $(object).attr('a','add'); $(object).attr('t',this.table); + that.showLoader(); $.post(this.moduleRelativeURL, object, function(data) { if(data.status == "SUCCESS"){ that.addSuccessCallBack(getFunctionCallBackData,data.object, callGetFunction, successCallback, that); }else{ that.addFailCallBack(getFunctionCallBackData,data.object); } - },"json"); + },"json").always(function() {that.hideLoader()}); this.trackEvent("add",this.tab,this.table); }); @@ -126,13 +127,14 @@ AdapterBase.method('addFailCallBack', function(callBackData,serverData) { AdapterBase.method('deleteObj', function(id,callBackData) { var that = this; + that.showLoader(); $.post(this.moduleRelativeURL, {'t':this.table,'a':'delete','id':id}, function(data) { if(data.status == "SUCCESS"){ that.deleteSuccessCallBack(callBackData,data.object); }else{ that.deleteFailCallBack(callBackData,data.object); } - },"json"); + },"json").always(function() {that.hideLoader()}); this.trackEvent("delete",this.tab,this.table); }); @@ -170,14 +172,15 @@ AdapterBase.method('get', function(callBackData) { sourceMappingJson = this.fixJSON(sourceMappingJson); filterJson = this.fixJSON(filterJson); - + + that.showLoader(); $.post(this.moduleRelativeURL, {'t':this.table,'a':'get','sm':sourceMappingJson,'ft':filterJson,'ob':orderBy}, function(data) { if(data.status == "SUCCESS"){ that.getSuccessCallBack(callBackData,data.object); }else{ that.getFailCallBack(callBackData,data.object); } - },"json"); + },"json").always(function() {that.hideLoader()}); that.initFieldMasterData(); @@ -274,13 +277,14 @@ AdapterBase.method('getElement', function(id,callBackData) { var that = this; var sourceMappingJson = JSON.stringify(this.getSourceMapping()); sourceMappingJson = this.fixJSON(sourceMappingJson); - $.post(this.moduleRelativeURL, {'t':this.table,'a':'getElement','id':id,'sm':sourceMappingJson}, function(data) { + that.showLoader(); + $.post(this.moduleRelativeURL, {'t':this.table,'a':'getElement','id':id,'sm':sourceMappingJson}, function(data) { if(data.status == "SUCCESS"){ that.getElementSuccessCallBack.apply(that,[callBackData,data.object]); }else{ that.getElementFailCallBack.apply(that,[callBackData,data.object]); } - },"json"); + },"json").always(function() {that.hideLoader()}); this.trackEvent("getElement",this.tab,this.table); }); @@ -361,6 +365,9 @@ AdapterBase.method('getFieldValues', function(fieldMaster,callBackData) { AdapterBase.method('setAdminProfile', function(empId) { var that = this; + try{ + localStorage.clear(); + }catch(e){} $.post(this.moduleRelativeURL, {'a':'setAdminEmp','empid':empId}, function(data) { top.location.href = clientUrl; },"json"); diff --git a/src/api/Base.js b/src/api/Base.js index 26273b1f..9628b9bd 100644 --- a/src/api/Base.js +++ b/src/api/Base.js @@ -1094,6 +1094,12 @@ IceHRMBase.method('showFilters', function(object) { }); }); + /* + $tempDomObj.find('.signatureField').each(function() { + $(this).data('signaturePad',new SignaturePad($(this))); + }); + */ + //var tHtml = $tempDomObj.wrap('
').parent().html(); this.showDomElement("Edit",$tempDomObj,null,null,true); $(".filterBtn").off(); @@ -1134,6 +1140,7 @@ IceHRMBase.method('preRenderForm', function(object) { IceHRMBase.method('renderForm', function(object) { var that = this; + var signatureIds = []; if(object == null || object == undefined){ this.currentId = null; } @@ -1200,6 +1207,12 @@ IceHRMBase.method('renderForm', function(object) { }); }); + + + $tempDomObj.find('.signatureField').each(function() { + //$(this).data('signaturePad',new SignaturePad($(this))); + signatureIds.push($(this).attr('id')); + }); for(var i=0;imoduleObject = $obj; + } + + public function getModuleObject(){ + return $this->moduleObject; + } + + public function setModuleType($type){ + $this->moduleType = $type; + } + + public function getModuleType(){ + return $this->moduleType; + } + + public function getModulePath(){ + $subClass = get_called_class(); + $reflector = new ReflectionClass($subClass); + $fn = $reflector->getFileName(); + $this->modulePath = realpath(dirname($fn)."/.."); + LogManager::getInstance()->info("Module Path: [$subClass | $fn]".$this->modulePath); + } + + public function getDashboardItemData(){ + return array(); + } public function getDashboardItem(){ - return null; + $this->getModulePath(); + if(!file_exists($this->modulePath."/dashboard.html")){ + //LogManager::getInstance()->error("Dashboard file not found :".$this->modulePath."/dashboard.html"); + return null; + } + $dashboardItem = file_get_contents($this->modulePath."/dashboard.html"); + if(empty($dashboardItem)){ + //LogManager::getInstance()->error("Dashboard file is empty :".$this->modulePath."/dashboard.html"); + return null; + } + + $data = $this->getDashboardItemData(); + $data['moduleLink'] = $this->getModuleLink(); + LogManager::getInstance()->info("Module Link:".$data['moduleLink']); + foreach($data as $k => $v){ + $dashboardItem = str_replace("#_".$k."_#", $v, $dashboardItem); + } + + return $dashboardItem; + + } + + public function getDashboardItemIndex(){ + $metaData = json_decode(file_get_contents($this->modulePath."/meta.json"),true); + if(!isset($metaData['dashboardPosition'])){ + return 100; + }else{ + return $metaData['dashboardPosition']; + } + + } + + + private function getModuleLink(){ + + $metaData = json_decode(file_get_contents($this->modulePath."/meta.json"),true); + + $mod = basename($this->modulePath); + $group = basename(realpath($this->modulePath."/..")); + + //?g=admin&n=candidates&m=admin_Recruitment + + return CLIENT_BASE_URL."?g=".$group."&n=".$mod."&m=".$group."_".str_replace(" ","_",$metaData['label']); } diff --git a/src/classes/BaseService.php b/src/classes/BaseService.php index ff73e86a..5e56cd7d 100644 --- a/src/classes/BaseService.php +++ b/src/classes/BaseService.php @@ -18,161 +18,161 @@ along with Ice Framework. If not, see . ------------------------------------------------------------------ -Original work Copyright (c) 2012 [Gamonoid Media Pvt. Ltd] +Original work Copyright (c) 2012 [Gamonoid Media Pvt. Ltd] Developer: Thilina Hasantha (thilina.hasantha[at]gmail.com / facebook.com/thilinah) */ /** - * BaseService class serves as the core logic for managing the application and for handling most + * BaseService class serves as the core logic for managing the application and for handling most * of the tasks related to retriving and saving data. This can be referred within any module using * BaseService::getInstance() - * -@class BaseService + * + @class BaseService */ class BaseService{ - - var $nonDeletables = array(); - var $errros = array(); - public $userTables = array(); - var $currentUser = null; - var $db = null; - var $auditManager = null; - var $notificationManager = null; - var $settingsManager = null; - var $fileFields = null; - var $moduleManagers = null; - var $emailSender = null; + + var $nonDeletables = array(); + var $errros = array(); + public $userTables = array(); + var $currentUser = null; + var $db = null; + var $auditManager = null; + var $notificationManager = null; + var $settingsManager = null; + var $fileFields = null; + var $moduleManagers = null; + var $emailSender = null; var $user = null; + + private static $me = null; + + private function __construct(){ + + } + + /** + * Get the only instance created for BaseService + * @method getInstance + * @return {BaseService} BaseService object + */ + + public static function getInstance(){ + if(empty(self::$me)){ + self::$me = new BaseService(); + } - private static $me = null; + return self::$me; + } + + /** + * Get an array of objects from database + * @method get + * @param $table {String} model class name of the table to retive data (e.g for Users table model class name is User) + * @param $mappingStr {String} a JSON string to specify fields of the $table should be mapped to other tables (e.g {"profile":["Profile","id","first_name+last_name"]} : this is how the profile field in Users table is mapped to Profile table. In this case users profile field will get filled by Profile first name and last name. The original value in User->profile field will get moved to User->profile_id) + * @param $filterStr {String} a JSON string to specify the ordering of the items (e.g {"job_title":"2","department":"2"} - this will select only items having job_title = 2 and department = 2) + * @param $orderBy {String} a string to specify the ordering (e.g in_time desc) + * @param string $limit {String} a string to specify the limit (e.g limit 2) + * @return {Array} an array of objects of type $table + */ + public function get($table,$mappingStr = null, $filterStr = null, $orderBy = null, $limit = null){ + + if(!empty($mappingStr)){ + $map = json_decode($mappingStr); + } + $obj = new $table(); + + $this->checkSecureAccess("get",$obj); + + $query = ""; + $queryData = array(); + if(!empty($filterStr)){ + $filter = json_decode($filterStr, true); + + if(!empty($filter)){ + foreach($filter as $k=>$v){ + LogManager::getInstance()->info($filterStr); + if($v == '__myid__'){ + $v = $this->getCurrentProfileId(); + } + $query.=" and ".$k."=?"; + $queryData[] = $v; + } + } + } + + if(empty($orderBy)){ + $orderBy = ""; + }else{ + $orderBy = " ORDER BY ".$orderBy; + } + + + if(in_array($table, $this->userTables)){ + $cemp = $this->getCurrentProfileId(); + if(!empty($cemp)){ + $signInMappingField = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME; + $list = $obj->Find($signInMappingField." = ?".$query.$orderBy, array_merge(array($cemp),$queryData)); + }else{ + $list = array(); + } + + }else{ + $list = $obj->Find("1=1".$query.$orderBy,$queryData); + } + + if(!empty($mappingStr) && count($map)>0){ + $list = $this->populateMapping($list, $map); + } - private function __construct(){ - - } - - /** - * Get the only instance created for BaseService - * @method getInstance - * @return {BaseService} BaseService object - */ - - public static function getInstance(){ - if(empty(self::$me)){ - self::$me = new BaseService(); - } - - return self::$me; - } - - /** - * Get an array of objects from database - * @method get - * @param $table {String} model class name of the table to retive data (e.g for Users table model class name is User) - * @param $mappingStr {String} a JSON string to specify fields of the $table should be mapped to other tables (e.g {"profile":["Profile","id","first_name+last_name"]} : this is how the profile field in Users table is mapped to Profile table. In this case users profile field will get filled by Profile first name and last name. The original value in User->profile field will get moved to User->profile_id) - * @param $filterStr {String} a JSON string to specify the ordering of the items (e.g {"job_title":"2","department":"2"} - this will select only items having job_title = 2 and department = 2) - * @param $orderBy {String} a string to specify the ordering (e.g in_time desc) - * @param string $limit {String} a string to specify the limit (e.g limit 2) - * @return {Array} an array of objects of type $table - */ - public function get($table,$mappingStr = null, $filterStr = null, $orderBy = null, $limit = null){ - - if(!empty($mappingStr)){ - $map = json_decode($mappingStr); - } - $obj = new $table(); - - $this->checkSecureAccess("get",$obj); - - $query = ""; - $queryData = array(); - if(!empty($filterStr)){ - $filter = json_decode($filterStr, true); - - if(!empty($filter)){ - foreach($filter as $k=>$v){ - LogManager::getInstance()->info($filterStr); + return $list; + } + + public function buildDefaultFilterQuery($filter){ + $query = ""; + $queryData = array(); + foreach($filter as $k=>$v){ + if(empty($v)){ + continue; + } + $vArr = json_decode($v); + if(is_array($vArr)){ + if(empty($vArr)){ + continue; + } + $v = $vArr; + $length = count($v); + for($i=0; $i<$length; $i++){ + $query.=$k." like ?"; + + if($i == 0){ + $query.=" and ("; + } + + if($i < $length -1){ + $query.=" or "; + }else{ + $query.=")"; + } + $queryData[] = "%".$v[$i]."%"; + } + + }else{ + if(!empty($v) && $v != 'NULL'){ + $query.=" and ".$k."=?"; if($v == '__myid__'){ $v = $this->getCurrentProfileId(); } - $query.=" and ".$k."=?"; - $queryData[] = $v; - } - } - } + $queryData[] = $v; + } + + } + + } - if(empty($orderBy)){ - $orderBy = ""; - }else{ - $orderBy = " ORDER BY ".$orderBy; - } - - - if(in_array($table, $this->userTables)){ - $cemp = $this->getCurrentProfileId(); - if(!empty($cemp)){ - $signInMappingField = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME; - $list = $obj->Find($signInMappingField." = ?".$query.$orderBy, array_merge(array($cemp),$queryData)); - }else{ - $list = array(); - } - - }else{ - $list = $obj->Find("1=1".$query.$orderBy,$queryData); - } - - if(!empty($mappingStr) && count($map)>0){ - $list = $this->populateMapping($list, $map); - } - - return $list; - } - - public function buildDefaultFilterQuery($filter){ - $query = ""; - $queryData = array(); - foreach($filter as $k=>$v){ - if(empty($v)){ - continue; - } - $vArr = json_decode($v); - if(is_array($vArr)){ - if(empty($vArr)){ - continue; - } - $v = $vArr; - $length = count($v); - for($i=0; $i<$length; $i++){ - $query.=$k." like ?"; - - if($i == 0){ - $query.=" and ("; - } - - if($i < $length -1){ - $query.=" or "; - }else{ - $query.=")"; - } - $queryData[] = "%".$v[$i]."%"; - } - - }else{ - if(!empty($v) && $v != 'NULL'){ - $query.=" and ".$k."=?"; - if($v == '__myid__'){ - $v = $this->getCurrentProfileId(); - } - $queryData[] = $v; - } - - } - - } - - return array($query, $queryData); - } + return array($query, $queryData); + } public function getSortingData($req){ @@ -187,55 +187,55 @@ class BaseService{ return $data; } + + /** + * An extention of get method for the use of data tables with ability to search + * @method getData + * @param $table {String} model class name of the table to retive data (e.g for Users table model class name is User) + * @param $mappingStr {String} a JSON string to specify fields of the $table should be mapped to other tables (e.g {"profile":["Profile","id","first_name+last_name"]} : this is how the profile field in Users table is mapped to Profile table. In this case users profile field will get filled by Profile first name and last name. The original value in User->profile field will get moved to User->profile_id) + * @param $filterStr {String} a JSON string to specify the ordering of the items (e.g {"job_title":"2","department":"2"} - this will select only items having job_title = 2 and department = 2) + * @param $orderBy {String} a string to specify the ordering (e.g in_time desc) + * @param string $limit {String} a string to specify the limit (e.g limit 2) + * @param string $searchColumns {String} a JSON string to specify names of searchable fields (e.g ["id","employee_id","first_name","last_name","mobile_phone","department","gender","supervisor"]) + * @param string $searchTerm {String} a string to specify term to search + * @param string $isSubOrdinates {Boolean} a Boolean to specify if we only need to retive subordinates. Any item is a subordinate item if the item has "profile" field defined and the value of "profile" field is equal to id of one of the subordinates of currenly logged in profile id. (Any Profile is a subordinate of curently logged in Profile if the supervisor field of a Profile is set to the id of currently logged in Profile) + * @param string $skipProfileRestriction {Boolean} default if false - TODO - I'll explain this later + * @return {Array} an array of objects of type $table + */ + public function getData($table,$mappingStr = null, $filterStr = null, $orderBy = null, $limit = null, $searchColumns = null, $searchTerm = null, $isSubOrdinates = false, $skipProfileRestriction = false, $sortData = array()){ + if(!empty($mappingStr)){ + $map = json_decode($mappingStr); + } + $obj = new $table(); + $this->checkSecureAccess("get",$obj); + $query = ""; + $queryData = array(); + if(!empty($filterStr)){ + $filter = json_decode($filterStr); + if(!empty($filter)){ + LogManager::getInstance()->debug("Building filter query"); + if(method_exists($obj,'getCustomFilterQuery')){ + LogManager::getInstance()->debug("Method: getCustomFilterQuery exists"); + $response = $obj->getCustomFilterQuery($filter); + $query = $response[0]; + $queryData = $response[1]; + }else{ + LogManager::getInstance()->debug("Method: getCustomFilterQuery not found"); + $defaultFilterResp = $this->buildDefaultFilterQuery($filter); + $query = $defaultFilterResp[0]; + $queryData = $defaultFilterResp[1]; + } + + + } - /** - * An extention of get method for the use of data tables with ability to search - * @method getData - * @param $table {String} model class name of the table to retive data (e.g for Users table model class name is User) - * @param $mappingStr {String} a JSON string to specify fields of the $table should be mapped to other tables (e.g {"profile":["Profile","id","first_name+last_name"]} : this is how the profile field in Users table is mapped to Profile table. In this case users profile field will get filled by Profile first name and last name. The original value in User->profile field will get moved to User->profile_id) - * @param $filterStr {String} a JSON string to specify the ordering of the items (e.g {"job_title":"2","department":"2"} - this will select only items having job_title = 2 and department = 2) - * @param $orderBy {String} a string to specify the ordering (e.g in_time desc) - * @param string $limit {String} a string to specify the limit (e.g limit 2) - * @param string $searchColumns {String} a JSON string to specify names of searchable fields (e.g ["id","employee_id","first_name","last_name","mobile_phone","department","gender","supervisor"]) - * @param string $searchTerm {String} a string to specify term to search - * @param string $isSubOrdinates {Boolean} a Boolean to specify if we only need to retive subordinates. Any item is a subordinate item if the item has "profile" field defined and the value of "profile" field is equal to id of one of the subordinates of currenly logged in profile id. (Any Profile is a subordinate of curently logged in Profile if the supervisor field of a Profile is set to the id of currently logged in Profile) - * @param string $skipProfileRestriction {Boolean} default if false - TODO - I'll explain this later - * @return {Array} an array of objects of type $table - */ - public function getData($table,$mappingStr = null, $filterStr = null, $orderBy = null, $limit = null, $searchColumns = null, $searchTerm = null, $isSubOrdinates = false, $skipProfileRestriction = false, $sortData = array()){ - if(!empty($mappingStr)){ - $map = json_decode($mappingStr); - } - $obj = new $table(); - $this->checkSecureAccess("get",$obj); - $query = ""; - $queryData = array(); - if(!empty($filterStr)){ - $filter = json_decode($filterStr); - if(!empty($filter)){ - LogManager::getInstance()->debug("Building filter query"); - if(method_exists($obj,'getCustomFilterQuery')){ - LogManager::getInstance()->debug("Method: getCustomFilterQuery exists"); - $response = $obj->getCustomFilterQuery($filter); - $query = $response[0]; - $queryData = $response[1]; - }else{ - LogManager::getInstance()->debug("Method: getCustomFilterQuery not found"); - $defaultFilterResp = $this->buildDefaultFilterQuery($filter); - $query = $defaultFilterResp[0]; - $queryData = $defaultFilterResp[1]; - } - - - } - - LogManager::getInstance()->debug("Filter Query:".$query); - LogManager::getInstance()->debug("Filter Query Data:".json_encode($queryData)); - } - - - if(!empty($searchTerm) && !empty($searchColumns)){ - $searchColumnList = json_decode($searchColumns); + LogManager::getInstance()->debug("Filter Query:".$query); + LogManager::getInstance()->debug("Filter Query Data:".json_encode($queryData)); + } + + + if(!empty($searchTerm) && !empty($searchColumns)){ + $searchColumnList = json_decode($searchColumns); $searchColumnList = array_diff($searchColumnList, $obj->getVirtualFields()); if(!empty($searchColumnList)){ $tempQuery = " and ("; @@ -250,7 +250,7 @@ class BaseService{ $query.= $tempQuery.")"; } - } + } if(!empty($sortData) && $sortData['sorting']."" == "1" && isset($sortData['column'])){ @@ -266,48 +266,60 @@ class BaseService{ - - if(empty($limit)){ - $limit = ""; - } - - - - if(in_array($table, $this->userTables) && !$skipProfileRestriction){ - - $cemp = $this->getCurrentProfileId(); - if(!empty($cemp)){ - if(!$isSubOrdinates){ - array_unshift($queryData, $cemp); - //$signInMappingField = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME; + + if(empty($limit)){ + $limit = ""; + } + + + + if(in_array($table, $this->userTables) && !$skipProfileRestriction){ + + $cemp = $this->getCurrentProfileId(); + if(!empty($cemp)){ + if(!$isSubOrdinates){ + array_unshift($queryData, $cemp); + //$signInMappingField = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME; $signInMappingField = $obj->getUserOnlyMeAccessField(); LogManager::getInstance()->debug("Data Load Query (x1):"."1=1".$signInMappingField." = ?".$query.$orderBy.$limit); LogManager::getInstance()->debug("Data Load Query Data (x1):".json_encode($queryData)); $list = $obj->Find($signInMappingField." = ?".$query.$orderBy.$limit, $queryData); - }else{ - $profileClass = ucfirst(SIGN_IN_ELEMENT_MAPPING_FIELD_NAME); - $subordinate = new $profileClass(); - $subordinates = $subordinate->Find("supervisor = ?",array($cemp)); - $subordinatesIds = ""; - foreach($subordinates as $sub){ - if($subordinatesIds != ""){ - $subordinatesIds.=","; + }else{ + $profileClass = ucfirst(SIGN_IN_ELEMENT_MAPPING_FIELD_NAME); + $subordinate = new $profileClass(); + $subordinates = $subordinate->Find("supervisor = ?",array($cemp)); + $subordinatesIds = ""; + foreach($subordinates as $sub){ + if($subordinatesIds != ""){ + $subordinatesIds.=","; + } + $subordinatesIds.=$sub->id; + } + + if($obj->allowIndirectMapping()){ + $indeirectEmployees = $subordinate->Find("indirect_supervisors IS NOT NULL and indirect_supervisors <> '' and status = 'Active'", array()); + foreach($indeirectEmployees as $ie){ + $indirectSupervisors = json_decode($ie->indirect_supervisors, true); + if(in_array($cemp, $indirectSupervisors)){ + if($subordinatesIds != ""){ + $subordinatesIds.=","; + } + $subordinatesIds.=$ie->id; + } } - $subordinatesIds.=$sub->id; } - $subordinatesIds.=""; - //$signInMappingField = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME; + $signInMappingField = $obj->getUserOnlyMeAccessField(); LogManager::getInstance()->debug("Data Load Query (x2):"."1=1".$signInMappingField." in (".$subordinatesIds.") ".$query.$orderBy.$limit); LogManager::getInstance()->debug("Data Load Query Data (x2):".json_encode($queryData)); - $list = $obj->Find($signInMappingField." in (".$subordinatesIds.") ".$query.$orderBy.$limit, $queryData); - } - - }else{ - $list = array(); - } - - }else if($isSubOrdinates){ + $list = $obj->Find($signInMappingField." in (".$subordinatesIds.") ".$query.$orderBy.$limit, $queryData); + } + + }else{ + $list = array(); + } + + }else if($isSubOrdinates){ $cemp = $this->getCurrentProfileId(); if(!empty($cemp)){ $profileClass = ucfirst(SIGN_IN_ELEMENT_MAPPING_FIELD_NAME); @@ -327,16 +339,16 @@ class BaseService{ }else{ $list = $obj->Find("1=1".$query.$orderBy.$limit,$queryData); } - }else{ - $list = $obj->Find("1=1".$query.$orderBy.$limit,$queryData); - } + }else{ + $list = $obj->Find("1=1".$query.$orderBy.$limit,$queryData); + } if(!$list){ LogManager::getInstance()->debug("Get Data Error:".$obj->ErrorMsg()); } - - LogManager::getInstance()->debug("Data Load Query:"."1=1".$query.$orderBy.$limit); - LogManager::getInstance()->debug("Data Load Query Data:".json_encode($queryData)); + + LogManager::getInstance()->debug("Data Load Query:"."1=1".$query.$orderBy.$limit); + LogManager::getInstance()->debug("Data Load Query Data:".json_encode($queryData)); $processedList = array(); foreach($list as $obj){ @@ -344,764 +356,798 @@ class BaseService{ } $list = $processedList; + + if(!empty($mappingStr) && count($map)>0){ + $list = $this->populateMapping($list, $map); + } + + + return $list; + } + + + /** + * Propulate field mappings for a given set of objects + * @method populateMapping + * @param $list {Array} array of model objects + * @param $map {Array} an associative array of Mappings (e.g {"profile":["Profile","id","first_name+last_name"]}) + * @return {Array} array of populated objects + */ + + public function populateMapping($list,$map){ + $listNew = array(); + if(empty($list)){ + return $listNew; + } + foreach($list as $item){ + $item = $this->populateMappingItem($item, $map); + $listNew[] = $item; + } + return $listNew; + } + + public function populateMappingItem($item,$map){ + foreach($map as $k=>$v){ + $fTable = $v[0]; + $tObj = new $fTable(); + $tObj->Load($v[1]."= ?",array($item->$k)); + + if($tObj->$v[1] == $item->$k){ + $v[2] = str_replace("+"," ",$v[2]); + $values = explode(" ", $v[2]); + if(count($values) == 1){ + $idField = $k."_id"; + $item->$idField = $item->$k; + $item->$k = $tObj->$v[2]; + + }else{ + $objVal = ""; + foreach($values as $v){ + if($objVal != ""){ + $objVal .= " "; + } + $objVal .= $tObj->$v; + } + $idField = $k."_id"; + $item->$idField = $item->$k; + $item->$k = $objVal; + } + } + } + return $item; + } + + /** + * Retive one element from db + * @method getElement + * @param $table {String} model class name of the table to get data (e.g for Users table model class name is User) + * @param $table {Integer} id of the item to get from $table + * @param $mappingStr {String} a JSON string to specify fields of the $table should be mapped to other tables (e.g {"profile":["Profile","id","first_name+last_name"]} : this is how the profile field in Users table is mapped to Profile table. In this case users profile field will get filled by Profile first name and last name. The original value in User->profile field will get moved to User->profile_id) + * @param $skipSecurityCheck {Boolean} if true won't check whether the user has access to that object + * @return {Object} an object of type $table + */ + + public function getElement($table,$id,$mappingStr = null, $skipSecurityCheck = false){ + $obj = new $table(); + + + if(in_array($table, $this->userTables)){ + $cemp = $this->getCurrentProfileId(); + if(!empty($cemp)){ + $obj->Load("id = ?", array($id)); + }else{ + } + + }else{ + $obj->Load("id = ?",array($id)); + } + + if(!$skipSecurityCheck){ + $this->checkSecureAccess("element",$obj); + } + + if(!empty($mappingStr)){ + $map = json_decode($mappingStr); + } + if($obj->id == $id){ + if(!empty($mappingStr)){ + foreach($map as $k=>$v){ + $fTable = $v[0]; + $tObj = new $fTable(); + $tObj->Load($v[1]."= ?",array($obj->$k)); + if($tObj->$v[1] == $obj->$k){ + $name = $k."_Name"; + $values = explode("+", $v[2]); + if(count($values) == 1){ + $idField = $name."_id"; + $obj->$idField = $obj->$name; + $obj->$name = $tObj->$v[2]; + }else{ + $objVal = ""; + foreach($values as $v){ + if($objVal != ""){ + $objVal .= " "; + } + $objVal .= $tObj->$v; + } + $idField = $name."_id"; + $obj->$idField = $obj->$name; + $obj->$name = $objVal; + } + } + } + } + return $obj; + } + return null; + } + + /** + * Add an element to a given table + * @method addElement + * @param $table {String} model class name of the table to add data (e.g for Users table model class name is User) + * @param $obj {Array} an associative array with field names and values for the new object. If the object id is not empty an existing object will be updated + * @return {Object} newly added or updated element of type $table + */ + + public function addElement($table,$obj){ + $isAdd = true; + $ele = new $table(); + if(class_exists("ProVersion")){ + $pro = new ProVersion(); + $subscriptionTables = $pro->getSubscriptionTables(); + if(in_array($table,$subscriptionTables)){ + $resp = $pro->subscriptionCheck($obj); + if($resp->getStatus() != IceResponse::SUCCESS){ + return $resp; + } + } + } + + if(!empty($obj['id'])){ + $isAdd = false; + $ele->Load('id = ?',array($obj['id'])); + } + + foreach($obj as $k=>$v){ + if($k == 'id' || $k == 't' || $k == 'a'){ + continue; + } + if($v == "NULL"){ + $v = null; + } + $ele->$k = $v; + } + + + if(empty($obj['id'])){ + if(in_array($table, $this->userTables)){ + $cemp = $this->getCurrentProfileId(); + if(!empty($cemp)){ + $signInMappingField = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME; + $ele->$signInMappingField = $cemp; + }else{ + return new IceResponse(IceResponse::ERROR,"Profile id is not set"); + } + } + } + + $this->checkSecureAccess("save",$ele); + + $resp =$ele->validateSave($ele); + if($resp->getStatus() != IceResponse::SUCCESS){ + return $resp; + } + + if($isAdd){ + if(empty($ele->created)){ + $ele->created = date("Y-m-d H:i:s"); + } + } + + if(empty($ele->updated)){ + $ele->updated = date("Y-m-d H:i:s"); + } + if($isAdd){ + $ele = $ele->executePreSaveActions($ele)->getData(); + }else{ + $ele = $ele->executePreUpdateActions($ele)->getData(); + } + + + $ok = $ele->Save(); + if(!$ok){ + + $error = $ele->ErrorMsg(); + + LogManager::getInstance()->info($error); + + if($isAdd){ + $this->audit(IceConstants::AUDIT_ERROR, "Error occured while adding an object to ".$table." \ Error: ".$error); + }else{ + $this->audit(IceConstants::AUDIT_ERROR, "Error occured while editing an object in ".$table." [id:".$ele->id."] \ Error: ".$error); + } + return new IceResponse(IceResponse::ERROR,$this->findError($error)); + } + + if($isAdd){ + $ele->executePostSaveActions($ele); + $this->audit(IceConstants::AUDIT_ADD, "Added an object to ".$table." [id:".$ele->id."]"); + }else{ + $ele->executePostUpdateActions($ele); + $this->audit(IceConstants::AUDIT_EDIT, "Edited an object in ".$table." [id:".$ele->id."]"); + } + + return new IceResponse(IceResponse::SUCCESS,$ele); + } + + /** + * Delete an element if not the $table and $id is defined as a non deletable + * @method deleteElement + * @param $table {String} model class name of the table to delete data (e.g for Users table model class name is User) + * @param $id {Integer} id of the item to delete + * @return NULL + */ + public function deleteElement($table,$id){ + $fileFields = $this->fileFields; + $ele = new $table(); + + $ele->Load('id = ?',array($id)); - if(!empty($mappingStr) && count($map)>0){ - $list = $this->populateMapping($list, $map); - } + $this->checkSecureAccess("delete",$ele); + + if(isset($this->nonDeletables[$table])){ + $nonDeletableTable = $this->nonDeletables[$table]; + if(!empty($nonDeletableTable)){ + foreach($nonDeletableTable as $field => $value){ + if($ele->$field == $value){ + return "This item can not be deleted"; + } + } + } + } + $ok = $ele->Delete(); + if(!$ok){ + $error = $ele->ErrorMsg(); + LogManager::getInstance()->info($error); + return $this->findError($error); + }else{ + //Backup + if($table == "Profile"){ + $newObj = $this->cleanUpAdoDB($ele); + $dataEntryBackup = new DataEntryBackup(); + $dataEntryBackup->tableType = $table; + $dataEntryBackup->data = json_encode($newObj); + $dataEntryBackup->Save(); + } + + $this->audit(IceConstants::AUDIT_DELETE, "Deleted an object in ".$table." [id:".$ele->id."]"); + } + + + + if(isset($fileFields[$table])){ + foreach($fileFields[$table] as $k=>$v){ + if(!empty($ele->$k)){ + FileService::getInstance()->deleteFileByField($ele->$k,$v); + } + + } + } + + return null; + } + + /** + * Get associative array of by retriving data from $table using $key field ans key and $value field as value. Mainly used for getting data for populating option lists of select boxes when adding and editing items + * @method getFieldValues + * @param $table {String} model class name of the table to get data (e.g for Users table model class name is User) + * @param $key {String} key field name + * @param $value {String} value field name (multiple fileds cam be concatinated using +) - e.g first_name+last_name + * @param $method {String} if not empty, use this menthod to get only a selected set of objects from db instead of retriving all objects. This method should be defined in class $table and should return an array of objects of type $table + * @return {Array} associative array + */ + + public function getFieldValues($table,$key,$value,$method,$methodParams = NULL){ + + $values = explode("+", $value); + + $ret = array(); + $ele = new $table(); + if(!empty($method)){ + LogManager::getInstance()->debug("Call method for getFieldValues:".$method); + LogManager::getInstance()->debug("Call method params for getFieldValues:".json_decode($methodParams)); + if(method_exists($ele,$method)){ + if(!empty($methodParams)){ + $list = $ele->$method(json_decode($methodParams)); + }else{ + $list = $ele->$method(array()); + } + }else{ + LogManager::getInstance()->debug("Could not find method:".$method." in Class:".$table); + $list = $ele->Find('1 = 1',array()); + } + + }else{ + $list = $ele->Find('1 = 1',array()); + } + + foreach($list as $obj){ + if(count($values) == 1){ + $ret[$obj->$key] = $obj->$value; + }else{ + $objVal = ""; + foreach($values as $v){ + if($objVal != ""){ + $objVal .= " "; + } + $objVal .= $obj->$v; + } + $ret[$obj->$key] = $objVal; + } + } + return $ret; + } + + public function setNonDeletables($table, $field, $value){ + if(!isset($this->nonDeletables[$table])){ + $this->nonDeletables[$table] = array(); + } + $this->nonDeletables[$table][$field] = $value; + } + + public function setSqlErrors($errros){ + $this->errros = $errros; + } + + public function setUserTables($userTables){ + $this->userTables = $userTables; + } + + /** + * Set the current logged in user + * @method setCurrentUser + * @param $currentUser {User} the current logged in user + * @return None + */ + + public function setCurrentUser($currentUser){ + $this->currentUser = $currentUser; + } + - return $list; - } - - - /** - * Propulate field mappings for a given set of objects - * @method populateMapping - * @param $list {Array} array of model objects - * @param $map {Array} an associative array of Mappings (e.g {"profile":["Profile","id","first_name+last_name"]}) - * @return {Array} array of populated objects - */ - - public function populateMapping($list,$map){ - $listNew = array(); - if(empty($list)){ - return $listNew; - } - foreach($list as $item){ - $item = $this->populateMappingItem($item, $map); - $listNew[] = $item; - } - return $listNew; - } - - public function populateMappingItem($item,$map){ - foreach($map as $k=>$v){ - $fTable = $v[0]; - $tObj = new $fTable(); - $tObj->Load($v[1]."= ?",array($item->$k)); - - if($tObj->$v[1] == $item->$k){ - $v[2] = str_replace("+"," ",$v[2]); - $values = explode(" ", $v[2]); - if(count($values) == 1){ - $idField = $k."_id"; - $item->$idField = $item->$k; - $item->$k = $tObj->$v[2]; - - }else{ - $objVal = ""; - foreach($values as $v){ - if($objVal != ""){ - $objVal .= " "; - } - $objVal .= $tObj->$v; - } - $idField = $k."_id"; - $item->$idField = $item->$k; - $item->$k = $objVal; - } - } - } - return $item; - } - - /** - * Retive one element from db - * @method getElement - * @param $table {String} model class name of the table to get data (e.g for Users table model class name is User) - * @param $table {Integer} id of the item to get from $table - * @param $mappingStr {String} a JSON string to specify fields of the $table should be mapped to other tables (e.g {"profile":["Profile","id","first_name+last_name"]} : this is how the profile field in Users table is mapped to Profile table. In this case users profile field will get filled by Profile first name and last name. The original value in User->profile field will get moved to User->profile_id) - * @param $skipSecurityCheck {Boolean} if true won't check whether the user has access to that object - * @return {Object} an object of type $table - */ - - public function getElement($table,$id,$mappingStr = null, $skipSecurityCheck = false){ - $obj = new $table(); - - - if(in_array($table, $this->userTables)){ - $cemp = $this->getCurrentProfileId(); - if(!empty($cemp)){ - $obj->Load("id = ?", array($id)); - }else{ - } - - }else{ - $obj->Load("id = ?",array($id)); - } - - if(!$skipSecurityCheck){ - $this->checkSecureAccess("element",$obj); - } - - if(!empty($mappingStr)){ - $map = json_decode($mappingStr); - } - if($obj->id == $id){ - if(!empty($mappingStr)){ - foreach($map as $k=>$v){ - $fTable = $v[0]; - $tObj = new $fTable(); - $tObj->Load($v[1]."= ?",array($obj->$k)); - if($tObj->$v[1] == $obj->$k){ - $name = $k."_Name"; - $values = explode("+", $v[2]); - if(count($values) == 1){ - $idField = $name."_id"; - $obj->$idField = $obj->$name; - $obj->$name = $tObj->$v[2]; - }else{ - $objVal = ""; - foreach($values as $v){ - if($objVal != ""){ - $objVal .= " "; - } - $objVal .= $tObj->$v; - } - $idField = $name."_id"; - $obj->$idField = $obj->$name; - $obj->$name = $objVal; - } - } - } - } - return $obj; - } - return null; - } - - /** - * Add an element to a given table - * @method addElement - * @param $table {String} model class name of the table to add data (e.g for Users table model class name is User) - * @param $obj {Array} an associative array with field names and values for the new object. If the object id is not empty an existing object will be updated - * @return {Object} newly added or updated element of type $table - */ - - public function addElement($table,$obj){ - $isAdd = true; - $ele = new $table(); - if(class_exists("ProVersion")){ - $pro = new ProVersion(); - $subscriptionTables = $pro->getSubscriptionTables(); - if(in_array($table,$subscriptionTables)){ - $resp = $pro->subscriptionCheck($obj); - if($resp->getStatus() != IceResponse::SUCCESS){ - return $resp; - } - } - } - - if(!empty($obj['id'])){ - $isAdd = false; - $ele->Load('id = ?',array($obj['id'])); - } - - foreach($obj as $k=>$v){ - if($k == 'id' || $k == 't' || $k == 'a'){ - continue; - } - if($v == "NULL"){ - $v = null; - } - $ele->$k = $v; - } - - - if(empty($obj['id'])){ - if(in_array($table, $this->userTables)){ - $cemp = $this->getCurrentProfileId(); - if(!empty($cemp)){ - $signInMappingField = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME; - $ele->$signInMappingField = $cemp; - }else{ - return new IceResponse(IceResponse::ERROR,"Profile id is not set"); - } - } - } - - $this->checkSecureAccess("save",$ele); - - $resp =$ele->validateSave($ele); - if($resp->getStatus() != IceResponse::SUCCESS){ - return $resp; - } - - if($isAdd){ - if(empty($ele->created)){ - $ele->created = date("Y-m-d H:i:s"); - } - } - - if(empty($ele->updated)){ - $ele->updated = date("Y-m-d H:i:s"); - } - if($isAdd){ - $ele = $ele->executePreSaveActions($ele)->getData(); - }else{ - $ele = $ele->executePreUpdateActions($ele)->getData(); - } - - - $ok = $ele->Save(); - if(!$ok){ - - $error = $ele->ErrorMsg(); - - LogManager::getInstance()->info($error); - - if($isAdd){ - $this->audit(IceConstants::AUDIT_ERROR, "Error occured while adding an object to ".$table." \ Error: ".$error); - }else{ - $this->audit(IceConstants::AUDIT_ERROR, "Error occured while editing an object in ".$table." [id:".$ele->id."] \ Error: ".$error); - } - return new IceResponse(IceResponse::ERROR,$this->findError($error)); - } - - if($isAdd){ - $ele->executePostSaveActions($ele); - $this->audit(IceConstants::AUDIT_ADD, "Added an object to ".$table." [id:".$ele->id."]"); - }else{ - $ele->executePostUpdateActions($ele); - $this->audit(IceConstants::AUDIT_EDIT, "Edited an object in ".$table." [id:".$ele->id."]"); - } - - return new IceResponse(IceResponse::SUCCESS,$ele); - } - - /** - * Delete an element if not the $table and $id is defined as a non deletable - * @method deleteElement - * @param $table {String} model class name of the table to delete data (e.g for Users table model class name is User) - * @param $id {Integer} id of the item to delete - * @return NULL - */ - public function deleteElement($table,$id){ - $fileFields = $this->fileFields; - $ele = new $table(); - - $ele->Load('id = ?',array($id)); - - $this->checkSecureAccess("delete",$ele); - - if(isset($this->nonDeletables[$table])){ - $nonDeletableTable = $this->nonDeletables[$table]; - if(!empty($nonDeletableTable)){ - foreach($nonDeletableTable as $field => $value){ - if($ele->$field == $value){ - return "This item can not be deleted"; - } - } - } - } - - $ok = $ele->Delete(); - if(!$ok){ - $error = $ele->ErrorMsg(); - LogManager::getInstance()->info($error); - return $this->findError($error); - }else{ - //Backup - if($table == "Profile"){ - $newObj = $this->cleanUpAdoDB($ele); - $dataEntryBackup = new DataEntryBackup(); - $dataEntryBackup->tableType = $table; - $dataEntryBackup->data = json_encode($newObj); - $dataEntryBackup->Save(); - } - - $this->audit(IceConstants::AUDIT_DELETE, "Deleted an object in ".$table." [id:".$ele->id."]"); - } - - - - if(isset($fileFields[$table])){ - foreach($fileFields[$table] as $k=>$v){ - if(!empty($ele->$k)){ - FileService::getInstance()->deleteFileByField($ele->$k,$v); - } - - } - } - - return null; - } - - /** - * Get associative array of by retriving data from $table using $key field ans key and $value field as value. Mainly used for getting data for populating option lists of select boxes when adding and editing items - * @method getFieldValues - * @param $table {String} model class name of the table to get data (e.g for Users table model class name is User) - * @param $key {String} key field name - * @param $value {String} value field name (multiple fileds cam be concatinated using +) - e.g first_name+last_name - * @param $method {String} if not empty, use this menthod to get only a selected set of objects from db instead of retriving all objects. This method should be defined in class $table and should return an array of objects of type $table - * @return {Array} associative array - */ - - public function getFieldValues($table,$key,$value,$method,$methodParams = NULL){ - - $values = explode("+", $value); - - $ret = array(); - $ele = new $table(); - if(!empty($method)){ - LogManager::getInstance()->debug("Call method for getFieldValues:".$method); - LogManager::getInstance()->debug("Call method params for getFieldValues:".json_decode($methodParams)); - if(method_exists($ele,$method)){ - if(!empty($methodParams)){ - $list = $ele->$method(json_decode($methodParams)); - }else{ - $list = $ele->$method(array()); - } - }else{ - LogManager::getInstance()->debug("Could not find method:".$method." in Class:".$table); - $list = $ele->Find('1 = 1',array()); - } - - }else{ - $list = $ele->Find('1 = 1',array()); - } - - foreach($list as $obj){ - if(count($values) == 1){ - $ret[$obj->$key] = $obj->$value; - }else{ - $objVal = ""; - foreach($values as $v){ - if($objVal != ""){ - $objVal .= " "; - } - $objVal .= $obj->$v; - } - $ret[$obj->$key] = $objVal; - } - } - return $ret; - } - - public function setNonDeletables($table, $field, $value){ - if(!isset($this->nonDeletables[$table])){ - $this->nonDeletables[$table] = array(); - } - $this->nonDeletables[$table][$field] = $value; - } - - public function setSqlErrors($errros){ - $this->errros = $errros; - } - - public function setUserTables($userTables){ - $this->userTables = $userTables; - } - - /** - * Set the current logged in user - * @method setCurrentUser - * @param $currentUser {User} the current logged in user - * @return None - */ - - public function setCurrentUser($currentUser){ - $this->currentUser = $currentUser; - } - - - public function findError($error){ - foreach($this->errros as $k=>$v){ - if(strstr($error, $k)){ - return $v; - }else{ - $keyParts = explode("|", $k); - if(count($keyParts) >= 2){ - if(strstr($error, $keyParts[0]) && strstr($error, $keyParts[1])){ - return $v; - } - } - } - } - return $error; - } - - /** - * Get the currently logged in user from session - * @method getCurrentUser - * @return {User} currently logged in user from session - */ - - public function getCurrentUser(){ + public function findError($error){ + foreach($this->errros as $k=>$v){ + if(strstr($error, $k)){ + return $v; + }else{ + $keyParts = explode("|", $k); + if(count($keyParts) >= 2){ + if(strstr($error, $keyParts[0]) && strstr($error, $keyParts[1])){ + return $v; + } + } + } + } + return $error; + } + + /** + * Get the currently logged in user from session + * @method getCurrentUser + * @return {User} currently logged in user from session + */ + + public function getCurrentUser(){ if(!empty($this->currentUser)){ return $this->currentUser; } - $user = SessionUtils::getSessionObject('user'); - return $user; - } + $user = SessionUtils::getSessionObject('user'); + return $user; + } + + /** + * Get the Profile id attached to currently logged in user. if the user is switched, this will return the id of switched Profile instead of currently logged in users Prifile id + * @method getCurrentProfileId + * @return {Integer} + */ + public function getCurrentProfileId(){ + if (!class_exists('SessionUtils')) { + include (APP_BASE_PATH."include.common.php"); + } + $adminEmpId = SessionUtils::getSessionObject('admin_current_profile'); + $user = SessionUtils::getSessionObject('user'); + if(empty($adminEmpId) && !empty($user)){ + $signInMappingField = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME; + return $user->$signInMappingField; + } + return $adminEmpId; + } + + /** + * Get User by profile id + * @method getUserFromProfileId + * @param $profileId {Integer} profile id + * @return {User} user object + */ + + public function getUserFromProfileId($profileId){ + $user = new User(); + $signInMappingField = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME; + $user->load($signInMappingField." = ?",array($profileId)); + if($user->$signInMappingField == $profileId){ + return $user; + } + return null; + } - /** - * Get the Profile id attached to currently logged in user. if the user is switched, this will return the id of switched Profile instead of currently logged in users Prifile id - * @method getCurrentProfileId - * @return {Integer} - */ - public function getCurrentProfileId(){ - if (!class_exists('SessionUtils')) { - include (APP_BASE_PATH."include.common.php"); - } - $adminEmpId = SessionUtils::getSessionObject('admin_current_profile'); - $user = SessionUtils::getSessionObject('user'); - if(empty($adminEmpId) && !empty($user)){ - $signInMappingField = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME; - return $user->$signInMappingField; - } - return $adminEmpId; - } - - /** - * Get User by profile id - * @method getUserFromProfileId - * @param $profileId {Integer} profile id - * @return {User} user object - */ - - public function getUserFromProfileId($profileId){ - $user = new User(); - $signInMappingField = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME; - $user->load($signInMappingField." = ?",array($profileId)); - if($user->$signInMappingField == $profileId){ - return $user; - } - return null; - } - - - public function setCurrentAdminProfile($profileId){ - if (!class_exists('SessionUtils')) { - include (APP_BASE_PATH."include.common.php"); - } - - if($profileId == "-1"){ - SessionUtils::saveSessionObject('admin_current_profile',null); - return; - } - - if($this->currentUser->user_level == 'Admin'){ - SessionUtils::saveSessionObject('admin_current_profile',$profileId); - - }else if($this->currentUser->user_level == 'Manager'){ - $signInMappingField = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME; - $signInMappingFieldTable = ucfirst($signInMappingField); - $subordinate = new $signInMappingFieldTable(); - $signInMappingField = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME; - $subordinates = $subordinate->Find("supervisor = ?",array($this->currentUser->$signInMappingField)); - $subFound = false; - foreach($subordinates as $sub){ - if($sub->id == $profileId){ - $subFound = true; - break; - } - } - - if(!$subFound){ - return; - } - - SessionUtils::saveSessionObject('admin_current_profile',$profileId); - - } - } - - public function cleanUpAdoDB($obj){ - unset($obj->_table); - unset($obj->_dbat); - unset($obj->_tableat); - unset($obj->_where); - unset($obj->_saved); - unset($obj->_lasterr); - unset($obj->_original); - unset($obj->foreignName); - - return $obj; - } - - public function setDB($db){ - $this->db = $db; - } - - public function getDB(){ - return $this->db; - } - - public function checkSecureAccessOld($type,$object){ - - $accessMatrix = array(); - if($this->currentUser->user_level == 'Admin'){ - $accessMatrix = $object->getAdminAccess(); - if (in_array($type, $accessMatrix)) { - return true; - } - }else if($this->currentUser->user_level == 'Manager'){ - $accessMatrix = $object->getManagerAccess(); - if (in_array($type, $accessMatrix)) { - return true; - }else{ - $accessMatrix = $object->getUserOnlyMeAccess(); - $signInMappingField = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME; - if (in_array($type, $accessMatrix) && $_REQUEST[$object->getUserOnlyMeAccessField()] == $this->currentUser->$signInMappingField) { - return true; - } - - if (in_array($type, $accessMatrix)) { - - $field = $object->getUserOnlyMeAccessField(); - $signInMappingField = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME; - if($this->currentUser->$signInMappingField."" == $object->$field){ - return true; - } - - } - } - - }else{ - $accessMatrix = $object->getUserAccess(); - if (in_array($type, $accessMatrix)) { - return true; - }else{ - $accessMatrix = $object->getUserOnlyMeAccess(); - $signInMappingField = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME; - if (in_array($type, $accessMatrix) && $_REQUEST[$object->getUserOnlyMeAccessField()] == $this->currentUser->$signInMappingField) { - return true; - } - - if (in_array($type, $accessMatrix)) { - - $field = $object->getUserOnlyMeAccessField(); - $signInMappingField = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME; - if($this->currentUser->$signInMappingField."" == $object->$field){ - return true; - } - - } - } - } - - $ret['status'] = "ERROR"; - $ret['message'] = "Access violation"; - echo json_encode($ret); - exit(); - } - - /** - * Use user level security functions defined in model classes to check whether a given action type is allowed to be executed by the current user on a given object - * @method checkSecureAccess - * @param $type {String} Action type - * @param $object {Object} object to test access - * @return {Boolen} true or exit - */ - - public function checkSecureAccess($type,$object){ + + public function setCurrentAdminProfile($profileId){ + if (!class_exists('SessionUtils')) { + include (APP_BASE_PATH."include.common.php"); + } + + if($profileId == "-1"){ + SessionUtils::saveSessionObject('admin_current_profile',null); + return; + } + + if($this->currentUser->user_level == 'Admin'){ + SessionUtils::saveSessionObject('admin_current_profile',$profileId); + + }else if($this->currentUser->user_level == 'Manager'){ + $signInMappingField = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME; + $signInMappingFieldTable = ucfirst($signInMappingField); + $subordinate = new $signInMappingFieldTable(); + $signInMappingField = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME; + $subordinates = $subordinate->Find("supervisor = ?",array($this->currentUser->$signInMappingField)); + $subFound = false; + foreach($subordinates as $sub){ + if($sub->id == $profileId){ + $subFound = true; + break; + } + } + + if(!$subFound){ + return; + } + + SessionUtils::saveSessionObject('admin_current_profile',$profileId); + + } + } + + public function cleanUpAdoDB($obj){ + unset($obj->_table); + unset($obj->_dbat); + unset($obj->_tableat); + unset($obj->_where); + unset($obj->_saved); + unset($obj->_lasterr); + unset($obj->_original); + unset($obj->foreignName); + + return $obj; + } + + public function setDB($db){ + $this->db = $db; + } + + public function getDB(){ + return $this->db; + } + + public function checkSecureAccessOld($type,$object){ + + $accessMatrix = array(); + if($this->currentUser->user_level == 'Admin'){ + $accessMatrix = $object->getAdminAccess(); + if (in_array($type, $accessMatrix)) { + return true; + } + }else if($this->currentUser->user_level == 'Manager'){ + $accessMatrix = $object->getManagerAccess(); + if (in_array($type, $accessMatrix)) { + return true; + }else{ + $accessMatrix = $object->getUserOnlyMeAccess(); + $signInMappingField = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME; + if (in_array($type, $accessMatrix) && $_REQUEST[$object->getUserOnlyMeAccessField()] == $this->currentUser->$signInMappingField) { + return true; + } + + if (in_array($type, $accessMatrix)) { + + $field = $object->getUserOnlyMeAccessField(); + $signInMappingField = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME; + if($this->currentUser->$signInMappingField."" == $object->$field){ + return true; + } + + } + } + + }else{ + $accessMatrix = $object->getUserAccess(); + if (in_array($type, $accessMatrix)) { + return true; + }else{ + $accessMatrix = $object->getUserOnlyMeAccess(); + $signInMappingField = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME; + if (in_array($type, $accessMatrix) && $_REQUEST[$object->getUserOnlyMeAccessField()] == $this->currentUser->$signInMappingField) { + return true; + } + + if (in_array($type, $accessMatrix)) { + + $field = $object->getUserOnlyMeAccessField(); + $signInMappingField = SIGN_IN_ELEMENT_MAPPING_FIELD_NAME; + if($this->currentUser->$signInMappingField."" == $object->$field){ + return true; + } + + } + } + } + + $ret['status'] = "ERROR"; + $ret['message'] = "Access violation"; + echo json_encode($ret); + exit(); + } + + /** + * Use user level security functions defined in model classes to check whether a given action type is allowed to be executed by the current user on a given object + * @method checkSecureAccess + * @param $type {String} Action type + * @param $object {Object} object to test access + * @return {Boolen} true or exit + */ + + public function checkSecureAccess($type,$object){ if(!empty($this->currentUser->user_roles)){ return true; } - - $accessMatrix = array(); - - //Construct permission method - $permMethod = "get".$this->currentUser->user_level."Access"; + + $accessMatrix = array(); + + //Construct permission method + $permMethod = "get".$this->currentUser->user_level."Access"; if(method_exists($object,$permMethod)){ $accessMatrix = $object->$permMethod(); }else{ $accessMatrix = $object->getDefaultAccessLevel(); } - if (in_array($type, $accessMatrix)) { - //The user has required permission, so return true - return true; - }else{ - //Now we need to check whther the user has access to his own records - $accessMatrix = $object->getUserOnlyMeAccess(); + if (in_array($type, $accessMatrix)) { + //The user has required permission, so return true + return true; + }else{ + //Now we need to check whther the user has access to his own records + $accessMatrix = $object->getUserOnlyMeAccess(); + + $userOnlyMeAccessRequestField = $object->getUserOnlyMeAccessRequestField(); + + //This will check whether user can access his own records using a value in request + if(isset($_REQUEST[$object->getUserOnlyMeAccessField()]) && isset($this->currentUser->$userOnlyMeAccessRequestField)){ + if (in_array($type, $accessMatrix) && $_REQUEST[$object->getUserOnlyMeAccessField()] == $this->currentUser->$userOnlyMeAccessRequestField) { + return true; + } + } + + //This will check whether user can access his own records using a value in requested object + if (in_array($type, $accessMatrix)) { + $field = $object->getUserOnlyMeAccessField(); + if($this->currentUser->$userOnlyMeAccessRequestField == $object->$field){ + return true; + } + + } + } + + $ret['status'] = "ERROR"; + $ret['message'] = "Access violation"; + echo json_encode($ret); + exit(); + } + + + + public function getInstanceId(){ + $settings = new Setting(); + $settings->Load("name = ?",array("Instance : ID")); + + if($settings->name != "Instance : ID" || empty($settings->value)){ + $settings->value = md5(time()); + $settings->name = "Instance : ID"; + $settings->Save(); + } + + return $settings->value; + } + + public function setInstanceKey($key){ + $settings = new Setting(); + $settings->Load("name = ?",array("Instance: Key")); + if($settings->name != "Instance: Key"){ + $settings->name = "Instance: Key"; + + } + $settings->value = $key; + $settings->Save(); + } + + public function getInstanceKey(){ + $settings = new Setting(); + $settings->Load("name = ?",array("Instance: Key")); + if($settings->name != "Instance: Key"){ + return null; + } + return $settings->value; + } + + public function validateInstance(){ + $instanceId = $this->getInstanceId(); + if(empty($instanceId)){ + return true; + } + + $key = $this->getInstanceKey(); + + if(empty($key)){ + return false; + } + + $data = AesCtr::decrypt($key, $instanceId, 256); + $arr = explode("|",$data); + if($arr[0] == KEY_PREFIX && $arr[1] == $instanceId){ + return true; + } + + return false; + } + + public function loadModulePermissions($group, $name, $userLevel){ + $module = new Module(); + $module->Load("update_path = ?",array($group.">".$name)); - $userOnlyMeAccessRequestField = $object->getUserOnlyMeAccessRequestField(); + LogManager::getInstance()->info(" Current Mod :".json_encode($module)); - //This will check whether user can access his own records using a value in request - if(isset($_REQUEST[$object->getUserOnlyMeAccessField()]) && isset($this->currentUser->$userOnlyMeAccessRequestField)){ - if (in_array($type, $accessMatrix) && $_REQUEST[$object->getUserOnlyMeAccessField()] == $this->currentUser->$userOnlyMeAccessRequestField) { - return true; - } - } + $arr = array(); + $arr['user'] = json_decode($module->user_levels,true); + $arr['user_roles'] = !empty($module->user_roles)?json_decode($module->user_roles,true):array(); - //This will check whether user can access his own records using a value in requested object - if (in_array($type, $accessMatrix)) { - $field = $object->getUserOnlyMeAccessField(); - if($this->currentUser->$userOnlyMeAccessRequestField == $object->$field){ - return true; - } + + $permission = new Permission(); + $modulePerms = $permission->Find("module_id = ? and user_level = ?",array($module->id,$userLevel)); - } - } + + $perms = array(); + foreach($modulePerms as $p){ + $perms[$p->permission] = $p->value; + } + + $arr['perm'] = $perms; + + return $arr; + } - $ret['status'] = "ERROR"; - $ret['message'] = "Access violation"; - echo json_encode($ret); - exit(); - } + public function isModuleAllowedForUser($moduleManagerObj){ + $moduleObject = $moduleManagerObj->getModuleObject(); - - - public function getInstanceId(){ - $settings = new Setting(); - $settings->Load("name = ?",array("Instance : ID")); - - if($settings->name != "Instance : ID" || empty($settings->value)){ - $settings->value = md5(time()); - $settings->name = "Instance : ID"; - $settings->Save(); - } - - return $settings->value; - } - - public function setInstanceKey($key){ - $settings = new Setting(); - $settings->Load("name = ?",array("Instance: Key")); - if($settings->name != "Instance: Key"){ - $settings->name = "Instance: Key"; - - } - $settings->value = $key; - $settings->Save(); - } - - public function getInstanceKey(){ - $settings = new Setting(); - $settings->Load("name = ?",array("Instance: Key")); - if($settings->name != "Instance: Key"){ - return null; - } - return $settings->value; - } - - public function validateInstance(){ - $instanceId = $this->getInstanceId(); - if(empty($instanceId)){ - return true; - } - - $key = $this->getInstanceKey(); - - if(empty($key)){ + //Check if the module is disabled + if($moduleObject['status'] == 'Disabled'){ return false; } - $data = AesCtr::decrypt($key, $instanceId, 256); - $arr = explode("|",$data); - if($arr[0] == KEY_PREFIX && $arr[1] == $instanceId){ - return true; + //Check if user has permissions to this module + //Check Module Permissions + $modulePermissions = BaseService::getInstance()->loadModulePermissions($moduleManagerObj->getModuleType(), $moduleObject['name'],BaseService::getInstance()->getCurrentUser()->user_level); + + + if(!in_array(BaseService::getInstance()->getCurrentUser()->user_level, $modulePermissions['user'])){ + + if(!empty(BaseService::getInstance()->getCurrentUser()->user_roles)){ + $userRoles = json_decode(BaseService::getInstance()->getCurrentUser()->user_roles,true); + }else{ + $userRoles = array(); + } + $commonRoles = array_intersect($modulePermissions['user_roles'], $userRoles); + if(empty($commonRoles)){ + return false; + } + } - return false; - } - - public function loadModulePermissions($group, $name, $userLevel){ - $module = new Module(); - $module->Load("update_path = ?",array($group.">".$name)); - $arr = array(); - $arr['user'] = json_decode($module->user_levels,true); - $arr['user_roles'] = !empty($module->user_roles)?json_decode($module->user_roles,true):array(); - - - $permission = new Permission(); - $modulePerms = $permission->Find("module_id = ? and user_level = ?",array($module->id,$userLevel)); - - - $perms = array(); - foreach($modulePerms as $p){ - $perms[$p->permission] = $p->value; - } - - $arr['perm'] = $perms; - - return $arr; - } - - public function getGAKey(){ - return SettingsManager::getInstance()->getSetting('Analytics: Google Key'); - } - - /** - * Set the audit manager - * @method setAuditManager - * @param $auditManager {AuditManager} - */ - - public function setAuditManager($auditManager){ - $this->auditManager = $auditManager; - } - - /** - * Set the NotificationManager - * @method setNotificationManager - * @param $notificationManager {NotificationManager} - */ - - public function setNotificationManager($notificationManager){ - $this->notificationManager = $notificationManager; - } - - /** - * Set the SettingsManager - * @method setSettingsManager - * @param $settingsManager {SettingsManager} - */ - - public function setSettingsManager($settingsManager){ - $this->settingsManager = $settingsManager; - } - - public function setFileFields($fileFields){ - $this->fileFields = $fileFields; - } - - public function audit($type, $data){ - if(!empty($this->auditManager)){ - $this->auditManager->addAudit($type, $data); - } - } - - public function fixJSON($json){ - $noJSONRequests = SettingsManager::getInstance()->getSetting("System: Do not pass JSON in request"); - if($noJSONRequests."" == "1"){ - $json = str_replace("|",'"',$json); - } - return $json; - } - - public function addModuleManager($moduleManager){ - if(empty($this->moduleManagers)){ - $this->moduleManagers = array(); - } - $this->moduleManagers[] = $moduleManager; - } - - public function getModuleManagers(){ - return $this->moduleManagers; - } - - public function setEmailSender($emailSender){ - $this->emailSender = $emailSender; - } - - public function getEmailSender(){ - return $this->emailSender; + return true; + } + + public function getGAKey(){ + return SettingsManager::getInstance()->getSetting('Analytics: Google Key'); + } + + /** + * Set the audit manager + * @method setAuditManager + * @param $auditManager {AuditManager} + */ + + public function setAuditManager($auditManager){ + $this->auditManager = $auditManager; + } + + /** + * Set the NotificationManager + * @method setNotificationManager + * @param $notificationManager {NotificationManager} + */ + + public function setNotificationManager($notificationManager){ + $this->notificationManager = $notificationManager; + } + + /** + * Set the SettingsManager + * @method setSettingsManager + * @param $settingsManager {SettingsManager} + */ + + public function setSettingsManager($settingsManager){ + $this->settingsManager = $settingsManager; + } + + public function setFileFields($fileFields){ + $this->fileFields = $fileFields; + } + + public function audit($type, $data){ + if(!empty($this->auditManager)){ + $this->auditManager->addAudit($type, $data); + } + } + + public function fixJSON($json){ + $noJSONRequests = SettingsManager::getInstance()->getSetting("System: Do not pass JSON in request"); + if($noJSONRequests."" == "1"){ + $json = str_replace("|",'"',$json); + } + return $json; + } + + public function addModuleManager($moduleManager){ + if(empty($this->moduleManagers)){ + $this->moduleManagers = array(); + } + $this->moduleManagers[] = $moduleManager; + } + + public function getModuleManagers(){ + return $this->moduleManagers; + } + + public function setEmailSender($emailSender){ + $this->emailSender = $emailSender; + } + + public function getEmailSender(){ + return $this->emailSender; + } public function getFieldNameMappings($type){ $fieldNameMap = new FieldNameMapping(); $data = $fieldNameMap->Find("type = ?",array($type)); return $data; } - + public function getCustomFields($type){ - $customField = new CustomField(); - $data = $customField->Find("type = ?",array($type)); - return $data; + $customField = new CustomField(); + $data = $customField->Find("type = ?",array($type)); + return $data; } public function getAllAdmins(){ @@ -1130,14 +1176,14 @@ class BaseService{ } class IceConstants{ - const AUDIT_AUTHENTICATION = "Authentication"; - const AUDIT_ADD = "Add"; - const AUDIT_EDIT = "Edit"; - const AUDIT_DELETE = "Delete"; - const AUDIT_ERROR = "Error"; - const AUDIT_ACTION = "User Action"; - - const NOTIFICATION_LEAVE = "Leave Module"; - const NOTIFICATION_TIMESHEET = "Time Module"; + const AUDIT_AUTHENTICATION = "Authentication"; + const AUDIT_ADD = "Add"; + const AUDIT_EDIT = "Edit"; + const AUDIT_DELETE = "Delete"; + const AUDIT_ERROR = "Error"; + const AUDIT_ACTION = "User Action"; + + const NOTIFICATION_LEAVE = "Leave Module"; + const NOTIFICATION_TIMESHEET = "Time Module"; const NOTIFICATION_TRAINING = "Training Module"; } \ No newline at end of file diff --git a/src/classes/CronUtils.php b/src/classes/CronUtils.php index d22fbc2d..78e7a58e 100644 --- a/src/classes/CronUtils.php +++ b/src/classes/CronUtils.php @@ -23,17 +23,25 @@ class CronUtils{ $count = 0; foreach($ams as $am){ if(is_dir($this->clientBasePath.$am) && $am != '.' && $am != '..'){ - //$command = "php ".$this->cronFile." -c".$this->clientBasePath.$am; - $command = "php ".$this->clientBasePath.$am."/".$this->cronFile; - echo "Run:".$command."\r\n"; - passthru($command, $res); - echo "Result :".$res."\r\n"; + $command = "php ".$this->clientBasePath.$am."/".$this->cronFile; + if(file_exists($this->clientBasePath.$am."/".$this->cronFile)){ - $count++; - if($count > 25){ - sleep(1); - $count = 0; + echo "Run:".$command."\r\n"; + error_log("Run:".$command); + passthru($command, $res); + echo "Result :".$res."\r\n"; + error_log("Result :".$res); + + $count++; + if($count > 25){ + sleep(1); + $count = 0; + } + }else{ + echo "Error (File Not Found):".$command."\r\n"; + error_log("Error (File Not Found):".$command); } + } } } diff --git a/src/classes/EmailSender.php b/src/classes/EmailSender.php index 5c37156e..72678dc8 100644 --- a/src/classes/EmailSender.php +++ b/src/classes/EmailSender.php @@ -79,7 +79,7 @@ abstract class EmailSender{ $emailBody = str_replace("#_emailBody_#", $body, $emailBody); $emailBody = str_replace("#_logourl_#", - BASE_URL."images/logo.png" + UIManager::getInstance()->getCompanyLogoUrl() , $emailBody); $user = new User(); @@ -113,7 +113,7 @@ abstract class EmailSender{ //Convert to an html email $emailBody = $body; $emailBody = str_replace("#_logourl_#", - BASE_URL."images/logo.png" + UIManager::getInstance()->getCompanyLogoUrl() , $emailBody); $user = new User(); @@ -271,6 +271,14 @@ class SMTPEmailSender extends EmailSender{ 'Reply-To' => $replyToEmail, 'Subject' => $subject); + if(!empty($ccList)){ + $headers['Cc'] = implode(",",$ccList); + } + + if(!empty($bccList)){ + $headers['Bcc'] = implode(",",$bccList); + } + $mail = $smtp->send($toEmail, $headers, $body); @@ -297,6 +305,12 @@ class PHPMailer extends EmailSender{ $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $headers .= 'From: '.$fromEmail. "\r\n"; + if(!empty($ccList)){ + $headers .= 'CC: '.implode(",",$ccList). "\r\n"; + } + if(!empty($bccList)){ + $headers .= 'BCC: '.implode(",",$bccList). "\r\n"; + } $headers .= 'ReplyTo: '.$replyToEmail. "\r\n"; $headers .= 'Ice-Mailer: PHP/' . phpversion(); diff --git a/src/config.base.php b/src/config.base.php index e1bf1ead..cebbe14e 100644 --- a/src/config.base.php +++ b/src/config.base.php @@ -9,4 +9,4 @@ if(!defined('SIGN_IN_ELEMENT_MAPPING_FIELD_NAME')){define('SIGN_IN_ELEMENT_MAPPI if(!defined('CONTACT_EMAIL')){define('CONTACT_EMAIL','ice-framework@gamonoid.com');} if(!defined('KEY_PREFIX')){define('KEY_PREFIX','iCEf');} -if(!defined('APP_SEC')){define('APP_SEC','4dcxudersqw');} \ No newline at end of file +if(!defined('APP_SEC')){define('APP_SEC','4dcxswfrds');} \ No newline at end of file diff --git a/src/configureUIManager.php b/src/configureUIManager.php index 11dce72b..836dbe4a 100644 --- a/src/configureUIManager.php +++ b/src/configureUIManager.php @@ -2,3 +2,12 @@ UIManager::getInstance()->setCurrentUser($user); UIManager::getInstance()->setProfiles($profileCurrent, $profileSwitched); UIManager::getInstance()->setHomeLink($homeLink); + +$moduleManagers = BaseService::getInstance()->getModuleManagers(); +foreach($moduleManagers as $moduleManagerObj){ + $allowed = BaseService::getInstance()->isModuleAllowedForUser($moduleManagerObj); + + if($allowed){ + $moduleManagerObj->initQuickAccessMenu(); + } +} diff --git a/src/crons/cronRunner.php b/src/crons/cronRunner.php index 1a904fd5..3537a02b 100644 --- a/src/crons/cronRunner.php +++ b/src/crons/cronRunner.php @@ -2,7 +2,7 @@ if(php_sapi_name() != 'cli'){ exit(); } -include "../config.base.php"; +include dirname(__FILE__)."/../config.base.php"; ini_set('error_log',CRON_LOG); $opts = getopt('f:p:'); $file = $opts['f']; diff --git a/src/header.php b/src/header.php index d4aded8d..5a386bff 100644 --- a/src/header.php +++ b/src/header.php @@ -37,7 +37,10 @@ if(empty($user->default_module)){ }else{ $defaultModule = new Module(); $defaultModule->Load("id = ?",array($user->default_module)); - $homeLink = CLIENT_BASE_URL."?g=".$defaultModule->mod_group."&&n=".$defaultModule->name. + if($defaultModule->mod_group == "user"){ + $defaultModule->mod_group = "modules"; + } + $homeLink = CLIENT_BASE_URL."?g=".$defaultModule->mod_group."&n=".$defaultModule->name. "&m=".$defaultModule->mod_group."_".str_replace(" ","_",$defaultModule->menu); } @@ -62,15 +65,14 @@ if(!in_array($user->user_level, $modulePermissions['user'])){ } - -$logoFileName = CLIENT_BASE_PATH."data/logo.png"; -$logoFileUrl = CLIENT_BASE_URL."data/logo.png"; -if(!file_exists($logoFileName)){ - $logoFileUrl = BASE_URL."images/logo.png"; -} +$logoFileUrl = UIManager::getInstance()->getCompanyLogoUrl(); $companyName = SettingsManager::getInstance()->getSetting('Company: Name'); +if(empty($companyName) || $companyName == "Sample Company Pvt Ltd"){ + $companyName = APP_NAME; +} + //Load meta info $meta = json_decode(file_get_contents(MODULE_PATH."/meta.json"),true); @@ -80,7 +82,7 @@ include('configureUIManager.php'); - <?=APP_NAME?> + <?=$companyName?> @@ -129,6 +131,7 @@ include('configureUIManager.php'); + @@ -175,8 +178,8 @@ include('configureUIManager.php');
-
+