ria/app/Controllers/User.php
2024-05-06 03:47:37 +00:00

1578 lines
54 KiB
PHP

<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use CodeIgniter\Validation\Exceptions\ValidationException;
use App\Models\Costcenter_model;
use App\Models\Dashboard_model;
use App\Models\Employeedetails_model;
use App\Models\User_model;
/**
* Module : User
* User Class to control all user related operations.
* @author : Kishor
* @version : 1.1
* @since : 15 November 2016
* @example : Revised at 15th april 2024
*/
class User extends BaseController
{
protected $costcenter_model;
protected $dahsboard_Model;
protected $employeedetails_model;
protected $user_model;
protected $session;
/**
* This is default constructor of the class
*/
public function __construct()
{
parent::__construct();
$this->dahsboard_Model = new Dashboard_model();
$this->costcenter_model = new Costcenter_model();
$this->employeedetails_model = new employeedetails_model();
$this->user_model = new User_model();
$this->session = session();
helper('form'); //$this->load->library('form_validation');
$this->isLoggedIn();
}
/**
* This function used to load the first screen of the user
*/
public function index()
{
$this->global['pageTitle'] = 'Dashboard';
log_message('error', '#####Dashboard session name : ' . $this->session->get('name'));
$this->global['pageTitle'] = 'Dashboard';
$data['EmpCount'] = $this->employeedetails_model->getEmployeeCount();
$data['UserCount'] = $this->dahsboard_Model->getUserCount();
$data['totalpurchaseorder'] = $this->dahsboard_Model->totalpurchaseorder();
$data['totalordervalue'] = $this->dahsboard_Model->totalordervalue();
$data['pendingpo'] = $this->dahsboard_Model->pendingpo();
$data['totalimportpo'] = $this->dahsboard_Model->totalimportpo();
$data['details'] = $this->dahsboard_Model->reqdetail();
$data['pending_details'] = $this->dahsboard_Model->req_pending();
$data['serviceprogress'] = $this->dahsboard_Model->serviceprogress();
$data['revenueprogress'] = $this->dahsboard_Model->revenueprogress();
$data['importprogress'] = $this->dahsboard_Model->importprogress();
$data['capitalprogress'] = $this->dahsboard_Model->capitalprogress();
//month-wise area chart
$data['getTotalServicePoCount'] = $this->dahsboard_Model->getTotalServicePoCount();
$data['getTotalimportPoCount'] = $this->dahsboard_Model->getTotalimportPoCount();
$data['getTotalcapitalPoCount'] = $this->dahsboard_Model->getTotalcapitalPoCount();
$data['getTotalrevenuePoCount'] = $this->dahsboard_Model->getTotalrevenuePoCount();
//dashboard pie chart
$data['importbudgt'] = $this->dahsboard_Model->importbudgt();
$data['servicebudgt'] = $this->dahsboard_Model->servicebudgt();
$data['revenuebudgt'] = $this->dahsboard_Model->revenuebudgt();
$data['capitalbud'] = $this->dahsboard_Model->capitalbud();
$data['typebal'] = $this->dahsboard_Model->typebal();
/* HR DASHBOARD Controller Start*/
$data['totemp'] = $this->dahsboard_Model->totemp();
$data['totloan'] = $this->dahsboard_Model->totloan();
$data['totpay'] = $this->dahsboard_Model->totpay();
$data['totrec'] = $this->dahsboard_Model->totrec();
$data['emplist'] = $this->dahsboard_Model->emplist();
$date = $this->request->getPost("id");
$dates = date('Y-m');
$date = $dates . '-01';
$dat = date('d', strtotime("-1 days"));
$WH = 'WH' . date('j', strtotime("-1 days"));
$yesterday = $this->dahsboard_Model->attyesterday($WH, $date);
$valuess = 0;
foreach ($yesterday as $weekda => $value) {
if ($value[$WH] == 0) {
$valuess++;
}
}
$data['today'] = $valuess;
$daydate = date('Y-m', strtotime($date));
$daydate = $daydate . '-01';
$yesterday = $this->dahsboard_Model->attyesterday($WH, $daydate);
$values = 0;
$absEmp = array();
foreach ($yesterday as $weekda => $value) {
if ($value[$WH] == 0) {
$values++;
$absendId = $value['EmpID'];
$absendName = $value['FirstName'];
$absEmp[] = $absendId . "-" . $absendName; //absend empid and name list
}
}
$data['today'] = sizeof($absEmp);
$data['abs_name'] = $absEmp;
$OT = 'OT' . date('j', strtotime($date));
$CUR_month = date('t');
$toDayEmployee = $this->dahsboard_Model->yesterdayAllPersentEmpSalary($WH, $OT, $daydate);
$EmpID = 0;
$employeeSalary = 0;
foreach ($toDayEmployee as $value) {
$values = 0;
$totalothour = 0;
if ($value[$WH] != 0) {
$totalothour = $value[$OT];
$values = 1;
$Empid = $value['EmpID'];
$totalEmployeePersent = $this->dahsboard_Model->persentEmployeeDetails($Empid);
if (!empty($totalEmployeePersent)) {
$HRA_Amount = $totalEmployeePersent[0]->HRA_Amount;
$Basic_Pay = $totalEmployeePersent[0]->Basic_Pay;
$totalsalary = $totalEmployeePersent[0]->TotalSalary;
$dayFoodAmt = $totalEmployeePersent[0]->Food_Allowances;
$Food_Allowances = $dayFoodAmt * $values;
$daySalary = $Basic_Pay / $CUR_month;
/**per day salary working hour**/
$dayHra = $HRA_Amount / $CUR_month;
/** per day hra amount **/
$onehoursSalary = ($daySalary + $dayHra) / 8;
/**one hour salay ot calculation**/
if ($totalothour != 0)
/** if ot not equal zero **/
{
$totSalayOT = $totalothour * $onehoursSalary;
} else {
$totSalayOT = 0;
}
$currentDaySalary = $daySalary * $values;
/** current day salary working days calculation**/
$currentDayHra = $dayHra * $values;
/** total working days hra calculations**/
$currentDatePF = $currentDaySalary + $currentDayHra + $totSalayOT;
/** current date pf calculation**/
if ($totalsalary <= 20000) {
$esiAmount = $currentDatePF * 1.75 / 100;
/** esiamount not elgiable for 20000 **/
} else {
$esiAmount = 0;
}
$pfAmount = $currentDaySalary * 12 / 100;
/** pf amount per day**/
$salaryInCurrentdays = $currentDaySalary + $totSalayOT + $currentDayHra + $Food_Allowances;
$salaryInCurrentday = $salaryInCurrentdays - ($esiAmount + $pfAmount);
$employeeSalary += round($salaryInCurrentday);
}
}
}
//$salaryInCurrentday++;
$data['employeeSalary'] = $employeeSalary;
$working = array();
$overtime = array();
//$holid = array();
for ($i = 1; $i <= $dat; $i++)
{
$Working[] = 'WH' . $i;
$overtime[] = 'OT' . $i;
$CUR_month = date('t');
// foreach ($holiday as $value)
// {
// //$holid []= 'WH'.$value;
// if($i==$value) {
// $holid []=$value;
// }
// }
}
$WH = implode(",", $Working);
$OT = implode(",", $overtime);
$salarycurrentdate = array();
$toDayEmployee = $this->dahsboard_Model->dayAllPersentEmpSalary($WH, $OT, $date);
$totalSalary = 0;
$working = explode(",", $WH);
$overtime = explode(",", $OT);
foreach ($toDayEmployee as $value) {
$values = 0;
foreach ($working as $work) {
// foreach ($overtime as $extra) {
if ($value[$work] != 0 || $value['OT' . substr($work, 2)] != 0) {
$totalothour = $value['OT' . substr($work, 2)];
$values = 1;
$Empid = $value['EmpID'];
$totalEmployeePersent = $this->dahsboard_Model->persentEmployeeDetails($Empid);
if (!empty($totalEmployeePersent)) {
$HRA_Amount = $totalEmployeePersent[0]->HRA_Amount;
$Basic_Pay = $totalEmployeePersent[0]->Basic_Pay;
$totalsalary = $totalEmployeePersent[0]->TotalSalary;
$dayFoodAmt = $totalEmployeePersent[0]->Food_Allowances;
//$allowances =$totalEmployeePersent[0]->Allowances;
// $Allowances = $allowances * $values;
$Food_Allowances = $dayFoodAmt * $values;
$daySalary = $Basic_Pay / $CUR_month;
/**per day salary working hour**/
$dayHra = $HRA_Amount / $CUR_month;
/** per day hra amount **/
$onehoursSalary = ($daySalary + $dayHra) / 8;
/**one hour salay ot calculation**/
$totSalayOT = ($totalothour != 0) ? $totalothour * $onehoursSalary : 0;
/** if ot not equal zero **/
$currentDaySalary = $daySalary * $values;
/** current day salary working days calculation**/
$currentDayHra = $dayHra * $values;
/** total working days hra calculations**/
$currentDatePF = $currentDaySalary + $currentDayHra + $totSalayOT;
/** current date pf calculation**/
$esiAmount = ($totalsalary <= 20000) ? $currentDatePF * 1.75 / 100 : 0;
/** esiamount not elgiable for 20000 **/
$pfAmount = $currentDaySalary * 12 / 100;
/** pf amount per day**/
$salaryInCurrentdays = $currentDaySalary + $totSalayOT + $currentDayHra + $Food_Allowances;
$salaryInCurrentday = $salaryInCurrentdays - ($esiAmount + $pfAmount);
$totalSalarys = $totalSalary + $salaryInCurrentday;
$totalSalary = round($totalSalarys);
// $salarycurrentdate[] = $salaryInCurrentday;;
}
}
}
}
$data['totalSalary'] = $totalSalary;
$this->loadViews("dashboard", $this->global, $data, NULL);
}
/*date click on day salary,absent name, total absent display*/
function dateFunctionChangeVales()
{
$date = $this->request->getPost("id");
$dates = date('Y-m');
$date = $dates . '-01';
// $dat = date('d', strtotime("-1 days"));
$WH = 'WH' . date('j', strtotime("-1 days"));
$yesterday = $this->dahsboard_Model->attyesterday($WH, $date);
$values = 0;
foreach ($yesterday as $weekda => $value) {
if ($value[$WH] == 0) {
$values++;
}
}
$data['values'] = $values;
$date = $this->request->getPost("id");
$daydate = format_date($date,0,'Y-m');
$daydate = $daydate . '-01';
$WH = 'WH' . format_date($date,0,'j');
$yesterday = $this->dahsboard_Model->attyesterday($WH, $daydate);
//$absEmp =array($absEmp);
$values = 0;
$absEmp = array();
foreach ($yesterday as $weekda => $value) {
if ($value[$WH] == 0) {
$values++;
$absendId = $value['EmpID'];
$absendName = $value['FirstName'];
$absEmp[] = $absendId . "-" . $absendName; //absend empid and name list
}
}
$data['today'] = $values;
$data['absname'] = $absEmp;
$OT = 'OT' .format_date($date,0,'j');
$CUR_month = date('t');
$toDayEmployee = $this->dahsboard_Model->dayAllPersentEmpSalary($WH, $OT, $daydate);
//$EmpID = $toDayEmployee[0]->EmpID;
$EmpID = 0;
$employeeSalary = 0;
foreach ($toDayEmployee as $value) {
$values = 0;
$totalothour = 0;
if ($value[$WH] != 0) {
$totalothour = $value[$OT];
$values = 1;
$Empid = $value['EmpID'];
$totalEmployeePersent = $this->dahsboard_Model->persentEmployeeDetails($Empid);
if (!empty($totalEmployeePersent)) {
$HRA_Amount = $totalEmployeePersent[0]->HRA_Amount;
$Basic_Pay = $totalEmployeePersent[0]->Basic_Pay;
$totalsalary = $totalEmployeePersent[0]->TotalSalary;
$dayFoodAmt = $totalEmployeePersent[0]->Food_Allowances;
//$allowances =$totalEmployeePersent[0]->Allowances;
//$Allowances = $allowances * $values;
$Food_Allowances = $dayFoodAmt * $values;
$daySalary = $Basic_Pay / $CUR_month;
/**per day salary working hour**/
$dayHra = $HRA_Amount / $CUR_month;
/** per day hra amount **/
$onehoursSalary = ($daySalary + $dayHra) / 8;
/**one hour salay ot calculation**/
if ($totalothour != 0)
/** if ot not equal zero **/
{
$totSalayOT = $totalothour * $onehoursSalary;
} else {
$totSalayOT = 0;
}
$currentDaySalary = $daySalary * $values;
/** current day salary working days calculation**/
$currentDayHra = $dayHra * $values;
/** total working days hra calculations**/
$currentDatePF = $currentDaySalary + $currentDayHra + $totSalayOT;
/** current date pf calculation**/
$esiAmount = ($totalsalary <= 20000) ? $currentDatePF * 1.75 / 100 : 0;
/** esiamount not elgiable for 20000 **/
$pfAmount = $currentDaySalary * 12 / 100;
/** pf amount per day**/
$salaryInCurrentdays = $currentDaySalary + $totSalayOT + $currentDayHra + $Food_Allowances;
$salaryInCurrentday = $salaryInCurrentdays - ($esiAmount + $pfAmount);
$employeeSalary += round($salaryInCurrentday);
}
}
}
//$salaryInCurrentday++;
$data['employeeSalary'] = $employeeSalary;
$working = array();
$overtime = array();
//$holid = array();
$len = format_date($date,0,'d');
for ($i = 1; $i <= $len; $i++) //echo $dat; die;
{
$Working[] = 'WH' . $i;
$overtime[] = 'OT' . $i;
$CUR_month = date('t');
// foreach ($holiday as $value)
// {
// //$holid []= 'WH'.$value;
// if($i==$value) {
// $holid []=$value;
// }
// }
}
$WH = implode(",", $Working);
$OT = implode(",", $overtime);
$salarycurrentdate = array();
$toDayEmployee = $this->dahsboard_Model->dayAllPersentEmpSalary($WH, $OT, $daydate);
$totalSalary = 0;
$working = explode(",", $WH);
$overtime = explode(",", $OT);
foreach ($toDayEmployee as $value) {
$values = 0;
foreach ($working as $work) {
//foreach ($overtime as $extra) {
if ($value[$work] != 0 || $value['OT' . substr($work, 2)] != 0) {
$totalothour = $value['OT' . substr($work, 2)];
$values = 1;
$Empid = $value['EmpID'];
$totalEmployeePersent = $this->dahsboard_Model->persentEmployeeDetails($Empid);
if (!empty($totalEmployeePersent)) {
$HRA_Amount = $totalEmployeePersent[0]->HRA_Amount;
$Basic_Pay = $totalEmployeePersent[0]->Basic_Pay;
$totalsalary = $totalEmployeePersent[0]->TotalSalary;
$dayFoodAmt = $totalEmployeePersent[0]->Food_Allowances;
//$allowances =$totalEmployeePersent[0]->Allowances;
// $Allowances = $allowances * $values;
$Food_Allowances = $dayFoodAmt * $values;
$daySalary = $Basic_Pay / $CUR_month;
/**per day salary working hour**/
$dayHra = $HRA_Amount / $CUR_month;
/** per day hra amount **/
$onehoursSalary = ($daySalary + $dayHra) / 8;
/**one hour salay ot calculation**/
$totSalayOT = ($totalothour != 0) ? $totalothour * $onehoursSalary : 0;
/** if ot not equal zero **/
$currentDaySalary = $daySalary * $values;
/** current day salary working days calculation**/
$currentDayHra = $dayHra * $values;
/** total working days hra calculations**/
$currentDatePF = $currentDaySalary + $currentDayHra + $totSalayOT;
/** current date pf calculation**/
$esiAmount = ($totalsalary <= 20000) ? $currentDatePF * 1.75 / 100 : 0;
/** esiamount not elgiable for 20000 **/
$pfAmount = $currentDaySalary * 12 / 100;
/** pf amount per day**/
$salaryInCurrentdays = $currentDaySalary + $totSalayOT + $currentDayHra + $Food_Allowances;
$salaryInCurrentday = $salaryInCurrentdays - ($esiAmount + $pfAmount);
$totalSalarys = $totalSalary + $salaryInCurrentday;
$totalSalary = round($totalSalarys);
// $salarycurrentdate[] = $salaryInCurrentday;
}
}
}
}
$data['totalSalary'] = $totalSalary;
// }
echo json_encode($data);
}
/*this function uesd to finance startdate */
public function getFinancialStartDate()
{
$CURMONTH = date('n');
$CURYEAR = date('Y');
$FINYEAR = 0;
if ($CURMONTH >= 4) {
$FINYEAR = $CURYEAR;
} else {
$FINYEAR = $CURYEAR - 1;
}
$dateInString = $FINYEAR . '-4-1';
$result = date_create($dateInString);
return $result;
}
/*this function uesd to finance EndDate */
public function getFinancialEndDate()
{
$CURMONTH = date('n');
$CURYEAR = date('Y');
$FINYEAR = 0;
if ($CURMONTH < 4) {
$FINYEAR = $CURYEAR;
} else {
$FINYEAR = $CURYEAR + 1;
}
$dateInString = $FINYEAR . '-3-31';
$result = date_create($dateInString);
return $result;
}
/*this function used to speedometer month emp performances display*/
function monthattendance($empID = '')
{
$date = date('Y-m');
$dates = $date . '-01';
$EmpID = '';
if (empty($empID)) {
$EmpID = $this->request->getPost('id');
} else {
$EmpID = $empID;
}
$monthabs = $this->dahsboard_Model->attendance($EmpID, $dates);
$persent_month = date('t'); //current month of days 31
$values = array();
$otvalues = array();
$weekdays = array();
$otHours = array();
$date = date('j'); //current month current date
$CURDATE = date('d'); //current month current date
$CUR_month = date('t'); //current month of days 31
$CURYEAR = date('Y');
$CURMONTH = date('m');
$datejoin = $this->dahsboard_Model->joindate($EmpID);
$DateofJoiningInString = $datejoin[0]->DateofJoining;
$DateofJoining = date_create($DateofJoiningInString);
// $doj_month = date_format($DateofJoining, "n");
// $doj_year = date_format($DateofJoining, "Y");
// $doj_day = date_format($DateofJoining, "j");
$doj_month = format_date($DateofJoining, 0, 'n');
$doj_year = format_date($DateofJoining, 0, 'Y');
$doj_day = format_date($DateofJoining, 0, 'j');
for ($i = 1; $i <= $persent_month; $i++) {
$weekdays[] = 'WH' . $i;
$otHours[] = 'OT' . $i;
}
$totalwhhours = 0;
foreach ($monthabs as $weekda) {
foreach ($weekda as $key => $value) {
foreach ($weekdays as $weeks) {
if ($weeks == $key) {
if ($value != 0) {
$values[] = $value;
}
}
}
foreach ($otHours as $ot) {
if ($ot == $key) {
if ($value != 0) {
$otvalues[] = $value;
}
}
}
}
}
$totalothour = array_sum($otvalues);
//$totalwhhour = sizeof($values);
$totalwhhours = array_sum($values);
$totalwhhour = $totalwhhours / 8;
if ($CURMONTH == $doj_month && $CURYEAR == $doj_year) {
$data['CUR_month'] = $CURDATE - $doj_day + 1;
} else {
$data['CUR_month'] = $date;
}
if ($totalwhhour != 0) {
$year = date('Y');
$current_month = date('m');
$data['values'] = $totalwhhour;
//$data['salaryInCurrentday'] = round($salaryInCurrentday);
$data['present_percentage'] = round(($totalwhhour / $data['CUR_month']) * 100);
} else {
$data['values'] = 0;
//$data['salaryInCurrentday'] = 0;
$data['present_percentage'] = 0;
}
if (empty($empID)) {
echo json_encode($data);
} else {
return $data;
}
}
/*this function used to speedometer year emp performances display*/
function attendanceyear($empID = '')
{
$CURMONTH = date('m');
$CURDATE = date('d');
$CURYEAR = date('Y');
$EmpID = '';
if (empty($empID)) {
$EmpID = $this->request->getPost('id');
} else {
$EmpID = $empID;
}
$day = array();
$datejoin = $this->dahsboard_Model->joindate($EmpID);
$DateofJoiningInString = $datejoin[0]->DateofJoining;
$DateofJoining = date_create($DateofJoiningInString);
// $doj_month = date_format($DateofJoining, "n");
// $doj_year = date_format($DateofJoining, "Y");
// $doj_day = date_format($DateofJoining, "j");
$doj_month = format_date($DateofJoining, 0, 'n');
$doj_year = format_date($DateofJoining, 0, 'Y');
$doj_day = format_date($DateofJoining, 0, 'j');
$finStart = $this->getFinancialStartDate();
$finEnd = $this->getFinancialEndDate();
$JoinedMonth = date_format($DateofJoining, "n");
if ($DateofJoining >= $finStart && $DateofJoining <= $finEnd) {
$JoinedMonthAttendance = $this->dahsboard_Model->getAllAttendances($EmpID, $JoinedMonth);
$joinedMonthDaysCount = cal_days_in_month(CAL_GREGORIAN, $doj_month, $doj_year);
if ($CURMONTH == $doj_month && $CURYEAR == $doj_year) {
$joinedMonthWorkingDayCount = $CURDATE - $doj_day + 1;
} else {
$joinedMonthWorkingDayCount = $joinedMonthDaysCount - $doj_day + 1;
}
$joinedMonthDays = 0;
for ($j = $doj_day; $j <= $joinedMonthDaysCount; $j++) {
$weekdays[] = 'WH' . $j;
}
foreach ($JoinedMonthAttendance as $day) {
foreach ($day as $key => $value) {
foreach ($weekdays as $weeks) {
if ($weeks == $key) {
if ($value != 0) {
// echo $value;
$joinedMonthDays++;
}
}
}
}
}
$result = $this->dahsboard_Model->attendanceyear($EmpID, $JoinedMonth + 1);
$yearabs = $this->dahsboard_Model->getAllAttendance($EmpID, $CURMONTH);
$TotalNoofDays = $result[0]->TotalWorkingDays;
$DaysWorked = $result[0]->DaysWorked;
$values = 0;
$values = array();
$weekdays = array();
$date = date('d');
$Work = array_sum($weekdays);
for ($j = 1; $j <= $date; $j++) {
$weekdays[] = 'WH' . $j;
}
$totalhours = 0;
foreach ($yearabs as $day) {
foreach ($day as $key => $value) {
foreach ($weekdays as $weeks) {
if ($weeks == $key) {
if ($value != 0) {
//$values++;
//$totalhours = array_sum($value);
$values[] = $value;
}
}
}
}
}
$DaysWorked = 0;
$totalhours = array_sum($values);
$values = $totalhours / 8;
if ($CURMONTH == $doj_month && $CURYEAR == $doj_year) {
$TotalNoofDays = $TotalNoofDays + $joinedMonthWorkingDayCount;
$DaysWorked = $joinedMonthDays;
} else {
$TotalNoofDays = $TotalNoofDays + $CURDATE + $joinedMonthWorkingDayCount;
$DaysWorked = $DaysWorked + $joinedMonthDays + $values;
}
$final_res = round(($DaysWorked / $TotalNoofDays) * 100);
$data['workeds'] = $DaysWorked;
$data['yeardata'] = $final_res;
$data['totaldays'] = $TotalNoofDays;
} else {
$result = $this->dahsboard_Model->attendanceyear($EmpID, 4);
$yearabs = $this->dahsboard_Model->getAllAttendance($EmpID, $CURMONTH);
$TotalNoofDays = $result[0]->TotalWorkingDays;
$DaysWorked = $result[0]->DaysWorked;
$values = 0;
$values = array();
$weekdays = array();
$date = date('d');
$Work = array_sum($weekdays);
for ($j = 1; $j <= $date; $j++) {
$weekdays[] = 'WH' . $j;
}
foreach ($yearabs as $day) {
foreach ($day as $key => $value) {
foreach ($weekdays as $weeks) {
if ($weeks == $key) {
if ($value != 0) {
$values[] = $value;
}
}
}
}
}
$totalhours = array_sum($values);
$values = $totalhours / 8;
$TotalNoofDays = $TotalNoofDays + $CURDATE;
$DaysWorked = $DaysWorked + $values;
$final_res = round(($DaysWorked / $TotalNoofDays) * 100);
$data['workeds'] = $DaysWorked;
$data['yeardata'] = $final_res;
$data['totaldays'] = $TotalNoofDays;
}
if (empty($empID)) {
echo json_encode($data);
} else {
return $data;
}
}
/****************HR DASHBOART Controller END **************************************/
/**
* This function is used to load the user list
*/
function userListing()
{
// if($this->isAdmin() == TRUE)
// {
// $this->loadThis();
// }
// else
// {
$data['userRecords'] = $this->user_model->userListing();
$this->global['pageTitle'] = 'User Listing';
$this->loadViews("userListing", $this->global, $data, NULL);
//}
}
/**
* This function is used to load the add new form
*/
function addNew()
{
// if($this->isAdmin() == TRUE)
// {
// $this->loadThis();
// }
// else
// {
$data['EmpList'] = $this->user_model->getAllEmployees();
$data['roles'] = $this->user_model->getUserRoles();
$data['Department'] = $this->costcenter_model->getDepartment();
$this->global['pageTitle'] = 'Add New User';
$this->loadViews("addUser", $this->global, $data, NULL);
// }
}
/**
* This function is used to check whether email already exist or not
*/
function checkEmailExists()
{
$userId = $this->request->getPost("userId");
$email = $this->request->getPost("email");
if (empty($userId)) {
$result = $this->user_model->checkEmailExists($email);
} else {
$result = $this->user_model->checkEmailExists($email, $userId);
}
if (empty($result)) {
echo ("true");
} else {
echo ("false");
}
}
/* Validation for Employee Dropdown
*/
function Employee_validate($selectValue)
{
//echo 'select_validate method called';
// 'none' is the first option and the text says something like "-Choose one-"
if ($selectValue == '0') {
// $this->validator->setMessage('Employee_validate', 'Please Select Employee.');
return false;
} else // user picked something
{
return true;
}
}
/* Validation for Employee Dropdown
*/
function Role_validate($selectValue)
{
//echo 'select_validate method called';
// 'none' is the first option and the text says something like "-Choose one-"
if ($selectValue == '0') {
// $this->validator->setMessage('Role_validate', 'Please Select Role.');
return false;
} else // user picked something
{
return true;
}
}
/**
* This function is used to add new user to the system
*/
public function addNewUser()
{
// $validationRules = [
// 'EmpList' => 'trim|callback_Employee_validate',
// 'password' => 'required|max_length[20]',
// 'cpassword' => 'trim|required|matches[password]|max_length[20]'
// ];
// $validationMessages = [
// 'EmpList' => [
// 'Employee_validateS' => 'Please select an employee.'
// ]
// ];
// $this->validate($validationRules, $validationMessages);
// Validation passed
$EmpID = $this->request->getPost('EmpList');
$roleId = '2';
$password = (string)$this->request->getPost('password');
$Createddt = date('Y-m-d H:i:s');
$email = $this->request->getPost('MailID');
$SelectedDepartment = (string)$this->request->getPost('txtSelectedDepartment');
$comma_separated = explode(':', $SelectedDepartment);
$userInfo = [
'email' => $email,
'EmpID' => $EmpID,
'password' => password_hash($password, PASSWORD_DEFAULT), // Use password_hash() for hashing passwords
'roleId' => $roleId,
'createdBy' => $this->vendorId,
'createdDtm' => $Createddt
];
$result = $this->user_model->addNewUser($userInfo);
if ($SelectedDepartment != '') {
foreach ($comma_separated as $DeptCode) {
$userdept = [
'EmpID' => $EmpID,
'Departmentcode' => $DeptCode
];
$access = $this->user_model->addAccess($userdept);
}
}
if ($result > 0) {
// return redirect()->to('userListing')->with('success', 'New user created successfully!');
$this->session->setFlashdata('success', 'New user created successfully!');
} else {
// return redirect()->to('userListing')->with('error', 'Failed to create user.');
$this->session->setFlashdata('error', 'Failed to create user.');
}
return redirect()->route('userListing');
}
function Adduserdepartment()
{
$empid = $this->request->getPost('Eid');
$Depcode = $this->request->getPost('Department');
$userdept = array('EmpID' => $empid, 'Departmentcode' => $Depcode);
$access = $this->user_model->addAccess($userdept);
if ($access > 0) {
echo "Successfully Added";
}
}
function Deleteuserdepartment()
{
$empid = $this->request->getPost('Eid');
$Depcode = $this->request->getPost('Department');
$userdept = array('EmpID' => $empid, 'Departmentcode' => $Depcode);
$access = $this->user_model->DeleteAccess($empid, $Depcode);
if ($access > 0) {
echo "Successfully Deleted";
}
}
/**
* This function is used load user edit information
* @param number $userId : Optional : This is user id
*/
function editOld($UserId = '')
{
// if($this->isAdmin() == TRUE )
// {
// $this->loadThis();
// }
// else
// {
if ($UserId == '') {
// redirect('userListing');
}
$Uid = $_GET['UID'];
$Empid = $_GET['EMPID'];
$data['roles'] = $this->user_model->getUserRoles();
$data['EmpList'] = $this->user_model->GetEmployeeDetails($Uid);
$data['Departmentlist'] = $this->costcenter_model->getDepartmentnotadded($Empid);
$data['EmpRole'] = $this->user_model->GetRoleNameByUserID($Uid);
$data['AccessDept'] = $this->costcenter_model->getaccessDept($Empid);
// $data['userInfo'] = $this->user_model->getUserInfo($userId);
$this->global['pageTitle'] = 'Edit User';
$this->loadViews("editOld", $this->global, $data, NULL);
//}
}
/**
* This function is used to edit the user information
*/
function editUser()
{
// if($this->isAdmin() == TRUE)
// {
// $this->loadThis();
// }
// else
// {
// $userId = $this->request->getPost('EmpList');
// $this->validator->setRules([ 'EmpList'=> 'trim|callback_Employee_validate',
// 'role'=> 'trim|callback_Role_validate',
// 'password'=> 'required|max_length[20]',
// 'cpassword'=> 'trim|required|matches[password]|max_length[20]']);
// if ($this->validator->run() == FALSE) {
// $this->editOld($userId);
// } else {
$EmpID = $this->request->getPost('EmpList');
$role = $this->request->getPost('role');
$password = $this->request->getPost('password');
$updatedDate = get_current_date_time();
// echo $EmpID;
$userInfo = array();
$userInfo = array('password' => getHashedPassword($password), 'roleId' => $role, 'EmpId' => $EmpID, 'updatedDtm' => $updatedDate);
$result = $this->user_model->editUser($userInfo, $EmpID);
if ($result == true) {
$this->session->setFlashdata('success', 'User updated successfully');
} else {
$this->session->setFlashdata('error', 'User updation failed');
}
return redirect()->route('userListing');
// }
//}
}
/**
* This function is used to delete the user using userId
* @return boolean $result : TRUE / FALSE
*/
function deleteUser()
{
echo 'Delete';
$Uid = $this->request->getPost('id');
$updatedDate = get_current_date_time();
$userInfo = array('isDeleted' => 1, 'updatedBy' => $this->vendorId, 'updatedDtm' => $updatedDate);
$result = $this->user_model->deleteUser($Uid, $userInfo);
echo 'Succssfully change the user status to InAcive';
}
/**
* This function is used to load the change password screen
*/
function loadChangePass()
{
$this->global['pageTitle'] = 'Change Password';
$this->loadViews("changePassword", $this->global, NULL, NULL);
}
/**
* This function is used to change the password of the user
*/
function changePassword()
{
helper('form'); //$this->load->library('form_validation');
$this->validator->setRules(['oldPassword', 'Old password'=> 'required|max_length[20]']);
$this->validator->setRules(['newPassword', 'New password'=> 'required|max_length[20]']);
$this->validator->setRules(['cNewPassword', 'Confirm new password'=> 'required|matches[newPassword]|max_length[20]']);
if ($this->validator->run() == FALSE) {
$this->loadChangePass();
} else {
$oldPassword = $this->request->getPost('oldPassword');
$newPassword = $this->request->getPost('newPassword');
$resultPas = $this->user_model->matchOldPassword($this->vendorId, $oldPassword);
if (empty($resultPas)) {
$this->session->setFlashdata('nomatch', 'Your old password not correct');
return redirect()->route('loadChangePass');
} else {
$usersData = array(
'password' => getHashedPassword($newPassword), 'updatedBy' => $this->vendorId,
'updatedDtm' => date('Y-m-d H:i:sa')
);
$result = $this->user_model->changePassword($this->vendorId, $usersData);
if ($result > 0) {
$this->session->setFlashdata('success', 'Password updation successful');
} else {
$this->session->setFlashdata('error', 'Password updation failed');
}
return redirect()->route('loadChangePass');
}
}
}
//this function used to delivery performances
function deliver_perform()
{
$this->global['pageTitle'] = 'Delivery Performance';
if ($this->request->getPost('btn_submit')) {
$ab = $this->request->getPost('financialyear');
$fa = substr($ab, 0, -5);
$aa = substr($ab, 5, 5);
$m = $this->request->getPost('month');
$data['fy'] = $this->user_model->fincalYear();
$data['per'] = $this->user_model->deliver_perform($fa, $aa, $m);
}
$data['fy'] = $this->user_model->fincalYear();
$this->loadviews("deliver_perform", $this->global, $data, NULL);
}
/*
*favourite add function and load view
*/
function favourite()
{
$this->global['pageTitle'] = 'Add Favourite';
// $data['ponoreset']=$this->purchaseorder_model->ponoresetfinyear();
$this->loadViews("Favourite", $this->global, Null);
}
function favouriteadd()
{
$name = $this->request->getPost('name');
$url = $this->request->getPost('url');
$status = $this->request->getPost('status');
$CreateBy = $this->session->get('userId');
$createddt = get_current_date_time();
$menu = $this->request->getPost('menu');
// $RowCount = $this->request->getPost('txtRowCount');
// $DeletedRow = $this->request->getPost('txtDeletedRow');
// $comma_separated = explode(':', $DeletedRow);
$favourite = array('Menu_Name' => $name, 'Menu_URL' => $url, 'Status' => $status, 'Created_BY' => $CreateBy, 'Created_ON' => $createddt, 'Menu_ID' => $menu);
$getdata = $this->user_model->favouriteadd($favourite);
if ($getdata == 1) {
echo "success";
} else {
echo "failed";
}
}
// start zoho API
function zohobooks_api_fetch_all()
{
if (isset($_POST['sync'])) {
$con = new mysqli($this->db->hostname, $this->db->username, $this->db->password, $this->db->database);
$ch = curl_init();
$organization_id = '776847408';
$client_id = '1000.0WMDLCXAZV5DR60IKE9P49YTYGVL6C';
$refresh_token = '1000.0fcf314cc7b7b598df6e519461bbe9b8.f77688a2254137532ae33ad5e152a064';
$client_secret = '99da3a05cfa13cf91eb6476a3c44cfa3e21b6106a8';
$redirect_uri = 'https://resicoindustries.com/RIA';
$date_today = get_current_date();
// $date_yesterday = format_date($date_today, 1);
//$date_today = '2022-08-23';
$date_yesterday = format_date($date_today, 7);
// echo $date_yesterday;die();
$url_org = "https://books.zoho.com/api/v3/invoices?";
$fields = array(
"usestate" => "true",
"organization_id" => "776847408",
"date_start" => $date_yesterday,
"date_end" => $date_today
);
$data_all = http_build_query($fields);
$accesstoken = '1000.095b66fc95fc81874c1cfc7d15b0904e.10bc9956d9b9ec14cce1350ee0cf8254';
//code => 57 -->expired
//code => 0 -->not expired
$headers = array(
'Authorization:Zoho-oauthtoken ' . $accesstoken,
'Content-Type:application/json'
);
$data_access = $url_org . $data_all;
curl_setopt($ch, CURLOPT_URL, $data_access);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
$body = '{}';
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$res = json_decode($result);
if ($res->code == "57") {
//echo 'new token';//die();
$url_getauthtoken = 'https://accounts.zoho.com/oauth/v2/token?refresh_token=' . $refresh_token . '&client_id=' . $client_id . '&client_secret=' . $client_secret . '&redirect_uri=' . $redirect_uri . '&grant_type=refresh_token';
curl_setopt($ch, CURLOPT_URL, $url_getauthtoken);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
$body = '{}';
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res_token = curl_exec($ch);
$ress = json_decode($res_token);
$newaccesstoken = $ress->access_token;
$headers_new = array(
'Authorization:Zoho-oauthtoken ' . $newaccesstoken,
'Content-Type:application/json'
);
curl_setopt($ch, CURLOPT_URL, $url_org . $data_access);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers_new);
curl_setopt($ch, CURLOPT_HEADER, 0);
$body = '{}';
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$res = json_decode($result, true);
$inv_array = $res['invoices'];
foreach ($inv_array as $inv) {
$invoice_id = $inv['invoice_id'];
if ($invoice_id !== "") {
$url2 = 'https://books.zoho.com/api/v3/invoices/' . $invoice_id . '?organization_id=' . $organization_id;
curl_setopt($ch, CURLOPT_URL, $url2);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers_new);
curl_setopt($ch, CURLOPT_HEADER, 0);
$body2 = '{}';
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_POSTFIELDS, $body2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result2 = curl_exec($ch);
$resall = json_decode($result2, true);
$res2[] = $resall['invoice'];
}
}
$insert_count = 0;
$update_count = 0;
foreach ($res2 as $rs) {
$gst_no = $rs['gst_no'];
$sku = $rs['line_items'][0]['sku'];
$invoice_number = $rs['invoice_number'];
$invoice_date = $rs['date'];
$due_date = $rs['due_date'];
$item_price = $rs['line_items'][0]['rate'];
$item_order = $rs['line_items'][0]['item_order'];
$item_product_unit = $rs['line_items'][0]['unit'];
$item_name = $rs['line_items'][0]['name'];
$item_description = $rs['line_items'][0]['description'];
$item_quantity = $rs['line_items'][0]['quantity'];
// $batch_no = $rs['custom_fields'][5]['value'];
$batch_no = "";
$invoice_time = $rs['created_time'];
$time_array = explode("T", $invoice_time);
$time_array = explode("+", $time_array[1]);
$invoice_time = $time_array[0];
$status = $rs['status'];
//$vehicle_number = $rs['custom_field_hash']['cf_vehicle_number'];
//$transport_mode =$rs['custom_field_hash']['cf_transport_mode'];
//$purchase_order_date = $rs['custom_field_hash']['cf_purchase_order_date'];
$driver = $rs['custom_field_hash']['cf_driver'];
$place_of_supply = $rs['custom_field_hash']['cf_place_of_supply'];
$cgst = $rs['taxes'][0]['tax_name'];
$sgst = $rs['taxes'][1]['tax_name'];
$cgst = $cgst[4];
$sgst = $sgst[4];
$cgst = $cgst . '.000';
$getcgsttax = "SELECT * FROM ip_tax_rates WHERE tax_rate_percent='$cgst'";
$res_cgsttax = $con->query($getcgsttax);
$rw_cgsttax = $res_cgsttax->fetch_assoc();
$cgsttaxid = $rw_cgsttax['tax_rate_id'];
$sgst = $sgst . '.000';
$getsgsttax = "SELECT * FROM ip_tax_rates WHERE tax_rate_percent='$sgst'";
$res_sgsttax = $con->query($getsgsttax);
$rw_sgsttax = $res_sgsttax->fetch_assoc();
$sgsttaxid = $rw_sgsttax['tax_rate_id'];
$item_subtotal = $rs['line_items'][0]['item_total'];
$item_tax_total = $rs['tax_total'];
$item_total = $rs['total'];
$item_sgst_amt = $rs['taxes'][1]['tax_amount'];
$item_cgst_amt = $rs['taxes'][0]['tax_amount'];
$item_discount = 0.00;
$item_igst_amt = 0.00;
if ($batch_no == "") {
$batch_no = "";
}
$gst_sql = "SELECT * FROM ip_clients WHERE client_tax_code='$gst_no'";
$res_gst = $con->query($gst_sql);
// $r_gst[] = $res_gst->fetch_assoc()['client_id'];
$client_id = $res_gst->fetch_assoc()['client_id'];
$sku_sql = "SELECT * FROM ip_products WHERE sku='$sku'";
$res_sku = $con->query($sku_sql);
// $r_sku[] = $res_sku->fetch_assoc()['product_id'];
$product_id = $res_sku->fetch_assoc()['product_id'];
$sql_invoice_chk = "SELECT * FROM ip_invoices WHERE invoice_number='$invoice_number' AND invoice_date_created='$invoice_date'";
$res_invoice = $con->query($sql_invoice_chk);
if ($res_invoice->num_rows <= 0) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < 16; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
$url_key = $randomString;
$sql_invoice_insert = "INSERT INTO ip_invoices(user_id,client_id,invoice_group_id,invoice_status_id,invoice_date_created,invoice_time_created,invoice_date_due,invoice_number,invoice_url_key,receivedstatus,crediT_Status)VALUES(1,'$client_id',6,2,'$invoice_date','$invoice_time','$due_date','$invoice_number','$url_key','ST066',0)";
$result_invoice_insert = $con->query($sql_invoice_insert);
$invoice_insert_id = $con->insert_id;
$sql_invoiceitem_insert = "INSERT INTO ip_invoice_items(invoice_id,item_product_id,item_date_added,item_name,item_description,item_quantity,item_price,item_order,item_product_unit,Sgst_item_tax_rate_id,Cgst_item_tax_rate_id)
VALUES('$invoice_insert_id','$product_id','$invoice_date','$item_name','$item_description','$item_quantity','$item_price','$item_order','$item_product_unit','$sgsttaxid','$cgsttaxid')";
$result_invoiceitem_insert = $con->query($sql_invoiceitem_insert);
$item_insert_id = $con->insert_id;
//tax amount -- ip_invoice_item_amounts - table
$sql_tax_amount_insert = "INSERT INTO ip_invoice_item_amounts(item_id,item_subtotal,item_tax_total,item_total,item_sgst_amt,item_cgst_amt,item_discount,item_igst_amt)VALUES('$item_insert_id','$item_subtotal','$item_tax_total','$item_total','$item_sgst_amt','$item_cgst_amt','$item_discount','$item_igst_amt')";
$result_tax_amount_insert = $con->query($sql_tax_amount_insert);
//custom fields insert
$sql_invoice_custom_insert = "INSERT INTO ip_invoice_custom(invoice_id,invoice_custom_fieldid,invoice_custom_fieldvalue)VALUES('$invoice_insert_id',62,'$batch_no')";
$result_invoice_custom_insert = $con->query($sql_invoice_custom_insert);
// $custom_vehicle = "INSERT INTO ip_invoice_custom(invoice_id,invoice_custom_fieldid,invoice_custom_fieldvalue)VALUES('$invoice_insert_id',8,'$vehicle_number')";
// $res_vehicle = $con->query($custom_vehicle);
// $custom_transport_mode = "INSERT INTO ip_invoice_custom(invoice_id,invoice_custom_fieldid,invoice_custom_fieldvalue)VALUES('$invoice_insert_id',7,'$transport_mode')";
// $res_transport_mode= $con->query($custom_transport_mode);
// $custom_purchase_order_date= "INSERT INTO ip_invoice_custom(invoice_id,invoice_custom_fieldid,invoice_custom_fieldvalue)VALUES('$invoice_insert_id',15,'$purchase_order_date')";
// $res_purchase_order_date = $con->query($custom_purchase_order_date);
$custom_driver = "INSERT INTO ip_invoice_custom(invoice_id,invoice_custom_fieldid,invoice_custom_fieldvalue)VALUES('$invoice_insert_id',58,'$driver')";
$res_driver = $con->query($custom_driver);
$custom_place = "INSERT INTO ip_invoice_custom(invoice_id,invoice_custom_fieldid,invoice_custom_fieldvalue)VALUES('$invoice_insert_id',10,'$place_of_supply')";
$res_place = $con->query($custom_place);
$insert_count = $insert_count + 1;
echo "success";
} else // update invoice status, especially for cancelled invoices
{
if ($status == "void") {
$sql_invoice_update = "UPDATE ip_invoices SET invoice_status_id = 5 WHERE invoice_number='$invoice_number' AND invoice_date_created='$invoice_date'";
$sql_invoice_update = $con->query($sql_invoice_update);
echo "update-" . $sql_invoice_update;
$update_count = $update_count + 1;
}
}
}
echo 'new invoice inserted count- ' . $insert_count . '/' . 'cancelled status updated count - ' . $update_count;
} else {
$invoice_id = $res->invoices[0]->invoice_id;
if ($invoice_id !== "") {
$url2 = 'https://books.zoho.com/api/v3/invoices/' . $invoice_id . '?organization_id=' . $organization_id;
curl_setopt($ch, CURLOPT_URL, $url2);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
$body2 = '{}';
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_POSTFIELDS, $body2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result2 = curl_exec($ch);
$res2 = json_decode($result2);
}
}
curl_close($ch);
}
}
// END zoho API
}