· 6 years ago · Aug 14, 2019, 01:42 PM
1<?php
2
3namespace App\Http\Controllers\Api\V1;
4
5use App\Http\Controllers\Controller;
6use App\Models\Brands;
7use App\Models\DidntPunch;
8use App\Models\EmployeesIODataTemp;
9use App\Models\ProAdditionalWork;
10use App\Models\ProTimeLockScreen;
11use Carbon\Carbon;
12use App\Models\Employees;
13use App\Models\EmployeeMeta;
14use App\Models\Projects;
15use App\Models\Terms;
16use Illuminate\Http\Request;
17use App\Http\Requests\EmployeeCreateRequest;
18use App\Repositories\EmployeesRepository;
19use App\Repositories\TimesheetsRepository;
20use App\Libraries\ResponseManager;
21use App\Models\TermRelationship;
22use App\Models\ProjectTasks;
23use App\Models\ProTask;
24use App\Models\ProTaskTime;
25use App\Models\Leaves;
26use App\Models\Holidays;
27use App\Models\Production;
28use App\Models\MongoCron;
29use App\Models\ProjectsData;
30use App\Models\TimeSheetData;
31use App\Models\EmployeeIODataTempTime;
32use App\Models\MongoLast90IOData;
33use App\Models\EmployeesProjectsData;
34use App\Models\EmployeeRolePermission;
35use App\Models\EmployeePermissions;
36use App\Models\RolePermissions;
37use App\Models\EmployeesIODataTodayYesterday;
38use App\Models\BusinessTour;
39use App\Models\Options;
40use DB;
41use DateTime;
42use Auth;
43use Tymon\JWTAuth\Facades\JWTAuth;
44use App\Http\Controllers\Api\V1\BrandsController;
45use App\Http\Requests\ApplyLeavesRulesRequest;
46use Illuminate\Validation\Validator;
47use App\Models\Groups;
48use App\Http\Requests\LeaveActionRequest;
49use App\Http\Requests\FlexiHourActionRequest;
50use App\Models\EmployeesWorkTypeData;
51use App\Repositories\MailRepository;
52use App\Models\AssociateAssign;
53use App\Models\AssociateAssignDetails;
54use App\Models\Templates;
55use App\Repositories\LeavePolicyRepository;
56use App\Models\Project;
57use App\Models\FlexiHours;
58
59
60/**
61 * @property EmployeesRepository employees
62 */
63class EmployeesController extends Controller {
64
65 /**
66 * Create a new controller instance.
67 *
68 * @return void
69 */
70 public function __construct(EmployeesRepository $employees, TimesheetsRepository $timesheets, MailRepository $mail, LeavePolicyRepository $leavepolicy) {
71 // dd(Auth::user()->employee_id);
72 $this->employees = $employees;
73 $this->timesheets = $timesheets;
74 $this->employeeModel = new Employees();
75 $this->mail = $mail;
76 $this->leavepolicy = $leavepolicy;
77 }
78
79 /**
80 * Generate JWT Token
81 * @param \Illuminate\Http\Request $request
82 * @return \Illuminate\Http\Response
83 */
84 public function getToken(Request $request) {
85 $response = $this->employees->create_jwt_token($request);
86 return $response;
87 }
88
89 /**
90 * @return array
91 */
92 public function motivation_quotes() {
93 $quotes = array(
94 "I want to put a ding in the universe. - Steve Jobs",
95 "Design is not just what it looks like and feels like. Design is how it works. - Steve Jobs",
96 "Innovation distinguishes between a leader and a follower. - Steve Jobs",
97 "Sometimes life is going to hit you in the head with a brick. Don't lose faith. - Steve Jobs",
98 "Be a yardstick of quality. Some people aren't used to an environment where excellence is expected. - Steve Jobs",
99 "We hire people who want to make the best things in the world. - Steve Jobs",
100 "Being the richest man in the cemetery doesn't matter to me. Going to bed at night saying we've done something wonderful, that's what matters to me. - Steve Jobs",
101 "It's really hard to design products by focus groups. A lot of times, people don't know what they want until you show it to them. - Steve Jobs",
102 "My favorite things in life don't cost any money. It's really clear that the most precious resource we all have is time. - Steve Jobs",
103 "Sometimes when you innovate, you make mistakes. It is best to admit them quickly, and get on with improving your other innovations. - Steve Jobs",
104 "Opportunities are brilliantly disguised as unsolved problems. - Margaret Mead",
105 "It always seems impossible until it's done. - Nelson Mandela",
106 "Failure will never overtake me if my determination to succeed is strong enough. - Og Mandino",
107 "Only I can change my life. No one can do it for me. - Carol Burnett",
108 "If you cannot do great things, do small things in a great way. - Napoleon Hill",
109 "There is nothing permanent except change. - Heraclitus",
110 "Life is 10% what happens to you and 90% how you react to it. - Charles R. Swindoll",
111 "Be happy for this moment. This moment is your life. - Omar Khayyam",
112 "It is always the simple that produces the marvelous. — Amelia Barr",
113 "Don’t Let Yesterday Take Up Too Much Of Today. – Will Rogers",
114 "Your limitation—it’s only your imagination.",
115 "Push yourself, because no one else is going to do it for you.",
116 "Sometimes later becomes never. Do it now.",
117 "Great things never come from comfort zones.",
118 "Dream it. Wish it. Do it.",
119 "Success doesn’t just find you. You have to go out and get it.",
120 "The harder you work for something, the greater you’ll feel when you achieve it.",
121 "Dream bigger. Do bigger.",
122 "Don’t stop when you’re tired. Stop when you’re done.",
123 "Wake up with determination. Go to bed with satisfaction.",
124 "Do something today that your future self will thank you for.",
125 "Little things make big days.",
126 "It’s going to be hard, but hard does not mean impossible.",
127 "Don’t wait for opportunity. Create it.",
128 "Sometimes we’re tested not to show our weaknesses, but to discover our strengths.",
129 "The key to success is to focus on goals, not obstacles.",
130 "Dream it. Believe it. Build it."
131 );
132 shuffle($quotes);
133 return ResponseManager::getResult($quotes[0], config('constants.StatusCode.Ok'), '', true);
134 }
135
136 /**
137 * @param Request $request
138 * @return array
139 */
140 public function working_days(Request $request) {
141 try {
142 $getTotalWrokingDays = $this->employees->get_working_day($request->get('startdate'), $request->get('enddate'));
143 foreach ($getTotalWrokingDays as $dates) {
144 $datesConveArray[] = ResponseManager::_date($dates);
145 }
146 $datesConveArray['count'] = count($datesConveArray);
147
148 return ResponseManager::getResult($datesConveArray, config('constants.StatusCode.Ok'), '', true);
149 } catch (JWTException $e) {
150 return ResponseManager::getError([], config('constants.StatusCode.BadRequest'), $e->getMessage(), config('constants.Boolean.False'));
151 }
152 }
153
154 /**
155 * @return array
156 */
157 public function is_lock_profile() {
158 try {
159 $user_info = $this->employees->user_info();
160 $_employee_id = $user_info['employee_id'];
161
162 $time_lock_data = ProTimeLockScreen::where('employee_id', $_employee_id)
163 ->where('lock_screen', 1)
164 ->orderBy('fill_dates', 'asc')
165 ->get();
166 $final_lock_details = array();
167 $index = 1;
168 foreach ($time_lock_data as $lock_data) {
169 $_lock_details = array();
170 $_lock_details['index'] = $index;
171 $_lock_details['id'] = $lock_data->id;
172 $_lock_details['project_id'] = $lock_data->project_id;
173 $_lock_details['project_name'] = $lock_data->project_name;
174 $_lock_details['project_po_number'] = $lock_data->project_po_number;
175 $_lock_details['task_id'] = $lock_data->task_id;
176 $_lock_details['employee_name'] = $lock_data->employee_name;
177 $_lock_details['employee_email'] = $lock_data->employee_email;
178 $_lock_details['employee_id'] = $lock_data->employee_id;
179 $_lock_details['last_fill_date'] = ResponseManager::_date($lock_data->last_fill_date);
180 $_lock_details['last_fill_days'] = $lock_data->last_fill_days;
181 $_lock_details['lock_screen'] = $lock_data->lock_screen;
182 $_lock_details['allocation_start_date'] = ResponseManager::_date($lock_data->allocation_start_date);
183 $_lock_details['allocation_end_date'] = ResponseManager::_date($lock_data->allocation_end_date);
184 $_lock_details['fill_dates'] = ResponseManager::_date($lock_data->fill_dates);
185
186 // check-in and check-out time format updated
187 $_temp_iodata_details = json_decode($lock_data->iodata_details, true);
188 $_temp_iodata_details['in_time'] = isset($_temp_iodata_details['in_time']) ? date('h:i A', strtotime($_temp_iodata_details['in_time'])) : '';
189 $_temp_iodata_details['out_time'] = isset($_temp_iodata_details['out_time']) ? date('h:i A', strtotime($_temp_iodata_details['out_time'])) : '';
190
191 $_lock_details['iodata_details'] = $_temp_iodata_details;
192 $_lock_details['minimum_timesheet'] = $lock_data->minimum_timesheet;
193 $_lock_details['work_from_home'] = $lock_data->work_from_home;
194
195 $final_lock_details[] = $_lock_details;
196 $index++;
197 }
198
199 return ResponseManager::getResult($final_lock_details, config('constants.StatusCode.Ok'), 'Lock screen', true);
200 } catch (JWTException $e) {
201 return ResponseManager::getError([], config('constants.StatusCode.BadRequest'), $e->getMessage(), config('constants.Boolean.False'));
202 }
203 }
204
205 /**
206 * @return array
207 */
208 public function manual_checkin_checkout() {
209 $final_details = array();
210 if (!@$_REQUEST['type'] || !in_array(strtolower(@$_REQUEST['type']), array("checkin", 'checkout'))) {
211 return ResponseManager::getResult($final_details, config('constants.StatusCode.Unprocessable'), 'required checkin / checkout type', true);
212 } else if ($_REQUEST['type']) {
213
214 $user_info = $this->employees->user_info();
215 $_employee_id = $user_info['employee_id'];
216 $_name = explode(' ', $user_info['name']);
217 $final_employee_name = @$_name[0] . " " . @$_name[2];
218 date_default_timezone_set("Asia/Kolkata");
219 $datetime = time();
220 $reporting_manager_id = $user_info['reporting_manager_id'];
221 $access_card_number = $user_info['access_card_number'];
222 if (strtolower($_REQUEST['type']) == "checkin") {
223 $io_type = "Entry";
224 $tripod = "Tripod ENTRY 1(I)";
225 $check_type = "Checked In";
226 $gate_number = "01-2";
227 } else {
228 $io_type = "Exit";
229 $tripod = "Tripod EXIT 1(O)";
230 $gate_number = "01-2";
231 $check_type = "Checked Out";
232 }
233
234 $didnt_punch = DidntPunch::where('employee_id', $_employee_id)
235 ->where('from_date', date('Y-m-d', $datetime))
236 ->where('to_date', date('Y-m-d', $datetime))
237 ->first();
238 $didnt_punch_id = ($didnt_punch['didnt_punch_id'])?$didnt_punch['didnt_punch_id']:0;
239
240 // if ($didnt_punch_id) {
241
242 // getting ip address for process
243 $ip_address = ResponseManager::get_ip_address();
244
245 // make entry for old ERP system gbl_employees_iodata_temp table
246 EmployeesIODataTemp::insert(
247 [
248 'didnt_punch_id' => $didnt_punch_id,
249 'cardNumber' => $access_card_number,
250 'employeeID' => $_employee_id,
251 'IODate' => date('Y-m-d', $datetime),
252 'IOTime' => date('H:i:s', $datetime),
253 'ip_address' => ResponseManager::get_ip_address(),
254 'IOStatus' => $io_type,
255 'reportingManagerID' => $reporting_manager_id,
256 'status' => 'Approved',
257 'remark' => 'Forgot Punch Card',
258 'iotime_added_by' => $_employee_id,
259 'action_by' => $_employee_id,
260 'action_datetime' => date('Y-m-d H:i:s', $datetime),
261 ]
262 );
263
264 EmployeesIODataTodayYesterday::insert(
265 [
266 'InOutID' => 0,
267 'cardNumber' => $access_card_number,
268 'employeeID' => $_employee_id,
269 'employeeName' => $final_employee_name,
270 'IODate' => date('Y-m-d', $datetime),
271 'IOTime' => date('H:i:s', $datetime),
272 'IOGateNo' => $gate_number,
273 'IOGateName' => $tripod,
274 'IOStatus' => $io_type,
275 'DepartmentNo' => 0,
276 'datetime' => date('Y-m-d H:i:s', $datetime),
277 ]
278 );
279
280 // update status in gbl_didnt_punch table
281 $didnt_punch = DidntPunch::where('status', 'Pending')
282 ->where('employee_id', $_employee_id)
283 ->where('from_date', date('Y-m-d', $datetime))
284 ->where('to_date', date('Y-m-d', $datetime))
285 ->update(['status' => 'Forgot Card']);
286 // print_r($didnt_punch);
287 // insert record in iodata_details collection
288
289 $day_check_length = date('j', $datetime);
290 if (strlen($day_check_length) == 1) {
291 $date_to_search = date('M j Y', $datetime) . " 12:00:00:000AM";
292 } else {
293 $date_to_search = date('M j Y', $datetime) . " 12:00:00:000AM";
294 }
295
296 $insert_response = MongoCron::create([
297 'InOutID' => (int) 0,
298 'CardNumber' => (string) $access_card_number,
299 'EmployeeName' => (string) $final_employee_name,
300 'employee_id' => (int) $_employee_id,
301 'io_date_time' => date('Y-m-d H:i:s', $datetime),
302 'IODate' => (string) $date_to_search,
303 'IOTime' => (string) date('H:i:s', $datetime) . ".0000000",
304 'IOGateNo' => (string) $gate_number,
305 'IOGateName' => (string) $tripod,
306 'IOStatus' => (string) $io_type,
307 'io_reason' => (string) 'Forgot Punch Card',
308 'DepartmentNo' => (int) 0,
309 'LocationName' => null,
310 'ip_address' => (string) $ip_address,
311 'created_at' => date('Y-m-d H:i:s', $datetime),
312 'oldid' => (string) '',
313 ]);
314 // }
315
316 $tmp = array();
317 $tmp['time'] = ResponseManager::_date($datetime, 'd M Y h:i:s A');
318 $tmp["gate"] = $tripod;
319 $tmp["check_type"] = $check_type;
320 $final_details = $tmp;
321 return ResponseManager::getResult($final_details, config('constants.StatusCode.New'), 'Manual checkin / checkout has been saved successful.', true);
322 }
323 }
324
325 /**
326 * @return array
327 */
328 public function timesheet_summary($emp_id = null,$date =null) {
329 $user_info = $this->employees->user_info();
330 $_employee_id =$emp_id ? $emp_id : $user_info['employee_id'];
331 $_for_date = $date ? $date : date('Y-m-d', strtotime($_REQUEST['for_date']));
332 $live_data = $this->get_employee_iodata_from_date($_for_date, $_employee_id);
333
334 // print_r($live_data);
335
336 $actual_hours = @$live_data['actual_hours']['h'] . "." . @$live_data['actual_hours']['i'];
337 $timesheets = ProjectTasks::select('pro_task_time.description', 'pro_task_time.task_time_id', 'pro_task_time.billable_hours', 'pro_task_time.date_time', 'gbl_employees.name as employee_name', 'pro_projects_modules.name as module_name', 'pro_projects.model as project_model', 'pro_projects.name as project_name', 'pro_task.task_id', 'pro_task.title', 'pro_task.module_id', 'pro_task.project_id')
338 ->leftJoin('pro_task_time', 'pro_task.task_id', '=', 'pro_task_time.task_id')
339 ->leftJoin('pro_projects', 'pro_task.project_id', '=', 'pro_projects.project_id')
340 ->leftJoin('pro_projects_modules', 'pro_task.module_id', '=', 'pro_projects_modules.id')
341 ->leftJoin('gbl_employees', 'pro_task.employee_id', '=', 'gbl_employees.employee_id')
342 ->where('pro_task_time.employee_id', $_employee_id)
343 ->where('pro_task_time.date', $_for_date)
344 ->orderBy('pro_task_time.task_id', 'asc')
345 ->get();
346
347 // print_r($timesheets);
348
349 $addition_timesheets = ProAdditionalWork::select('id', 'pro_additional_work.employee_id', 'pm_id', 'project_id', 'timesheet_date', 'task_title', 'task_module_id', 'project_module_id', 'skill_id', 'efforts', 'description', 'moderate_by', 'work_type', 'company_website_url', 'category_of_work', 'pro_additional_work.status', 'pro_additional_work.date_time')
350 ->leftJoin('gbl_employees', 'pro_additional_work.employee_id', '=', 'gbl_employees.employee_id')
351 ->where('pro_additional_work.employee_id', $_employee_id)
352 ->where('pro_additional_work.timesheet_date', $_for_date)
353 ->where('pro_additional_work.status', 'Pending')
354 ->get();
355
356 $_summary = array();
357 $total_efforts = 0;
358
359 // print_r($addition_timesheets);
360
361 foreach ($addition_timesheets as $times) {
362 $_tmp = array();
363 $_tmp['project_id'] = $times->project_id;
364 $_tmp['project_name'] = ($times->project_name) ? $times->project_name : "NON Project";
365 $_tmp['project_icon_url'] = ($times->project_name) ? 'https://www.indianic.com/wp-content/uploads/2016/11/app-icon.png' : 'https://www.indianic.com/wp-content/uploads/2016/11/app-icon.png';
366 $_tmp['project_model'] = ($times->project_name) ? $times->project_model : "";
367 $_tmp['module_name'] = $times->task_module_id;
368 $_tmp['title'] = @$times->task_title;
369 $_tmp['task_id'] = '';
370 $_tmp['task_description'] = $times->description;
371 $_tmp['task_time_id'] = '';
372 $_tmp['time_date_time'] = $times->date_time;
373 $_tmp['hours_ago'] = ResponseManager::time_ago($times['date_time']);
374 $_tmp['total_hours'] = $times->efforts;
375 $total_efforts = $total_efforts + $times->efforts;
376 $_summary[] = $_tmp;
377 }
378
379 foreach ($timesheets as $times) {
380 $_tmp = array();
381 $_tmp['project_id'] = $times->project_id;
382 $_tmp['project_name'] = $times->project_name;
383 $_tmp['project_icon_url'] = "https://www.indianic.com/wp-content/uploads/2016/11/app-icon.png";
384 $_tmp['project_model'] = $times->project_model;
385 $_tmp['module_name'] = $times->module_name;
386 $_tmp['title'] = $times->title;
387 $_tmp['task_id'] = $times->task_id;
388 $_tmp['task_description'] = $times->description;
389 $_tmp['task_time_id'] = $times->task_time_id;
390 $_tmp['time_date_time'] = $times->date_time;
391 $_tmp['hours_ago'] = ResponseManager::time_ago($times['date_time']);
392 $_tmp['total_hours'] = $times->billable_hours;
393 $total_efforts = $total_efforts + $times->billable_hours;
394 $_summary[] = $_tmp;
395 }
396
397 $actual_array = explode(".", $actual_hours);
398 $actual_minutes = $this->minutes_split_60(@$actual_array[1]);
399 $actual_final_hours = @$actual_array[0] . "." . $actual_minutes;
400 $final_remaining_hours = number_format($actual_final_hours - ($total_efforts), 2);
401 $_hours = explode('.', $final_remaining_hours);
402 $minutes = $this->minutes_split_100(@$_hours[1]);
403 $_final_hours = @$_hours[0] . "h " . $minutes . "m";
404
405 $_summary_final['tasks'] = $_summary;
406 $_summary_final['summary'] = array('label' => 'Remaining Time', 'value' => $_final_hours, 'value_in_hours' => @$_hours[0], 'value_in_minutes' => @$minutes);
407
408 return ResponseManager::getResult($_summary_final, config('constants.StatusCode.Ok'), '', true);
409 }
410
411 /**
412 * @param $req_minutes
413 * @return int
414 */
415 public function minutes_split_100($req_minutes) {
416 $minutes = 0;
417
418 if ($req_minutes >= 25 && $req_minutes < 50) {
419 $minutes = 15;
420 } else if ($req_minutes >= 50 && $req_minutes < 75) {
421 $minutes = 30;
422 } else if ($req_minutes >= 75 && $req_minutes < 100) {
423 $minutes = 45;
424 }
425 return $minutes;
426 }
427
428 /**
429 * @param $req_minutes
430 * @return int
431 */
432 public function minutes_split_60($req_minutes) {
433 $minutes = 0;
434 if ($req_minutes > 0 && $req_minutes <= 15) {
435 $minutes = 0;
436 } else if ($req_minutes > 15 && $req_minutes <= 30) {
437 $minutes = 25;
438 } else if ($req_minutes > 30 && $req_minutes <= 45) {
439 $minutes = 50;
440 } else if ($req_minutes > 45 && $req_minutes <= 60) {
441 $minutes = 75;
442 }
443 return $minutes;
444 }
445
446 /**
447 * @return array
448 */
449 public function today_timesheet() {
450 $obj_user = $this->employees->user_info();
451 $_for_date = date('Y-m-d');
452 $tasks = ProTask::select('p.name as project_name', 'p.model', 'p.project_unique_id', 'pro_task.estimated_hours', 'pro_task.task_id', 'pro_task.title as task_title', 'pro_task.associate_ids', 'pro_task.project_id', 'pro_task.module_id', 'pro_task.start_date', 'pro_task.due_date', 'pm.name as module_name')
453 ->leftJoin('pro_projects as p', 'p.project_id', '=', 'pro_task.project_id')
454 ->leftJoin('pro_projects_modules as pm', 'pm.id', '=', 'pro_task.module_id')
455 ->where('pro_task.start_date', '<=', $_for_date)
456 ->where('pro_task.due_date', '>=', $_for_date)
457 ->where('pro_task.status', 'Open')
458 ->where('pro_task.associate_ids', $obj_user['employee_id'])
459 ->get()
460 ->toArray();
461
462 $_summary_tasks = array();
463 $_module = array();
464 $_index = 1;
465 foreach ($tasks as $task) {
466
467 $actual_data = ProTaskTime::where('project_id', $task['project_id'])
468 ->where('employee_id', $obj_user['employee_id'])
469 ->where('task_id', $task['task_id'])
470 ->groupBy('project_id')
471 ->sum('billable_hours');
472
473 $minutes = $actual_data * 60;
474 $hours = floor($minutes / 60);
475 $min = $minutes - ($hours * 60);
476
477 //$get_hours = gmdate("H:i:s", $task['estimated_hours'] * 3600);
478 $_hours = explode('.', $task['estimated_hours']);
479 $_final_hours = $_hours[0] . "h " . $_hours[1] . "m";
480
481 $_temp = array();
482 $_temp['index'] = $_index;
483 $_temp['task_name'] = $task['task_title'];
484 $_temp['project_name'] = $task['project_name'];
485 $_temp['project_unique_id'] = $task['project_unique_id'];
486 $_temp['project_model'] = $task['model'];
487 $_temp['project_icon_url'] = "https://www.indianic.com/wp-content/uploads/2016/11/app-icon.png";
488 $_temp['estimated_hours'] = $_final_hours;
489 $_temp['task_id'] = $task['task_id'];
490 $_temp['associate_ids'] = $task['associate_ids'];
491 $_temp['project_id'] = $task['project_id'];
492 $_temp['task_start_date'] = ResponseManager::_date($task['start_date']);
493 $_temp['task_due_date'] = ResponseManager::_date($task['due_date']);
494 $_temp['actual_hours'] = $hours . "h" . " " . round($min) . "m";
495
496 if (in_array($task['module_id'], $_module)) {
497 $_summary_tasks['tasks'][] = $_temp;
498 } else {
499 $_module['module_id'] = $task['module_id'];
500 $_module['module_name'] = $task['module_name'];
501 $_summary_tasks = $_module;
502 $_summary_tasks['tasks'][] = $_temp;
503 }
504 $_index++;
505 }
506
507 return ResponseManager::getResult($_summary_tasks, config('constants.StatusCode.Ok'), '', true);
508 }
509
510 /**
511 * @return array
512 */
513 public function search_employee() {
514 if (strlen($_GET['q']) > 2) {
515 $search_string = $_GET['q'];
516 if (isset($_GET['circle']) && $_GET['circle'] == 'true') {
517 $obj_user = $this->employees->user_info();
518 $employee_id = (isset($_GET['employee_id'])) ? $_GET['employee_id'] : $obj_user['employee_id'];
519 $details = Employees::select('employee_id', 'name', 'email', 'status')
520 ->where(function ($query) use ($search_string) {
521 $query->where('name', 'Like', "%" . $search_string . "%")
522 ->orWhere('email', 'Like', $search_string . "%");
523 })
524 ->wherein('status', array('Active', 'Applied for resignation'))
525 ->where('reporting_manager_id', $employee_id)
526 ->orderBy('name', 'asc')
527 ->limit(10)
528 ->get();
529 } else {
530 $details = Employees::select('employee_id', 'name', 'email', 'status')
531 ->where(function ($query) use ($search_string) {
532 $query->where('name', 'Like', "%" . $search_string . "%")
533 ->orWhere('email', 'Like', $search_string . "%");
534 })
535 ->wherein('status', array('Active', 'Applied for resignation'))
536 ->orderBy('name', 'asc')
537 ->limit(10)
538 ->get();
539 }
540 $employee_final_array = array();
541 foreach ($details as $employee) {
542 $temp_employee = array();
543 $_name = explode(' ', $employee['name']);
544 $_final_name = $_name[0] . " " . $_name[2];
545 $temp_employee['employee_id'] = $employee['employee_id'];
546 $temp_employee['employee_name'] = $_final_name;
547 $temp_employee['employee_email'] = $employee['email'];
548 $temp_employee['employee_designation'] = $this->get_designation($employee['employee_id']);
549
550 $_urls = ResponseManager::get_profile_pic_urls($employee['employee_id']);
551 $temp_employee['image'] = $_urls['image'];
552 $temp_employee['image_150px_url'] = $_urls['image_150px_url'];
553 $temp_employee['image_500px_url'] = $_urls['image_500px_url'];
554
555 $employee_final_array[] = $temp_employee;
556 }
557 return ResponseManager::getResult($employee_final_array, config('constants.StatusCode.Ok'), '', true);
558 } else {
559 return ResponseManager::getResult('', config('constants.StatusCode.Forbidden'), 'The server understood the request!', true);
560 }
561 }
562
563 /**
564 * @return array
565 */
566 public function all_employees() {
567 $employees = Employees::select('employee_id', 'name', 'email', 'status')
568 ->wherein('status', array('Active', 'Applied for resignation'))
569 ->orderBy('name', 'asc')
570 ->get()->toArray();
571
572 $employee_final_array = array();
573 $_index = 1;
574 foreach ($employees as $employee) {
575 $temp_employee = array();
576 $_name = explode(' ', $employee['name']);
577 $_final_name = @$_name[0] . " " . @$_name[2];
578 $temp_employee['index'] = $_index;
579 $temp_employee['employee_id'] = $employee['employee_id'];
580 $temp_employee['employee_name'] = $_final_name;
581 $temp_employee['employee_email'] = $employee['email'];
582 $temp_employee['employee_designation'] = $this->get_designation($employee['employee_id']);
583
584 $_urls = ResponseManager::get_profile_pic_urls($employee['employee_id']);
585 $temp_employee['image'] = $_urls['image'];
586 $temp_employee['image_150px_url'] = $_urls['image_150px_url'];
587 $temp_employee['image_500px_url'] = $_urls['image_500px_url'];
588
589 $employee_final_array[] = $temp_employee;
590 $_index++;
591 }
592 return ResponseManager::getResult($employee_final_array, config('constants.StatusCode.Ok'), '', true);
593 }
594
595 /**
596 * @param $employee_id
597 * @return string
598 */
599 function get_designation($employee_id) {
600 $_designation = TermRelationship::select('gbl_term.name as Designation')
601 ->leftJoin('gbl_term', 'gbl_term_relationship.term_id', '=', 'gbl_term.term_id')
602 ->where('gbl_term_relationship.relation_type', 'emp_designation')
603 ->where('gbl_term_relationship.relation_id', $employee_id)
604 ->orderBy('gbl_term.name', 'asc')
605 ->first();
606 return ($_designation['Designation']) ? $_designation['Designation'] : '';
607 }
608
609 /**
610 * @return array
611 */
612 public function getEmployee() {
613 $response = $this->employees->get_user();
614 return $response;
615 }
616
617 /**
618 * @return array
619 * @throws \Exception
620 */
621 public function get_my_production_summary() {
622 $obj_user = $this->employees->user_info();
623 $for_date = (isset($_REQUEST['for_date'])) ? date('Y-m-d', strtotime($_REQUEST['for_date'])) : date('Y-m-d');
624 $employee_id = (isset($_REQUEST['employee_id'])) ? $_REQUEST['employee_id'] : $obj_user['employee_id'];
625 $live_data = $this->get_employee_iodata_from_date($for_date, $employee_id);
626// print_r($live_data);
627
628 if ($for_date) {
629 if ($employee_id && $for_date) {
630
631 $leaves = Leaves::select('gbl_leaves.leave_type', 'gbl_leaves.id', 'gbl_leaves.planned')
632 ->leftJoin('gbl_leaves_details as ld', function ($join) use ($for_date) {
633 $join->on('gbl_leaves.id', '=', 'ld.leave_id');
634 $join->where('ld.leave_date', $for_date);
635 })
636 ->where('gbl_leaves.user_id', $employee_id)
637 ->wherein('gbl_leaves.leave_status', array('Approved', 'Pending'))
638 ->whereRaw('? between gbl_leaves.date_from and gbl_leaves.date_to', $for_date)
639 ->first();
640
641 if (isset($leaves->id) && $leaves->id != 0) {
642 $_for_date = ResponseManager::_date($for_date);
643 $production_summary = array();
644 $production_summary['leave'] = true;
645 $production_summary['total_hrs'] = "";
646 $production_summary['break_hours'] = "";
647 $production_summary['actual_hours'] = "";
648 $production_summary['number_of_break'] = 0;
649 $production_summary['for_date'] = $_for_date;
650 $production_summary['in_time'] = "";
651 $production_summary['out_time'] = "";
652 $production_summary['leave_details'] = array();
653 $production_summary['pro_hour'] = 0;
654 $production_summary['pro_minut'] = 0;
655
656 $live_data['shift_time_from'] = isset($live_data['shift_time_from']) ? date('h:i A', strtotime($live_data['shift_time_from'])) : '';
657 $live_data['shift_time_to'] = isset($live_data['shift_time_to']) ? date('h:i A', strtotime($live_data['shift_time_to'])) : '';
658
659 $production_summary['iodata_details'] = $live_data;
660 } else {
661
662 $_for_date = ResponseManager::_date($for_date);
663 $production_summary = array();
664 $production_summary['leave'] = false;
665 $production_summary['total_hrs'] = isset($live_data['total_hrs']['h']) ? $live_data['total_hrs']['h'] . "h " . $live_data['total_hrs']['i'] . "m" : '';
666 $production_summary['break_hours'] = isset($live_data['break_hours']['h']) ? $live_data['break_hours']['h'] . "h " . $live_data['break_hours']['i'] . "m" : '';
667 $production_summary['actual_hours'] = isset($live_data['actual_hours']['h']) ? $live_data['actual_hours']['h'] . "h " . $live_data['actual_hours']['i'] . "m" : '';
668 $production_summary['pro_hour'] = isset($live_data['actual_hours']['h']) ? $live_data['actual_hours']['h'] : 0;
669 $production_summary['pro_minut'] = isset($live_data['actual_hours']['h']) ? $live_data['actual_hours']['i'] : 0;
670 $production_summary['number_of_break'] = isset($live_data['number_of_break']) ? $live_data['number_of_break'] : 0;
671 $production_summary['for_date'] = $_for_date;
672 $production_summary['in_time'] = isset($live_data['in_time']) ? date('h:i A', strtotime($live_data['in_time'])) : '';
673 $production_summary['out_time'] = isset($live_data['out_time']) ? date('h:i A', strtotime($live_data['out_time'])) : '';
674 $production_summary['leave_details'] = array();
675// $production_summary['iodata_details'] = json_decode('{"IODate":"2019-02-21","shift_time_from":"11:00:00","shift_time_to":"20:30:00","access_card_number":"0486","in_time":"2019-02-21 10:19:25.0000000","in_time_alert":0,"out_time":"2019-02-21 20:32:43.0000000","out_time_alert":0,"number_of_break":2,"total_hrs":{"h":"10","i":"13","s":"18","alert":0},"break_hours":{"h":"01","i":"17","s":"28","alert":1},"actual_hours":{"h":"08","i":"55","s":"50","alert":1},"gain_loss":{"h":"00","i":"43","s":"18","alert":0},"gain_loss_production":{"h":"00","i":"04","s":"10","alert":1},"io_original_entries":[{"IOTime":"2019-02-21 10:17:50.0000000","IOStatus":"Exit","IOGateName":"Basement Exit(I)","IOGateNo":"03-5"},{"IOTime":"2019-02-21 10:19:25.0000000","IOStatus":"Entry","IOGateName":"Tripod ENTRY 1(I)","IOGateNo":"01-2"},{"IOTime":"2019-02-21 12:45:19.0000000","IOStatus":"Exit","IOGateName":"Tripod EXIT 2(O)","IOGateNo":"02-5"},{"IOTime":"2019-02-21 12:45:25.0000000","IOStatus":"Exit","IOGateName":"Tripod EXIT 2(O)","IOGateNo":"02-5"},{"IOTime":"2019-02-21 13:32:37.0000000","IOStatus":"Exit","IOGateName":"Basement Exit(I)","IOGateNo":"03-5"},{"IOTime":"2019-02-21 13:34:12.0000000","IOStatus":"Entry","IOGateName":"Tripod ENTRY 1(I)","IOGateNo":"01-2"},{"IOTime":"2019-02-21 17:54:47.0000000","IOStatus":"Exit","IOGateName":"Tripod EXIT 2(O)","IOGateNo":"02-5"},{"IOTime":"2019-02-21 17:54:49.0000000","IOStatus":"Exit","IOGateName":"Tripod EXIT 2(O)","IOGateNo":"02-5"},{"IOTime":"2019-02-21 18:22:17.0000000","IOStatus":"Entry","IOGateName":"Ground Floor Enrty(O)","IOGateNo":"03-2"},{"IOTime":"2019-02-21 18:23:22.0000000","IOStatus":"Entry","IOGateName":"Tripod ENTRY 1(I)","IOGateNo":"01-2"},{"IOTime":"2019-02-21 20:32:43.0000000","IOStatus":"Exit","IOGateName":"Tripod EXIT 1(O)","IOGateNo":"01-5"}],"io_unique_entries":[{"IOTime":"2019-02-21 10:19:25.0000000","IOStatus":"Entry","IOGateName":"Tripod ENTRY 1(I)","IOGateNo":"01-2"},{"IOTime":"2019-02-21 12:45:19.0000000","IOStatus":"Exit","IOGateName":"Tripod EXIT 2(O)","IOGateNo":"02-5"},{"IOTime":"2019-02-21 13:34:12.0000000","IOStatus":"Entry","IOGateName":"Tripod ENTRY 1(I)","IOGateNo":"01-2"},{"IOTime":"2019-02-21 17:54:47.0000000","IOStatus":"Exit","IOGateName":"Tripod EXIT 2(O)","IOGateNo":"02-5"},{"IOTime":"2019-02-21 18:23:22.0000000","IOStatus":"Entry","IOGateName":"Tripod ENTRY 1(I)","IOGateNo":"01-2"},{"IOTime":"2019-02-21 20:32:43.0000000","IOStatus":"Exit","IOGateName":"Tripod EXIT 1(O)","IOGateNo":"01-5"}],"error":false,"leave":false,"leave_type":false,"work_from_home":"0"}');
676
677 $live_data['shift_time_from'] = isset($live_data['shift_time_from']) ? date('h:i A', strtotime($live_data['shift_time_from'])) : '';
678 $live_data['shift_time_to'] = isset($live_data['shift_time_to']) ? date('h:i A', strtotime($live_data['shift_time_to'])) : '';
679
680 $production_summary['iodata_details'] = $live_data;
681 }
682 return ResponseManager::getResult($production_summary, config('constants.StatusCode.Ok'), '', true);
683 }
684 } else {
685 return ResponseManager::getResult('', config('constants.StatusCode.Forbidden'), 'date is required!', true);
686 }
687 }
688
689 /**
690 * @return array
691 */
692 public function get_my_day_wise_attendance_chart_summary() {
693 $obj_user = $this->employees->user_info();
694 $employee_id = (isset($_REQUEST['employee_id']) && $_REQUEST['employee_id'] != null) ? $_REQUEST['employee_id'] : $obj_user['employee_id'];
695 $req_month = (isset($_REQUEST['month_year']) && $_REQUEST['month_year'] != null) ? $_REQUEST['month_year'] : date('M Y');
696
697 $production_summary = array();
698 $production_summary['employee_details'] = $this->employees->get_employee_basic_profile($employee_id, true);
699 $production_summary['segments'] = array(
700 array("segment_name" => "Holidays", "segment_color" => "ffa04f"),
701 array("segment_name" => "Weekends", "segment_color" => "e5e5e5"),
702 array("segment_name" => "Production Hours", "segment_color" => "0E7BE0"),
703 array("segment_name" => "Break Hours", "segment_color" => "efe058"),
704 );
705
706 $req_start_date = date('Y-m-01', strtotime($req_month));
707 $req_end_date = date('Y-m-t', strtotime($req_start_date));
708
709 // make holiday array
710 $holiday_date = Holidays::whereBetween('date', [$req_start_date, $req_end_date])->get();
711 $_holiday_list = array();
712 if (!empty($holiday_date)) {
713 foreach ($holiday_date as $holiday_date_val) {
714 $_holiday_list[] = $holiday_date_val['date'];
715 }
716 }
717
718 $_format = 'Y-m-d';
719 $start_date = strtotime($req_start_date);
720 $end_date = strtotime($req_end_date);
721
722 if ($req_month == date('M Y')) {
723 $working_days = $this->employees->get_working_day($req_start_date, date('Y-m-d'));
724 $end_date = strtotime(date('Y-m-d'));
725 } else {
726 $working_days = $this->employees->get_working_day($req_start_date, $req_end_date);
727 }
728 $total_employee_working_days = count($working_days);
729 $monthly_total_taken_leaves = 0;
730 $_dates_array = array();
731 while ($start_date <= $end_date) {
732
733 // get iodata from employee id and date
734 $live_data = $this->get_employee_iodata_from_date(date('Y-m-d', $start_date), $employee_id);
735 if ($live_data['io_original_entries'][0]['IOStatus'] == "IO Entry not exist.") {
736 $entries_exist = false;
737 } else {
738 $entries_exist = true;
739 }
740
741 if (@$live_data["leave"] && @$live_data['leave'] == "Full Day") {
742 $monthly_total_taken_leaves += 1;
743 $total_employee_working_days -= 1;
744 } else if (@$live_data["leave_type"] && @$live_data["leave_type"] == "First Half") {
745 $monthly_total_taken_leaves += 1;
746 $total_employee_working_days -= 1;
747 } else if (@$live_data["leave_type"] && @$live_data["leave_type"] == "Second Half") {
748 $monthly_total_taken_leaves += 1;
749 $total_employee_working_days -= 1;
750 }
751
752 $shift_time_from = isset($live_data['in_time']) ? date('h.i', strtotime($live_data['in_time'])) : '';
753 $shift_time_to = isset($live_data['out_time']) ? date('h.i', strtotime($live_data['out_time'])) : '';
754
755 $shift_time_from_string = isset($live_data['in_time']) ? date('h.i A', strtotime($live_data['in_time'])) : '';
756 $shift_time_to_string = isset($live_data['out_time']) ? date('h.i A', strtotime($live_data['out_time'])) : '';
757
758
759 // getting segment
760 $get_leaves = Leaves::where(['user_id' => $employee_id])->whereRaw('? between date_from and date_to', date('Y-m-d', $start_date))->get();
761 $_temp = array();
762 $_temp['day'] = ResponseManager::_date($start_date);
763 $_segment = "";
764 if ($start_date == date('Y-m-d')) {
765 $_segment = "Current";
766 } else if (in_array(date('Y-m-d', $start_date), $_holiday_list)) {
767 $_segment = "Holiday";
768 } else if (isset($get_leaves[0]['id']) && $get_leaves[0]['id'] != 0) {
769 $_segment = "Leave";
770 } else if (in_array(date('Y-m-d', $start_date), $working_days)) {
771 $_segment = "Production";
772 } else {
773 $_segment = "Weekend";
774 }
775
776 $deficit = (($live_data['actual_hours']['h'] * 60) + $live_data['actual_hours']['i']) - (9 * 60);
777
778 $deficit_in_min = ($live_data['actual_hours']['h'] * 60) + $live_data['actual_hours']['i'];
779 $final_diff_type = $final_diff_type_string = '';
780 if ($deficit_in_min > 540) {
781 $final_diff = round($deficit) . "% hours till today";
782 $final_diff_type = "up";
783 $final_diff_type_string = "+";
784 } else {
785 $final_diff = round($deficit) . "% hours till today";
786 $final_diff_type = "down";
787 $final_diff_type_string = '-';
788 }
789
790 $get_hours = gmdate("H:i:s", ltrim($deficit * 60, '-'));
791 $_hours = explode(':', $get_hours);
792 // print_r($_hours);
793 // print_r($deficit);
794 // print_r($live_data);
795 $shift_from_in_minutes = date('H', strtotime($live_data['shift_time_from'])) * 60;
796 $shift_from_in_minutes += date('i', strtotime($live_data['shift_time_from']));
797
798 // day start on
799 $shift_start_in_minutes = date('H', strtotime($live_data['in_time'])) * 60;
800 $shift_start_in_minutes += date('i', strtotime($live_data['in_time']));
801
802 // check how many times on time
803 if (in_array(date('Y-m-d', $start_date), $working_days)) {
804 $day_start_on_total = ($live_data['in_time'] == 0 || $shift_start_in_minutes >= $shift_from_in_minutes) ? false : true;
805 } else {
806 $day_start_on_total = "";
807 }
808
809 $_temp['entries_exist'] = $entries_exist;
810 $_temp['day_segment'] = $_segment;
811 $_temp['day_checkin_time'] = $shift_time_from;
812 $_temp['day_checkout_time'] = $shift_time_to;
813 $_temp['day_checkin_time_string'] = $shift_time_from_string;
814 $_temp['day_checkout_time_string'] = $shift_time_to_string;
815 $_temp['actual_total_hrs'] = $live_data['total_hrs']['h'] . "." . $live_data['total_hrs']['i'];
816 $_temp['actual_total_hrs_string'] = $live_data['total_hrs']['h'] . "h " . $live_data['total_hrs']['i'] . "m";
817 $_temp['start_day_on_time'] = $day_start_on_total;
818 $_temp['actual_production_hours'] = $live_data['actual_hours']['h'] . "." . $live_data['actual_hours']['i'];
819 $_temp['actual_production_hours_string'] = $live_data['actual_hours']['h'] . "h " . $live_data['actual_hours']['i'] . "m";
820 $_temp['break_hours'] = $live_data['break_hours']['h'] . "." . $live_data['break_hours']['i'];
821 $_temp['number_of_break'] = $live_data['number_of_break'];
822 $_temp['break_hours_string'] = $live_data['break_hours']['h'] . "h " . $live_data['break_hours']['i'] . "m";
823 $_temp['deficit_hours'] = @$_hours[0] . "." . @$_hours[1];
824 $_temp['deficit_flag'] = $final_diff_type;
825 $_temp['deficit_hours_string'] = $final_diff_type_string . @$_hours[0] . 'h ' . @$_hours[1] . 'm';
826
827 $_dates_array[] = $_temp;
828 $start_date = strtotime("+1 day", $start_date);
829 }
830 rsort($_dates_array);
831 $production_summary['dates'] = $_dates_array;
832 return ResponseManager::getResult($production_summary, config('constants.StatusCode.Ok'), '.', true);
833 }
834
835 /**
836 * @return array
837 */
838 public function production_day_wise_summary_team_members()
839 {
840 $obj_user = $this->employees->user_info();
841 $employee_id = (isset($_REQUEST['employee_id']) && $_REQUEST['employee_id'] != null) ? $_REQUEST['employee_id'] : $obj_user['employee_id'];
842 $req_month = (isset($_REQUEST['month_year']) && $_REQUEST['month_year'] != null) ? $_REQUEST['month_year'] : date('M Y');
843
844 $req_start_date = date('Y-m-01', strtotime($req_month));
845 $req_end_date = date('Y-m-t', strtotime($req_start_date));
846
847 // make holiday array
848 $holiday_date = Holidays::whereBetween('date', [$req_start_date, $req_end_date])->get();
849 $_holiday_list = array();
850 if (!empty($holiday_date)) {
851 foreach ($holiday_date as $holiday_date_val) {
852 $_holiday_list[] = $holiday_date_val['date'];
853 }
854 }
855
856 $_format = 'Y-m-d';
857 $start_date = strtotime($req_start_date);
858 $end_date = strtotime($req_end_date);
859
860 if ($req_month == date('M Y')) {
861 $working_days = $this->employees->get_working_day($req_start_date, date('Y-m-d'));
862 $end_date = strtotime(date('Y-m-d'));
863 } else {
864 $working_days = $this->employees->get_working_day($req_start_date, $req_end_date);
865 }
866 $total_employee_working_days = count($working_days);
867
868 $production_summary = array();
869 $production_summary['employee_details'] = $this->employees->get_employee_basic_profile($employee_id, true);
870
871 $details = Employees::select('employee_id', 'name', 'email', 'status')
872 ->wherein('status', array('Active', 'Applied for resignation'))
873 ->where('reporting_manager_id', $employee_id)
874 ->orderBy('name', 'asc')
875 ->get();
876
877 $members_id_array = array();
878 foreach ($details as $employee) {
879 $members_id_array[] = $employee['employee_id'];
880 }
881 $query_month = date("Y-m", strtotime($req_month));
882
883 $not_start_work_ontime = MongoLast90IOData::where("YearMonth", '=', $query_month)
884 ->wherein('EmployeeID', $members_id_array)
885 ->where('day_not_start_on_total', '!=', 0)
886 ->orderBy('day_not_start_on_total', 'desc')
887 ->limit(10)
888 ->get();
889 $not_started = array();
890 foreach ($not_start_work_ontime as $details) {
891
892 $temp = array();
893 $temp['employee_id'] = $details['EmployeeID'];
894 $temp['employee_name'] = $details['EmployeeName'];
895
896 $designation = Terms::select('gbl_term.name as designation')
897 ->leftJoin('gbl_term_relationship', 'gbl_term_relationship.term_id', '=', 'gbl_term.term_id')
898 ->where(['gbl_term_relationship.relation_id' => $details['EmployeeID'], 'taxonomy' => 'designation'])
899 ->first();
900 $temp['designation'] = @$designation['designation'];
901
902 $temp['total_day_not_start_on_time'] = $details['day_not_start_on_total'];
903 $_urls = ResponseManager::get_profile_pic_urls($details['EmployeeID']);
904 $temp['image'] = $_urls['image'];
905 $temp['image_150px_url'] = $_urls['image_150px_url'];
906 $temp['image_500px_url'] = $_urls['image_500px_url'];
907
908 $not_started[] = $temp;
909 }
910
911 $not_finish_production = MongoLast90IOData::where("YearMonth", '=', $query_month)
912 ->wherein('EmployeeID', $members_id_array)
913 ->where('total_production_not_finish', '!=', 0)
914 ->orderBy('total_production_not_finish', 'desc')
915 ->limit(10)
916 ->get();
917 $didnt_finish_production = array();
918 foreach ($not_finish_production as $details) {
919
920 $temp = array();
921 $temp['employee_id'] = $details['EmployeeID'];
922 $temp['employee_name'] = $details['EmployeeName'];
923
924 $designation = Terms::select('gbl_term.name as designation')
925 ->leftJoin('gbl_term_relationship', 'gbl_term_relationship.term_id', '=', 'gbl_term.term_id')
926 ->where(['gbl_term_relationship.relation_id' => $details['EmployeeID'], 'taxonomy' => 'designation'])
927 ->first();
928
929 $temp['designation'] = @$designation['designation'];
930
931 $temp['total_production_not_finish'] = $details['total_production_not_finish'];
932 $_urls = ResponseManager::get_profile_pic_urls($details['EmployeeID']);
933 $temp['image'] = $_urls['image'];
934 $temp['image_150px_url'] = $_urls['image_150px_url'];
935 $temp['image_500px_url'] = $_urls['image_500px_url'];
936
937 $didnt_finish_production[] = $temp;
938 }
939
940 $longest_breaks = MongoLast90IOData::where("YearMonth", '=', $query_month)
941 ->wherein('EmployeeID', $members_id_array)
942 ->where('total_longest_break', '!=', 0)
943 ->orderBy('total_longest_break', 'desc')
944 ->limit(10)
945 ->get();
946 $longest_breaks_array = array();
947 foreach ($longest_breaks as $details) {
948
949 $temp = array();
950 $temp['employee_id'] = $details['EmployeeID'];
951 $temp['employee_name'] = $details['EmployeeName'];
952
953 $designation = Terms::select('gbl_term.name as designation')
954 ->leftJoin('gbl_term_relationship', 'gbl_term_relationship.term_id', '=', 'gbl_term.term_id')
955 ->where(['gbl_term_relationship.relation_id' => $details['EmployeeID'], 'taxonomy' => 'designation'])
956 ->first();
957 $temp['designation'] = @$designation['designation'];
958
959 $temp['total_longest_break'] = $details['total_longest_break'];
960 $_urls = ResponseManager::get_profile_pic_urls($details['EmployeeID']);
961 $temp['image'] = $_urls['image'];
962 $temp['image_150px_url'] = $_urls['image_150px_url'];
963 $temp['image_500px_url'] = $_urls['image_500px_url'];
964
965 $longest_breaks_array[] = $temp;
966 }
967
968
969 $start_work_ontime = MongoLast90IOData::where("YearMonth", '=', $query_month)
970 ->wherein('EmployeeID', $members_id_array)
971 ->where('total_day_start_on', '!=', 0)
972 ->orderBy('total_day_start_on', 'desc')
973 ->limit(10)
974 ->get();
975 $started_works = array();
976 foreach ($start_work_ontime as $details) {
977
978 $temp = array();
979 $temp['employee_id'] = $details['EmployeeID'];
980 $temp['employee_name'] = $details['EmployeeName'];
981
982 $designation = Terms::select('gbl_term.name as designation')
983 ->leftJoin('gbl_term_relationship', 'gbl_term_relationship.term_id', '=', 'gbl_term.term_id')
984 ->where(['gbl_term_relationship.relation_id' => $details['EmployeeID'], 'taxonomy' => 'designation'])
985 ->first();
986 $temp['designation'] = @$designation['designation'];
987
988 $temp['total_day_start_on'] = $details['total_day_start_on'];
989 $_urls = ResponseManager::get_profile_pic_urls($details['EmployeeID']);
990 $temp['image'] = $_urls['image'];
991 $temp['image_150px_url'] = $_urls['image_150px_url'];
992 $temp['image_500px_url'] = $_urls['image_500px_url'];
993
994 $started_works[] = $temp;
995 }
996
997 $finish_production = MongoLast90IOData::where("YearMonth", '=', $query_month)
998 ->wherein('EmployeeID', $members_id_array)
999 ->where('total_production_finish', '!=', 0)
1000 ->orderBy('total_production_finish', 'desc')
1001 ->limit(10)
1002 ->get();
1003 $finish_production_array = array();
1004 foreach ($finish_production as $details) {
1005
1006 $temp = array();
1007 $temp['employee_id'] = $details['EmployeeID'];
1008 $temp['employee_name'] = $details['EmployeeName'];
1009
1010 $designation= Terms::select('gbl_term.name as designation')
1011 ->leftJoin('gbl_term_relationship', 'gbl_term_relationship.term_id', '=', 'gbl_term.term_id')
1012 ->where(['gbl_term_relationship.relation_id' => $details['EmployeeID'], 'taxonomy' => 'designation'])
1013 ->first();
1014 $temp['designation'] = @$designation['designation'];
1015
1016 $temp['total_production_finish'] = $details['total_production_finish'];
1017 $_urls = ResponseManager::get_profile_pic_urls($details['EmployeeID']);
1018 $temp['image'] = $_urls['image'];
1019 $temp['image_150px_url'] = $_urls['image_150px_url'];
1020 $temp['image_500px_url'] = $_urls['image_500px_url'];
1021
1022 $finish_production_array[] = $temp;
1023 }
1024
1025 $short_breaks = MongoLast90IOData::where("YearMonth", '=', $query_month)
1026 ->wherein('EmployeeID', $members_id_array)
1027 ->where('total_not_taken_break', '!=', 0)
1028 ->orderBy('total_not_taken_break', 'desc')
1029 ->limit(10)
1030 ->get();
1031 $short_breaks_array = array();
1032 foreach ($short_breaks as $details) {
1033
1034 $temp = array();
1035 $temp['employee_id'] = $details['EmployeeID'];
1036 $temp['employee_name'] = $details['EmployeeName'];
1037 $designation = Terms::select('gbl_term.name as designation')
1038 ->leftJoin('gbl_term_relationship', 'gbl_term_relationship.term_id', '=', 'gbl_term.term_id')
1039 ->where(['gbl_term_relationship.relation_id' => $details['EmployeeID'], 'taxonomy' => 'designation'])
1040 ->first();
1041 $temp['designation'] = @$designation['designation'];
1042 $temp['total_not_taken_break'] = $details['total_not_taken_break'];
1043 $_urls = ResponseManager::get_profile_pic_urls($details['EmployeeID']);
1044 $temp['image'] = $_urls['image'];
1045 $temp['image_150px_url'] = $_urls['image_150px_url'];
1046 $temp['image_500px_url'] = $_urls['image_500px_url'];
1047
1048 $short_breaks_array[] = $temp;
1049 }
1050
1051 $not_start_work_month = MongoLast90IOData::where("YearMonth", '=', $query_month)
1052 ->wherein('EmployeeID', $members_id_array)
1053 ->where('day_not_start_on_total', '!=', 0)
1054 ->get();
1055 $late_members = array();
1056 foreach ($not_start_work_month as $details) {
1057 if (!in_array($details['EmployeeID'], $late_members)) {
1058 $late_members[] = $details['EmployeeID'];
1059 }
1060 }
1061 $total_members = count($members_id_array);
1062 // Member did not start -> (number of member who are late / total number of member (today) x 100)
1063 $total = 0;
1064 if(count($late_members)!=0 && $total_members!=0) {
1065 $total = count($late_members)/$total_members;
1066 }
1067 $production_summary['summary']['didnt_start_their_work'] = array(
1068 'percentage' => round($total * 100),
1069 'label' => 'Members DID not start their day on time'
1070 );
1071
1072 $not_finish_production_month = MongoLast90IOData::where("YearMonth", '=', $query_month)
1073 ->wherein('EmployeeID', $members_id_array)
1074 ->where('total_production_not_finish', '!=', 0)
1075 ->get();
1076 $not_finish_members = array();
1077 foreach ($not_finish_production_month as $details) {
1078 if (!in_array($details['EmployeeID'], $late_members)) {
1079 $not_finish_members[] = $details['EmployeeID'];
1080 }
1081 }
1082 // Did not finish their work -> total late member (unique) / total number of team member x 100
1083
1084 $temp_per = 0;
1085 if(count($not_finish_members)!=0 && $total_members!=0){
1086 $temp_per = count($not_finish_members) / $total_members;
1087 }
1088 $production_summary['summary']['didnt_finish_their_work'] = array(
1089 'percentage' => round(($temp_per) * 100),
1090 'label' => 'DID NOT finish their daily hours'
1091 );
1092
1093 // Average Daily access of Break Hours
1094 $breaks_month = MongoLast90IOData::where("YearMonth", '=', $query_month)
1095 ->wherein('EmployeeID', $members_id_array)
1096 ->where('break_hours', '!=', 0.0)
1097 ->get();
1098 $total_breaks_hours_members = 0;
1099 $total_members_working_days = 0;
1100 foreach ($breaks_month as $details) {
1101 $total_breaks_hours_members += $details['break_hours'];
1102 $total_members_working_days = $details['working_days'];
1103 }
1104 if ($total_breaks_hours_members != 0) {
1105 $_avg = round($total_breaks_hours_members / $total_members_working_days);
1106 } else {
1107 $_avg = 0;
1108 }
1109
1110 $production_summary['summary']['avg_daily_break_hours'] = array(
1111 'value' => $_avg,
1112 'label' => 'Average Daily access of Break Hours'
1113 );
1114
1115 // Average break hours by a person
1116 $avg_members = 0;
1117 if($total_breaks_hours_members!=0 && $total_members!=0){
1118 $avg_members = number_format($total_breaks_hours_members / $total_members, 2);
1119 }
1120
1121 $avg_hours_array = explode(".", $avg_members);
1122 $avg_hours_string = @$avg_hours_array[0] . "h " . @$avg_hours_array[1] . "m";
1123 $production_summary['summary']['avg_break_hours_by_person'] = array(
1124 'value' => $avg_hours_string,
1125 'label' => 'Average break hours by a person'
1126 );
1127
1128 $top_5_gainers = MongoLast90IOData::where("YearMonth", '=', $query_month)
1129 ->wherein('EmployeeID', $members_id_array)
1130 ->where('production_plus', '!=', 0.0)
1131 ->orderBy('production_plus', 'desc')
1132 ->limit(5)
1133 ->get();
1134 $gainers = array();
1135 foreach ($top_5_gainers as $details) {
1136
1137 $temp = array();
1138 $temp['employee_id'] = $details['EmployeeID'];
1139 $temp['employee_name'] = $details['EmployeeName'];
1140
1141 $designation = Terms::select('gbl_term.name as designation')
1142 ->leftJoin('gbl_term_relationship', 'gbl_term_relationship.term_id', '=', 'gbl_term.term_id')
1143 ->where(['gbl_term_relationship.relation_id' => $details['EmployeeID'], 'taxonomy' => 'designation'])
1144 ->first();
1145
1146 $temp['designation'] = @$designation['designation'];
1147
1148 $temp['production_plus'] = number_format($details['production_plus'], 2);
1149 $_urls = ResponseManager::get_profile_pic_urls($details['EmployeeID']);
1150 $temp['image'] = $_urls['image'];
1151 $temp['image_150px_url'] = $_urls['image_150px_url'];
1152 $temp['image_500px_url'] = $_urls['image_500px_url'];
1153
1154 $gainers[] = $temp;
1155 }
1156 $production_summary['summary']['top_5_gainers'] = $gainers;
1157
1158
1159 $top_5_losers = MongoLast90IOData::where("YearMonth", '=', $query_month)
1160 ->wherein('EmployeeID', $members_id_array)
1161 ->where('production_minus', '!=', 0.0)
1162 ->orderBy('production_minus', 'desc')
1163 ->limit(5)
1164 ->get();
1165 $losers = array();
1166 foreach ($top_5_losers as $details) {
1167
1168 $temp = array();
1169 $temp['employee_id'] = $details['EmployeeID'];
1170 $temp['employee_name'] = $details['EmployeeName'];
1171
1172 $designation = Terms::select('gbl_term.name as designation')
1173 ->leftJoin('gbl_term_relationship', 'gbl_term_relationship.term_id', '=', 'gbl_term.term_id')
1174 ->where(['gbl_term_relationship.relation_id' => $details['EmployeeID'], 'taxonomy' => 'designation'])
1175 ->first();
1176 $temp['designation'] = @$designation['designation'];
1177
1178 $temp['production_minus'] = number_format($details['production_minus'], 2);
1179 $_urls = ResponseManager::get_profile_pic_urls($details['EmployeeID']);
1180 $temp['image'] = $_urls['image'];
1181 $temp['image_150px_url'] = $_urls['image_150px_url'];
1182 $temp['image_500px_url'] = $_urls['image_500px_url'];
1183 $losers[] = $temp;
1184 }
1185 $production_summary['summary']['top_5_losers'] = $losers;
1186
1187 $production_summary['Leader_board']['Fail']['not_started_work'] = $not_started;
1188 $production_summary['Leader_board']['Fail']['didnt_finish_production'] = $didnt_finish_production;
1189 $production_summary['Leader_board']['Fail']['longest_breaks'] = $longest_breaks_array;
1190
1191 $production_summary['Leader_board']['Win']['started_work'] = $started_works;
1192 $production_summary['Leader_board']['Win']['finish_production'] = $finish_production_array;
1193 $production_summary['Leader_board']['Win']['not_taken_longest_breaks'] = $short_breaks_array;
1194
1195
1196 return ResponseManager::getResult($production_summary, config('constants.StatusCode.Ok'), 'Get my day wise production summary for chart of selected.', true);
1197 }
1198
1199 /**
1200 * @return array
1201 */
1202 public function production_day_wise_details_team_members() {
1203 $obj_user = $this->employees->user_info();
1204 $employee_id = (isset($_REQUEST['employee_id']) && $_REQUEST['employee_id'] != null) ? $_REQUEST['employee_id'] : $obj_user['employee_id'];
1205 $member_id = (isset($_REQUEST['member_id']) && $_REQUEST['member_id'] != null) ? $_REQUEST['member_id'] : 0;
1206 $req_for_date = (isset($_REQUEST['for_date']) && $_REQUEST['for_date'] != null) ? $_REQUEST['for_date'] : date('Y-m-d');
1207
1208 $production_summary = array();
1209 $production_summary['employee_details'] = $this->employees->get_employee_basic_profile($employee_id, true);
1210// $production_summary['segments'] = array(
1211// array("segment_name" => "Holidays", "segment_color" => "ffa04f"),
1212// array("segment_name" => "Weekends", "segment_color" => "e5e5e5"),
1213// array("segment_name" => "Production Hours", "segment_color" => "0E7BE0"),
1214// array("segment_name" => "Break Hours", "segment_color" => "efe058"),
1215// );
1216
1217 $req_start_date = date('Y-m-d', strtotime($req_for_date));
1218 $req_end_date = date('Y-m-d', strtotime($req_for_date));
1219 if ($req_start_date == date("Y-m-d")) {
1220 $production_summary['label'] = "Today";
1221 } else if ($req_start_date == date("Y-m-d", strtotime("-1 day"))) {
1222 $production_summary['label'] = "Yesterday";
1223 } else {
1224 $production_summary['label'] = ResponseManager::_date($req_start_date);
1225 }
1226
1227 // make holiday array
1228 $holiday_date = Holidays::whereBetween('date', [$req_start_date, $req_end_date])->get();
1229 $_holiday_list = array();
1230 if (!empty($holiday_date)) {
1231 foreach ($holiday_date as $holiday_date_val) {
1232 $_holiday_list[] = $holiday_date_val['date'];
1233 }
1234 }
1235
1236 $start_date = strtotime($req_start_date);
1237 $working_days = $this->employees->get_working_day($req_start_date, $req_end_date);
1238 if ($member_id != 0) {
1239 $details = Employees::select('employee_id', 'name', 'email', 'status')
1240 ->wherein('status', array('Active', 'Applied for resignation'))
1241 ->where('employee_id', $member_id)
1242 ->where('reporting_manager_id', $employee_id)
1243 ->orderBy('name', 'asc')
1244 ->get();
1245 } else {
1246 $details = Employees::select('employee_id', 'name', 'email', 'status')
1247 ->wherein('status', array('Active', 'Applied for resignation'))
1248 ->where('reporting_manager_id', $employee_id)
1249 ->orderBy('name', 'asc')
1250 ->get();
1251 }
1252
1253 $_dates_array = array();
1254 foreach ($details as $employee) {
1255
1256 // get iodata from employee id and date
1257 $live_data = $this->get_employee_iodata_from_date(date('Y-m-d', $start_date), $employee['employee_id']);
1258 if ($live_data['io_original_entries'][0]['IOStatus'] == "IO Entry not exist.") {
1259 $entries_exist = false;
1260 } else {
1261 $entries_exist = true;
1262 }
1263
1264 $shift_time_from = isset($live_data['in_time']) ? date('h.i', strtotime($live_data['in_time'])) : '';
1265 $shift_time_to = isset($live_data['out_time']) ? date('h.i', strtotime($live_data['out_time'])) : '';
1266
1267 $shift_time_from_string = isset($live_data['in_time']) ? date('h.i A', strtotime($live_data['in_time'])) : '';
1268 $shift_time_to_string = isset($live_data['out_time']) ? date('h.i A', strtotime($live_data['out_time'])) : '';
1269
1270 // getting segment
1271 $get_leaves = Leaves::where(['user_id' => $employee['employee_id']])->whereRaw('? between date_from and date_to', date('Y-m-d', $start_date))->get();
1272 $_temp = array();
1273 $_temp['day'] = ResponseManager::_date($start_date);
1274 $_segment = "";
1275 if ($start_date == date('Y-m-d')) {
1276 $_segment = "Current";
1277 } else if (in_array(date('Y-m-d', $start_date), $_holiday_list)) {
1278 $_segment = "Holiday";
1279 } else if (isset($get_leaves[0]['id']) && $get_leaves[0]['id'] != 0) {
1280 $_segment = "Leave";
1281 } else if (in_array(date('Y-m-d', $start_date), $working_days)) {
1282 $_segment = "Production";
1283 } else {
1284 $_segment = "Weekend";
1285 }
1286
1287 $deficit = (($live_data['actual_hours']['h'] * 60) + $live_data['actual_hours']['i']) - (9 * 60);
1288
1289 $deficit_in_min = ($live_data['actual_hours']['h'] * 60) + $live_data['actual_hours']['i'];
1290 $final_diff_type = $final_diff_type_string = '';
1291 if ($deficit_in_min > 540) {
1292 $final_diff = round($deficit) . "% hours till today";
1293 $final_diff_type = "up";
1294 $final_diff_type_string = "+";
1295 } else {
1296 $final_diff = round($deficit) . "% hours till today";
1297 $final_diff_type = "down";
1298 $final_diff_type_string = '-';
1299 }
1300
1301 $get_hours = gmdate("H:i:s", ltrim($deficit * 60, '-'));
1302 $_hours = explode(':', $get_hours);
1303 // print_r($_hours);
1304 // print_r($deficit);
1305 // print_r($live_data);
1306 $shift_from_in_minutes = date('H', strtotime($live_data['shift_time_from'])) * 60;
1307 $shift_from_in_minutes += date('i', strtotime($live_data['shift_time_from']));
1308
1309 // day start on
1310 $shift_start_in_minutes = date('H', strtotime($live_data['in_time'])) * 60;
1311 $shift_start_in_minutes += date('i', strtotime($live_data['in_time']));
1312
1313 // check how many times on time
1314 if (in_array(date('Y-m-d', $start_date), $working_days)) {
1315 $day_start_on_total = ($live_data['in_time'] == 0 || $shift_start_in_minutes >= $shift_from_in_minutes) ? false : true;
1316 } else {
1317 $day_start_on_total = "";
1318 }
1319
1320 $_name = explode(' ', $employee['name']);
1321 $_final_name = $_name[0] . " " . $_name[2];
1322
1323 $_temp['employee_id'] = $employee['employee_id'];
1324 $_temp['employee_name'] = $_final_name;
1325 $_urls = ResponseManager::get_profile_pic_urls($employee['employee_id']);
1326 $_temp['image'] = $_urls['image'];
1327 $_temp['image_150px_url'] = $_urls['image_150px_url'];
1328 $_temp['image_500px_url'] = $_urls['image_500px_url'];
1329 $_temp['entries_exist'] = $entries_exist;
1330 $_temp['day_segment'] = $_segment;
1331 $_temp['day_checkin_time'] = $shift_time_from;
1332 $_temp['day_checkout_time'] = $shift_time_to;
1333 $_temp['day_checkin_time_string'] = $shift_time_from_string;
1334 $_temp['day_checkout_time_string'] = $shift_time_to_string;
1335 $_temp['actual_total_hrs'] = $live_data['total_hrs']['h'] . "." . $live_data['total_hrs']['i'];
1336 $_temp['actual_total_hrs_string'] = $live_data['total_hrs']['h'] . "h " . $live_data['total_hrs']['i'] . "m";
1337 $_temp['start_day_on_time'] = $day_start_on_total;
1338 $_temp['actual_production_hours'] = $live_data['actual_hours']['h'] . "." . $live_data['actual_hours']['i'];
1339 $_temp['actual_production_hours_string'] = $live_data['actual_hours']['h'] . "h " . $live_data['actual_hours']['i'] . "m";
1340 $_temp['break_hours'] = $live_data['break_hours']['h'] . "." . $live_data['break_hours']['i'];
1341 $_temp['number_of_break'] = $live_data['number_of_break'];
1342 $_temp['break_hours_string'] = $live_data['break_hours']['h'] . "h " . $live_data['break_hours']['i'] . "m";
1343 $_temp['deficit_hours'] = @$_hours[0] . "." . @$_hours[1];
1344 $_temp['deficit_flag'] = $final_diff_type;
1345 $_temp['deficit_hours_string'] = $final_diff_type_string . @$_hours[0] . 'h ' . @$_hours[1] . 'm';
1346
1347 $_dates_array[] = $_temp;
1348 }
1349 // rsort($_dates_array);
1350 $production_summary['list'] = $_dates_array;
1351 return ResponseManager::getResult($production_summary, config('constants.StatusCode.Ok'), 'Get my day wise production summary for chart of selected.', true);
1352 }
1353
1354 /**
1355 * @return array
1356 */
1357 public function production_day_iodata_summary() {
1358 $obj_user = $this->employees->user_info();
1359 $employee_id = (isset($_REQUEST['employee_id']) && $_REQUEST['employee_id'] != null) ? $_REQUEST['employee_id'] : $obj_user['employee_id'];
1360 $for_date = (isset($_REQUEST['for_date']) && $_REQUEST['for_date'] != null) ? date('Y-m-d', strtotime($_REQUEST['for_date'])) : date('Y-m-d');
1361 $day_summary = array();
1362
1363 $day_summary['title'] = "11 Dec 2019 - Timeline";
1364 $day_summary['history'][0]['time'] = "11 Dec 20199:30 AM";
1365 $day_summary['history'][0]['gate'] = "Ground Floor - Lift";
1366 $day_summary['history'][0]['check_type'] = "checked in";
1367 $day_summary['history'][0]['type'] = "Ignored";
1368 $day_summary['history'][0]['duration'] = "";
1369
1370 $day_summary['history'][1]['time'] = "11 Dec 20199:32 AM";
1371 $day_summary['history'][1]['gate'] = "2nd Floor - Tripod 1";
1372 $day_summary['history'][1]['check_type'] = "checked in";
1373 $day_summary['history'][1]['type'] = "Production";
1374 $day_summary['history'][1]['duration'] = "4h 30m";
1375
1376 $day_summary['history'][2]['time'] = "11 Dec 20199:32 AM";
1377 $day_summary['history'][2]['gate'] = "2nd Floor - Tripod 1";
1378 $day_summary['history'][2]['check_type'] = "checked in";
1379 $day_summary['history'][2]['type'] = "Break";
1380 $day_summary['history'][2]['duration'] = "2m";
1381
1382 $day_summary['history'][3]['time'] = "11 Dec 20192:00 PM";
1383 $day_summary['history'][3]['gate'] = "2nd Floor - Tripod 2";
1384 $day_summary['history'][3]['check_type'] = "checked Out";
1385 $day_summary['history'][3]['type'] = "Break";
1386 $day_summary['history'][3]['duration'] = "2m";
1387
1388 $day_summary['history'][4]['time'] = "11 Dec 20192:00 PM";
1389 $day_summary['history'][4]['gate'] = "1st Floor - Lunch Area";
1390 $day_summary['history'][4]['check_type'] = "checked in";
1391 $day_summary['history'][4]['type'] = "Production";
1392 $day_summary['history'][4]['duration'] = "4h 30m";
1393
1394 $day_summary['history'][5]['time'] = "11 Dec 20193:00 PM";
1395 $day_summary['history'][5]['gate'] = "Via ERP on Desktop";
1396 $day_summary['history'][5]['check_type'] = "checked in";
1397 $day_summary['history'][5]['type'] = "Break";
1398 $day_summary['history'][5]['duration'] = "2m";
1399
1400 $day_summary['history'][6]['time'] = "11 Dec 20195:00 PM";
1401 $day_summary['history'][6]['gate'] = "Via ERP on Desktop";
1402 $day_summary['history'][6]['check_type'] = "checked Out";
1403 $day_summary['history'][6]['type'] = "Production";
1404 $day_summary['history'][6]['duration'] = "4h 30m";
1405
1406 $day_summary['history'][7]['time'] = "11 Dec 20193:00 PM";
1407 $day_summary['history'][7]['gate'] = "Via ERP on Desktop";
1408 $day_summary['history'][7]['check_type'] = "checked in";
1409 $day_summary['history'][7]['type'] = "Break";
1410 $day_summary['history'][7]['duration'] = "5m";
1411
1412 $day_summary['history'][8]['time'] = "11 Dec 20197:00 PM";
1413 $day_summary['history'][8]['gate'] = "Via ERP on Desktop";
1414 $day_summary['history'][8]['check_type'] = "checked Out";
1415 $day_summary['history'][8]['type'] = "Production";
1416 $day_summary['history'][8]['duration'] = "4h 30m";
1417
1418 return ResponseManager::getResult($day_summary, config('constants.StatusCode.Ok'), 'Get each day iodata summary!.', true);
1419 }
1420
1421 /**
1422 * @return array
1423 */
1424 public function get_my_production_monthly_summary() {
1425 $obj_user = $this->employees->user_info();
1426 $employee_id = (isset($_REQUEST['employee_id']) && $_REQUEST['employee_id'] != '') ? $_REQUEST['employee_id'] : $obj_user['employee_id'];
1427
1428 $production_summary = array();
1429 $employee = $this->employees->get_employee_basic_profile($employee_id, true);
1430 $production_summary['employee_details'] = $employee;
1431 $production_summary['production'] = array();
1432 $production_summary['beginning'] = array();
1433 $production_summary['break'] = array();
1434
1435 $total_working_days = 0;
1436 $total_hrs_days = 0;
1437 $total_actual_hours = 0;
1438 $total_break_hours = 0;
1439 $total_number_of_break = 0;
1440 $total_day_start_on = 0;
1441 $total_day_not_start_on = 0;
1442 $total_day_not_start_delay = 0;
1443
1444 foreach (array('30' => 0, '60' => 1, '90' => 2) as $key => $month) {
1445 $for_month = date('Y-m', strtotime("-{$month} Month", time()));
1446 $employee_records = MongoLast90IOData::where('EmployeeName', '=', $employee['name'])->where('YearMonth', '=', $for_month)->first();
1447 // print_r($employee_records);
1448 $total_working_days += $employee_records['employee_working_days'];
1449 $total_hrs_days += $employee_records['total_hrs'];
1450 $total_actual_hours += $employee_records['actual_hours'];
1451 $total_break_hours += $employee_records['break_hours'];
1452 $total_number_of_break += $employee_records['number_of_break'];
1453 $total_day_start_on += $employee_records['total_day_start_on'];
1454 $total_day_not_start_on += $employee_records['day_not_start_on_total'];
1455 $total_day_not_start_delay += $employee_records['day_start_delay_min'];
1456
1457 // production summary
1458 $days_30_summary = array();
1459 $label_from_days = ($key == '30') ? "CURRENT MONTH" : $key . " DAYS";
1460 $days_30_summary['label'] = "PROD. HRS FOR " . $label_from_days;
1461 $days_30_summary['total_hrs'] = round($total_actual_hours) . " hrs";
1462 $days_30_summary['total_working_days'] = $total_working_days . " working days";
1463 $deficit = $total_actual_hours - ($total_working_days * 9);
1464 $pr = @(float) ($total_actual_hours / ($total_working_days * 9)) * 100;
1465 if ($pr > 100) {
1466 $final_diff = round($deficit) . " hours till today";
1467 $final_diff_type = "up";
1468 } else {
1469 $final_diff = round($deficit) . " hours till today";
1470 $final_diff_type = "down";
1471 }
1472 $days_30_summary['avg_in_string'] = $final_diff;
1473 $days_30_summary['progress_percentage'] = number_format($pr, 2);
1474 $days_30_summary['avg_icon'] = $final_diff_type;
1475 $production_summary['production'][$key] = $days_30_summary;
1476
1477 // beginning summary
1478 $days_30_summary = array();
1479 $label_from_days = ($key == '30') ? "CURRENT MONTH" : $key . " DAYS";
1480 $days_30_summary['label'] = "BEGINNING YOUR DAY FOR " . $label_from_days;
1481 if ($total_day_start_on != 0 && $total_working_days!=0) {
1482 $percentage = ($total_day_start_on / $total_working_days) * 100;
1483 } else {
1484 $percentage = 0;
1485 }
1486
1487 $days_30_summary['percentage'] = round($percentage);
1488 $days_30_summary['percentage_formula'] = "({$total_day_start_on}/$total_working_days)";
1489 $delay_min = ($total_day_not_start_on != 0) ? round($total_day_not_start_delay / $total_day_not_start_on) : 0;
1490 $days_30_summary['avg_in_string'] = ($delay_min == 0) ? "On time" : "late by average {$delay_min} min";
1491 $days_30_summary['avg_icon'] = ($delay_min == 0) ? "Up" : "down";
1492 $production_summary['beginning'][$key] = $days_30_summary;
1493
1494 // break summary
1495 $days_30_summary = array();
1496 $label_from_days = ($key == '30') ? "CURRENT MONTH" : $key . " DAYS";
1497 $days_30_summary['label'] = "BREAK HOURS FOR " . $label_from_days;
1498 // formula ( 9 / 205 )*100 = 4.39 percenatage - percentage
1499 if ($total_break_hours != 0 && $total_hrs_days != 0) {
1500 $percentage = ($total_break_hours / $total_hrs_days) * 100;
1501 } else {
1502 $percentage = 0;
1503 }
1504
1505 $days_30_summary['percentage'] = round($percentage);
1506
1507 $get_hours = gmdate("H:i:s", $total_break_hours * 3600);
1508 $_hours = explode(':', $get_hours);
1509 $_final_hours = $_hours[0] . "h " . $_hours[1] . "m";
1510 $days_30_summary['total_break_hrs'] = "(" . $_final_hours . ")";
1511
1512 if ($total_number_of_break != 0 && $total_working_days!=0) {
1513 $avg_in = round(($total_number_of_break / $total_working_days));
1514 } else {
1515 $avg_in = 0;
1516 }
1517
1518 $days_30_summary['avg_in_string_formula'] = "Average {$avg_in} / day";
1519 if ($total_number_of_break != 0 && $total_break_hours!=0) {
1520 $avg_in_string = number_format(($total_break_hours / $total_number_of_break), 2);
1521 $avg_array = explode(".", $avg_in_string);
1522 $avg_in_string = ($avg_array[0] != 0) ? ($avg_array[0] * 60) + $avg_array[1] : $avg_array[1];
1523 } else {
1524 $avg_in_string = 0;
1525 }
1526 if ($avg_in_string > 30) {
1527 $days_30_summary['avg_icon'] = "down";
1528 } else {
1529 $days_30_summary['avg_icon'] = "up";
1530 }
1531 $days_30_summary['avg_in_string'] = "Avg. time {$avg_in_string}m";
1532 $production_summary['break'][$key] = $days_30_summary;
1533 }
1534 return ResponseManager::getResult($production_summary, config('constants.StatusCode.Ok'), 'Production Monthly Summary', true);
1535 }
1536
1537 /**
1538 * @param $for_date
1539 * @param $employee_id
1540 * @return array
1541 * @throws \Exception
1542 */
1543 public function get_employee_iodata_from_date($for_date, $employee_id) {
1544
1545 $return = array("IODate" => "", "shift_time_from" => 0, "shift_time_to" => 0, "access_card_number" => 0, "in_time" => 0, "in_time_alert" => 0, "out_time" => 0, "out_time_alert" => 0, "number_of_break" => 0, "total_hrs" => array("h" => 0, "i" => 0, "s" => 0), "break_hours" => array("h" => 0, "i" => 0, "s" => 0), "actual_hours" => array("h" => 0, "i" => 0, "s" => 0), "gain_loss" => array("h" => 0, "i" => 0, "s" => 0, "type" => "", "alert" => 0), "gain_loss_production" => array("h" => 0, "i" => 0, "s" => 0, "type" => "", "alert" => 0), "io_original_entries" => array(), "io_unique_entries" => array(), "error" => FALSE, "leave" => FALSE, "leave_type" => FALSE);
1546 $IOGates = array('Tripod ENTRY 1(I)', 'Tripod EXIT 1(O)', 'Tripod ENTRY 2(I)', 'Tripod EXIT 2(O)', 'Manual Entry');
1547
1548 if (!strtotime($for_date)) {
1549 return ("Please provide valid date.");
1550 }
1551 $return["IODate"] = date("Y-m-d", strtotime($for_date));
1552
1553 if (!$employee_id) {
1554 return ("Please provide employee id.");
1555 }
1556
1557 $have_applied_leave = Leaves::select('ld.type as type', 'gbl_leaves.leave_type', 'gbl_leaves.id', 'gbl_leaves.planned')
1558 ->leftJoin('gbl_leaves_details as ld', function ($join) use ($for_date) {
1559 $join->on('gbl_leaves.id', '=', 'ld.leave_id');
1560 $join->where('ld.leave_date', $for_date);
1561 })
1562 ->where('gbl_leaves.user_id', $employee_id)
1563 ->where('gbl_leaves.leave_status', 'Approved')
1564 ->whereRaw('? between gbl_leaves.date_from and gbl_leaves.date_to', $for_date)
1565 ->first();
1566
1567 if (!empty($have_applied_leave)) {
1568 $return["leave"] = (isset($have_applied_leave["type"]) ? $have_applied_leave["type"] : "Full Day");
1569 $return["leave_is_planned_unplanned"] = $have_applied_leave["planned"] ? "planned" : "unplanned";
1570 if ($have_applied_leave["leave_type"] == "Full Day") {
1571 return ("On Leave");
1572 }
1573 }
1574
1575 $emp_detail = Employees::select('employee_id', 'date_of_join', 'work_from_home', 'access_card_number', 'shift_from', 'shift_to')
1576 ->where('employee_id', $employee_id)
1577 ->where('date_of_join', '<=', $return["IODate"])
1578 ->first();
1579
1580 if (empty($emp_detail)) {
1581// return ("Employee does not exist on day {$return["IODate"]}.");
1582 $return["not_exist"] = "Employee does not exist on day";
1583 }
1584
1585 $return["work_from_home"] = $emp_detail["work_from_home"];
1586 $return["shift_time_from"] = $emp_detail["shift_from"];
1587 $return["shift_time_to"] = $emp_detail["shift_to"];
1588 $return["access_card_number"] = $emp_detail["access_card_number"];
1589
1590 $check_tmp_shift_time = EmployeeIODataTempTime::select('shift_from', 'shift_to')
1591 ->where('employee_id', $employee_id)
1592 ->whereRaw('? between from_date and to_date', $for_date)
1593 ->orderBy('status', '1')
1594 ->first();
1595
1596 if (!empty($check_tmp_shift_time)) {
1597 $return["shift_time_from"] = $check_tmp_shift_time["shift_from"];
1598 $return["shift_time_to"] = $check_tmp_shift_time["shift_to"];
1599 }
1600
1601 if (!empty($have_applied_leave)) {
1602 if ($have_applied_leave["leave_type"] == "First Half") {
1603 $return["shift_time_from"] = date("H:i:s", strtotime("4 hours 30 minutes", strtotime($emp_detail["shift_from"])));
1604 } else if ($have_applied_leave["leave_type"] == "Second Half") {
1605 $return["shift_time_to"] = date("H:i:s", strtotime("4 hours 30 minutes", strtotime($emp_detail["shift_from"])));
1606 }
1607 }
1608
1609 $io_times = array();
1610 if (isset($return["access_card_number"]) && $return["access_card_number"]) {
1611 $day_check_length = date('j', strtotime($for_date));
1612 if (strlen($day_check_length) == 1) {
1613 $date_to_search = date('M j Y', strtotime($for_date)) . " 12:00:00:000AM";
1614 } else {
1615 $date_to_search = date('M j Y', strtotime($for_date)) . " 12:00:00:000AM";
1616 }
1617 $io_times_data = Production::where('CardNumber', $return["access_card_number"])
1618 ->where('IODate', $date_to_search)
1619 ->orderBy('IOTime', 'asc')
1620 ->get();
1621
1622 $kk = 0;
1623 foreach ($io_times_data as $value) {
1624 $io_times[$kk]['IOTime'] = date("Y-m-d", strtotime($value['IODate'])) . ' ' . $value['IOTime'];
1625 $io_times[$kk]['IOStatus'] = $value['IOStatus'];
1626 $io_times[$kk]['IOGateName'] = $value['IOGateName'];
1627 $io_times[$kk]['IOGateNo'] = $value['IOGateNo'];
1628 $kk++;
1629 }
1630 }
1631 if (empty($io_times)) {
1632 // return ("IO Entry not exist.");
1633 $io_times[0]['IOTime'] = null;
1634 $io_times[0]['IOStatus'] = 'IO Entry not exist.';
1635 $io_times[0]['IOGateName'] = null;
1636 $io_times[0]['IOGateNo'] = null;
1637 }
1638
1639 $return["io_original_entries"] = $io_times;
1640
1641 foreach ($io_times as $index => $io_entry) {
1642 if (!in_array($io_entry["IOGateName"], $IOGates)) {
1643 unset($io_times[$index]);
1644 }
1645 }
1646 $io_times = array_values($io_times);
1647
1648 if (ResponseManager::_date($for_date, 'Y-m-d') != date("Y-m-d")) {
1649 if (@$io_times[count($io_times) - 1]['IOStatus'] == "Entry") {
1650 $next_day_date = date('Y-m-d', strtotime("+1 day", strtotime($for_date)));
1651 $io_times_next_date = array();
1652 if (isset($return["access_card_number"]) && $return["access_card_number"]) {
1653// $chkdate = array('$gte' => new MongoDate(strtotime(date("Y-m-d 00:00:00", strtotime($next_day_date)))), '$lte' => new MongoDate(strtotime(date("Y-m-d 23:59:59", strtotime($next_day_date)))));
1654// $io_times_next_date_data = $mdb->iodata_details->find(array('io_date_time'=>$chkdate,'CardNumber'=>$return["access_card_number"]))->sort(array("IOTime"=>1))->limit(1);
1655 //$kk=0;
1656
1657
1658 date_default_timezone_set("Asia/Kolkata");
1659 $day_check_length = date('j', strtotime($next_day_date));
1660 if (strlen($day_check_length) == 1) {
1661 $date_to_search = date('M j Y', strtotime($next_day_date)) . " 12:00:00:000AM";
1662 } else {
1663 $date_to_search = date('M j Y', strtotime($next_day_date)) . " 12:00:00:000AM";
1664 }
1665 $io_times_next_date_data = Production::where('CardNumber', $return["access_card_number"])
1666 ->where('IODate', $date_to_search)
1667 ->orderBy('IOTime', 'asc')
1668 ->limit(1)
1669 ->get();
1670
1671 foreach ($io_times_next_date_data as $value) {
1672 // print_r($value);
1673 $io_times_next_date['IOTime'] = date("Y-m-d", strtotime($value['IODate'])) . ' ' . $value['IOTime'];
1674 $io_times_next_date['IOStatus'] = $value['IOStatus'];
1675 $io_times_next_date['IOGateName'] = $value['IOGateName'];
1676 $io_times_next_date['IOGateNo'] = $value['IOGateNo'];
1677 // $kk++;
1678 }
1679 }
1680
1681 if (!empty($io_times_next_date) && $io_times_next_date['IOStatus'] == 'Exit') {
1682 $io_times[] = array("IOTime" => $io_times_next_date['IOTime'], "IOStatus" => "Exit");
1683 } else {
1684 $io_times[] = array("IOTime" => date('Y-m-d', strtotime($for_date)) . ' ' . $return["shift_time_to"], "IOStatus" => "Exit");
1685 }
1686 }
1687 } else {
1688 if (@$io_times[count($io_times) - 1]['IOStatus'] == "Entry") {
1689 date_default_timezone_set("Asia/Kolkata");
1690 $io_times[] = array("IOTime" => date("Y-m-d H:i:s"), "IOStatus" => "Exit");
1691 }
1692 }
1693
1694 foreach ($io_times as $io_times_for_in_date) {
1695 if ($io_times_for_in_date["IOStatus"] == "Entry") {
1696 $return["in_time"] = $io_times_for_in_date["IOTime"];
1697 $time1 = new DateTime(date("H:i:s", strtotime($return["in_time"])));
1698
1699 $shiftDate = strtotime($return["shift_time_from"]);
1700 $time2 = new DateTime(date($return["shift_time_from"]));
1701
1702 $interval = $time1->diff($time2);
1703
1704 if ($interval->invert > 0) {
1705 $return["in_time_alert"] = 1;
1706 }
1707 break;
1708 }
1709 }
1710
1711 if (isset($io_times[count($io_times) - 1]["IOStatus"]) && $io_times[count($io_times) - 1]["IOStatus"] == "Exit") {
1712 $return["out_time"] = $io_times[count($io_times) - 1]["IOTime"];
1713
1714 $time1 = new DateTime(date($return["shift_time_to"]));
1715 $time2 = new DateTime(date("H:i:s", strtotime($return["out_time"])));
1716 $interval = $time1->diff($time2);
1717
1718 if ($interval->invert > 0) {
1719 $return["out_time_alert"] = 1;
1720 }
1721 }
1722
1723 $io_times_unique_entry = array();
1724 $prev_in = $prev_out = FALSE;
1725 foreach ($io_times as $io_time) {
1726 if ($io_time['IOStatus'] == "Entry" && $prev_out == FALSE) {
1727 $prev_in = $io_time;
1728 } else if ($io_time['IOStatus'] == "Exit" && $prev_in) {
1729 $prev_out = $io_time;
1730 }
1731
1732 if ($prev_in && $prev_out) {
1733 $io_times_unique_entry[] = $prev_in;
1734 $io_times_unique_entry[] = $prev_out;
1735
1736 $prev_in = $prev_out = FALSE;
1737 }
1738 }
1739
1740 $return["io_unique_entries"] = $io_times_unique_entry;
1741
1742 $io_times_for_break = $io_times_unique_entry;
1743 unset($io_times_for_break[count($io_times_for_break) - 1], $io_times_for_break[0]);
1744
1745 if (!empty($io_times_for_break)) {
1746 $exit = $in = FALSE;
1747
1748 foreach ($io_times_for_break as $io_times_for_break) {
1749 if ($io_times_for_break['IOStatus'] == "Exit" && $in == FALSE) {
1750 $exit = $io_times_for_break["IOTime"];
1751 }
1752
1753 if ($io_times_for_break['IOStatus'] == "Entry" && $exit) {
1754 $in = $io_times_for_break["IOTime"];
1755 }
1756
1757 if ($exit && $in) {
1758 $time1 = new DateTime($in);
1759 $time2 = new DateTime($exit);
1760 $interval = $time1->diff($time2);
1761
1762 $return["break_hours"]["h"] = $return["break_hours"]["h"] + $interval->h;
1763 $return["break_hours"]["i"] = $return["break_hours"]["i"] + $interval->i;
1764 $return["break_hours"]["s"] = $return["break_hours"]["s"] + $interval->s;
1765 ++$return["number_of_break"];
1766 $exit = $in = FALSE;
1767 }
1768 }
1769 }
1770
1771 $return["break_hours"] = $this->get_time_diff_from_h_i_s($return["break_hours"]);
1772
1773 $time1 = new DateTime(($return["in_time"]) ? $return["in_time"] : '');
1774 $time2 = new DateTime(($return["out_time"]) ? $return["out_time"] : '');
1775 $interval = $time1->diff($time2);
1776
1777 $return["total_hrs"] = $this->get_time_diff_from_h_i_s($interval);
1778
1779
1780 if ($return["number_of_break"] > 0) {
1781 $time1 = new DateTime(date("{$return["total_hrs"]['h']}:{$return["total_hrs"]['i']}:{$return["total_hrs"]['s']}"));
1782 $time2 = new DateTime(date("{$return["break_hours"]['h']}:{$return["break_hours"]['i']}:{$return["break_hours"]['s']}"));
1783 $interval = $time1->diff($time2);
1784 $return["actual_hours"] = $this->get_time_diff_from_h_i_s($interval);
1785
1786 $time1 = new DateTime(date("{$return["break_hours"]['h']}:{$return["break_hours"]['i']}:{$return["break_hours"]['s']}"));
1787 if (date("Y-m-d", strtotime($for_date)) >= "2018-10-01") {
1788 $time2 = new DateTime(date("00:30:00"));
1789 } else {
1790 $time2 = new DateTime(date("00:45:00"));
1791 }
1792 $interval = $time1->diff($time2);
1793 if ($interval->invert > 0) {
1794 $return["break_hours"]["alert"] = 1;
1795 } else {
1796 $return["break_hours"]["alert"] = 0;
1797 }
1798 } else {
1799 $return["actual_hours"] = $return["total_hrs"];
1800 $return["break_hours"]["alert"] = 0;
1801 }
1802
1803 if (!empty($have_applied_leave)) {
1804 $time1 = new DateTime(date("04:30:00"));
1805 } else {
1806 if (date("Y-m-d", strtotime($for_date)) >= "2018-10-01") {
1807 $time1 = new DateTime(date("09:30:00"));
1808 } else {
1809 $time1 = new DateTime(date("09:00:00"));
1810 }
1811 }
1812
1813 $time2 = new DateTime(date("{$return["total_hrs"]['h']}:{$return["total_hrs"]['i']}:{$return["total_hrs"]['s']}"));
1814 $interval = $time1->diff($time2);
1815 $return["gain_loss"] = $this->get_time_diff_from_h_i_s($interval);
1816 if ($interval->invert > 0) {
1817 $return["gain_loss"]["alert"] = 1;
1818 $return["total_hrs"]["alert"] = 1;
1819 } else {
1820 $return["gain_loss"]["alert"] = 0;
1821 $return["total_hrs"]["alert"] = 0;
1822 }
1823
1824 if (!empty($have_applied_leave)) {
1825 $ac_time1 = new DateTime(date("04:30:00"));
1826 } else {
1827 if (date("Y-m-d", strtotime($for_date)) >= "2018-10-01") {
1828 $ac_time1 = new DateTime(date("09:00:00"));
1829 } else {
1830 $ac_time1 = new DateTime(date("08:15:00"));
1831 }
1832 }
1833
1834 $ac_time2 = new DateTime(date("{$return["actual_hours"]['h']}:{$return["actual_hours"]['i']}:{$return["actual_hours"]['s']}"));
1835 $ac_interval = $ac_time1->diff($ac_time2);
1836 $return["gain_loss_production"] = $this->get_time_diff_from_h_i_s($ac_interval);
1837 if ($ac_interval->invert > 0) {
1838 $return["gain_loss_production"]["alert"] = 1;
1839 $return["actual_hours"]["alert"] = 1;
1840 } else {
1841 $return["gain_loss_production"]["alert"] = 0;
1842 $return["actual_hours"]["alert"] = 0;
1843 }
1844
1845 return $return;
1846 }
1847
1848 /**
1849 * @param $interval
1850 * @return array
1851 */
1852 function get_time_diff_from_h_i_s($interval) {
1853 $interval_array = array();
1854 if (is_object($interval)) {
1855 $interval_array["h"] = $interval->h;
1856 $interval_array["i"] = $interval->i;
1857 $interval_array["s"] = $interval->s;
1858 } else {
1859 $interval_array = $interval;
1860 }
1861
1862 $seconds = ($interval_array["h"] > 0) ? (($interval_array["h"] * 60) * 60) : 0;
1863 if ($interval_array["i"] > 0) {
1864 $seconds = $seconds + ($interval_array["i"] * 60);
1865 }
1866 $seconds = $seconds + $interval_array["s"];
1867
1868
1869 $interval_array["h"] = sprintf("%02d", intval($seconds / 60 / 60));
1870 $interval_array["i"] = sprintf("%02d", abs(intval(($seconds % 3600) / 60)));
1871 $interval_array["s"] = sprintf("%02d", abs($seconds % 60));
1872
1873 return $interval_array;
1874 }
1875
1876 /**
1877 * @param $employee_id
1878 * @return array
1879 */
1880 public function employee_projects($employee_id) {
1881
1882 $_projects = Projects::select('pro_projects.project_id', 'pro_projects.po_number', 'pro_projects.project_unique_id', 'pro_projects.primary_project_manager_id', 'pro_projects.date_time', 'pro_projects.name', 'pro_projects.customer_type', 'pro_projects.model', 'pro_projects.start_date', 'pro_projects.end_date', 'pro_projects.status', 'pro_projects.is_inhouse')
1883 ->whereIn('pro_projects.primary_project_manager_id', array($employee_id))
1884 ->wherein('pro_projects.status', array("Open"))
1885 ->orderBy('pro_projects.project_id', 'desc')
1886 ->groupBy('pro_projects.project_id')
1887 ->get();
1888
1889 $_all_projects = array();
1890 foreach ($_projects as $project) {
1891
1892 $_res_rm = Employees::where('employee_id', $project->primary_project_manager_id)->first();
1893 $_name = explode(' ', $_res_rm->name);
1894 $_final_name = $_name[0] . " " . $_name[2];
1895
1896 $_pro_details = array();
1897 $_pro_details['project_id'] = $project->project_id;
1898 $_pro_details['project_manager'] = $_final_name;
1899 $_pro_details['project_manager_role'] = "Project Manager";
1900 $_pro_details['project_manager_image_url'] = config('constants.aws.aws_employee_image_url') . $project->primary_project_manager_id . '/150x150.jpg';
1901
1902 $_pro_details['project_unique_id'] = $project->project_unique_id;
1903 $_pro_details['po_number'] = $project->po_number;
1904 $_pro_details['project_name'] = $project->name;
1905
1906 $_pro_details['start_date'] = $project->start_date;
1907 $_pro_details['end_date'] = $project->end_date;
1908 $_pro_details['is_inhouse'] = ($project->is_inhouse == 1) ? 'Yes' : 'No';
1909 $_pro_details['model'] = $project->model;
1910 $_pro_details['status'] = $project->status;
1911 $_all_projects[] = $_pro_details;
1912 }
1913 return ResponseManager::getResult($_all_projects, config('constants.StatusCode.Ok'), '', true);
1914 }
1915
1916 /**
1917 * @return array
1918 */
1919 public function index($employee_id) {
1920 $employee_id = (int) $employee_id;
1921
1922 if (isset($employee_id)) {
1923 switch ($_SERVER['REQUEST_METHOD']) {
1924 case "GET":
1925 $_pre = $this->employees->employee_details($employee_id);
1926 return ResponseManager::getResult($_pre, config('constants.StatusCode.Ok'), '', true);
1927
1928 break;
1929 default:
1930 return ResponseManager::getResult('', config('constants.StatusCode.Forbidden'), 'The server understood the request!', true);
1931 }
1932 } else {
1933 return ResponseManager::getResult('', config('constants.StatusCode.Forbidden'), '', true);
1934 }
1935 }
1936
1937 /**
1938 * @return array
1939 */
1940 public function auth()
1941 {
1942
1943 if (empty($type)) {
1944 $type = isset($_GET['requested_by']) && (!empty($_GET['requested_by'])) ? $_GET['requested_by'] : "";
1945 }
1946 $type = isset($data->requested_by) && !empty($data->requested_by) ? $data->requested_by : "";
1947
1948 switch ($_SERVER['REQUEST_METHOD']) {
1949 case "GET":
1950 $array_of_allowed_switch_users = array('13563', '1', '13', '14', '25', '13173','13763','13716','13719','13582','13694','13695','13721');
1951 $_pre = $this->employees->employee_details();
1952
1953 $didnt_punch = DidntPunch::wherein('status', array('Pending', 'Forgot Card'))
1954 ->where('employee_id', $_pre['employee_id'])
1955 ->where('from_date', date('Y-m-d'))
1956 ->where('to_date', date('Y-m-d'))
1957 ->first();
1958
1959 $business_tours = BusinessTour::where('employee_id', $_pre['employee_id'])
1960 ->where('date_from','<=', date('Y-m-d'))
1961 ->where('date_to','>=', date('Y-m-d'))
1962 ->first();
1963 // print_r($business_tours->toArray());
1964
1965 $members = Employees::select('employee_id', 'name', 'nickname', 'mobile', 'email', 'status')
1966 ->wherein('status', array('Active', 'Applied for resignation'))
1967 ->where('email', '!=', '')
1968 ->where('reporting_manager_id', $_pre['employee_id'])
1969 ->orderBy('name', 'asc')
1970 ->count();
1971 $_pre['allow_team_view'] = ($members != 0) ? true : false;
1972
1973 $role_details = EmployeeMeta::where('employee_id', $_pre['employee_id'])
1974 ->orderBy('meta_id', 'asc')
1975 ->first();
1976
1977 $employee_permissions = EmployeePermissions::where('employee_id', $_pre['employee_id'])
1978 ->leftJoin('gbl_permissions', 'gbl_permissions.permission_id', '=', 'gbl_employee_permissions.permission_id')
1979 ->orderBy('employee_permissions_id', 'asc')
1980 ->get();
1981
1982 $role_permissions = RolePermissions::where('role_name', $role_details['meta_value'])
1983 ->leftJoin('gbl_permissions', 'gbl_permissions.permission_id', '=', 'gbl_role_permissions.permission_id')
1984 ->orderBy('role_permissions_id', 'asc')
1985 ->get();
1986
1987 $permissions_array = array();
1988 if(count($employee_permissions)!=0) {
1989 $custom_permissions_flag = true;
1990 foreach ($employee_permissions as $permission) {
1991 $module = ($permission['module_name']=='*')?"All":$permission['module_name'];
1992 $permissions_array[$module][] = $permission['permission_name'];
1993 }
1994 }else{
1995 $custom_permissions_flag = false;
1996 foreach ($role_permissions as $permission) {
1997 $module = ($permission['module_name']=='*')?"All":$permission['module_name'];
1998 $permissions_array[$module][] = $permission['permission_name'];
1999 }
2000 }
2001
2002 $_pre['permissions']['role'] = (isset($role_details['meta_value']) ? $role_details['meta_value'] : "");
2003 $_pre['permissions']['custom_permissions'] = $custom_permissions_flag;
2004 $_pre['permissions']['role_permissions'] = $permissions_array;
2005
2006 $_pre['permissions']['projects'] = array();
2007 $employee_id = (isset($_GET['employee_id'])) ? $_GET['employee_id'] : $_pre['employee_id'];
2008 $details = Projects::select('project_id')
2009 ->leftJoin('gbl_assigned_users', 'pro_projects.project_id', '=', 'gbl_assigned_users.relation_id')
2010 ->WhereIn('gbl_assigned_users.relation_type', array('project_manager', 'project_tech_lead'))
2011 ->where('primary_project_manager_id', $employee_id)
2012 ->wherein('pro_projects.status', array("Open"))
2013 ->count();
2014 if ($details > 0) {
2015 $_pre['permissions']['projects']['can_review_timesheet'] = true;
2016 } else {
2017 $_pre['permissions']['projects']['can_review_timesheet'] = false;
2018 }
2019 $opentask = ProAdditionalWork::select('id')
2020 ->where('pm_id', $employee_id)
2021 ->wherein('status', array("Pending", 'Approved'))
2022 ->count();
2023 if ($opentask > 0) {
2024 $_pre['permissions']['projects']['can_review_open_task'] = true;
2025 } else {
2026 $_pre['permissions']['projects']['can_review_open_task'] = false;
2027 }
2028
2029 $ip_address = ResponseManager::get_ip_address();
2030 if ($_pre['work_from_home'] == 1 || @$business_tours['tour_id'] != 0) {
2031 $didnt_punch['didnt_punch_id'] = 1;
2032 }
2033 if (!isset($didnt_punch['didnt_punch_id']) || $didnt_punch['didnt_punch_id'] == 0) {
2034 $_pre['didnt_punch_today'] = false;
2035 } else {
2036 $ip_array = explode(".", $ip_address);
2037 $tmp = array();
2038
2039 date_default_timezone_set("Asia/Kolkata");
2040 $day_check_length = date('j');
2041 if (strlen($day_check_length) == 1) {
2042 $date_to_search = date('M j Y', strtotime(date('Y-m-d'))) . " 12:00:00:000AM";
2043 } else {
2044 $date_to_search = date('M j Y', strtotime(date('Y-m-d'))) . " 12:00:00:000AM";
2045 }
2046 $forgot_card = Production::where('IODate', $date_to_search)
2047 ->where('employee_id', $_pre['employee_id'])
2048 ->where('CardNumber', $_pre['access_card_number'])
2049 ->where('oldid', '')
2050 ->orderBy('_id', 'desc')
2051 ->first();
2052
2053 if (isset($forgot_card['IOStatus'])) {
2054 if ($forgot_card['IOStatus'] == "Entry") {
2055 $tripod = "Tripod EXIT 1(O)";
2056 $check_type = "Checked In";
2057 } else {
2058 $tripod = "Tripod ENTRY 1(I)";
2059 $check_type = "Checked Out";
2060 }
2061 $tmp['time'] = ResponseManager::_date($forgot_card['io_date_time'], 'd M Y h:i:s A');
2062 $tmp["gate"] = $tripod;
2063 $tmp["check_type"] = $check_type;
2064 }
2065
2066 if ($_pre['work_from_home'] == 1 || @$business_tours['tour_id'] != 0) {
2067 $_pre['didnt_punch_today'] = true;
2068 $_pre['iodata_last_entry'] = $tmp;
2069 } else {
2070 if ($ip_array[0] == 10 && $ip_array[1] == 2) {
2071 $_pre['didnt_punch_today'] = true;
2072 $_pre['iodata_last_entry'] = $tmp;
2073 } else if ($ip_array[0] == 172 && $ip_array[1] == 16) {
2074 $_pre['didnt_punch_today'] = true;
2075 $_pre['iodata_last_entry'] = $tmp;
2076 } else {
2077 $_pre['didnt_punch_today'] = false;
2078 }
2079 }
2080 }
2081 $_pre['ip_address'] = $ip_address;
2082
2083 if (in_array($_pre['employee_id'], $array_of_allowed_switch_users)) {
2084 $_pre['allow_team_view'] = true;
2085 $_pre['allow_switch_user'] = true;
2086 } else {
2087 $_pre['allow_switch_user'] = false;
2088 }
2089 return ResponseManager::getResult($_pre, config('constants.StatusCode.Ok'), 'As per token provide employee details', true, $type);
2090 break;
2091
2092 default:
2093 return ResponseManager::getResult('', config('constants.StatusCode.Forbidden'), 'The server understood the request!', true, $type);
2094 }
2095 }
2096
2097 /**
2098 * @return array
2099 */
2100 public function switch_user_list() {
2101 switch ($_SERVER['REQUEST_METHOD']) {
2102 case "GET":
2103 $employees = Employees::select('employee_id', 'name', 'nickname', 'mobile', 'email', 'status')
2104 ->wherein('status', array('Active', 'Applied for resignation'))
2105 ->where('email', '!=', 'abc@indianic.com')
2106 ->where('email', '!=', '')
2107 ->orderBy('name', 'asc')
2108 ->get();
2109 $employee_list = array();
2110 foreach ($employees as $employee) {
2111 $_tmp = array();
2112 $_name = explode(' ', $employee['name']);
2113 $_final_name = @$_name[0] . " " . @$_name[2];
2114 $_tmp['employee_id'] = $employee['employee_id'];
2115 $_tmp['name'] = $_final_name;
2116 $_tmp['email'] = $employee['email'];
2117 $_tmp['nickname'] = $employee['nickname'];
2118 $_tmp['mobile'] = $employee['mobile'];
2119 $_tmp['status'] = $employee['status'];
2120 $_urls = ResponseManager::get_profile_pic_urls($employee['employee_id']);
2121 $_tmp['image'] = $_urls['image'];
2122 $_tmp['image_150px_url'] = $_urls['image_150px_url'];
2123 $_tmp['image_500px_url'] = $_urls['image_500px_url'];
2124
2125 $employee_list[] = $_tmp;
2126 }
2127 $list = $employee_list;
2128 return ResponseManager::getResult($list, config('constants.StatusCode.Ok'), 'Switch user for provide active users list.', true);
2129 break;
2130 default:
2131 return ResponseManager::getResult('', config('constants.StatusCode.Forbidden'), 'The server understood the request!', true);
2132 }
2133 }
2134
2135 /**
2136 * Get all leaves for $employee_id.
2137 *
2138 * Devloped By Ikshit Chavda
2139 */
2140 public function leaves($employee_id, $leave_id = null) {
2141 if (empty($employee_id)) {
2142 $employee_id = Auth::user()->employee_id;
2143 }
2144 return $this->employees->getLeaves($employee_id, $leave_id, $_GET);
2145 }
2146
2147 public function associates($employee_id) {
2148 return $this->employees->associates($employee_id);
2149 }
2150
2151 public function memberDetails($logged_id, $employee_id) {
2152 return $this->employees->memberDetails($logged_id, $employee_id);
2153 }
2154
2155 public function associatedLeaves($employee_id) {
2156 return $this->employees->associatesgetAllLeaves($employee_id);
2157 }
2158
2159 public function associatedLeavesDetails($employee_id, $leave_id) {
2160 return $this->employees->associatedLeavesDetails($employee_id, $leave_id);
2161 }
2162
2163 public function personal_details($employee_id) {
2164 $type = $_GET['type'];
2165 return $this->employees->get_personal_details($employee_id, $type);
2166 }
2167
2168 public function employeeEducationsDetails($employee_id) {
2169 return $this->employeeModel->employeeEducationsDetails($employee_id);
2170 }
2171
2172 public function employeeOfficeDetails($employee_id) {
2173 return $this->employeeModel->employeeOfficeDetails($employee_id);
2174 }
2175
2176 public function employeeExperiences($employee_id) {
2177 return $this->employeeModel->employeeExperiences($employee_id);
2178 }
2179
2180 public function employeeSkills($employee_id) {
2181 return $this->employeeModel->employeeSkills($employee_id);
2182 }
2183
2184 public function employeeDocuments($employee_id) {
2185 return $this->employeeModel->employeeDocuments($employee_id);
2186 }
2187
2188 public function uploadDocuments($employee_id, Request $request) {
2189 return $this->employees->upload_documents($employee_id, $request->all());
2190 }
2191
2192 public function skillAction($employee_id, Request $request) {
2193 if (!empty($employee_id)) {
2194 return $this->employees->skill_action($employee_id, $request->all());
2195 }
2196 }
2197 public function assignSkills($employee_id, Request $request) {
2198 if (!empty($employee_id)) {
2199 return $this->employees->skill_assign($employee_id, $request->all());
2200 }
2201 }
2202
2203 public function getSkillList($employee_id) {
2204 return $this->employees->get_all_skills($employee_id);
2205 }
2206 public function deleteDocuments($document_id) {
2207 $employee_id = Auth::user()->employee_id;
2208 return $this->employees->deleteEmployeeDocument($employee_id,$document_id);
2209 }
2210
2211 public function deleteSkill($employee_id, $skill_id) {
2212 return $this->employees->delete_skill($employee_id, $skill_id);
2213 }
2214
2215 public function getTimesheetProjectList($employee_id) {
2216 return $this->employees->get_assigned_projectlist($employee_id);
2217 }
2218
2219 public function applyForLeaves(Request $request) {
2220
2221 $leavePolicyLogic = $this->apply_rules($request);
2222
2223 $countOfdays = $this->employees->get_working_day($request->get('startdate'),$request->get('enddate'),'Y-m-d',false);
2224 $allformDate = $request->all();
2225
2226 $allformDate['count'] = count($countOfdays);
2227
2228 // For sending email
2229 $empLoggedId = Auth::user();
2230 $data = [
2231 'employee_id' => $empLoggedId->employee_id,
2232 'employee_name' => $this->employeeModel->removed_Middle_Name($empLoggedId['name']),
2233 'reporting_manager_id' => $empLoggedId['reporting_manager_id'],
2234 'no_of_days' => $allformDate['count'],
2235 'remarks' => $allformDate['resone'],
2236 'start_date' => $allformDate['startdate'],
2237 'end_date' => $allformDate['enddate']
2238 ];
2239 $this->sendEmail($data);
2240
2241 return $this->employeeModel->applayLeaves($allformDate, $leavePolicyLogic);
2242 }
2243
2244 public function sendEmail($dataArray){
2245 try{
2246 $allEmailArray = [];
2247 $emp_ids = [];
2248 $employee_ids = array();
2249
2250 $obj_user = $this->mail->user_info();
2251 $_from_user_name = $obj_user['name'];
2252
2253 $reporting_manager_Email = Employees::where('employee_id',$dataArray['reporting_manager_id'] )->first();
2254 array_push($allEmailArray,$reporting_manager_Email->email);
2255
2256 // PM email id is avilable && If project manager found then bind with clusterHead or reportingmanager email in array.
2257 $get_pm_email = $this->get_ProjectManeger_Email($dataArray);
2258 if($get_pm_email['status'] === true){
2259 foreach($get_pm_email['data'][0] as $email){
2260 array_push($allEmailArray,$email);
2261 }
2262 }
2263
2264 // Get empId based on employeeEmail
2265 if($allEmailArray){
2266 foreach($allEmailArray as $email){
2267 $emp_id = Employees::where('email',$email)->first();
2268 array_push($emp_ids,$emp_id->employee_id);
2269 }
2270 }
2271
2272 //Get Template
2273 $have_template = Templates::where('title', 'Apply Leave')->get();
2274 $search_subject = array('{#Employee Name}');
2275 $replace_subject_name = array($dataArray['employee_name']);
2276
2277 $search_email_body = array('{#Employee Name}','{#No of Days}','{#Start Date}','{#End Date}','{#Remarks}');
2278 $replace_email_body = array($dataArray['employee_name'],$dataArray['no_of_days'],$dataArray['start_date'],$dataArray['end_date'],$dataArray['remarks']);
2279
2280 foreach ($have_template as $have_template) {
2281 $role = explode(',', $have_template['role']);
2282 $to_send_employee_ids = explode(',', $have_template['user']);
2283 $template_email_subject = nl2br(str_replace($search_subject, $replace_subject_name, $have_template['template_email_subject']));
2284 $template_email_body = nl2br(str_replace($search_email_body, $replace_email_body, $have_template['template_email_body']));
2285 $template_notification = nl2br(str_replace($search_email_body, $replace_email_body, $have_template['template_notification']));
2286 if ($template_email_subject && $template_email_body ) {
2287 $params = [
2288 "to" => $allEmailArray,
2289 "from" => ['do-not-reply@indianic.com', $_from_user_name],
2290 ];
2291
2292 if(count($emp_ids) > 0){
2293 foreach ($emp_ids as $id)
2294 {
2295 DB::table('gbl_notifications')->insert(
2296 [
2297 'from_employee_id'=> $dataArray['employee_id'],
2298 'from_employee_name'=>$dataArray['employee_name'],
2299 'to_employee_id'=>$id,
2300 'message'=>$template_notification,
2301 'module_method'=>$have_template['module_method'],
2302 'is_read'=>0
2303 ]
2304 );
2305 }
2306 }
2307
2308 $res = $this->leavepolicy->send_mail($params, $template_email_subject, $template_email_body);
2309 }
2310 }
2311 }catch (JWTException $e) {
2312 return ResponseManager::getError([], config('constants.StatusCode.BadRequest'), $e->getMessage(), config('constants.Boolean.False'));
2313 }
2314 }
2315
2316
2317
2318 public function applayForFlexihours(Request $request) {
2319 // For sending email when Applyflexihours
2320 $empLoggedId = Auth::user();
2321
2322 $datetime1 =Carbon::createFromFormat("Y-m-d", $request->get('toDate'));
2323 $datetime2 = Carbon::createFromFormat("Y-m-d", $request->get('fromDate'));
2324 $countOfdays = $datetime1->diffInDays($datetime2);
2325
2326 $data = [
2327 'employee_id' => $empLoggedId->employee_id,
2328 'employee_name' => $this->employeeModel->removed_Middle_Name($empLoggedId['name']),
2329 'reporting_manager_id' => $empLoggedId['reporting_manager_id'],
2330 'no_of_days' => $countOfdays === 0 ? 1 : $countOfdays ,//0 means 1 day
2331 'remarks' => $request->get('flexiResone'),
2332 'start_date' => $request->get('toDate'),
2333 'end_date' => $request->get('fromDate'),
2334 'startHour' => $request->get('startHour'),
2335 'endHour' => $request->get('endHour'),
2336 ];
2337 $this->sendEmailFlexihours($data);
2338 return $this->employeeModel->applayFlexiHours($request->all());
2339 }
2340
2341 public function sendEmailFlexihours($dataArray){
2342 try{
2343 $allEmailArray = [];
2344 $emp_ids = [];
2345 $employee_ids = array();
2346
2347 $obj_user = $this->mail->user_info();
2348 $_from_user_name = $obj_user['name'];
2349
2350 $reporting_manager_Email = Employees::where('employee_id',$dataArray['reporting_manager_id'] )->first();
2351 array_push($allEmailArray,$reporting_manager_Email->email);
2352
2353 // PM email id is avilable && If project manager found then bind with clusterHead or reportingmanager email in array.
2354 $get_pm_email = $this->get_ProjectManeger_Email($dataArray);
2355 if($get_pm_email['status'] === true){
2356 foreach($get_pm_email['data'][0] as $email){
2357 array_push($allEmailArray,$email);
2358 }
2359 }
2360
2361 // Get empId based on employeeEmail
2362 if($allEmailArray){
2363 foreach($allEmailArray as $email){
2364 $emp_id = Employees::where('email',$email)->first();
2365 array_push($emp_ids,$emp_id->employee_id);
2366 }
2367 }
2368
2369 //Get Template
2370 $have_template = Templates::where('title', 'Apply Flexi Hours')->get();
2371 $search_subject = array('{#Employee Name}');
2372 $replace_subject_name = array($dataArray['employee_name']);
2373
2374 $search_email_body = array('{#Employee Name}','{#No of Days}','{#Start Date}','{#End Date}','{#Start Hour}','{#End Hour}','{#Remarks}');
2375 $replace_email_body = array($dataArray['employee_name'],$dataArray['no_of_days'],$dataArray['start_date'],$dataArray['end_date'],$dataArray['startHour'],$dataArray['endHour'],$dataArray['remarks']);
2376
2377 foreach ($have_template as $have_template) {
2378 $role = explode(',', $have_template['role']);
2379 $to_send_employee_ids = explode(',', $have_template['user']);
2380 $template_email_subject = nl2br(str_replace($search_subject, $replace_subject_name, $have_template['template_email_subject']));
2381 $template_email_body = nl2br(str_replace($search_email_body, $replace_email_body, $have_template['template_email_body']));
2382 $template_notification = nl2br(str_replace($search_email_body, $replace_email_body, $have_template['template_notification']));
2383 if ($template_email_subject && $template_email_body ) {
2384 $params = [
2385 "to" => $allEmailArray,
2386 "from" => ['do-not-reply@indianic.com', $_from_user_name],
2387 ];
2388
2389 if(count($emp_ids) > 0){
2390 foreach ($emp_ids as $id)
2391 {
2392 DB::table('gbl_notifications')->insert(
2393 [
2394 'from_employee_id'=> $dataArray['employee_id'],
2395 'from_employee_name'=>$dataArray['employee_name'],
2396 'to_employee_id'=>$id,
2397 'message'=>$template_notification,
2398 'module_method'=>$have_template['module_method'],
2399 'is_read'=>0
2400 ]
2401 );
2402 }
2403 }
2404 // dd($params,$template_email_subject,$template_email_body);
2405 // $res = $this->leavepolicy->send_mail_flexihours($params, $template_email_subject, $template_email_body);
2406 $res = $this->leavepolicy->send_mail($params, $template_email_subject, $template_email_body);
2407
2408 }
2409 }
2410 }catch (JWTException $e) {
2411 return ResponseManager::getError([], config('constants.StatusCode.BadRequest'), $e->getMessage(), config('constants.Boolean.False'));
2412 }
2413 }
2414
2415 public function get_ProjectManeger_Email($dataArray){
2416
2417 // Get Project Manager Details If leaves start date is match with assign project
2418 $get_emp_project_assign_rec = AssociateAssign::where('employee_id',$dataArray['employee_id']) //'13173' -> kiran sir id
2419 ->where('status','=','Assigned')
2420 ->get();
2421
2422 $assign_id_array = [];
2423 $project_id_array = [];
2424
2425 // Store assign ids in to array
2426 foreach($get_emp_project_assign_rec as $emp_rec){
2427 $assign_id_array[] = $emp_rec['assign_id'];
2428 }
2429
2430 // Check using assign id and apply start date of leave is matching to project assigment then get new assign_id array
2431 // \DB::enableQueryLog();
2432 $assign_id_array_True = [];
2433 foreach($assign_id_array as $assign_id){
2434 $assign_id_array_True = AssociateAssignDetails::where('assign_id',$assign_id)
2435 ->whereDate('start_date','<=',$dataArray['start_date']) //'2019-07-02' testing date
2436 ->whereDate('end_date', '>=',$dataArray['start_date'])
2437 ->pluck('assign_id');
2438 }
2439 if(count($assign_id_array_True)>0){
2440
2441 // get projectids in to array
2442 foreach($assign_id_array_True as $id){
2443 $project_id_array[] = AssociateAssign::where('assign_id',$id)->pluck('project_id');
2444 }
2445
2446 // get project manager id, name, and email
2447 foreach($project_id_array as $id){
2448 $get_pm_ids = Project::where('project_id',$id)->pluck('primary_project_manager_id');
2449 }
2450
2451 foreach($get_pm_ids as $id){
2452 $get_pm_email[] = Employees::where('employee_id', $id)->pluck('email');
2453 }
2454
2455 $dataArray['status'] = true;
2456 $dataArray['data'] = $get_pm_email;
2457 return $dataArray;
2458 }else{
2459 $dataArray['status'] = false;
2460 return $dataArray;
2461 }
2462 }
2463
2464 public function leavesDateFilter(Request $request) {
2465 return $this->employeeModel->leavesDatesFilter($request->all());
2466 }
2467
2468// public function appl_rules(Request $request)
2469// {
2470// try {
2471//
2472// $current_date = date("Y-m-d");
2473// $apply_before_days = 0;
2474// if ($request) {
2475// $validate = $this->getValidationFactory()->make($request->all(), (new ApplyLeavesRulesRequest())->rules($request->all()), (new ApplyLeavesRulesRequest())->message(), []);
2476// if ($validate->fails()) {
2477// return ResponseManager::getError([], config('constants.StatusCode.Unprocessable'), $validate->errors(), config('constants.Boolean.False'));
2478// } else {
2479// $leaves_status = Leaves::where('user_id', Auth::user()->employee_id)
2480// ->whereDate('date_from', '<=', $current_date)
2481// ->whereDate('date_to', '>=', $current_date)->where('leave_status', '!=', 'Void')->first();
2482// $all_leaves_status = Leaves::where('user_id', Auth::user()->employee_id)
2483// ->whereDate('date_from', '>=', $current_date)->where('leave_status', '!=', 'Void')->get();
2484//
2485// //Apply leave for start date to end date,get all working days between start dates and end date
2486// $getTotalWrokingDays = $this->employees->get_working_day($request->get('startdate'), $request->get('enddate'));
2487// if ($getTotalWrokingDays) {
2488// $exists = $this->employees->checkAplliedDayExists($getTotalWrokingDays);
2489// if (!empty($exists)) {
2490// return ResponseManager::getError($exists, config('constants.StatusCode.Unprocessable'), __('message.Leaves.leaveApplyExist'), config('constants.Boolean.False'));
2491// }
2492// foreach ($getTotalWrokingDays as $dates) {
2493// $datesConveArray[] = ResponseManager::_date($dates);
2494// }
2495// //count working days
2496// $datesConveArray['count'] = count($datesConveArray);
2497// //get diffrence between aplly date to leave start date
2498// $_start_date = date("Y-m-d");
2499// $_end_date = $request->get('startdate');
2500// $now = time(); // or your date as well
2501// $your_date = strtotime($request->startdate);
2502// $datediff = $your_date - $now;
2503// $applied_before_days = round($datediff / (60 * 60 * 24));
2504// $getdaysDiffrence = $this->employees->get_working_day($_start_date, $_end_date);
2505// if ($applied_before_days != 0) {
2506// $days_diffrence['count'] = $applied_before_days;
2507// } else {
2508// $data_response['remark'] = 'unplanned';
2509// $days_diffrence['count'] = 0;
2510// }
2511// $start_leave = holidaysBeforeStartDate($request->startdate);
2512// $end_date = holidaysAfterEndDate($request->enddate);
2513// if ($request->get('startdate') == $request->get('enddate') || $datesConveArray['count'] <= 3) {
2514// $get_start_day = date("D", strtotime($request->get('startdate')));
2515// $get_end_day = date("D", strtotime($request->get('enddate')));
2516// if ($get_start_day == 'Mon') {
2517// $data_response['rules_day'] = 7;
2518// $apply_before_days = 7;
2519// } elseif ($get_start_day == 'Fri') {
2520// $data_response['rules_day'] = 7;
2521// $apply_before_days = 7;
2522// } elseif ($get_end_day == 'Mon') {
2523// $data_response['rules_day'] = 7;
2524// $apply_before_days = 7;
2525// } elseif ($get_end_day == 'Fri') {
2526// $data_response['rules_day'] = 7;
2527// $apply_before_days = 7;
2528// }
2529//
2530// if ($get_start_day == $get_end_day && ($get_start_day == 'Mon' || $get_start_day == 'Fri')) {
2531// $apply_before_days = 7;
2532// $data_response['rules_day'] = $apply_before_days;
2533// }
2534// if ((isset($end_date['leaves']) && !empty($end_date['leaves'])) || (isset($_start_date['leaves']) && !empty($_start_date['leaves']))) {
2535// $apply_before_days = 7;
2536// $data_response['rules_day'] = $apply_before_days;
2537// } else {
2538// if ($apply_before_days == 0) {
2539// $apply_before_days = getRules($datesConveArray['count']);
2540// $data_response['rules_day'] = $apply_before_days;
2541// }
2542// }
2543// } else {
2544// //get days according policy, how much days before we should apply for leave according working leave days
2545//
2546//
2547// $apply_before_days = getRules($datesConveArray['count']);
2548// $data_response['rules_day'] = $apply_before_days;
2549// }
2550// if ($request->get('startdate') != $request->get('enddate')) {
2551// if ($datesConveArray['count'] == 1) {
2552// $apply_before_days = 7;
2553// $data_response['rules_day'] = $apply_before_days;
2554// }
2555// }
2556//
2557// /**
2558// * eg. start_date= "2019-03-13" to end_date = "2019-03-14" = 2 working days *
2559// *
2560// * get difference b/w apply date to leave start date
2561// * now(2018-03-09) to 2019-03-13 = 4 days
2562// *
2563// * get rules according leave applied for official working day
2564// * here is 2 working day so i got rule, apply leave before 5 days for 2 days
2565// *
2566// * but I have applied before 4 days but rules is valid for apply before or equal to rules day
2567// * if rules day is greater than applied days difference it will be unplanned leave vice versa.
2568// * rules day > applied days == 'un planned leave'
2569// * rules day <= applied days == 'planned leave'
2570// *
2571// */
2572// if ($days_diffrence['count'] == 0) {
2573// $days_diffrence['count'] = 1;
2574// }
2575// //check applicant is following policy of leave apply,according to diffrence we decide leave is planned or un planned
2576// if ($apply_before_days <= $days_diffrence['count']) {
2577// $data_response['remark'] = 'Planned';
2578// } else {
2579// $data_response['remark'] = 'Unplanned';
2580// }
2581// //get holidays of current year
2582// $holidays = getHolidays();
2583//
2584// // if $data_response['remark'] == 'unplanned' than use sandwich rulles of commpany and calculate how much additional leave day will be deducted from working day
2585//
2586// $leave_days = Carbon::parse($request->get('startdate'))->diffInDays(Carbon::parse($request->get('enddate'))) + 1;
2587// $get_start_day = date("D", strtotime($request->get('startdate')));
2588// $get_end_day = date("D", strtotime($request->get('enddate')));
2589// if ($days_diffrence['count'] != 0) {
2590// if ($get_start_day == 'Mon') {
2591// $leave_days = $leave_days + 2;
2592// $prev_saturday_date = date('Y-m-d', strtotime('-2 day', strtotime($request->get('startdate'))));
2593// $prev_sundayday_date = date('Y-m-d', strtotime('-1 day', strtotime($request->get('startdate'))));
2594// $request->startdate = $prev_saturday_date;
2595// unset($prev_saturday_date);
2596// unset($prev_sundayday_date);
2597// }
2598// if ($get_end_day == 'Fri') {
2599// $leave_days = $leave_days + 2;
2600// $next_saturday_date = date('Y-m-d', strtotime('+1 day', strtotime($request->get('startdate'))));
2601// $next_sundayday_date = date('Y-m-d', strtotime('+2 day', strtotime($request->get('enddate'))));
2602// $request->enddate = $next_sundayday_date;
2603// unset($next_saturday_date);
2604// unset($next_sundayday_date);
2605// }
2606// if ($get_end_day == 'Sat') {
2607// $leave_days = $leave_days + 1;
2608// $next_sundayday_date = date('Y-m-d', strtotime('+1 day', strtotime($request->get('enddate'))));
2609// $request->enddate = $next_sundayday_date;
2610// unset($next_sundayday_date);
2611// }
2612// if ($get_start_day == 'Sat') {
2613// $leave_days = $leave_days + 1;
2614// $next_sundayday_date = date('Y-m-d', strtotime('+1 day', strtotime($request->get('startdate'))));
2615// unset($next_sundayday_date);
2616// }
2617// if ($get_start_day == 'Sun') {
2618// $leave_days = $leave_days + 1;
2619// $prev_saturday_date = date('Y-m-d', strtotime('-1 day', strtotime($request->get('startdate'))));
2620// $request->startdate = $prev_saturday_date;
2621// unset($prev_saturday_date);
2622// }
2623// if (isset($end_date['leaves']) && !empty($end_date['leaves'])) {
2624// $request->endtdate = $end_date['end_date'];
2625// }
2626// if (isset($_start_date['leaves']) && !empty($_start_date['leaves'])) {
2627// $request->startdate = $end_date['start_date'];
2628// }
2629// }
2630// $leave_balance = Auth::user()->leave_balance;
2631// if ($data_response['remark'] == 'Unplanned') {
2632// $start_leave = holidaysBeforeStartDate($request->startdate);
2633// $end_date = holidaysAfterEndDate($request->enddate);
2634// $data_response['total_leave'] = $start_leave['leaves'] + $leave_days + $end_date['leaves'];
2635// $data_response['sandwich_leave'] = $data_response['total_leave'] - $datesConveArray['count'];
2636// $data_response['applied_leave'] = $datesConveArray['count'];
2637// $data_response['unplanned_total_leave'] = ($start_leave['leaves'] + $leave_days + $end_date['leaves']) * 2;
2638// $data_response['old_leave_balance'] = $leave_balance ? $leave_balance : 0;
2639// $data_response['deducted_from_leave'] = 0;
2640// $data_response['LOP'] = $data_response['deducted_from_leave'] < $data_response['unplanned_total_leave'] ? $data_response['unplanned_total_leave'] - $data_response['deducted_from_leave'] : $data_response['deducted_from_leave'] - $datesConveArray['count'];
2641// //$data_response['new_leave_balance'] = $data_response['old_leave_balance'];
2642// $data_response['day_details'] = getSpecificdayList($start_leave['start_date'] ? $start_leave['start_date'] : $request->startdate, $end_date['end_date'] ? $end_date['end_date'] : $request->enddate);
2643// }
2644// if ($data_response['remark'] == 'Planned') {
2645//
2646// $start_leave = holidaysBeforeStartDate($request->startdate);
2647// $end_date = holidaysAfterEndDate($request->enddate);
2648// $data_response['total_leave'] = $start_leave['leaves'] + $leave_days + $end_date['leaves'];
2649// $data_response['sandwich_leave'] = 0;
2650// $data_response['applied_leave'] = $datesConveArray['count'];
2651// $data_response['old_leave_balance'] = $leave_balance ? $leave_balance : 0;
2652// $data_response['deducted_from_leave'] = $leave_balance >= $datesConveArray['count'] ? $datesConveArray['count'] : $leave_balance;
2653// $data_response['LOP'] = $data_response['deducted_from_leave'] < $datesConveArray['count'] ? $datesConveArray['count'] - $data_response['deducted_from_leave'] : $data_response['deducted_from_leave'] - $datesConveArray['count'];
2654// //$data_response['new_leave_balance'] = $leave_balance >= $datesConveArray['count'] ? $leave_balance - $datesConveArray['count'] : 0;
2655// $data_response['day_details'] = getSpecificdayList($start_leave['start_date'] ? $start_leave['start_date'] : $request->startdate, $end_date['end_date'] ? $end_date['end_date'] : $request->enddate);
2656// }
2657// } else {
2658// return ResponseManager::getResult([], config('constants.StatusCode.Unprocessable'), __('message.Leaves.isNotWorkingDay'), config('constants.Boolean.True'));
2659// }
2660// }
2661// }
2662//
2663// return ResponseManager::getResult($data_response, config('constants.StatusCode.Ok'), __('message.Leaves.getDeductedDay'), config('constants.Boolean.True'));
2664// } catch (JWTException $e) {
2665// return ResponseManager::getResult([], config('constants.StatusCode.ServerError'), __('message.Logout.error_msg'), config('constants.Boolean.True'));
2666// }
2667// }
2668 //***************** New leave Policy 1 April 2019 **********************
2669 public function apply_rules(Request $request) {
2670 try {
2671 $type = isset($request->requested_by) && !empty($request->requested_by) ? $request->requested_by : "";
2672 $data_response = [];
2673 $current_date = date("Y-m-d");
2674 $apply_before_days = 0;
2675 if ($request) {
2676 $validate = $this->getValidationFactory()->make($request->all(), (new ApplyLeavesRulesRequest())->rules($request->all()), (new ApplyLeavesRulesRequest())->message(), []);
2677 if ($validate->fails()) {
2678 return ResponseManager::getError([], config('constants.StatusCode.Unprocessable'), $validate->errors(), config('constants.Boolean.False'), $type);
2679 } else {
2680 $getTotalWrokingDays = $this->employees->get_working_day($request->get('startdate'), $request->get('enddate'));
2681 $exists = $this->employees->checkAplliedDayExists($getTotalWrokingDays);
2682 if (!empty($exists)) {
2683 if($type){
2684 $_msg = __('message.Leave.allreadyApplied');
2685 }else{
2686 $_msg = __('message.Leaves.leaveApplyExist');
2687 }
2688 return ResponseManager::getError($exists, config('constants.StatusCode.Unprocessable'),$_msg, config('constants.Boolean.False'), $type);
2689 }
2690 $check_first_holiday_exist = Holidays::where('date', $request->get('startdate'))->first();
2691 $check_last_holiday_exist = Holidays::where('date', $request->get('enddate'))->first();
2692
2693 $checkBeforeAndAfterLeaveExist = $this->checkBeforeAndAfterLeave($request->get('startdate'), $request->get('enddate'),$request->get('flexiHoursRequest'));
2694
2695 if ($checkBeforeAndAfterLeaveExist['exists']) {
2696
2697 if($type){
2698 $_mess = __('message.Leave.revokeOldLeave');
2699 $_mess['revokeOldLeave'] = [$_mess['revokeOldLeave'][0]." ".$checkBeforeAndAfterLeaveExist['date']];
2700 }else{
2701 $_mess = __('message.Leaves.revokeOld')." ". $checkBeforeAndAfterLeaveExist['date'];
2702 }
2703 return ResponseManager::getError($checkBeforeAndAfterLeaveExist['exists'], config('constants.StatusCode.Unprocessable'),$_mess, config('constants.Boolean.False'), $type);
2704 }
2705
2706 //Apply leave for start date to end date,get all working days between start dates and end date
2707
2708 if ($getTotalWrokingDays) {
2709
2710 foreach ($getTotalWrokingDays as $dates) {
2711 $datesConveArray[] = ResponseManager::_date($dates);
2712 }
2713 //count working days
2714 $datesConveArray['count'] = count($datesConveArray);
2715 //get diffrence between aplly date to leave start date
2716 $_start_date = date("Y-m-d");
2717 $_end_date = $request->get('startdate');
2718 $applied_before_days = getDateDifferArray(time(), $request->startdate);
2719 $days_diffrence['count'] = $applied_before_days;
2720 $getdaysDiffrence = $this->employees->get_working_day($_start_date, $_end_date);
2721 $total_all_days = createDateRange($request->startdate, $request->enddate);
2722 $total_all_days = count($total_all_days);
2723 $start_leave = holidaysBeforeStartDate($request->startdate);
2724 $end_date = holidaysAfterEndDate($request->enddate);
2725 if ($request->get('startdate') == $request->get('enddate') || $datesConveArray['count'] <= 3) {
2726 $get_start_day = date("D", strtotime($request->get('startdate')));
2727 $get_end_day = date("D", strtotime($request->get('enddate')));
2728 if ($get_start_day == 'Mon') {
2729 $data_response['rules_day'] = 7;
2730 $apply_before_days = 7;
2731 } elseif ($get_start_day == 'Fri') {
2732 $data_response['rules_day'] = 7;
2733 $apply_before_days = 7;
2734 } elseif ($get_end_day == 'Mon') {
2735 $data_response['rules_day'] = 7;
2736 $apply_before_days = 7;
2737 } elseif ($get_end_day == 'Fri') {
2738 $data_response['rules_day'] = 7;
2739 $apply_before_days = 7;
2740 }
2741
2742 if ($get_start_day == $get_end_day && ($get_start_day == 'Mon' || $get_start_day == 'Fri')) {
2743 $apply_before_days = 7;
2744 $data_response['rules_day'] = $apply_before_days;
2745 }
2746 if ((isset($end_date['leaves']) && !empty($end_date['leaves'])) || (isset($_start_date['leaves']) && !empty($_start_date['leaves']) )) {
2747 $apply_before_days = 7;
2748 $data_response['rules_day'] = $apply_before_days;
2749 } else {
2750 if ($apply_before_days == 0) {
2751 $apply_before_days = getRules($datesConveArray['count']);
2752 $data_response['rules_day'] = $apply_before_days;
2753 }
2754 }
2755 } else {
2756 //get days according policy, how much days before we should apply for leave according working leave days
2757
2758
2759 $apply_before_days = getRules($datesConveArray['count']);
2760 $data_response['rules_day'] = $apply_before_days;
2761 }
2762 if ($request->get('startdate') != $request->get('enddate')) {
2763 if ($datesConveArray['count'] == 1) {
2764 $apply_before_days = 7;
2765 $data_response['rules_day'] = $apply_before_days;
2766 }
2767 }
2768
2769 /**
2770 * eg. start_date= "2019-03-13" to end_date = "2019-03-14" = 2 working days *
2771 *
2772 * get difference b/w apply date to leave start date
2773 * now(2018-03-09) to 2019-03-13 = 4 days
2774 *
2775 * get rules according leave applied for official working day
2776 * here is 2 working day so i got rule, apply leave before 5 days for 2 days
2777 *
2778 * but I have applied before 4 days but rules is valid for apply before or equal to rules day
2779 * if rules day is greater than applied days difference it will be unplanned leave vice versa.
2780 * rules day > applied days == 'un planned leave'
2781 * rules day <= applied days == 'planned leave'
2782 *
2783 */
2784 if ($days_diffrence['count'] == 0) {
2785 $days_diffrence['count'] = 1;
2786 }
2787 //check applicant is following policy of leave apply,according to diffrence we decide leave is planned or un planned
2788 if ($apply_before_days <= $days_diffrence['count']) {
2789 $data_response['remark'] = 'Planned';
2790 } else {
2791 $data_response['remark'] = 'Unplanned';
2792 }
2793 //get holidays of current year
2794 $holidays = getHolidays();
2795
2796 // if $data_response['remark'] == 'unplanned' than use sandwich rulles of commpany and calculate how much additional leave day will be deducted from working day
2797
2798 $leave_days = Carbon::parse($request->get('startdate'))->diffInDays(Carbon::parse($request->get('enddate'))) + 1;
2799 $get_start_day = date("D", strtotime($request->get('startdate')));
2800 $get_end_day = date("D", strtotime($request->get('enddate')));
2801 if ($days_diffrence['count'] != 0) {
2802 if ($get_start_day == 'Mon') {
2803 $leave_days = $leave_days + 2;
2804 $prev_saturday_date = date('Y-m-d', strtotime('-2 day', strtotime($request->get('startdate'))));
2805 $prev_sundayday_date = date('Y-m-d', strtotime('-1 day', strtotime($request->get('startdate'))));
2806 $request->startdate = $prev_saturday_date;
2807 unset($prev_saturday_date);
2808 unset($prev_sundayday_date);
2809 }
2810 if ($get_end_day == 'Fri') {
2811 $leave_days = $leave_days + 2;
2812 $next_saturday_date = date('Y-m-d', strtotime('+1 day', strtotime($request->get('startdate'))));
2813 $next_sundayday_date = date('Y-m-d', strtotime('+2 day', strtotime($request->get('enddate'))));
2814 $request->enddate = $next_sundayday_date;
2815 unset($next_saturday_date);
2816 unset($next_sundayday_date);
2817 }
2818 if ($get_end_day == 'Sat') {
2819 $leave_days = $leave_days + 1;
2820 $next_sundayday_date = date('Y-m-d', strtotime('+1 day', strtotime($request->get('enddate'))));
2821 $request->enddate = $next_sundayday_date;
2822 $total_all_days = $total_all_days - 1;
2823 unset($next_sundayday_date);
2824 }
2825 if ($get_end_day == 'Sun') {
2826 $total_all_days = $total_all_days - 2;
2827 }
2828 if ($get_start_day == 'Sat') {
2829 $leave_days = $leave_days + 1;
2830 $next_sundayday_date = date('Y-m-d', strtotime('+1 day', strtotime($request->get('startdate'))));
2831 $total_all_days = $total_all_days - 1;
2832 unset($next_sundayday_date);
2833 }
2834 if ($get_start_day == 'Sun') {
2835 $leave_days = $leave_days + 1;
2836 $prev_saturday_date = date('Y-m-d', strtotime('-1 day', strtotime($request->get('startdate'))));
2837 $request->startdate = $prev_saturday_date;
2838 $total_all_days = $total_all_days - 1;
2839 unset($prev_saturday_date);
2840 }
2841 if (isset($end_date['leaves']) && !empty($end_date['leaves'])) {
2842 $request->endtdate = $end_date['end_date'];
2843 }
2844 if (isset($_start_date['leaves']) && !empty($_start_date['leaves'])) {
2845 $request->startdate = $end_date['start_date'];
2846 }
2847 if ($check_first_holiday_exist) {
2848 $total_all_days = $total_all_days - 1;
2849 }
2850 if ($check_last_holiday_exist) {
2851 $total_all_days = $total_all_days - 1;
2852 }
2853 }
2854 $leave_balance = Auth::user()->leave_balance;
2855 if ($data_response['remark'] == 'Unplanned') {
2856 $start_leave = holidaysBeforeStartDate($request->startdate);
2857 $end_date = holidaysAfterEndDate($request->enddate);
2858 $data_response['total_leave'] = $start_leave['leaves'] + $leave_days + $end_date['leaves'];
2859 $data_response['sandwich_leave'] = $total_all_days - $datesConveArray['count'];
2860 $data_response['applied_leave'] = $datesConveArray['count'];
2861 $data_response['unplanned_total_leave'] = $total_all_days + 1;
2862 $data_response['old_leave_balance'] = $leave_balance ? $leave_balance : 0;
2863 $data_response['deducted_from_leave'] = 0;
2864 $data_response['LOP'] = $total_all_days + 1;
2865 $data_response['new_leave_balance'] = $leave_balance ? $leave_balance : 0;
2866 $data_response['day_details'] = getSpecificdayList($start_leave['start_date'] ? $start_leave['start_date'] : $request->startdate, $end_date['end_date'] ? $end_date['end_date'] : $request->enddate);
2867 }
2868 if ($data_response['remark'] == 'Planned') {
2869 $start_leave = holidaysBeforeStartDate($request->startdate);
2870 $end_date = holidaysAfterEndDate($request->enddate);
2871 $data_response['total_leave'] = $start_leave['leaves'] + $leave_days + $end_date['leaves'];
2872 $data_response['sandwich_leave'] = 0;
2873 $data_response['applied_leave'] = $datesConveArray['count'];
2874 $data_response['old_leave_balance'] = $leave_balance ? $leave_balance : 0;
2875 $data_response['deducted_from_leave'] = $leave_balance >= $datesConveArray['count'] ? (string)$datesConveArray['count'] : $leave_balance;
2876 $data_response['LOP'] = $data_response['deducted_from_leave'] < $datesConveArray['count'] ? $datesConveArray['count'] - $data_response['deducted_from_leave'] : $data_response['deducted_from_leave'] - $datesConveArray['count'];
2877 //$data_response['new_leave_balance'] = $leave_balance >= $datesConveArray['count'] ? $leave_balance - $datesConveArray['count'] : 0;
2878 $convertString = (string)(float)($leave_balance - $datesConveArray['count']);
2879 $data_response['new_leave_balance'] = $leave_balance >= $datesConveArray['count'] ? (string)$convertString : "0";
2880 $data_response['day_details'] = getSpecificdayList($start_leave['start_date'] ? $start_leave['start_date'] : $request->startdate, $end_date['end_date'] ? $end_date['end_date'] : $request->enddate);
2881 }
2882 } else {
2883 if($type){
2884 $mess = __('message.Leave.notWorkingDay');
2885 }else{
2886 $mess = __('message.Leaves.isNotWorkingDay');
2887 }
2888
2889 return ResponseManager::getResult([], config('constants.StatusCode.Unprocessable'),$mess, config('constants.Boolean.True'), $type);
2890 }
2891 }
2892 }
2893
2894 ///////////////////
2895 $current_year = date("Y");
2896 $whereIn = ['Approved', 'System marked leave'];
2897 $emergency_count = Leaves::where('user_id', \Auth::user()->employee_id)
2898 ->where('date_from', ">=", "2019-04-01")
2899 ->where('date_from', "<=", $current_year . "-12-31")
2900 ->where('leave_type', 'emergency_leave')
2901 ->whereIn('leave_status', $whereIn)->get();
2902
2903 $emergency_leave = 0;
2904 if ($emergency_count) {
2905 $count = count($emergency_count) > 3 ? 0 : config('constants.EmergencyLeaveCount.count') - count($emergency_count);
2906 $emergency_leave = $count;
2907 } else {
2908 $emergency_leave = 3;
2909 }
2910 $data_response['emergencyPendingLeaveTime'] = $emergency_leave;
2911 ///////////////////
2912 return ResponseManager::getResult($data_response, config('constants.StatusCode.Ok'), __('message.Leaves.getDeductedDay'), config('constants.Boolean.True'), $type);
2913 } catch (JWTException $e) {
2914 return ResponseManager::getResult([], config('constants.StatusCode.ServerError'), __('message.Logout.error_msg'), config('constants.Boolean.True'), $type);
2915 }
2916 }
2917
2918 /*
2919 *
2920 * Get Today's tasks of Logged in Employee's
2921 *
2922 *
2923 */
2924
2925 public function employeeTodayProjectTasks($employee_id) {
2926 return $this->employees->employee_today_project_task($employee_id);
2927 }
2928
2929 public function logout(Request $request) {
2930 $token = $request->header('Authorization');
2931 try {
2932 JWTAuth::invalidate($token);
2933 return ResponseManager::getResult([], config('constants.StatusCode.Ok'), __('message.Logout.success_msg'), config('constants.Boolean.True'));
2934 } catch (JWTException $e) {
2935 return ResponseManager::getResult([], config('constants.StatusCode.ServerError'), __('message.Logout.error_msg'), config('constants.Boolean.True'));
2936 }
2937 }
2938
2939 /*
2940 *
2941 * Request Type Get
2942 * return Logged in use task timesheet
2943 *
2944 */
2945
2946 public function employeeTimesheet(Request $request, $get_employee_id) {
2947 $data = $_GET;
2948 if ($get_employee_id) {
2949 return $this->employees->employee_timesheet($request, $get_employee_id, $data);
2950 } else {
2951 return ResponseManager::getError([], config('constants.StatusCode.Unprocessable'), __('messages.Employee.not_exist_id'), config('constants.Boolean.False'));
2952 }
2953 }
2954
2955 public function reviewing_timesheet(Request $request) {
2956 $user_obj = \Auth::user();
2957 $data = $_GET;
2958 if ($user_obj->employee_id) {
2959 return $this->timesheets->get_reviewing_timesheet($request, $user_obj->employee_id, $data);
2960 } else {
2961 return ResponseManager::getError([], config('constants.StatusCode.Unprocessable'), __('messages.Employee.not_exist_id'), config('constants.Boolean.False'));
2962 }
2963 }
2964 public function reviewing_timesheet_my_team(Request $request) {
2965 $user_obj = \Auth::user();
2966 $data = $_GET;
2967 if ($user_obj->employee_id) {
2968 return $this->timesheets->get_reviewing_timesheet_my_team($request, $user_obj->employee_id, $data);
2969 } else {
2970 return ResponseManager::getError([], config('constants.StatusCode.Unprocessable'), __('messages.Employee.not_exist_id'), config('constants.Boolean.False'));
2971 }
2972 }
2973
2974 public function show_timesheet($timesheet_id) {
2975 if ($timesheet_id) {
2976 return $this->timesheets->get_show_timesheet($timesheet_id);
2977 } else {
2978 return ResponseManager::getError([], config('constants.StatusCode.Unprocessable'), __('messages.Employee.not_exist_id'), config('constants.Boolean.False'));
2979 }
2980 }
2981
2982 public function projectsTimesheet($get_project_id) {
2983 $data = $_GET;
2984 if ($get_project_id) {
2985 return $this->timesheets->projects_timesheet($get_project_id, $data);
2986 } else {
2987 return ResponseManager::getError([], config('constants.StatusCode.Unprocessable'), __('messages.Employee.not_exist_id'), config('constants.Boolean.False'));
2988 }
2989 }
2990
2991 /* End */
2992
2993 public function leaves_summary(Request $request) {
2994 $employee_id = "";
2995 if (isset($_GET['employee_id']) && !empty($_GET['employee_id'])) {
2996 $employee_id = $_GET['employee_id'];
2997 }
2998 if (empty($employee_id)) {
2999 $employee_id = Auth::user()->employee_id;
3000 }
3001 return $this->employees->getLeavesSummary($employee_id);
3002 }
3003
3004 public function leaves_summary_year(Request $request) {
3005 $employee_id = "";
3006 if (isset($_GET['employee_id']) && !empty($_GET['employee_id'])) {
3007 $employee_id = $_GET['employee_id'];
3008 }
3009 $data = (isset($_GET['team_view']) && $_GET['team_view'] == true) ? $_GET['team_view'] : "" ;
3010 if (empty($employee_id)) {
3011 $employee_id = Auth::user()->employee_id;
3012 }
3013 if (isset($_GET['year']) && !empty($_GET['year'])) {
3014 $year = $_GET['year'];
3015 } else {
3016 $year = date("Y");
3017 }
3018 return $this->employees->getLeavesSummaryYearWise1($employee_id, $year,$data);
3019 }
3020
3021 public function leaves_summary_list($leave_id = null) {
3022 $employee_id = "";
3023 if (isset($_GET['employee_id']) && !empty($_GET['employee_id'])) {
3024 $employee_id = $_GET['employee_id'];
3025 }
3026 if (empty($employee_id)) {
3027 $employee_id = Auth::user()->employee_id;
3028 }
3029 return $this->employees->getLeaves($employee_id, $leave_id = null, $_GET);
3030 }
3031
3032 public function revoke_leave($leave_id) {
3033 return $this->employees->revokeLeave($leave_id);
3034 }
3035
3036 public function flexible_hour_summary_list() {
3037 $employee_id = "";
3038 if (isset($_GET['employee_id']) && !empty($_GET['employee_id'])) {
3039 $employee_id = $_GET['employee_id'];
3040 }
3041 if (empty($employee_id)) {
3042 $employee_id = Auth::user()->employee_id;
3043 }
3044 return $this->employees->getFlexibleHourList($employee_id, $_GET);
3045 }
3046
3047 public function flexible_hour_summary(Request $request) {
3048 $employee_id = "";
3049 if (isset($_GET['employee_id']) && !empty($_GET['employee_id'])) {
3050 $employee_id = $_GET['employee_id'];
3051 }
3052 if (empty($employee_id)) {
3053 $employee_id = Auth::user()->employee_id;
3054 }
3055 return $this->employees->getFlexibleSummary($employee_id);
3056 }
3057
3058 public function flexible_hour_revoke($flexi_id) {
3059 return $this->employees->revokeFlexiHour($flexi_id);
3060 }
3061
3062 public function conferenceBooking(Request $request) {
3063 $employee_id = Auth::user()->employee_id;
3064 return $this->employees->conferenceBookingForMeeting($employee_id, $request);
3065 }
3066
3067 public function getConferenceRoomList() {
3068 return $this->employees->getConferenceRoomsList();
3069 }
3070
3071 public function getConferenceRoomNeedList() {
3072 return $this->employees->getConferenceRoomsNeedList();
3073 }
3074
3075 public function getGroupNameList() {
3076 $perent_id_array = [];
3077 $group_data = [];
3078 $perent_id_finle = [];
3079 // $data = \App\Models\Groups::select('group_id','parent_id','name')->where('is_cluster',1)->get();
3080 $data = Groups::with(['employeeName', 'groupSelfJoin', 'groupSelfJoin.employeeName' => function ($q) {
3081 $q->select('name as employee_name', 'employee_id');
3082 }])->select('group_id', 'parent_id', 'name', 'head_id')->where('status', 'Active')->get();
3083 if ($data) {
3084 $name = removeMiddleName($data->toArray()[0]['employee_name']['employee_name']);
3085 $parent_key = $data->toArray()[0]['name'] . " - " . $name;
3086 foreach ($data->toArray()[0]['group_self_join'] as $new_val) {
3087 $perent_id_array[] = $new_val['group_id'];
3088 }
3089 foreach ($data->toArray() as $key => $array_data) {
3090 if ($key != 0) {
3091 $response = in_array($array_data['parent_id'], $perent_id_array);
3092 $counter = 0;
3093 if ($response) {
3094
3095 $new_name = removeMiddleName($array_data['employee_name']['employee_name']);
3096 $perent_id_finle[$parent_key][$counter][] = $array_data['group_id'];
3097 $perent_id_finle[$parent_key][$counter][] = $array_data['name'] . " - " . $new_name;
3098 $perent_id_finle[$parent_key][$counter][] = $array_data['group_self_join'];
3099 $counter++;
3100 }
3101 }
3102 }
3103 echo '<pre>';
3104 print_r($perent_id_finle);
3105 exit();
3106 }
3107 return $this->employees->getConferenceRoomsNeedList();
3108 }
3109
3110 public function AllEmployeeList() {
3111 $data = ResponseManager::getEmployeeAllList();
3112 if (isset($data['select_list']) && !empty($data['select_list'])) {
3113 $data['total'] = count($data['select_list']);
3114 unset($data["all"]);
3115 return ResponseManager::getResult($data, config('constants.StatusCode.Ok'), __('message.ConferenceBooking.allEmployeeListExist'), config('constants.Boolean.True'));
3116 } else {
3117 return ResponseManager::getError([], config('constants.StatusCode.BadRequest'), __('message.ConferenceBooking.allEmployeeListNoExist'), config('constants.Boolean.False'));
3118 }
3119 }
3120
3121 public function leaveActionByTl(Request $request) {
3122 $emp_id = Auth::user()->employee_id;
3123 $validate = $this->getValidationFactory()->make($request->all(), (new LeaveActionRequest())->rules($request->all()), (new LeaveActionRequest())->message($request->all()), []);
3124 if ($validate->fails()) {
3125 return ResponseManager::getError([], config('constants.StatusCode.Unprocessable'), $validate->errors(), config('constants.Boolean.False'));
3126 } else {
3127 $response = $this->employees->leave_action_by_tl($request->all(), $emp_id);
3128 $leaveDetails = Leaves::findOrFail($request->get('leave_id'));
3129
3130 $empLoggedId = Auth::user();
3131 $reporting_manager_Email = Employees::where('employee_id',$empLoggedId['reporting_manager_id'])->first();
3132 $data = [
3133 'employee_id' => $empLoggedId->employee_id,
3134 'employee_name' => $this->employeeModel->removed_Middle_Name($empLoggedId['name']),
3135 'employee_email' => $empLoggedId['email'],
3136 'reporting_manager_id' => $empLoggedId['reporting_manager_id'],
3137 'reporting_manager_name'=>$this->employeeModel->removed_Middle_Name($reporting_manager_Email['name']),
3138 'no_of_days' => $leaveDetails['apply_days'],
3139 'start_date' => $leaveDetails['date_from'],
3140 'end_date' => $leaveDetails['date_to'],
3141 'status'=>$request->get('action')
3142 ];
3143 $this->sendApproveEmail($data);
3144 return $response;
3145 }
3146 }
3147
3148 public function sendApproveEmail($dataArray){
3149 try{
3150 $allEmailArray = [];
3151 $emp_ids = [];
3152 $employee_ids = array();
3153
3154 $obj_user = $this->mail->user_info();
3155 $_from_user_name = $obj_user['name'];
3156
3157 // $reporting_manager_Email = Employees::where('employee_id',$dataArray['reporting_manager_id'] )->first();
3158 // array_push($allEmailArray,$reporting_manager_Email->email);
3159
3160 // Add employee email
3161 array_push($allEmailArray,$dataArray['employee_email']);
3162
3163
3164 // PM email id is avilable && If project manager found then bind with clusterHead or reportingmanager email in array.
3165 $get_pm_email = $this->get_ProjectManeger_Email($dataArray);
3166 if($get_pm_email['status'] === true){
3167 foreach($get_pm_email['data'][0] as $email){
3168 array_push($allEmailArray,$email);
3169 }
3170 }
3171
3172 // Get empId based on employeeEmail
3173 if($allEmailArray){
3174 foreach($allEmailArray as $email){
3175 $emp_id = Employees::where('email',$email)->first();
3176 array_push($emp_ids,$emp_id->employee_id);
3177 }
3178 }
3179
3180 $leaveStatus;
3181 if($dataArray['status'] === 'Approved'){
3182 $leaveStatus = 'Leave Approved';
3183 }else if($dataArray['status'] === 'Reject'){
3184 $leaveStatus = 'Leave Reject';
3185 }
3186
3187 //Get Template
3188 $have_template = Templates::where('title', $leaveStatus)->get();
3189 $search_subject = array('{#Cluster Name}');
3190 $replace_subject_name = array($dataArray['reporting_manager_name']);
3191
3192 $search_email_body = array('{#Employee Name}','{#No of Days}','{#Start Date}','{#End Date}','{#Status}','{#Cluster Name}');
3193 $replace_email_body = array($dataArray['employee_name'],$dataArray['no_of_days'],$dataArray['start_date'],$dataArray['end_date'],$dataArray['status'],$dataArray['reporting_manager_name']);
3194
3195 foreach ($have_template as $have_template) {
3196 $role = explode(',', $have_template['role']);
3197 $to_send_employee_ids = explode(',', $have_template['user']);
3198 $template_email_subject = nl2br(str_replace($search_subject, $replace_subject_name, $have_template['template_email_subject']));
3199 $template_email_body = nl2br(str_replace($search_email_body, $replace_email_body, $have_template['template_email_body']));
3200 $template_notification = nl2br(str_replace($search_email_body, $replace_email_body, $have_template['template_notification']));
3201 if ($template_email_subject && $template_email_body ) {
3202 $params = [
3203 "to" => $allEmailArray,
3204 "from" => ['do-not-reply@indianic.com', $_from_user_name],
3205 ];
3206
3207 if(count($emp_ids) > 0){
3208 foreach ($emp_ids as $id)
3209 {
3210 DB::table('gbl_notifications')->insert(
3211 [
3212 'from_employee_id'=> $dataArray['employee_id'],
3213 'from_employee_name'=>$dataArray['employee_name'],
3214 'to_employee_id'=>$id,
3215 'message'=>$template_notification,
3216 'module_method'=>$have_template['module_method'],
3217 'is_read'=>0
3218 ]
3219 );
3220 }
3221 }
3222 // dd($params, $template_email_subject, $template_email_body);
3223 $res = $this->leavepolicy->send_mail($params, $template_email_subject, $template_email_body);
3224 }
3225 }
3226 }catch (JWTException $e) {
3227 return ResponseManager::getError([], config('constants.StatusCode.BadRequest'), $e->getMessage(), config('constants.Boolean.False'));
3228 }
3229 }
3230
3231 public function flexiHourActionByTl(Request $request) {
3232 $emp_id = Auth::user()->employee_id;
3233 $validate = $this->getValidationFactory()->make($request->all(), (new FlexiHourActionRequest())->rules($request->all()), (new FlexiHourActionRequest())->message($request->all()), []);
3234 if ($validate->fails()) {
3235 return ResponseManager::getError([], config('constants.StatusCode.Unprocessable'), $validate->errors(), config('constants.Boolean.False'));
3236 } else {
3237 $response = $this->employees->flexi_action_by_tl($request->all(), $emp_id);
3238 $empLoggedId = Auth::user();
3239 $flexihours_Details = FlexiHours::findOrFail($request->get('flexi_id'));
3240 $reporting_manager_Email = Employees::where('employee_id',$empLoggedId['reporting_manager_id'])->first();
3241 $datetime1 =Carbon::createFromFormat("Y-m-d", $flexihours_Details['from_date']);
3242 $datetime2 = Carbon::createFromFormat("Y-m-d", $flexihours_Details['to_date']);
3243 $countOfdays = $datetime1->diffInDays($datetime2);
3244
3245
3246 $data = [
3247 'employee_id' => $empLoggedId->employee_id,
3248 'employee_name' => $this->employeeModel->removed_Middle_Name($empLoggedId['name']),
3249 'employee_email' => $empLoggedId['email'],
3250 'reporting_manager_id' => $empLoggedId['reporting_manager_id'],
3251 'reporting_manager_name'=>$this->employeeModel->removed_Middle_Name($reporting_manager_Email['name']),
3252 'no_of_days' => $countOfdays === 0 ? 1 : $countOfdays,
3253 'start_date' => $flexihours_Details['from_date'],
3254 'end_date' => $flexihours_Details['to_date'],
3255 'status'=>$request->get('action')
3256 ];
3257 $this->sendApproveFlexiHours($data);
3258 return $response;
3259 }
3260 }
3261
3262 public function sendApproveFlexiHours($dataArray){
3263 try{
3264 $allEmailArray = [];
3265 $emp_ids = [];
3266 $employee_ids = array();
3267
3268 $obj_user = $this->mail->user_info();
3269 $_from_user_name = $obj_user['name'];
3270
3271 // $reporting_manager_Email = Employees::where('employee_id',$dataArray['reporting_manager_id'] )->first();
3272 // array_push($allEmailArray,$reporting_manager_Email->email);
3273
3274 // Add employee email
3275 array_push($allEmailArray,$dataArray['employee_email']);
3276
3277
3278 // PM email id is avilable && If project manager found then bind with clusterHead or reportingmanager email in array.
3279 $get_pm_email = $this->get_ProjectManeger_Email($dataArray);
3280 if($get_pm_email['status'] === true){
3281 foreach($get_pm_email['data'][0] as $email){
3282 array_push($allEmailArray,$email);
3283 }
3284 }
3285
3286 // Get empId based on employeeEmail
3287 if($allEmailArray){
3288 foreach($allEmailArray as $email){
3289 $emp_id = Employees::where('email',$email)->first();
3290 array_push($emp_ids,$emp_id->employee_id);
3291 }
3292 }
3293
3294 $flexihoursStatus;
3295 if($dataArray['status'] === 'Approved'){
3296 $flexihoursStatus = 'Flexi Hours Approved';
3297 }else if($dataArray['status'] === 'Reject'){
3298 $flexihoursStatus = 'Flexi Hours Reject';
3299 }
3300
3301 //Get Template
3302 $have_template = Templates::where('title', $flexihoursStatus)->get();
3303 $search_subject = array('{#Cluster Name}');
3304 $replace_subject_name = array($dataArray['reporting_manager_name']);
3305
3306 $search_email_body = array('{#Employee Name}','{#No of Days}','{#Start Date}','{#End Date}','{#Status}','{#Cluster Name}');
3307 $replace_email_body = array($dataArray['employee_name'],$dataArray['no_of_days'],$dataArray['start_date'],$dataArray['end_date'],$dataArray['status'],$dataArray['reporting_manager_name']);
3308
3309 foreach ($have_template as $have_template) {
3310 $role = explode(',', $have_template['role']);
3311 $to_send_employee_ids = explode(',', $have_template['user']);
3312 $template_email_subject = nl2br(str_replace($search_subject, $replace_subject_name, $have_template['template_email_subject']));
3313 $template_email_body = nl2br(str_replace($search_email_body, $replace_email_body, $have_template['template_email_body']));
3314 $template_notification = nl2br(str_replace($search_email_body, $replace_email_body, $have_template['template_notification']));
3315
3316 if ($template_email_subject && $template_email_body ) {
3317 $params = [
3318 "to" => $allEmailArray,
3319 "from" => ['do-not-reply@indianic.com', $_from_user_name],
3320 ];
3321
3322 if(count($emp_ids) > 0){
3323 foreach ($emp_ids as $id)
3324 {
3325 DB::table('gbl_notifications')->insert(
3326 [
3327 'from_employee_id'=> $dataArray['employee_id'],
3328 'from_employee_name'=>$dataArray['employee_name'],
3329 'to_employee_id'=>$id,
3330 'message'=>$template_notification,
3331 'module_method'=>$have_template['module_method'],
3332 'is_read'=>0
3333 ]
3334 );
3335 }
3336 }
3337 $res = $this->leavepolicy->send_mail($params, $template_email_subject, $template_email_body);
3338 }
3339 }
3340 }catch (JWTException $e) {
3341 return ResponseManager::getError([], config('constants.StatusCode.BadRequest'), $e->getMessage(), config('constants.Boolean.False'));
3342 }
3343 }
3344
3345 /**LmsCountryCallingCode
3346 * @return array
3347 */
3348 public function get_my_timesheet_snapshot() {
3349 $obj_user = $this->employees->user_info();
3350 $employee_id = (isset($_REQUEST['employee_id']) && $_REQUEST['employee_id'] != null) ? $_REQUEST['employee_id'] : $obj_user['employee_id'];
3351 $req_month = (isset($_REQUEST['month_year']) && $_REQUEST['month_year'] != null) ? $_REQUEST['month_year'] : date('M Y');
3352
3353 $production_summary = array();
3354 $req_start_date = date('Y-m-01', strtotime($req_month));
3355 $req_end_date = date('Y-m-t', strtotime($req_start_date));
3356
3357 // make holiday array
3358 $holiday_date = Holidays::whereBetween('date', [$req_start_date, $req_end_date])->get();
3359 $_holiday_list = array();
3360 if (!empty($holiday_date)) {
3361 foreach ($holiday_date as $holiday_date_val) {
3362 $_holiday_list[] = $holiday_date_val['date'];
3363 }
3364 }
3365
3366 $_format = 'Y-m-d';
3367 $start_date = strtotime($req_start_date);
3368 $end_date = strtotime($req_end_date);
3369
3370 if ($req_month == date('M Y')) {
3371 $working_days = $this->employees->get_working_day($req_start_date, date('Y-m-d'));
3372 $end_date = strtotime(date('Y-m-d'));
3373 } else {
3374 $working_days = $this->employees->get_working_day($req_start_date, $req_end_date);
3375 }
3376 $total_employee_working_days = count($working_days);
3377 $monthly_total_taken_leaves = 0;
3378 $_dates_array = array();
3379 while ($start_date <= $end_date) {
3380
3381 $times_projects = array();
3382
3383 $for_date = date("Y-m-d", $start_date);
3384 $timesheets = ProjectTasks::select('pro_task_time.billable_hours', 'pro_task_time.project_id', 'pro_task_time.description')
3385 ->leftJoin('pro_task_time', 'pro_task.task_id', '=', 'pro_task_time.task_id')
3386 ->leftJoin('pro_projects', 'pro_task.project_id', '=', 'pro_projects.project_id')
3387 ->leftJoin('pro_projects_modules', 'pro_task.module_id', '=', 'pro_projects_modules.id')
3388 ->leftJoin('gbl_employees', 'pro_task.employee_id', '=', 'gbl_employees.employee_id')
3389 ->where('pro_task_time.employee_id', $employee_id)
3390 ->where('pro_task_time.date', $for_date)
3391 ->orderBy('pro_task_time.task_id', 'asc')
3392 ->get();
3393
3394 // print_r($timesheets);
3395
3396 $addition_timesheets = ProAdditionalWork::select('project_id', 'task_title', 'efforts')
3397 ->leftJoin('gbl_employees', 'pro_additional_work.employee_id', '=', 'gbl_employees.employee_id')
3398 ->where('pro_additional_work.employee_id', $employee_id)
3399 ->where('pro_additional_work.timesheet_date', $for_date)
3400 ->where('pro_additional_work.status', 'Pending')
3401 ->get();
3402
3403 $total_efforts = 0;
3404 foreach ($addition_timesheets as $times) {
3405 $total_efforts = $total_efforts + $times->efforts;
3406
3407 if ($times['project_id'] == 0) {
3408 $tmp_pro_details = array();
3409 $tmp_pro_details['project_id'] = "0";
3410 $tmp_pro_details['project_name'] = "NON-PROJECT";
3411 $tmp_pro_details['task_title'] = $times->task_title;
3412 $tmp_pro_details['hours'] = $times->efforts;
3413 $times_projects[] = $tmp_pro_details;
3414 } else {
3415 $project_records = ProjectsData::where('project_id', '=', $times['project_id'])->first();
3416 $tmp_pro_details = array();
3417 $tmp_pro_details['project_id'] = ($project_records['project_id'] ? $project_records['project_id'] : "");
3418 $tmp_pro_details['project_name'] = ($project_records['project_name'] ? $project_records['project_name'] : "");
3419 $tmp_pro_details['task_title'] = $times->task_title;
3420 $tmp_pro_details['hours'] = $times->efforts;
3421 $times_projects[] = $tmp_pro_details;
3422 }
3423 }
3424
3425 foreach ($timesheets as $times) {
3426 $total_efforts = $total_efforts + $times->billable_hours;
3427
3428 if ($times['project_id'] == 0) {
3429 $tmp_pro_details = array();
3430 $tmp_pro_details['project_id'] = "0";
3431 $tmp_pro_details['project_name'] = "NON-PROJECT";
3432 $tmp_pro_details['task_title'] = $times->description;
3433 $tmp_pro_details['hours'] = $times->billable_hours;
3434 $times_projects[] = $tmp_pro_details;
3435 } else {
3436 $project_records = ProjectsData::where('project_id', '=', $times['project_id'])->first();
3437 $tmp_pro_details = array();
3438 $tmp_pro_details['project_id'] = ($project_records['project_id'] ? $project_records['project_id'] : "");
3439 $tmp_pro_details['project_name'] = ($project_records['project_name'] ? $project_records['project_name'] : "");
3440 $tmp_pro_details['task_title'] = $times->description;
3441 $tmp_pro_details['hours'] = $times->billable_hours;
3442 $times_projects[] = $tmp_pro_details;
3443 }
3444 }
3445
3446 // get iodata from employee id and date
3447 $live_data = $this->get_employee_iodata_from_date(date('Y-m-d', $start_date), $employee_id);
3448 if ($live_data['io_original_entries'][0]['IOStatus'] == "IO Entry not exist.") {
3449 $entries_exist = false;
3450 } else {
3451 $entries_exist = true;
3452 }
3453
3454 if (@$live_data["leave"] && @$live_data['leave'] == "Full Day") {
3455 $monthly_total_taken_leaves += 1;
3456 $total_employee_working_days -= 1;
3457 } else if (@$live_data["leave_type"] && @$live_data["leave_type"] == "First Half") {
3458 $monthly_total_taken_leaves += 1;
3459 $total_employee_working_days -= 1;
3460 } else if (@$live_data["leave_type"] && @$live_data["leave_type"] == "Second Half") {
3461 $monthly_total_taken_leaves += 1;
3462 $total_employee_working_days -= 1;
3463 }
3464
3465 // getting segment
3466 $get_leaves = Leaves::where(['user_id' => $employee_id])->whereRaw('? between date_from and date_to', date('Y-m-d', $start_date))->get();
3467 $_temp = array();
3468 $_temp['day'] = ResponseManager::_date($start_date);
3469 $_segment = "";
3470 if ($start_date == date('Y-m-d')) {
3471 $_segment = "Current";
3472 } else if (in_array(date('Y-m-d', $start_date), $_holiday_list)) {
3473 $_segment = "Holiday";
3474 } else if (isset($get_leaves[0]['id']) && $get_leaves[0]['id'] != 0) {
3475 $_segment = "Leave";
3476 } else if (in_array(date('Y-m-d', $start_date), $working_days)) {
3477 $_segment = "Production";
3478 } else {
3479 $_segment = "Weekend";
3480 }
3481
3482 $deficit = (($live_data['actual_hours']['h'] * 60) + $live_data['actual_hours']['i']) - (9 * 60);
3483 $deficit_in_min = ($live_data['actual_hours']['h'] * 60) + $live_data['actual_hours']['i'];
3484
3485 if (date('Y-m-d',$start_date)>date('Y-m-d')) {
3486 $final_diff_type = "";
3487 } else {
3488 if ($deficit_in_min > 540) {
3489 $final_diff_type = "up";
3490 } else {
3491 $final_diff_type = "down";
3492 }
3493 }
3494
3495 $get_hours = gmdate("H:i:s", ltrim($deficit * 60, '-'));
3496 $_hours = explode(':', $get_hours);
3497
3498 $_temp['entries_exist'] = $entries_exist;
3499 $_temp['day_segment'] = $_segment;
3500 if ($_segment == "Production") {
3501 $_temp['actual_total_hrs'] = $live_data['total_hrs']['h'] . "." . $live_data['total_hrs']['i'];
3502 $_temp['deficit_hours'] = @$_hours[0] . "." . @$_hours[1];
3503 $_temp['deficit_flag'] = $final_diff_type;
3504 $_temp['deficit_hours_string'] = @$_hours[0] . 'h ' . @$_hours[1] . 'm';
3505 $total_efforts_hours = explode('.', $total_efforts);
3506 $_temp['total_timesheet_hours'] = $total_efforts;
3507 $_temp['total_timesheet_flag'] = ($total_efforts_hours[0] < 9) ? true : false;
3508 // $_temp['projects'] = array('0' => array("project_id" => "5450", "project_name" => "ERP Version", "task_title" => "thsis just test", "hours" => "5h 30m"), '1' => array("project_id" => "5450", "project_name" => "ERP Version", "task_title" => "thsis just test", "hours" => "5h 30m"));
3509 $_temp['projects'] = $times_projects;
3510 } else {
3511 $_temp['actual_total_hrs'] = 0.0;
3512 $_temp['deficit_hours'] = 0.0;
3513 $_temp['deficit_flag'] = "";
3514 $_temp['deficit_hours_string'] = 0.0;
3515 $_temp['total_timesheet_hours'] = 0.0;
3516 $_temp['total_timesheet_flag'] = "";
3517 $_temp['projects'] = array();
3518 }
3519 $_dates_array[] = $_temp;
3520 $start_date = strtotime("+1 day", $start_date);
3521 }
3522 rsort($_dates_array);
3523 $production_summary['dates'] = $_dates_array;
3524 return ResponseManager::getResult($production_summary, config('constants.StatusCode.Ok'), 'Get my day wise production summary for chart of selected.', true);
3525 }
3526
3527 /**
3528 * @return array
3529 */
3530 public function get_my_timesheet_breakdown() {
3531 $obj_user = $this->employees->user_info();
3532 $employee_id = (isset($_REQUEST['employee_id']) && $_REQUEST['employee_id'] != null) ? $_REQUEST['employee_id'] : $obj_user['employee_id'];
3533 $req_month = (isset($_REQUEST['month_year']) && $_REQUEST['month_year'] != null) ? $_REQUEST['month_year'] : date('M Y');
3534
3535 $production_summary = array();
3536 $summary = array();
3537
3538 $req_start_date = date('Y-m-01', strtotime($req_month));
3539 $records = EmployeesWorkTypeData::where('year_month', '=', date("Y-m", strtotime($req_start_date)))
3540 ->where('employee_id', '=', (int)$employee_id)
3541 ->get();
3542 $total_hours = 0;
3543 foreach ($records as $type){
3544 $summary[$type['work_type']] = (int)$type['total_timesheet_hours'];
3545 $total_hours += (int)$type['total_timesheet_hours'];
3546 }
3547 $production_summary['label'] = "Breakdown - ".date("F")." ".date('Y');
3548 $production_summary['summary'] = $summary;
3549 $production_summary['total_hours_string'] = $total_hours." Hours";
3550 $production_summary['total_hours'] = $total_hours;
3551
3552 return ResponseManager::getResult($production_summary, config('constants.StatusCode.Ok'), 'Get my timesheet breakdown summary.', true);
3553 }
3554
3555 /**
3556 * @return array
3557 */
3558 public function get_my_timesheet_top_projects() {
3559 $obj_user = $this->employees->user_info();
3560 $employee_id = (isset($_REQUEST['employee_id']) && $_REQUEST['employee_id'] != null) ? $_REQUEST['employee_id'] : $obj_user['employee_id'];
3561 $final_array = array();
3562 $for_month_array = array();
3563
3564 foreach (array('30' => 0, '60' => 1, '90' => 2) as $key => $month) {
3565 $for_month = date('Y-m', strtotime("-{$month} Month", time()));
3566 $for_month_array[] = $for_month;
3567 $employee_records = EmployeesProjectsData::where('employee_id', '=', (int) $employee_id)
3568 ->wherein('year_month', $for_month_array)
3569 ->groupby('project_name')
3570 ->get();
3571
3572 $production_summary = array();
3573 $index = 0;
3574 foreach ($employee_records as $records) {
3575
3576 $employee_records = EmployeesProjectsData::where('employee_id', '=', (int) $employee_id)
3577 ->wherein('year_month', $for_month_array)
3578 ->where('project_name', $records['project_name'])
3579 ->get();
3580
3581 $total_efforts = 0.0;
3582 foreach ($employee_records as $records) {
3583 $total_efforts += $records['total_timesheet_hours'];
3584 }
3585
3586 $_hours = explode('.', $total_efforts);
3587 $hours = (@$_hours[0]) ? @$_hours[0] : 0;
3588 $minutes = (@$_hours[1]) ? @$_hours[1] : 0;
3589 $_final_hours = $hours . "." . $minutes;
3590 $_final_hours_string = $hours . "h " . $minutes . "m";
3591
3592 $production_summary[$index]['project_id'] = $records['project_id'];
3593 $production_summary[$index]['project_name'] = $records['project_name'];
3594 $production_summary[$index]['total_hours'] = $_final_hours;
3595 $production_summary[$index]['total_hours_string'] = $_final_hours_string;
3596 $production_summary[$index]['month'] = $for_month;
3597 $index++;
3598 }
3599 $final_array[$key] = $production_summary;
3600 }
3601 return ResponseManager::getResult($final_array, config('constants.StatusCode.Ok'), 'Get my timesheet breakdown summary.', true);
3602 }
3603
3604 /**
3605 * @return array
3606 */
3607 public function get_my_timesheet_weekly_summary() {
3608 $obj_user = $this->employees->user_info();
3609 $employee_id = (isset($_REQUEST['employee_id']) && $_REQUEST['employee_id'] != null) ? $_REQUEST['employee_id'] : $obj_user['employee_id'];
3610 $for_week = (isset($_REQUEST['for_week']) && $_REQUEST['for_week'] != null) ? $_REQUEST['for_week'] : 0;
3611 $production_summary = array();
3612
3613 $production_summary['label'] = "Weekly Summary";
3614
3615 foreach (array(0 => "0", 1 => "-1") as $key => $value) {
3616 if ($key == 0) {
3617 $week_name = "current";
3618 } else {
3619 $week_name = "previous";
3620 }
3621 // set current date
3622 $date = date("Y-m-d");
3623 $ts = strtotime("{$value} week", strtotime($date));
3624 $year = date('o', $ts);
3625 $week = date('W', $ts);
3626 $date_array = array();
3627 for ($i = 1; $i <= 7; $i++) {
3628 $ts = strtotime($year . 'W' . $week . $i);
3629 $date_array[] = date("Y-m-d", $ts);
3630 }
3631
3632 $index = 0;
3633 foreach ($date_array as $this_date) {
3634 $details = TimeSheetData::where('employee_id', '=', (int) $employee_id)->where('day_date', '=', date("Y-m-d", strtotime($this_date)))->first();
3635
3636 if(isset($details->day_number)){
3637 $day_number = @$details->day_number;
3638 $day_date = ResponseManager::_date(@$details->day_date);
3639 $day_name = @$details->day_name;
3640 $day_actual_hours = @$details->day_actual_hours;
3641 $day_actual_hours_string = @$details->day_actual_hours_string;
3642 $day_timeheet_hours = @$details->day_timeheet_hours;
3643 $day_timeheet_hours_string = @$details->day_timeheet_hours_string;
3644 } else{
3645 $day_number = (int)date("N", strtotime($this_date));
3646 $day_date = ResponseManager::_date(@$this_date);
3647 $day_name = date("D", strtotime($this_date));
3648 $day_actual_hours = "0";
3649 $day_actual_hours_string = "0h 0m";;
3650 $day_timeheet_hours = "0.0";
3651 $day_timeheet_hours_string = "0h 0m";
3652 }
3653
3654 $production_summary[$week_name][$index]['day_number'] = $day_number;
3655 $production_summary[$week_name][$index]['day_date'] = $day_date;
3656 $production_summary[$week_name][$index]['day_name'] = $day_name;
3657 $production_summary[$week_name][$index]['day_actual_hours'] = $day_actual_hours;
3658 $production_summary[$week_name][$index]['day_actual_hours_string'] = $day_actual_hours_string;
3659 $production_summary[$week_name][$index]['day_timeheet_hours'] = $day_timeheet_hours;
3660 $production_summary[$week_name][$index]['day_timeheet_hours_string'] = $day_timeheet_hours_string;
3661 $index++;
3662 }
3663 }
3664 return ResponseManager::getResult($production_summary, config('constants.StatusCode.Ok'), 'Get my timesheet breakdown summary.', true);
3665 }
3666
3667 public function checkBeforeAndAfterLeave($start_date, $end_date,$flexiHoursRequest=false) {
3668 $data = FALSE;
3669 $get_start_day = date("D", strtotime($start_date));
3670 $get_end_day = date("D", strtotime($end_date));
3671 $query = Leaves::where('user_id', Auth::user()->employee_id);
3672 $leaves = [];
3673 $where = ['Approved', 'Pending', 'System marked leave'];
3674 if ($get_start_day != date("Y-m-d")) {
3675 $leaves = false;
3676
3677 if ($get_start_day == "Mon" && $get_end_day == "Mon") {
3678 $get_start_day1 = date('Y-m-d', strtotime('-3 day', strtotime($start_date)));
3679 $get_end_day1 = date('Y-m-d', strtotime('+1 day', strtotime($end_date)));
3680 $start_leaves = Leaves::where('user_id', Auth::user()->employee_id)->where('date_to', $get_start_day1)
3681 ->whereIn('leave_status', $where)
3682 ->first();
3683 $end_leaves = Leaves::where('user_id', Auth::user()->employee_id)->where('date_from', $get_end_day1)
3684 ->whereIn('leave_status', $where)
3685 ->first();
3686 $data['date'] = $start_leaves ? ($end_leaves ? getcommonDateformat($get_start_day1) . "," . getcommonDateformat($get_end_day1) : getcommonDateformat($get_start_day1)) : ($end_leaves ? getcommonDateformat($get_end_day1) : "");
3687 }
3688 if ($get_start_day != "Mon" && $get_end_day == "Mon") {
3689 $get_start_day1 = date('Y-m-d', strtotime('-1 day', strtotime($start_date)));
3690 $get_end_day1 = date('Y-m-d', strtotime('+1 day', strtotime($end_date)));
3691 $start_leaves = Leaves::where('user_id', Auth::user()->employee_id)->where('date_to', $get_start_day1)
3692 ->whereIn('leave_status', $where)
3693 ->first();
3694
3695 $end_leaves = Leaves::where('user_id', Auth::user()->employee_id)->where('date_from', $get_end_day1)
3696 ->whereIn('leave_status', $where)
3697 ->first();
3698 $data['date'] = $start_leaves ? ($end_leaves ? getcommonDateformat($get_start_day1) . "," . getcommonDateformat($get_end_day1) : getcommonDateformat($get_start_day1)) : ($end_leaves ? getcommonDateformat($get_end_day1) : "");
3699 }
3700 if ($get_start_day == "Mon" && $get_end_day != "Fri") {
3701 $get_start_day1 = date('Y-m-d', strtotime('-3 day', strtotime($start_date)));
3702 $get_end_day1 = date('Y-m-d', strtotime('+1 day', strtotime($end_date)));
3703 $start_leaves = Leaves::where('user_id', Auth::user()->employee_id)->where('date_to', $get_start_day1)
3704 ->whereIn('leave_status', $where)
3705 ->first();
3706 $end_leaves = Leaves::where('user_id', Auth::user()->employee_id)->where('date_from', $get_end_day1)
3707 ->whereIn('leave_status', $where)
3708 ->first();
3709 $data['date'] = $start_leaves ? ($end_leaves ? getcommonDateformat($get_start_day1) . "," . getcommonDateformat($get_end_day1) : getcommonDateformat($get_start_day1)) : ($end_leaves ? getcommonDateformat($get_end_day1) : "");
3710 }
3711 if ($get_start_day == "Fri" && $get_end_day == "Fri") {
3712 $get_start_day1 = date('Y-m-d', strtotime('-1 day', strtotime($start_date)));
3713 $get_end_day1 = date('Y-m-d', strtotime('+3 day', strtotime($end_date)));
3714 $start_leaves = Leaves::where('user_id', Auth::user()->employee_id)->where('date_to', $get_start_day1)
3715 ->whereIn('leave_status', $where)
3716 ->first();
3717 $end_leaves = Leaves::where('user_id', Auth::user()->employee_id)->where('date_from', $get_end_day1)
3718 ->whereIn('leave_status', $where)
3719 ->first();
3720 $data['date'] = $start_leaves ? ($end_leaves ? getcommonDateformat($get_start_day1) . "," . getcommonDateformat($get_end_day1) : getcommonDateformat($get_start_day1)) : ($end_leaves ? getcommonDateformat($get_end_day1) : "");
3721 }
3722
3723 if ($get_start_day != "Mon" && $get_end_day == "Fri") {
3724
3725 $get_start_day1 = date('Y-m-d', strtotime('-1 day', strtotime($start_date)));
3726 $get_end_day1 = date('Y-m-d', strtotime('+3 day', strtotime($end_date)));
3727 $start_leaves = Leaves::where('user_id', Auth::user()->employee_id)->where('date_to', $get_start_day1)
3728 ->whereIn('leave_status', $where)
3729 ->first();
3730 $end_leaves = Leaves::where('user_id', Auth::user()->employee_id)->where('date_from', $get_end_day1)
3731 ->whereIn('leave_status', $where)
3732 ->first();
3733 $data['date'] = $start_leaves ? ($end_leaves ? getcommonDateformat($get_start_day1) . "," . getcommonDateformat($get_end_day1) : getcommonDateformat($get_start_day1)) : ($end_leaves ? getcommonDateformat($get_end_day1) : "");
3734 }
3735 if ($get_start_day != "Fri" && $get_start_day != "Fri" && $get_end_day != "Mon" && $get_start_day != "Mon") {
3736
3737 $get_start_day1 = date('Y-m-d', strtotime('-1 day', strtotime($start_date)));
3738 $get_end_day1 = date('Y-m-d', strtotime('+1 day', strtotime($end_date)));
3739 $start_leaves = Leaves::where('user_id', Auth::user()->employee_id)->where('date_to', $get_start_day1)
3740 ->whereIn('leave_status', $where)
3741 ->first();
3742 $end_leaves = Leaves::where('user_id', Auth::user()->employee_id)->where('date_from', $get_end_day1)
3743 ->whereIn('leave_status', $where)
3744 ->first();
3745 $data['date'] = $start_leaves ? ($end_leaves ? getcommonDateformat($get_start_day1) . "," . getcommonDateformat($get_end_day1) : getcommonDateformat($get_start_day1)) : ($end_leaves ? getcommonDateformat($get_end_day1) : "");
3746 }
3747 }
3748
3749 if($flexiHoursRequest===true){
3750 $data['exists'] = FALSE;
3751 }else{
3752 if ($data['date']) {
3753 $data['exists'] = TRUE;
3754 } else {
3755 $data['exists'] = FALSE;
3756 }
3757 }
3758 return $data;
3759 }
3760
3761 public function getClusterAvgDay() {
3762 $data = $_GET;
3763 $employee_id = Auth::user()->employee_id;
3764 $response = $this->employees->getClusterDeveloperAvgProductionPerDay($employee_id, $data);
3765 return $response;
3766 }
3767
3768 public function leave_rules() {
3769 $type = isset($data->requested_by) && !empty($data->requested_by) ? $data->requested_by : "";
3770 $type = isset($data->requested_by) && !empty($data->requested_by) ? $data->requested_by : "";
3771 if (empty($type)) {
3772 $type = isset($_GET['requested_by']) && (!empty($_GET['requested_by'])) ? $_GET['requested_by'] : "";
3773 }
3774 $data = [];
3775 $leave_balance = Employees::where('employee_id', Auth::user()->employee_id)->select('leave_balance')->first();
3776 $data['leave_rules'] = config('constants.Rules');
3777 $data['leave_balance'] = $leave_balance ? (string)(float)$leave_balance['leave_balance'] : 0.00;
3778 return ResponseManager::getResult($data, config('constants.StatusCode.Ok'), __('message.LeaveSummary.leave_summary'), true, $type);
3779 }
3780
3781 /**
3782 * @return array
3783 */
3784 public function production_day_wise_summary_chart_members()
3785 {
3786 $obj_user = $this->employees->user_info();
3787 $employee_id = (isset($_REQUEST['employee_id']) && $_REQUEST['employee_id'] != null) ? $_REQUEST['employee_id'] : $obj_user['employee_id'];
3788 $req_month = (isset($_REQUEST['month_year']) && $_REQUEST['month_year'] != null) ? $_REQUEST['month_year'] : date('M Y');
3789
3790 $req_start_date = date('Y-m-01', strtotime($req_month));
3791 $req_end_date = date('Y-m-t', strtotime($req_start_date));
3792
3793 $details = Employees::select('employee_id', 'name', 'email', 'status')
3794 ->wherein('status', array('Active', 'Applied for resignation'))
3795 ->where('reporting_manager_id', $employee_id)
3796 ->orderBy('name', 'asc')
3797 ->get();
3798
3799 $members_id_array = array();
3800 foreach ($details as $employee) {
3801 $members_id_array[] = $employee['employee_id'];
3802 }
3803 $start_date = strtotime($req_start_date);
3804 $end_date = strtotime($req_end_date);
3805
3806 $total_members = count($members_id_array);
3807
3808 $_dates_array = array();
3809 while ($start_date <= $end_date) {
3810
3811 $iodatas = TimeSheetData::where("day_date", date('Y-m-d', $start_date))
3812 ->wherein('employee_id', $members_id_array)
3813 ->get();
3814 $total_production_hours = $total_break_hours = 0;
3815 foreach($iodatas as $data){
3816 $total_break_hours += $data['day_break_hours'];
3817 $total_production_hours += $data['day_actual_hours'];
3818 }
3819
3820 $_temp['day_date'] = ResponseManager::_date($start_date,"d M");
3821 $_temp['day_capacity_hours'] = $total_members * 9;
3822 $_temp['day_production_hours'] = round($total_production_hours);
3823 $_temp['day_break_hours'] = round($total_break_hours);
3824
3825 $_dates_array[] = $_temp;
3826 $start_date = strtotime("+1 day", $start_date);
3827 }
3828 $production_summary = $_dates_array;
3829
3830 return ResponseManager::getResult($production_summary, config('constants.StatusCode.Ok'), 'Get team members production summary for chart.', true);
3831 }
3832
3833 /**
3834 * @param null $employee_id
3835 * @return mixed
3836 */
3837 function get_signature($employee_id = null)
3838 {
3839 $obj_user = $this->employees->user_info();
3840 $employee_id = (isset($employee_id) && $employee_id != null) ? $employee_id : $obj_user['employee_id'];
3841 $emp_details = Employees::select('employee_id', 'name', 'email', 'status', 'mobile', 'reporting_manager_id')->where('employee_id', $employee_id)->first();
3842 $designation = Terms::select('gbl_term.name as designation')->leftJoin('gbl_term_relationship', 'gbl_term_relationship.term_id', '=', 'gbl_term.term_id')->where(['gbl_term_relationship.relation_id' => $employee_id, 'taxonomy' => 'designation'])->first()->designation;
3843
3844 $_res_rm = Employees::where('employee_id', $emp_details['reporting_manager_id'])->first();
3845 $_name = explode(' ', $_res_rm->name);
3846 $_final_name = $_name[0] . " " . $_name[2];
3847
3848 $replace = array();
3849 array_push($replace, $emp_details['name']);
3850 array_push($replace, $emp_details['email']);
3851 array_push($replace, $emp_details['mobile']);
3852 // array_push($replace, get_technology($emp_details['technology_id'], 'true'));
3853 array_push($replace, $designation);
3854 array_push($replace, $_final_name);
3855 array_push($replace, $emp_details['emergency_contact']);
3856
3857 $employee_signature_body = Options::where('option_name', 'template_signature_body')->first();
3858 $search = array("{#Employee Name}", "{#Email}", "{#MOBILE}", "{#Technology Stream}", "{#Designation}", "{#Reporting Manager}", "{#Emergency Contact}");
3859 $template_signature_body = str_replace($search, $replace, $employee_signature_body);
3860 return $template_signature_body;
3861 }
3862
3863// function employeeOfficialUpdate($employee_id, Request $request){
3864// $empData = $this->employees->updateEmployeeOfficial($employee_id, $request->all());
3865//
3866// }
3867
3868}