NASER add task functions

This commit is contained in:
mobinesaghi
2026-04-23 14:49:46 +03:30
parent 2419808175
commit 2bcf9f1b7e
47 changed files with 5793 additions and 1029 deletions
+12 -12
View File
@@ -358,18 +358,18 @@ class AdminController extends Controller
}
private function fa2en_numbers($input)
{
if (is_string($input)) {
$fa_numbers = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
$en_numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
return str_replace($fa_numbers, $en_numbers, $input);
} elseif (is_array($input)) {
return array_map([$this, __FUNCTION__], $input);
} else {
return $input;
}
}
// private function fa2en_numbers($input)
// {
// if (is_string($input)) {
// $fa_numbers = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
// $en_numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
// return str_replace($fa_numbers, $en_numbers, $input);
// } elseif (is_array($input)) {
// return array_map([$this, __FUNCTION__], $input);
// } else {
// return $input;
// }
// }
}
+50 -127
View File
@@ -82,8 +82,7 @@ class AttendanceController extends Controller
? 'admin/'
: 'attendance/';
$now = Carbon::now()->format('Y-m-d 00:00:00');
$existed = $Attendance->whereNull('exited_at')->where('entered_at', '>=', $now)->first();
$existed = $Attendance->whereNull('exited_at')->where('entered_at', '>=', now()->format('Y-m-d 00:00:00'))->where('entered_at', '<=', now()->format('Y-m-d 23:59:59'))->first();
$user = User::where('user_name', $_COOKIE['user_identity'])->first();
$until_now = null;
@@ -321,7 +320,7 @@ class AttendanceController extends Controller
$attendance->duration = $duration;
$attendance->save();
send_tel($user->name, $attendance, 'attendance');
$this->send($user->name, $attendance, 'attendance');
return redirect()->back()->with('message', [
'color' => '#3b82f6',
@@ -340,7 +339,7 @@ class AttendanceController extends Controller
$attendance->office_location = ['lat' => $officeLat, 'lng' => $officeLng];
$attendance->save();
send_tel($user->name, $attendance, 'attendance');
$this->send($user->name, $attendance, 'attendance');
return redirect()->back()->with('message', [
'color' => '#22c55e',
@@ -354,15 +353,15 @@ class AttendanceController extends Controller
if (!$user) {
return response()->json(['error' => 'Unauthorized'], 401);
}
$attendance = Attendance::where('user_identity', $user->user_name)
->whereNull('exited_at')
->latest('entered_at')
->where('entered_at', '>=', now()->format('Y-m-d 00:00:00'))->where('entered_at', '<=', now()->format('Y-m-d 23:59:59'))
->first();
$today = Carbon::now()->format('Y-m-d');
$day = Carbon::parse($attendance->entered_at)->format('Y-m-d');
if ($today !== $day || !$attendance) {
if (!$attendance) {
return response()->json([
'status' => 'error',
'color' => '#C30004',
@@ -386,7 +385,7 @@ class AttendanceController extends Controller
'duration' => $durationSeconds
]);
dd(send_tel($user->name, $break, 'break'));
// dd($this->send($user->name, $break, 'break'));
return response()->json([
"break_status" => 'ended',
'duration' => $durationSeconds
@@ -398,7 +397,7 @@ class AttendanceController extends Controller
'break_start' => $now,
]);
dd(send_tel($user->name, $break, 'break'));
// dd($this->send($user->name, $break, 'break'));
$user->update([
'break' => 1
@@ -486,7 +485,7 @@ class AttendanceController extends Controller
$status = 'request';
$d = "ایجاد روز کاری";
send_tel($user->name, $d, $status);
$this->send($user->name, $d, $status);
$user->req_counts += 1;
$user->save();
return redirect('/')->with('message', [
@@ -517,7 +516,7 @@ class AttendanceController extends Controller
$att->save();
$status = 'request';
$d = "تغییر ساعت کاری";
send_tel($user->name, $d, $status);
$this->send($user->name, $d, $status);
$user->req_counts += 1;
$user->save();
return redirect('/')->with('message', [
@@ -564,7 +563,7 @@ class AttendanceController extends Controller
$attendance->save();
$status = 'request';
$d = "حذف روز کاری";
send_tel($user->name, $d, $status);
$this->send($user->name, $d, $status);
$user->req_counts += 1;
$user->save();
return redirect()->back()->with('message', [
@@ -643,122 +642,46 @@ class AttendanceController extends Controller
]);
}
private function fa2en_numbers($input)
{
if (is_string($input)) {
$fa_numbers = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
$en_numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
return str_replace($fa_numbers, $en_numbers, $input);
} elseif (is_array($input)) {
return array_map([$this, __FUNCTION__], $input);
} else {
return $input;
}
}
}
function send_tel($user, $data, $status)
{
if ($status == 'attendance') {
// dd('hi');
$enter = Carbon::parse($data->entered_at)->format('H:i');
$date = Jalalian::fromCarbon(Carbon::parse($data->entered_at))->format('Y/m/d');
$exit = $data->exited_at ? Carbon::parse($data->exited_at)->format('H:i') : null;
// $user = json_decode($user);
$message = "تاریخ: {$date}\n {$user} در ساعت ";
if (!$exit) {
$message .= "{$enter} وارد شد.";
} else {
$message .= "{$exit} خارج شد.";
}
}
if ($status == 'break') {
$date = Jalalian::fromCarbon(Carbon::parse($data->break_start))->format('Y/m/d');
$start = Carbon::parse($data->break_start)->format('H:i');
$end = Carbon::parse($data->break_end)->format('H:i');
if (!$data->break_end)
$message = "تاریخ: {$date}\n {$user} در ساعت {$start} شروع به استراحت کرد.";
else
$message = "تاریخ: {$date}\n {$user} در ساعت {$end} به استراحت پایان داد.";
}
if ($status == 'request') {
$message = "{$user} درخواست {$data} ثبت کرد.";
}
$admins = User::whereIn('is_admin', [1,2])->whereNotNull('chatid')->select('chatid', 'bale', 'user_name')->get();
if ($_COOKIE['user_identity'] !== 'test') {
foreach ($admins as $admin) {
if (!$admin->bale) {continue;}
// dd($admin->chatid);
// Http::get("https://api.wwwapp.ir/telegran_send.php", [
// 'botToken' => "7467099619:AAF2V6yYcbAb8oSIRSCyH5i2GKfdWVO3a7k",
// 'chatId' => $admin->chatid,
// 'message' => $message,
// ]);
if ($admin->bale) {
try {
$response = Http::post('https://tapi.bale.ai/1482838710:sYbLzby0tuLRzHvP4d3LsbcNwg2sjSDLTAU/sendMessage', [
"chat_id" => $admin->bale,
'text' => $message,
]);
}catch (\Exception $e){}
}
Log::create([
'error' => $response->body(),
'user' => "کاربر: $user
ادمین: {$admin->user_name}",
]);
}
}else{
try {
$response = Http::post('https://tapi.bale.ai/1482838710:sYbLzby0tuLRzHvP4d3LsbcNwg2sjSDLTAU/sendMessage', [
"chat_id" => '985309723',
'text' => $message,
]);
}catch (\Exception $e){}
}
// return $message;
}
function auto_break($user_id, $force_method = null)
{
$user = User::where('user_name', $user_id)->first();
if (!$attendances = Attendance::whereNull('exited_at')->latest('entered_at')->where('user_identity', $user_id)->first()) {
throw new UnprocessableEntityHttpException('attendance not found');
}
$break = "start";
if ($AttendanceBreak = AttendanceBreak::where('attendance_id', $attendances->id)->whereNull('break_end')->first()) {
$break = "end";
}
if ($force_method) {
$break = $force_method;
}
if ($break == "end") {
$start = Carbon::parse($break->break_start)->format('H:i:s');
$end = Carbon::parse($break->break_end)->format('H:i:s');
$status = 'ended';
$att = new Attendance();
$break->break_end = now();
$break->duration = $att->duration($start, $end);
$break->save();
$time = Carbon::parse($break->break_end)->format('H:i:s');
sendbot($user->chatid, "پایان استراحت: $time");
} elseif ($break == "start" and empty($AttendanceBreak)) {
$status = 'started';
$break = new AttendanceBreak();
$break->attendance_id = $attendances->id;
$break->break_start = now();
$break->save();
$time = Carbon::parse($break->break_start)->format('H:i:s');
sendbot($user->chatid, "شروع استراحت: $time");
}
return $status ?? $break;
}
//function auto_break($user_id, $force_method = null)
//{
// $user = User::where('user_name', $user_id)->first();
// if (!$attendances = Attendance::whereNull('exited_at')->latest('entered_at')->where('user_identity', $user_id)->first()) {
// throw new UnprocessableEntityHttpException('attendance not found');
// }
// $break = "start";
// if ($AttendanceBreak = AttendanceBreak::where('attendance_id', $attendances->id)->whereNull('break_end')->first()) {
// $break = "end";
//
// }
// if ($force_method) {
// $break = $force_method;
// }
//
// if ($break == "end") {
// $start = Carbon::parse($break->break_start)->format('H:i:s');
// $end = Carbon::parse($break->break_end)->format('H:i:s');
// $status = 'ended';
// $att = new Attendance();
// $break->break_end = now();
// $break->duration = $att->duration($start, $end);
// $break->save();
// $time = Carbon::parse($break->break_end)->format('H:i:s');
// sendbot($user->chatid, "پایان استراحت: $time");
//
// } elseif ($break == "start" and empty($AttendanceBreak)) {
// $status = 'started';
// $break = new AttendanceBreak();
// $break->attendance_id = $attendances->id;
// $break->break_start = now();
// $break->save();
// $time = Carbon::parse($break->break_start)->format('H:i:s');
//
// sendbot($user->chatid, "شروع استراحت: $time");
//
// }
// return $status ?? $break;
//}
+118 -2
View File
@@ -1,11 +1,127 @@
<?php
namespace App\Http\Controllers;
use App\Models\Log;
use App\Models\Setting;
abstract class Controller
use App\Models\User;
use Illuminate\Support\Facades\Http;
abstract class Controller
{
public static function Config($name)
{
return Setting::where('key',$name)->first()->value ?? false;
}
}
public function fa2en_numbers($input)
{
if (is_string($input)) {
$fa_numbers = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
$en_numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
return str_replace($fa_numbers, $en_numbers, $input);
} elseif (is_array($input)) {
return array_map([$this, __FUNCTION__], $input);
} else {
return $input;
}
}
public function send($user, $data, $status)
{
if ($status == 'attendance') {
// dd('hi');
$enter = Carbon::parse($data->entered_at)->format('H:i');
$date = Jalalian::fromCarbon(Carbon::parse($data->entered_at))->format('Y/m/d');
$exit = $data->exited_at ? Carbon::parse($data->exited_at)->format('H:i') : null;
// $user = json_decode($user);
$message = "تاریخ: {$date}\n {$user} در ساعت ";
if (!$exit) {
$message .= "{$enter} وارد شد.";
} else {
$message .= "{$exit} خارج شد.";
}
}
if ($status == 'break') {
$date = Jalalian::fromCarbon(Carbon::parse($data->break_start))->format('Y/m/d');
$start = Carbon::parse($data->break_start)->format('H:i');
$end = Carbon::parse($data->break_end)->format('H:i');
if (!$data->break_end)
$message = "تاریخ: {$date}\n {$user} در ساعت {$start} شروع به استراحت کرد.";
else
$message = "تاریخ: {$date}\n {$user} در ساعت {$end} به استراحت پایان داد.";
}
if ($status == 'request') {
$message = "{$user} درخواست {$data} ثبت کرد.";
}
$admins = User::whereIn('is_admin', [1,2])->whereNotNull('chatid')->select('chatid', 'bale', 'user_name')->get();
if ($_COOKIE['user_identity'] !== 'test') {
foreach ($admins as $admin) {
if (!$admin->bale) {continue;}
// dd($admin->chatid);
// Http::get("https://api.wwwapp.ir/telegran_send.php", [
// 'botToken' => "7467099619:AAF2V6yYcbAb8oSIRSCyH5i2GKfdWVO3a7k",
// 'chatId' => $admin->chatid,
// 'message' => $message,
// ]);
if ($admin->bale) {
try {
$response = Http::post('https://tapi.bale.ai/1482838710:sYbLzby0tuLRzHvP4d3LsbcNwg2sjSDLTAU/sendMessage', [
"chat_id" => $admin->bale,
'text' => $message,
]);
}catch (\Exception $e){}
}
Log::create([
'error' => $response->body(),
'user' => "کاربر: $user
ادمین: {$admin->user_name}",
]);
}
}else{
try {
$response = Http::post('https://tapi.bale.ai/1482838710:sYbLzby0tuLRzHvP4d3LsbcNwg2sjSDLTAU/sendMessage', [
"chat_id" => '985309723',
'text' => $message,
]);
}catch (\Exception $e){}
}
// return $message;
}
public function send_admins($message)
{
$admins = User::whereNotNull('is_admin')->whereNotNull('bale')->select('bale')->get();
foreach ($admins as $admin) {
try{
Http::/*withOptions([
'curl' => [
CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
CURLOPT_TCP_FASTOPEN => 1,
]
])->*/withoutVerifying()->post('https://tapi.bale.ai/1482838710:sYbLzby0tuLRzHvP4d3LsbcNwg2sjSDLTAU/sendMessage', [
"chat_id" => $admin->bale,
'text' => $message,
]);
}catch (\Exception $e){}
}
}
public function send_level1_admins($message)
{
$admins = User::where('is_admin', 1)->whereNotNull('bale')->select('bale')->get();
foreach ($admins as $admin) {
try {
Http::withoutVerifying()->post('https://tapi.bale.ai/1482838710:sYbLzby0tuLRzHvP4d3LsbcNwg2sjSDLTAU/sendMessage', [
"chat_id" => $admin->bale,
'text' => $message,
]);
} catch (\Exception $e) {
}
}
}
}
+480 -207
View File
@@ -2,6 +2,11 @@
namespace App\Http\Controllers;
use App\Models\App;
use App\Models\TaskComment;
use App\Models\TaskDuration;
use http\Env\Response;
use http\Message;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Request;
use App\Models\Pivot_Tasks;
@@ -10,262 +15,530 @@ use GuzzleHttp\Client;
use App\Models\Tasks;
use App\Models\User;
use Carbon\Carbon;
use Morilog\Jalali\Jalalian;
use Carbon\CarbonInterval;
class TaskController extends Controller
{
private function taskChangeMessage(Tasks $task, array $before, array $after, ?User $actor): string
{
$lines = [];
$actorName = $actor?->name ?? 'نامشخص';
$titleBefore = (string)($before['title'] ?? '');
$titleAfter = (string)($after['title'] ?? $task->title ?? '');
$lines[] = "ویرایش تسک: «{$titleAfter}»";
$lines[] = "توسط: {$actorName}";
$appBefore = $before['app'] ?? null;
$appAfter = $after['app'] ?? $task->app ?? null;
$a1 = App::find($appBefore)?->name_fa ?? ($appBefore ?? '-');
$a2 = App::find($appAfter)?->name_fa ?? ($appAfter ?? '-');
$lines[] = ($appBefore != $appAfter) ? "اپ: {$a1} ← {$a2}" : "اپ: {$a2}";
$lines[] = (($before['title'] ?? null) !== ($after['title'] ?? null))
? "عنوان: {$titleBefore} ← {$titleAfter}"
: "عنوان: {$titleAfter}";
$priorityFa = [
'none' => 'ندارد',
'low' => 'کم',
'medium' => 'عادی',
'high' => 'زیاد',
'urgent' => 'فوری',
];
$p1 = $before['priority'] ?? null;
$p2 = $after['priority'] ?? null;
$lines[] = ($p1 !== $p2)
? "اولویت: " . ($priorityFa[$p1] ?? ($p1 ?? '-')) . " ← " . ($priorityFa[$p2] ?? ($p2 ?? '-'))
: "اولویت: " . ($priorityFa[$p2] ?? ($p2 ?? '-'));
$stateFa = [
1 => 'انباشته',
2 => 'برای انجام',
3 => 'درحال انجام',
4 => 'پایان یافته',
];
$s1 = (int)($before['state'] ?? 0);
$s2 = (int)($after['state'] ?? 0);
$lines[] = ($s1 !== $s2 && $s2)
? "وضعیت: " . ($stateFa[$s1] ?? ($before['state'] ?? '-')) . " ← " . ($stateFa[$s2] ?? ($after['state'] ?? '-'))
: "وضعیت: " . ($stateFa[$s2] ?? ($after['state'] ?? '-'));
$d1 = $before['start_date'] ?? null;
$d2 = $after['start_date'] ?? null;
$lines[] = ($d1 !== $d2)
? "شروع: " . ($d1 ?: '-') . " ← " . ($d2 ?: '-')
: "شروع: " . ($d2 ?: '-');
$t1 = $before['target_date'] ?? null;
$t2 = $after['target_date'] ?? null;
$lines[] = ($t1 !== $t2)
? "ددلاین: " . ($t1 ?: '-') . " ← " . ($t2 ?: '-')
: "ددلاین: " . ($t2 ?: '-');
$desc1 = trim((string)($before['description'] ?? ''));
$desc2 = trim((string)($after['description'] ?? ''));
$lines[] = ($desc1 !== $desc2)
? "توضیحات: " . (!empty($desc2) ? 'تغییر کرد' : 'پاک شد')
: "توضیحات: بدون تغییر";
$aBefore = $before['assignees'] ?? null;
$aAfter = $after['assignees'] ?? null;
$arr1 = is_string($aBefore) ? json_decode($aBefore, true) : $aBefore;
$arr2 = is_string($aAfter) ? json_decode($aAfter, true) : $aAfter;
$arr1 = is_array($arr1) ? array_map('strval', $arr1) : [];
$arr2 = is_array($arr2) ? array_map('strval', $arr2) : [];
sort($arr1);
sort($arr2);
$names1 = User::whereIn('id', $arr1)->pluck('name')->all();
$names2 = User::whereIn('id', $arr2)->pluck('name')->all();
$lines[] = ($arr1 !== $arr2)
? "مسئولین: " . (!empty($names1) ? implode('، ', $names1) : '-') . " ← " . (!empty($names2) ? implode('، ', $names2) : '-')
: "مسئولین: " . (!empty($names2) ? implode('، ', $names2) : '-');
return implode("\n", $lines);
}
// public function tasks()
// {
// $user = User::where('user_name', $_COOKIE['user_identity'])->first();
// $tasks = $user->tasks;
// $users = User::get();
//
// $state_order = [
// "c73c2044-ea14-42cb-b08d-cecf3d1fdfb5",
// "a9ce312f-cfca-491e-8e3d-1975aa6ebc10",
// "dea1fb57-a281-4fe7-8f3e-ee5567637e35",
// "770fbe42-99f6-41db-9b9e-773d9cced1a5",
// "b0e464e1-34eb-41ea-b2f7-3ef7483bc9f0",
// "d61d14a3-72f7-4f44-894b-efe8b2a75be1",
// ];
//
// $work_item = $tasks->whereNull('parent')->sortBy(fn($t) => array_search($t->state, $state_order));
// $sub_work_items = $tasks->whereNotNull('parent')->sortBy(fn($t) => array_search($t->state, $state_order));
//
// foreach ($work_item as $w) {
// foreach ($sub_work_items as $t) {
// foreach ($users as $u) {
// if ($t->created_by == $u->plain_id)
// $t->created_by = $u->name;
// if ($w->created_by == $u->plain_id)
// $w->created_by = $u->name;
// }
// }
// }
//
// return view('tasks.tasks', compact('tasks', 'work_item', 'sub_work_items'));
// }
public function tasks()
{
$user = User::where('user_name', $_COOKIE['user_identity'])->first();
$tasks = $user->tasks;
$users = User::get();
if ($user) {
if ($user->is_admin == 1) {
$tasks = Tasks::with(['duration', 'comments.user'])
->orderBy('target_date', 'desc')
->get();
// dd($tasks);
foreach ($tasks as $task) {
$totalSeconds = 0;
foreach ($task->duration as $item) {
if ($item->duration !== null) {
$totalSeconds += CarbonInterval::createFromFormat('H:i:s', $item->duration)->totalSeconds;
}
}
$state_order = [
"c73c2044-ea14-42cb-b08d-cecf3d1fdfb5",
"a9ce312f-cfca-491e-8e3d-1975aa6ebc10",
"dea1fb57-a281-4fe7-8f3e-ee5567637e35",
"770fbe42-99f6-41db-9b9e-773d9cced1a5",
"b0e464e1-34eb-41ea-b2f7-3ef7483bc9f0",
"d61d14a3-72f7-4f44-894b-efe8b2a75be1",
];
$task->totalDuration = CarbonInterval::seconds($totalSeconds)->cascade()->format('%H:%I:%S');
$active_task = TaskDuration::where('task_id', $task->id)->orderBy('start', 'desc')->first();
$task->active = !empty($active_task) && $active_task->end == null;
}
} else {
$tasks = Tasks::with(['duration', 'comments.user'])->where('created_by', $user->id)
->orWhereJsonContains('assignees', (string)$user->id)
->orderBy('target_date', 'desc')
->get();
// dd($tasks);
foreach ($tasks as $task) {
$totalSeconds = 0;
foreach ($task->duration as $item) {
if ($user->id == $item->user_id && $item->duration !== null) {
$totalSeconds += CarbonInterval::createFromFormat('H:i:s', $item->duration)->totalSeconds;
}
}
$work_item = $tasks->whereNull('parent')->sortBy(fn($t) => array_search($t->state, $state_order));
$sub_work_items = $tasks->whereNotNull('parent')->sortBy(fn($t) => array_search($t->state, $state_order));
foreach ($work_item as $w) {
foreach ($sub_work_items as $t) {
foreach ($users as $u) {
if ($t->created_by == $u->plain_id)
$t->created_by = $u->name;
if ($w->created_by == $u->plain_id)
$w->created_by = $u->name;
$task->totalDuration = CarbonInterval::seconds($totalSeconds)->cascade()->format('%H:%I:%S');
$active_task = TaskDuration::where('task_id', $task->id)->where('user_id', $user->id)->orderBy('start', 'desc')->first();
$task->active = !empty($active_task) && $active_task->end == null;
}
}
}
return view('tasks.tasks', compact('tasks', 'work_item', 'sub_work_items'));
$count = count($tasks);
// dd((new Tasks())->filterByState($tasks)['backlog'][0], 'count ='.$count);
return view('tasks.tasks', [
'tasks' => (new Tasks())->filterByState($tasks),
'count' => $count,
'user_id' => $user->id,
]);
} else {
return back()->with('message', [
'color' => 'red',
'text' => 'کاربر یافت نشد!'
]);
}
}
public function activeTask(Request $request)
public function showTask($id)
{
// dd($request->all());
// dd($request->uid);
$user = User::where('id', $request->uid)->first();
$p_task = Pivot_Tasks::where('task_id', $request->task_id)
->where('user_id', $user->plain_id)->first();
$task = Tasks::where('task_id', $request->task_id)->first();
if ($p_task) {
// dd('task is set in pivot');
if ($p_task->started_at == null || ($p_task->started_at !== null && $p_task->ended_at !== null)) {
// dd('in if');
$p_task->started_at = now();
$p_task->ended_at = null;
$user->active_task = $task->name;
$p_task->save();
$user->save();
return back()->with('message', [
'color' => 'green',
'text' => 'وظیفه شما شروع شد، موفق باشید.'
]);
} else {
// dd('in elseif');
$task = Tasks::with(['comments.user'])->find($id ?? null);
return view('tasks.create', ['task' => $task]);
$now = now();
$attendance = new Attendance();
$s = Carbon::parse($p_task->started_at)->format('H:i:s');
$e = Carbon::parse($now)->format('H:i:s');
$duration = $p_task->duration;
if ($e > $s) {
$diff = $attendance->duration($s, $e);
if ($duration !== null) {
[$h1, $m1, $s1] = explode(':', $duration);
$durationSeconds = $h1 * 3600 + $m1 * 60 + $s1;
}
[$h2, $m2, $s2] = explode(':', $diff);
$diffSeconds = $h2 * 3600 + $m2 * 60 + $s2;
public function editTask(Request $request)
{
// dd($request->all());
if (!isset($_COOKIE['user_identity'])) {
return back()->with('message', [
'color' => 'red',
'text' => 'ابتدا باید وارد شوید!'
]);
}
$actor = User::where('user_name', $_COOKIE['user_identity'])->first();
$totalSeconds = $durationSeconds + $diffSeconds;
$data = $request->all();
$task = Tasks::find($data['id'] ?? null);
if (!$task) {
return back()->with('message', [
'color' => 'red',
'text' => 'وظیفه یافت نشد!'
]);
}
$hours = floor($totalSeconds / 3600);
$minutes = floor(($totalSeconds % 3600) / 60);
$seconds = $totalSeconds % 60;
$before = $task->toArray();
$duration = sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
} else {
$duration = $diff;
}
$p_task->ended_at = $now;
$p_task->duration = $duration;
$user->active_task = null;
$p_task->save();
$user->save();
return back()->with('message', [
'color' => 'green',
'text' => 'وظیفه شما با موفقیت پایان یافت.'
]);
$data['updated_by'] = $actor?->id;
if (array_key_exists('assignees', $data)) {
$data['assignees'] = !empty($data['assignees']) ? json_encode($data['assignees']) : null;
} else {
unset($data['assignees']);
}
unset($data['_token'], $data['id'], $data['start_date_display'], $data['target_date_display']);
$task->update($data);
$after = $task->toArray();
$title = $task->title;
$message = "تسک «{$title}» برای شما به‌روزرسانی شد.";
$message_admin = $this->taskChangeMessage($task, $before, $after, $actor);
if (!empty($request->assignees)) {
foreach ($request->assignees as $assignee) {
$assigneeUser = User::where('id', $assignee)->first();
if ($assigneeUser && $assigneeUser->bale !== null) {
$this->send_bale($assigneeUser->bale, $message);
}
}
}
// dd($data, $message, $message_admin);
$this->send_level1_admins($message_admin);
return back()->with('message', [
'color' => 'red',
'text' => 'وظیفه یافت نشد✖️'
'color' => 'green',
'text' => $message
]);
// $action = $request->input('action_type');
// $start = $request->input('started_at');
// $end = $request->input('ended_at');
// $duration = $request->input('duration');
//
// if ($action == 'end') {
// $attendance = new Attendance();
// $s = Carbon::parse($start)->format('H:i:s');
// $e = Carbon::parse($end)->format('H:i:s');
// if ($e > $s) {
// $diff = $attendance->duration($s, $e);
// if ($duration !== null) {
// [$h1, $m1, $s1] = explode(':', $duration);
// $durationSeconds = $h1 * 3600 + $m1 * 60 + $s1;
//
// [$h2, $m2, $s2] = explode(':', $diff);
// $diffSeconds = $h2 * 3600 + $m2 * 60 + $s2;
//
// $totalSeconds = $durationSeconds + $diffSeconds;
//
// $hours = floor($totalSeconds / 3600);
// $minutes = floor(($totalSeconds % 3600) / 60);
// $seconds = $totalSeconds % 60;
//
// $duration = sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
// } else {
// $duration = $diff;
// }
// }
// $data = [
// 'started_at' => $start,
// 'ended_at' => $end,
// 'duration' => $duration,
// ];
// } else {
// $data = [
// 'started_at' => $start,
// 'ended_at' => null,
//
// ];
// }
// try {
//
// DB::table('pivot_tasks')->where('id', $request->p_id)->update($data);
//
//
// return "record saved";
// } catch (\Exception $e) {
// return $e->getMessage();
// }
}
public function createTask()
{
$users = User::whereNotNull('plain_id')->get();
$tasks = Tasks::all();
return view('tasks.create');
}
return view('tasks.create', [
'users' => $users,
'tasks' => $tasks,
public function deleteTask($id)
{
Tasks::destroy($id);
return response()->json([
"success" => true,
"message" => "Task deleted successfully.",
"task_id" => 45
]);
}
public function addTask(Request $request){
// dd($request);
$task = new Tasks();
$task->name = $request->input('taskTitle');
$task->created_at = Carbon::now()->format('Y-m-d H:i:s');
$task->save();
return response()->with('message', "تسک اضافه شد");
}
public function storeTask(Request $request)
{
$created_by = User::where('user_name', $_COOKIE['user_identity'])->first()->plain_id;
// dd($request->all());
if (!isset($_COOKIE['user_identity'])) {
return back()->with('message', [
'color' => 'red',
'text' => 'ابتدا باید وارد شوید!'
]);
}
$user = User::where('user_name', $_COOKIE['user_identity'])->first();
Tasks::create([
"name" => $request->name,
"desc" => $request->description_html,
"priority" => $request->priority,
"start_date" => $request->start_date,
"target_date" => $request->target_date,
"state" => $request->state,
"assignees" => $request->assignees,
"parent" => $request->parent,
"estimate_point" => $request->estimate_point,
$data = $request->all();
$data['created_by'] = $user->id;
$data['assignees'] = !empty($data['assignees']) ? json_encode($data['assignees']) : null;
]);
$task = Tasks::create($data);
// $headers = [
// 'x-api-key' => 'plane_api_ec378e977ceb4bd1bbd2332855370645',
// 'Content-Type' => 'application/json'
// ];
//
// $body = json_encode([
// "name" => $name,
// "description_html" => $desc ?: '',
// "priority" => $priority ?: 'none',
// "start_date" => $start_date ?: null,
// "target_date" => $target_date ?: null,
// "estimate_point" => $estimate_point ?: '',
// "state" => $state ?: '',
// "parent" => $parent ?: '',
// "assignees" => $assignees ?: '',
// // "labels" => $labels ?: null,
// // "created_by" => $created_by
// ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
//
// $client = new Client();
//
// $response = $client->post(
// 'https://api.plane.so/api/v1/workspaces/montzar/projects/c1df4085-582f-4b57-b3c6-95b7d4d19007/issues/',
// [
// 'headers' => $headers,
// 'body' => $body,
// ]
// );
//
// $data = json_decode($response->getBody(), true);
$message = "تسک جدیدی با عنوان {$data['title']} برای شما ایجاد شد.";
$deadline = !empty($data['target_date']) ? Jalalian::fromCarbon(Carbon::parse($data['target_date']))->format('Y-m-d') : null;
$app = App::find($data['app']);
$message_admin = "ایجاد تسک: «{$data['title']}»";
$message_admin .= !empty($app) ? "\nاپ {$app->name_fa}" : null;
$message_admin .= !empty($deadline) ? "\nددلاین {$deadline}" : null;
$message_admin .= !empty($data['start_date']) ? "\nتاریخ شروع {$data['start_date']}" : null;
$message_admin .= !empty($data['state_fa']) ? "\nوضعیت: {$data['state_fa']}" : null;
$message_admin .= !empty($data['description']) ? "\nبا توضیحات:\n" . $data['description'] : null;
$message_admin .= !empty($data['assignees']) ? "\nتوسط " . $user->name . " ساخته شد و به" : null;
// update_tasks($data);
if (!empty($data['assignees'])) {
foreach ($request->assignees as $assignee) {
$user = User::where('id', $assignee)->first();
$message_admin .= "\n$user->name";
if ($user && $user->bale !== null) {
$this->send_bale($user->bale, $message);
}
}
$message_admin .= "\nاختصاص یافت.";
} else {
$message_admin .= "\nتوسط " . $user->name . " ساخته شد";
}
// dd($data, $message, $message_admin);
$this->send_level1_admins($message_admin);
return back()->with('message', [
'color' => 'green',
'text' => 'وظیفه با موفقیت ایجاد شد.'
'text' => $message
]);
}
// public function webhookPlane(Request $request)
// {
// $d = $request->all();
//
// // فقط وقتی تغییر state هست
// if (isset($d['event'], $d['action'], $d['data']['name'], $d['data']['state']['name'])) {
// $msg = "Event: {$d['event']}\nAction: {$d['action']}\nName: {$d['data']['name']}\nNew Status: {$d['data']['state']['name']}";
//
// // ارسال به تلگرام
// Http::get("https://api.wwwapp.ir/telegran_send.php", [
// 'botToken' => "7467099619:AAF2V6yYcbAb8oSIRSCyH5i2GKfdWVO3a7k",
// 'chatId' => "-4742642674",
// 'message' => $msg,
// ]);
// }
//
// // اگر خواستی ثبت در دیتابیس هم اضافه کنی
// // DB::table('tst')->insert([
// // 'data' => json_encode($d, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE),
// // ]);
//
// return response()->json(['status' => 'ok'], 200);
// }
public function activeTask(Request $request)
{
// dd($request);
$user = User::where('user_name', $_COOKIE['user_identity'])->first();
$task = Tasks::find($request->task_id);
if (!$task) {
return response()->json([
'action' => 'not_found',
'status' => false
]);
}
$taskDU = TaskDuration::where('user_id', $user->id)
->where('task_id', $request->task_id)
->orderBy('id', 'desc')
->first();
// اگر رکورد باز داریم => پایان
if (!empty($taskDU) && ($taskDU->start !== null && $taskDU->end == null)) {
// dd('in if');
$attendance = new Attendance();
$s = Carbon::parse($taskDU->start)->format('H:i:s');
$e = Carbon::parse(now())->format('H:i:s');
$duration = $taskDU->duration;
if ($e > $s) {
$diff = $attendance->duration($s, $e);
if ($duration !== null) {
[$h1, $m1, $s1] = explode(':', $duration);
$durationSeconds = $h1 * 3600 + $m1 * 60 + $s1;
[$h2, $m2, $s2] = explode(':', $diff);
$diffSeconds = $h2 * 3600 + $m2 * 60 + $s2;
$totalSeconds = $durationSeconds + $diffSeconds;
$hours = floor($totalSeconds / 3600);
$minutes = floor(($totalSeconds % 3600) / 60);
$seconds = $totalSeconds % 60;
$duration = sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
} else {
$duration = $diff;
}
$taskDU->end = now();
$taskDU->duration = $duration;
$user->active_task = null;
$taskDU->save();
$user->save();
$this->send_level1_admins("پایان تسک: «{$task->title}»\nتوسط: {$user->name}\nمدت این نوبت: {$duration}");
return response()->json([
'action' => 'ended',
'status' => true,
'duration' => $duration,
'start' => $taskDU->start,
'end' => $taskDU->end,
]);
} else
return response()->json([
'action' => 'end',
'status' => false
]);
} else {
// شروع => همیشه یک رکورد جدید بساز
$new_task_duration = TaskDuration::create([
'task_id' => $task->id,
'user_id' => $user->id,
'start' => now(),
'end' => null,
]);
$user->active_task = $task->title;
$user->save();
$this->send_level1_admins("شروع تسک: «{$task->title}»\nتوسط: {$user->name}");
return response()->json([
'action' => 'start',
'status' => true,
'start' => $new_task_duration->start,
'id' => $new_task_duration->id,
]);
}
return back()->with('message', ['color' => 'red',
'text' => 'وظیفه یافت نشد✖️']);
}
public function addTask(Request $request)
{
if (isset($_COOKIE['user_identity'])) {
$user = User::where('user_name', $_COOKIE['user_identity'])->first();
} else {
return back()->with('message', [
'color' => 'red',
'text' => 'auth failed!'
]);
}
$request->validate([
'title' => 'required',
'description' => 'required',
'assignees' => 'required',
'start_date' => 'required',
'target_date' => 'required',
'priority' => 'required',
'description_html' => 'required',
'completed_at' => 'required',
'state' => 'required',
'created_at' => 'required',
'updated_at' => 'required',
'app' => 'required',
'task_type' => 'required',
]);
$data = $request->all();
$data['user_id'] = $user->id;
Tasks::create([$data]);
return back()->with('message', [
'color' => 'green',
'text' => 'وظیفه ایجاد شد.'
]);
}
public function storeComment(Request $request, $id)
{
if (!isset($_COOKIE['user_identity'])) {
return back()->with('message', [
'color' => 'red',
'text' => 'ابتدا باید وارد شوید!'
]);
}
$actor = User::where('user_name', $_COOKIE['user_identity'])->first();
$task = Tasks::find($id ?? null);
if (!$task) {
return back()->with('message', [
'color' => 'red',
'text' => 'وظیفه یافت نشد!'
]);
}
$request->validate([
'body' => 'required|string',
]);
$body = trim((string)$request->input('body'));
preg_match_all('/@([\p{L}\p{N}_.-]+)/u', $body, $matches);
$usernames = array_values(array_unique($matches[1] ?? []));
$mentionedUsers = !empty($usernames)
? User::whereIn('user_name', $usernames)->get()
: collect();
$mentionedIds = $mentionedUsers->pluck('id')->values()->all();
TaskComment::create([
'task_id' => $task->id,
'user_id' => $actor->id,
'body' => $body,
'mentioned_user_ids' => !empty($mentionedIds) ? $mentionedIds : null,
]);
$text = "کامنت جدید روی تسک «{$task->title}»\n"
. "توسط: {$actor->name}\n\n"
. $body;
foreach ($mentionedUsers as $mu) {
if ($mu->id === $actor->id) {
continue;
}
if ($mu->bale) {
$this->send_bale($mu->bale, $text);
}
}
$this->send_level1_admins($text);
return back()->with('message', [
'color' => 'green',
'text' => 'کامنت ثبت شد.'
]);
}
public function webhookPlane(Request $request)
{
$d = $request->all();
// فقط وقتی تغییر state هست
if (isset($d['event'], $d['action'], $d['data']['name'], $d['data']['state']['name'])) {
$msg = "Event: {$d['event']}\nAction: {$d['action']}\nName: {$d['data']['name']}\nNew Status: {$d['data']['state']['name']}";
// ارسال به تلگرام
Http::get("https://api.wwwapp.ir/telegran_send.php", [
'botToken' => "7467099619:AAF2V6yYcbAb8oSIRSCyH5i2GKfdWVO3a7k",
'chatId' => "-4742642674",
'message' => $msg,
]);
}
// اگر خواستی ثبت در دیتابیس هم اضافه کنی
// DB::table('tst')->insert([
// 'data' => json_encode($d, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE),
// ]);
return response()->json(['status' => 'ok'], 200);
}
private function send_bale($chat_id, $message)
{
try {
Http::withOptions([
'curl' => [
CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
CURLOPT_TCP_FASTOPEN => 1,
]
])->withoutVerifying()->post('https://tapi.bale.ai/1482838710:sYbLzby0tuLRzHvP4d3LsbcNwg2sjSDLTAU/sendMessage', [
"chat_id" => $chat_id,
'text' => $message,
]);
} catch (\Exception $e) {
}
}
}