Code Coverage
 
Classes and Traits
Functions and Methods
Lines
Total
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 8
CRAP
0.00% covered (danger)
0.00%
0 / 218
UpdateAttendanceController
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 8
1332
0.00% covered (danger)
0.00%
0 / 217
 index
0.00% covered (danger)
0.00%
0 / 1
12
0.00% covered (danger)
0.00%
0 / 14
 create
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 store
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 show
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 edit
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 update
0.00% covered (danger)
0.00%
0 / 1
156
0.00% covered (danger)
0.00%
0 / 73
 destroy
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 updateAttendanceDetail
0.00% covered (danger)
0.00%
0 / 1
272
0.00% covered (danger)
0.00%
0 / 125
<?php
namespace App\Http\Controllers\Attendance;
use App\Http\Controllers\FirebaseController\FirebaseCloudMessaging;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Auth\User;
use App\Models\Admin\UserDetail;
use App\Models\Dashboard\AttendanceDetail;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;
use Session;
use App\Models\Admin\Team;
use App\Models\Auth\UserShift;
use App\Models\Schedule\Schedule;
use App\Models\Admin\TeamShiftDetail;
use App\Models\Admin\Shift;
use GetShiftDetailHelper;
use App\Notifications\AppNotifications;
use App\Models\Leave\ApplyLeave;
use App\Helpers\LeaveHelper;
use App\Helpers\AttendanceHelper;
ini_set('memory_limit', '256M');
class UpdateAttendanceController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $title = '/Attendance/Update Attendance';
        $backurl = route('home');
        if(auth()->user()->can('Can mark Attendance for all employees')){
            $users = User::all();
        }else{
            //Can mark Attendance for reporting employees
            $userIds =  GetShiftDetailHelper::getMyReportingEmployees();
            $users = User::whereIn('id', $userIds)->get();
        }
        $attendances = AttendanceDetail::all();
        $atdnce = '';
        foreach($attendances as $attendance)
        {
            $atdnce = $attendance->id;
        }
        // For Attendance Marking
        $val = AttendanceHelper::getAttendanceMarkValue();
        $valTeam = AttendanceHelper::getAttendanceTeam($request);
        $valUser = AttendanceHelper::getAttendanceUser($request);
        return view('attendance.AttendanceForm',compact('title','users','attendances','atdnce','backurl','val','valTeam','valUser'));
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
    }
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $user = User::find($request->user);
        // $date = Carbon::parse( Carbon::createFromFormat( config('settings.php_date_format') , $request->date ) )->format('Y-m-d');
        $date = Carbon::parse( Carbon::createFromFormat( config('settings.php_date_format') , $request->date ) )->format('Y-m-d');
        $checkIn = date("H:i:s", strtotime($request->check_in));
        $checkOut = date("H:i:s", strtotime($request->check_out));
        $request['check_in']= $checkIn;
        $request['check_out']= $checkOut;
        if($request->check_in > $request->check_out)  //If check in time greater than  check out time means two day shift
        {
            //$addDayToRequestDate = Carbon::parse($request->date,Config('app.timezone'))->addDay()->toDateString();
            $addDayToRequestDate = Carbon::parse(Carbon::createFromFormat( config('settings.php_date_format') , $request->date ),Config('app.timezone'))->addDay()->toDateString();
            $timeStampCheckIn = $date.' '.$request->check_in;
            $timeStampCheckOut = $addDayToRequestDate.' '.$request->check_out;
        }
        else
        {
            $timeStampCheckIn = $date.' '.$request->check_in;
            $timeStampCheckOut = $date.' '.$request->check_out;
        }
        $timeStampCheckIn = Carbon::parse($timeStampCheckIn,config('settings.time_zone'));
        $timeStampCheckIn = ($timeStampCheckIn)->setTimezone(config('app.timezone'));
        $timeStampCheckOut = Carbon::parse($timeStampCheckOut,config('settings.time_zone'));
        $timeStampCheckOut = ($timeStampCheckOut)->setTimezone(config('app.timezone'));
        $timeStampCheckIn = Carbon::parse($timeStampCheckIn)->format('Y-m-d H:i:s');
        $timeStampCheckOut = Carbon::parse($timeStampCheckOut)->format('Y-m-d H:i:s');
        if($request->has('shift')){
            $shift = Shift::where('id',$request->shift)->first();
            $shiftStartTime =  $shift->start_time;
            $shiftEndTime =  $shift->end_time;
        }
        else{
        $shiftDetails = $user->userdetail->shifts;
        if($shiftDetails->count() == 1) //if there is only one applicable shift for a user
        {
            foreach ($shiftDetails  as $shift)
            {
                $shiftStartTime =  $shift->start_time;
                $shiftEndTime =  $shift->end_time;
            }
        }
        else
        {
            return;
        }
        }           
        $atdnce = AttendanceDetail::updateOrCreate(
        [
            'id'=>$request->attendanceDetailId
        ],
        [
            'user_id' => $user->id,
            'check_in' => $timeStampCheckIn,
            'check_out' =>  $timeStampCheckOut,
            'shift_start'=> $shiftStartTime,
            'shift_end' => $shiftEndTime,
            'mode' => 'On Request',
            'start_time' => $shiftStartTime,
            'end_time' => $shiftEndTime
        ]);
            $dcheck_in = Carbon::parse($atdnce->check_in);
            $dcheck_in->setTimezone(config('settings.time_zone'));
            // $dcheck_in =  $dcheck_in->format('Y-m-d');
            $dcheck_in =  $dcheck_in->format(config('settings.php_date_format'));
            //if user is on leave
            $userOnLeave = ApplyLeave::where('from_date', '<=', $dcheck_in)
                                        ->where('to_date', '>=', $dcheck_in)
                                        ->where('status', 'Approve')
                                        ->where('user_id', $atdnce->user_id)
                                        ->first();
            if(!empty($userOnLeave)){
            $reason = $userOnLeave->reason.' '.'(System : Leave length reduced due to  approving attendance)';
            if($userOnLeave->leave_length == 1 ){
                if (strstr($userOnLeave->reason , 'System : Leave length reduced due to  approving attendance)')){
                   $userOnLeave->update(['status' => 'cancel','leave_length' => 0]);
                }else{
                   $userOnLeave->update(['status' => 'cancel','leave_length' => 0,'reason' => $reason]);
                }
            }else if($userOnLeave->leave_length > 1){
                if (strstr($userOnLeave->reason , 'System : Leave length reduced due to  approving attendance)')){
                    $userOnLeave->update(['leave_length' => $userOnLeave->leave_length-1]);
                }else{
                    $userOnLeave->update(['leave_length' => $userOnLeave->leave_length-1,'reason' => $reason]);
                }
            }
            else if($userOnLeave->leave_length == '0.5'){
                     //to do the logic while approving the leave on a half day leave request.
            }
            if($userOnLeave->leave_length == '0.5'){
                $length = '0.5';
            }else{
                $length = 1;
            }
            LeaveHelper::updateLeaveBalanceOnAdminCancelling($atdnce->user_id,$userOnLeave->leave_id,$length);
            }
        $user_detail = UserDetail::where('user_id',$atdnce->user_id)->first();
        $attedance_date = Carbon::parse($atdnce->check_in,Config('app.timezone'))->format(config('settings.php_date_format'));
        //notification to user
        $title = "Attendance Request";
        $message = "Your attendance has been approved for ".$attedance_date;
        $actionUrl = null;
        $arr = null;
        $arr = [$title, $message, $actionUrl];
       
        $user_detail->user->notify(new AppNotifications($arr));
        $firebaseObject = new FirebaseCloudMessaging();
        $firebaseObject->sendFirebaseNotification($title,$message,$user_detail->user->id);
        Session::flash('success', 'Attendance Updated Successfully!');
        return redirect()->route('update-attendance.index');
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
    public function updateAttendanceDetail(Request $request)
    {
        $user =User::find($request->userId);
        $shiftTimes = [];
        $shiftNames = [];
        // dd($user->id);
        //$currentDateTime =$request->date;
        $currentDateTime = Carbon::parse( Carbon::createFromFormat( config('settings.php_date_format') , $request->date ) )->format('Y-m-d');
        // $currentDateTime = Carbon::parse( Carbon::createFromFormat( config('settings.php_date_format') , $request->date ) )->format(config('settings.php_date_format'));
        
        $startDate = Carbon::parse($currentDateTime.'00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
        $endDate = Carbon::parse(Carbon::parse($currentDateTime)->addDay()->toDateString().'00:00:00', config('settings.time_zone'))->setTimezone(config('app.time_zone'));
        $currentDateTime1 = Carbon::parse($currentDateTime,config('settings.time_zone'));
        $user_shift_name = '';
        if(isset($user))
        {
        
        $attendance_requet = null;
        //primary team id
        $teamId = $user->userdetail->primary_team_id;
        if($teamId == 0){
            return response()->json([
                'warning' => 'Team is not assigned to user',
            ]);
        }
        $team =  Team::find($teamId);
        if($team->has_schedule == 1) {
                 //$schedules = Schedule::where('team_id', $teamId)->get();
                 $schedule = Schedule::where('from_date', '<=', $currentDateTime1)
                 ->where('to_date', '>=', $currentDateTime1)->where('status', '0')
                 ->where('team_id', $teamId)
                 ->first();
                 $teamSchedule = $schedule;
                 if(!isset($teamSchedule)) {
                   $teamSchedule = Schedule::where('is_default', 1)
                   ->where('status', '0')
                   ->where('team_id', $teamId)
                   ->first();
                 }
                 if(isset($teamSchedule)) {
                    $shift = UserShift::where('date', $currentDateTime)->where('user_id',$request->userId)->first();
                     $teamShifts = TeamShiftDetail::where('team_id', $teamSchedule->team_id)->with('shift')->get();
                   // dd( $shift );
                //      $user_shift_name .= '<select id ="shift" name="shift" class="form-control required">';
                //      $user_shift_name .= '<option disabled="" selected="" value="">Please Select Shift</option>';
                //     foreach($teamShifts as $teamShift){
                //         $user_shift_name .= '<option value="'.$teamShift->shift->id.'">'.$teamShift->shift->shift.'</option>';
                //     }
                //     $user_shift_name .= '</select>';
                //  }
                if ($shift) {
                    $user_shift_name = $shift->shift_name;
                    $user_shift_name .= '<input type="hidden" name="shift" value="'.$shift->shift_id.'">';
                   $dataQuery = AttendanceDetail::where('user_id', $user->id)
                               ->whereDate('check_in', '=', $currentDateTime)
                               ->exists();
                   if ($dataQuery == false){
                       $utcStartTime = Carbon::parse($shift->shift_start, 'UTC');
                       $istStartTime = $utcStartTime->setTimezone(Config('settings.time_zone'));
                       $formattedIstStartTime = $istStartTime->format('h:i A');
                       // For converting end_time of shift from UTC into IST
                       $utcEndTime = Carbon::parse($shift->shift_end, 'UTC');
                       $istEndTime = $utcEndTime->setTimezone(Config('settings.time_zone'));
                       $formattedIstEndTime = $istEndTime->format('h:i A');
                       return response()->json([
                           'check_in' => $formattedIstStartTime,
                           'check_out' =>$formattedIstEndTime  ,
                           'id'=> null,
                           'attendance_requet' => $attendance_requet,
                           'user_shift_name' => $user_shift_name
                       ]);
                    }
                
            } else {
                $user_shift_name = 'Shift was not assigned for that day';
                return response()->json([
                    'check_in' => null,
                    'check_out' =>null  ,
                    'id'=> null,
                    'attendance_requet' => $attendance_requet,
                    'user_shift_name' => $user_shift_name
                ]);
               
            }
        }
    }else{
            $shiftDetails = $user->userdetail->shifts;
            if(empty($shiftDetails)){
            return response()->json([
                'warning' => 'Shift is not assigned to user',
            ]);
            }
            $teamShifts = Shift::all();
            $shiftDetails = $user->userdetail->shifts;
            $user_shift_name .= '<table><tr>';
            $columnOne = '<th>';
            $columnTwo = '<th>';
            if ($shiftDetails->count() == 1) //if there is only one applicable shift for a user
            {
                $shift = $shiftDetails[0];
                $columnOne .= '<div id="shiftNameDiv">'.$shift->shift.'</div>';
                $columnOne .= '<input type="hidden" name="shift" value="'.$shift->id.'">';
                $columnOne .= '</th>';
            }
            $columnTwo .= '<select id="shift" name="shift" class="form-control">';
            $columnTwo .= '<option disabled="" selected="" value="">Please Select Shift</option>';
            foreach ($teamShifts as $teamShift) {
                $time["start_time"] = Carbon::parse($teamShift->start_time, 'UTC')->setTimezone('Asia/Kolkata')->format('h:i A');
                $time["end_time"] = Carbon::parse($teamShift->end_time, 'UTC')->setTimezone('Asia/Kolkata')->format('h:i A');
                $shiftTimes[$teamShift->id] = $time;
                $shiftNames[$teamShift->id] = $teamShift->shift;
                // Add an option for each shift
                $columnTwo .= '<option value="' . $teamShift->id . '">' . $teamShift->shift . '</option>';
            }
            $columnTwo .= '</select>';
            $columnTwo .= '</th>';
            $user_shift_name.= $columnOne;
            $user_shift_name .= '<th>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp</th>';
            $user_shift_name .= $columnTwo;
            $user_shift_name .= '</tr>';
            $user_shift_name .= '</table>';
        }
            $query = AttendanceDetail::query();
            $query->where('user_id','=',$user->id);
            $query->whereBetween('check_in', [$startDate, $endDate]);
            $query->where('user_id','=',$user->id);
            $attendanceDetail = $query->get();
            $count = $attendanceDetail->count();
            if($count != 0)
            {
                foreach ($attendanceDetail as $value)
                {
                    if(isset($value->user_id))
                    {
                      $attendanceDetailId = $value->id;
                        if(isset($value->check_in))
                        {
                            $check_in = Carbon::parse($value->check_in,config('app.timezone'));
                            $check_in->setTimezone(Config('settings.time_zone'));
                            $check_in = Carbon::parse($check_in)->toTimeString();
                            $check_in =  date(Config('settings.time_format'), strtotime($check_in));
                        }
                        else
                        {
                            $check_in = null;
                        }
                        if(isset($value->check_out))
                        {
                            $check_out = Carbon::parse($value->check_out,config('app.timezone'));
                            $check_out->setTimezone(Config('settings.time_zone'));
                            $check_out = Carbon::parse($check_out)->toTimeString();
                            $check_out =  date(Config('settings.time_format'), strtotime($check_out));
                        }
                        else
                        {
                            $check_out = null;
                        }
                    }
                }
            }
            else
            {
                $utcStartTime = Carbon::parse($shift->start_time, 'UTC');
                $istStartTime = $utcStartTime->setTimezone(Config('settings.time_zone'));
                $formattedIstStartTime = $istStartTime->format('h:i A');
                // For converting end_time of shift from UTC into IST
                $utcEndTime = Carbon::parse($shift->end_time, 'UTC');
                $istEndTime = $utcEndTime->setTimezone(Config('settings.time_zone'));
                $formattedIstEndTime = $istEndTime->format('h:i A');
                return response()->json([
                    'check_in' => $formattedIstStartTime,
                    'check_out' => $formattedIstEndTime,
                    'id'=> null,
                    'user_shift_name' => $user_shift_name,
                    'warning' => '',
                    'shiftTimings' => $shiftTimes,
                    'shiftNames' => $shiftNames
                ]);
            }
            return response()->json([
                'id'=> $attendanceDetailId,
                'check_in' => $check_in ,
                'check_out' => $check_out,
                'user_shift_name' => $user_shift_name,
                'warning' => '',
                'shiftTimings' => $shiftTimes,
                'shiftNames' => $shiftNames
            ]);
        }
    }
}