first change

This commit is contained in:
2025-07-27 17:40:56 +05:45
commit f8b9a6725b
3152 changed files with 229528 additions and 0 deletions

View File

@@ -0,0 +1,163 @@
<?php
namespace Modules\Employee\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Modules\Employee\Models\Department;
use Modules\Employee\Services\DepartmentService;
use Modules\User\Services\UserService;
use Yajra\DataTables\Facades\DataTables;
class DepartmentController extends Controller
{
protected $departmentService;
protected $userService;
public function __construct(DepartmentService $departmentService, UserService $userService)
{
$this->departmentService = $departmentService;
$this->userService = $userService;
}
/**
* Display a listing of the resource.
*/
public function index(?int $id = null)
{
$isEditing = !is_null($id);
$department = $isEditing ? $this->departmentService->getDepartmentById($id) : null;
if (request()->ajax()) {
$model = Department::query()->orderBy('order');
return DataTables::eloquent($model)
->addIndexColumn()
->setRowClass('tableRow')
->editColumn('status', function (Department $department) {
$status = $department->status ? 'Published' : 'Draft';
$color = $department->status ? 'text-success' : 'text-danger';
return "<p class='{$color}'>{$status}</p>";
})
->addColumn('head', function (Department $department) {
return $department->departmentHead?->name ?? '-';
})
->addColumn('action', 'employee::department.datatable.action')
->rawColumns(['action', 'status', 'head'])
->toJson();
}
$userOptions = $this->userService->pluck();
return view('employee::department.index', [
'department' => $department,
'userOptions' => $userOptions,
'title' => $isEditing ? 'Edit Department' : 'Add Department',
]);
}
/**
* Show the form for creating a new resource.
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
$isEditing = $request->has('id');
$request->merge([
'slug' => Str::slug($request->title),
]);
if ($isEditing) {
$validated = $request->validate([
'title' => ['required', 'string', 'max:255', 'unique:departments,title,' . $request->id],
'slug' => ['required', 'string'],
'user_id' => ['nullable', 'integer'],
]);
$department = $this->departmentService->updateDepartment($request->id, $validated);
flash()->success("Department for {$department->title} has been updated.");
return to_route('department.index');
}
$maxOrder = Department::max('order');
$order = $maxOrder ? ++$maxOrder : 1;
$request->mergeIfMissing([
'order' => $order
]);
$validated = $request->validate([
'title' => ['required', 'string', 'unique:departments,title'],
'slug' => ['required', 'string'],
'order' => ['integer'],
'user_id' => ['nullable', 'integer'],
]);
$department = $this->departmentService->storeDepartment($validated);
flash()->success("Department for {$department->title} has been created.");
return to_route('department.index');
}
/**
* Show the specified resource.
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*/
public function destroy($id)
{
$department = $this->departmentService->deleteDepartment($id);
return response()->json(['status' => 200, 'message' => "Department has been deleted."], 200);
}
public function reorder(Request $request)
{
$departments = $this->departmentService->getAllDepartments();
foreach ($departments as $department) {
foreach ($request->order as $order) {
if ($order['id'] == $department->id) {
$department->update(['order' => $order['position']]);
}
}
}
return response(['status' => true, 'message' => 'Reordered successfully'], 200);
}
public function toggle($id)
{
$department = Department::findOrFail($id);
$department->update(['status' => !$department->status]);
return response(['status' => 200, 'message' => 'Toggled successfully'], 200);
}
}

View File

@@ -0,0 +1,163 @@
<?php
namespace Modules\Employee\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Modules\Employee\Models\Designation;
use Modules\Employee\Services\DepartmentService;
use Modules\Employee\Services\DesignationService;
use Yajra\DataTables\Facades\DataTables;
class DesignationController extends Controller
{
protected $designationService;
protected $departmentService;
public function __construct(DesignationService $designationService, DepartmentService $departmentService)
{
$this->designationService = $designationService;
$this->departmentService = $departmentService;
}
/**
* Display a listing of the resource.
*/
public function index(?int $id = null)
{
$isEditing = !is_null($id);
$designation = $isEditing ? $this->designationService->getDesignationById($id) : null;
if (request()->ajax()) {
$model = Designation::query()->orderBy('order');
return DataTables::eloquent($model)
->addIndexColumn()
->setRowClass('tableRow')
->editColumn('status', function (Designation $designation) {
$status = $designation->status ? 'Published' : 'Draft';
$color = $designation->status ? 'text-success' : 'text-danger';
return "<p class='{$color}'>{$status}</p>";
})
->editColumn('department_id', function (Designation $designation) {
return $designation->department?->title ?? "-";
})
->addColumn('action', 'employee::designation.datatable.action')
->rawColumns(['action', 'status'])
->toJson();
}
$departmentOptions = $this->departmentService->pluck();
return view('employee::designation.index', [
'designation' => $designation,
'departmentOptions'=> $departmentOptions,
'title' => $isEditing ? 'Edit Designation' : 'Add Designation',
]);
}
/**
* Show the form for creating a new resource.
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
$isEditing = $request->has('id');
$request->merge([
'slug' => Str::slug($request->title),
]);
if ($isEditing) {
$validated = $request->validate([
'title' => ['required', 'string', 'max:255', 'unique:designations,title,' . $request->id],
'slug' => ['required', 'string'],
'department_id' => ['nullable', 'integer'],
]);
$designation = $this->designationService->updateDesignation($request->id, $validated);
flash()->success("Designation for {$designation->title} has been updated.");
return to_route('designation.index');
}
$maxOrder = Designation::max('order');
$order = $maxOrder ? ++$maxOrder : 1;
$request->mergeIfMissing([
'order' => $order
]);
$validated = $request->validate([
'title' => ['required', 'string', 'unique:designations,title'],
'slug' => ['required', 'string'],
'order' => ['integer'],
'department_id' => ['nullable', 'integer'],
]);
$designation = $this->designationService->storeDesignation($validated);
flash()->success("Designation for {$designation->title} has been created.");
return to_route('designation.index');
}
/**
* Show the specified resource.
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*/
public function destroy($id)
{
$designation = $this->designationService->deleteDesignation($id);
return response()->json(['status' => 200, 'message' => "Designation has been deleted."], 200);
}
public function reorder(Request $request)
{
$designations = $this->designationService->getAllDesignations();
foreach ($designations as $designation) {
foreach ($request->order as $order) {
if ($order['id'] == $designation->id) {
$designation->update(['order' => $order['position']]);
}
}
}
return response(['status' => true, 'message' => 'Reordered successfully'], 200);
}
public function toggle($id)
{
$designation = Designation::findOrFail($id);
$designation->update(['status' => !$designation->status]);
return response(['status' => 200, 'message' => 'Toggled successfully'], 200);
}
}

View File

@@ -0,0 +1,258 @@
<?php
namespace Modules\Employee\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\CCMS\Models\Branch;
use Modules\Employee\Interfaces\EmployeeInterface;
use Modules\Employee\Models\Employee;
use Modules\Employee\Services\DepartmentService;
use Modules\Employee\Services\DesignationService;
use Modules\User\Services\UserService;
class EmployeeController extends Controller
{
private $employee;
private $userService;
private $branchService;
private $designationService;
private $departmentService;
public function __construct(EmployeeInterface $employee, UserService $userService, DesignationService $designationService, DepartmentService $departmentService)
{
$this->employee = $employee;
$this->userService = $userService;
$this->designationService = $designationService;
$this->departmentService = $departmentService;
}
/**
* Display a listing of the resource.
*/
public function index(Request $request)
{
$data['title'] = "Employee List";
if ($request->ajax()) {
$data['employees'] = $this->employee->findAll(request: $request, query: function ($query) {
$query->where('status', "!=", "terminated")->with('user')->latest();
}, paginate:true, limit:12);
$view = view('employee::employee.partials.employee-list', $data)->render();
return response()->json(['status', 200, 'html' => $view], 200);
}
return view('employee::employee.index', $data);
}
/**
* Show the form for creating a new resource.
*/
public function create()
{
$data['title'] = 'Create Employee';
$data['editable'] = false;
$data['genderOptions'] = config("constants.gender_options");
$data['statusOptions'] = config("constants.employee_status_options");
$data['branchOptions'] = Branch::pluck('title', 'id');
$data['departmentOptions'] = $this->departmentService->pluck();
$data['designationOptions'] = $this->designationService->pluck();
return view('employee::employee.create', $data);
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
$validatedData = $request->validate([
'mobile' => [
'required',
'regex:/^(98|97)[0-9]{8}$/',
],
'photo' => 'nullable',
'email' => 'required|email|unique:employees,email',
], [
'mobile.required' => 'Mobile number is required.',
'mobile.regex' => 'Mobile number must start with 98 or 97 and be 10 digits long.',
'email.required' => 'Email is required.',
'email.email' => 'Invalid email format.',
'email.unique' => 'The email has already been taken.',
]);
$request->merge([
'employee_code' => 'EMP' . mt_rand(1000, 9999),
]);
try {
DB::transaction(function () use ($validatedData, $request) {
$employeeInput = $request->only(Employee::getFillableFields());
$userInput = $request->only(User::getFillableFields());
$employee = $this->employee->create($employeeInput);
$userInput['name'] = $employee->full_name;
$userInput['order'] = ($maxOrder = User::max('order')) !== null ? ++$maxOrder : 1;
$user = $this->userService->storeUser($userInput);
$employee->update(['user_id' => $user->id]);
});
flash()->success('Employee has been created successfully!');
return redirect()->route('employee.index');
} catch (\Exception $e) {
flash()->error($e->getMessage());
return redirect()->back()->withInput();
}
}
/**
* Show the specified resource.
*/
public function show($id)
{
$data['employee'] = $this->employee->findById($id);
// $data['leaves'] = $this->leave->getLeaveByEmployeeId(id: $id);
// $data['leaveTypeList'] = $this->leaveType->pluck();
// $data['status'] = Leave::PROGRESS_STATUS;
// $data['duration'] = Leave::DURATION;
// $data['attends'] = $this->attendance->getAttendanceByEmployeeId(id: $id);
// $data['roleList'] = $this->role->pluck();
// $data['desgination'] = $data['employee']->designation->name;
// $data['department'] = $data['employee']->department_id ? optional($this->dropDown->getDropdownById($data['employee']->department_id))->title : null;
// $data['leaveBalance'] = $this->leaveBalance->where([
// 'employee_id' => $id,
// ])->with(['leaveType:leave_type_id,name'])->get()
// ->transform(function ($leaveBalance) {
// return [
// 'leave_type_id' => $leaveBalance->leave_type_id,
// 'leave_type' => $leaveBalance->leaveType?->name,
// 'total' => $leaveBalance->total,
// 'remain' => $leaveBalance->remain,
// ];
// });
return view('employee::show', $data);
}
/**ss
* Show the form for editing the specified resource.
*/
public function edit($id)
{
$data['title'] = 'Edit Employee';
$data['editable'] = true;
$data['genderOptions'] = config("constants.gender_options");
$data['statusOptions'] = config("constants.employee_status_options");
$data['branchOptions'] = Branch::pluck('title', 'id');
$data['departmentOptions'] = $this->departmentService->pluck();
$data['designationOptions'] = $this->designationService->pluck();
$data['employee'] = $this->employee->findById($id);
return view('employee::employee.edit', $data);
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, $id)
{
$validated = $request->validate([
'mobile' => [
'required',
'regex:/^(98|97)[0-9]{8}$/',
],
'email' => 'required|email|unique:employees,email,' . $id,
], [
'contact.required' => 'The contact number is required.',
'contact.regex' => 'The contact number must start with 98 or 97 and be 10 digits long.',
'email.required' => 'The email is required.',
'email.email' => 'The email must be a valid email address.',
'email.unique' => 'The email has already been taken.',
]);
try {
DB::transaction(function () use ($request, $id) {
$input = $request->only(Employee::getFillableFields());
$employee = $this->employee->update($id, $input);
$userData = [
'name' => $employee->full_name,
'email' => $employee->email,
];
if ($employee->isDirty("email")) {
$userData["can_login"] = false;
}
$employee->user->update($userData);
});
flash()->success('Employee has been updated!');
return redirect()->route('employee.index');
} catch (\Throwable $th) {
flash()->error($th->getMessage());
return redirect()->back()->withInput();
}
}
/**
* Remove the specified resource from storage.
*/
public function destroy($id)
{
try {
DB::transaction(function () use ($id) {
$employee = $this->employee->delete($id);
$employee->user->delete();
});
return response()->json([
'status' => 200,
'message' => 'Employee has been deleted!',
], 200);
} catch (\Throwable $th) {
return response()->json([
'status' => 500,
'message' => 'Failed to delete employee!',
'error' => $th->getMessage(),
], 500);
}
}
public function terminate($id)
{
try {
DB::transaction(function () use ($id) {
$employee = $this->employee->terminate($id);
$employee->user->update([
"can_login" => false,
]);
});
return response()->json([
'status' => 200,
'message' => 'Employee has been terminate!',
], 200);
} catch (\Throwable $th) {
return response()->json([
'status' => 500,
'message' => 'Failed to terminate employee!',
'error' => $th->getMessage(),
], 500);
}
}
}

View File

@@ -0,0 +1,10 @@
<?php
namespace Modules\Employee\Interfaces;
use App\Interfaces\ModelInterface;
interface EmployeeInterface extends ModelInterface
{
public function terminate($id);
}

View File

@@ -0,0 +1,37 @@
<?php
namespace Modules\Employee\Models;
use App\Models\User;
use App\Traits\CreatedUpdatedBy;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Modules\Employee\Database\Factories\DepartmentFactory;
class Department extends Model
{
use HasFactory, CreatedUpdatedBy;
/**
* The attributes that are mass assignable.
*/
protected $fillable = [
'title',
'slug',
'status',
'order',
'user_id',
'createdby',
'updatedby',
];
public function departmentHead()
{
return $this->belongsTo(User::class, 'user_id');
}
protected static function newFactory(): DepartmentFactory
{
return DepartmentFactory::new();
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace Modules\Employee\Models;
use App\Models\User;
use App\Traits\CreatedUpdatedBy;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Modules\Employee\Database\Factories\DesignationFactory;
class Designation extends Model
{
use HasFactory, CreatedUpdatedBy;
/**
* The attributes that are mass assignable.
*/
protected $fillable = [
'title',
'slug',
'status',
'order',
'department_id',
'createdby',
'updatedby',
];
public function department()
{
return $this->belongsTo(Department::class, 'department_id');
}
protected static function newFactory(): DesignationFactory
{
return DesignationFactory::new();
}
}

View File

@@ -0,0 +1,113 @@
<?php
namespace Modules\Employee\Models;
use App\Models\User;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Storage;
use Modules\CCMS\Models\Branch;
use Modules\Employee\Database\Factories\EmployeeFactory;
use Modules\User\Models\ActivityLog;
class Employee extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*/
protected $fillable = [
'first_name',
'middle_name',
'last_name',
'dob',
'email',
'contact',
'mobile',
'photo',
'guardian_name',
'guardian_contact',
'temporary_address',
'permanent_address',
'employee_code',
'join_date',
'gender_id',
'designation_id',
'department_id',
'branch_id',
'user_id',
'status',
'remarks',
];
/**
* Get the employee's full name.
*/
protected function casts(): array
{
return [
"dob" => "date",
"join_date" => "date",
];
}
protected function fullName(): Attribute
{
return Attribute::make(
get: fn() => trim(
implode(' ', array_filter([$this->first_name, $this->middle_name, $this->last_name]))
),
);
}
protected function photo(): Attribute
{
return Attribute::make(
get: fn(string $value) => asset($value),
);
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id');
}
public function department()
{
return $this->belongsTo(Department::class, 'department_id');
}
public function designation()
{
return $this->belongsTo(Designation::class, 'designation_id');
}
public function branch()
{
return $this->belongsTo(Branch::class, 'branch_id');
}
public function activityLogs()
{
return $this->hasManyThrough(
ActivityLog::class,
User::class,
'id',
'loggable_id'
)
->where('loggable_type', User::class);
}
protected static function newFactory(): EmployeeFactory
{
return EmployeeFactory::new();
}
public static function getFillableFields()
{
return (new static())->getFillable();
}
}

View File

View File

@@ -0,0 +1,138 @@
<?php
namespace Modules\Employee\Providers;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
use Modules\Employee\Interfaces\EmployeeInterface;
use Modules\Employee\Repositories\EmployeeRepository;
use Nwidart\Modules\Traits\PathNamespace;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
class EmployeeServiceProvider extends ServiceProvider
{
use PathNamespace;
protected string $name = 'Employee';
protected string $nameLower = 'employee';
/**
* Boot the application events.
*/
public function boot(): void
{
$this->registerCommands();
$this->registerCommandSchedules();
$this->registerTranslations();
$this->registerConfig();
$this->registerViews();
$this->loadMigrationsFrom(module_path($this->name, 'database/migrations'));
}
/**
* Register the service provider.
*/
public function register(): void
{
$this->app->bind(EmployeeInterface::class, EmployeeRepository::class);
$this->app->register(EventServiceProvider::class);
$this->app->register(RouteServiceProvider::class);
}
/**
* Register commands in the format of Command::class
*/
protected function registerCommands(): void
{
// $this->commands([]);
}
/**
* Register command Schedules.
*/
protected function registerCommandSchedules(): void
{
// $this->app->booted(function () {
// $schedule = $this->app->make(Schedule::class);
// $schedule->command('inspire')->hourly();
// });
}
/**
* Register translations.
*/
public function registerTranslations(): void
{
$langPath = resource_path('lang/modules/'.$this->nameLower);
if (is_dir($langPath)) {
$this->loadTranslationsFrom($langPath, $this->nameLower);
$this->loadJsonTranslationsFrom($langPath);
} else {
$this->loadTranslationsFrom(module_path($this->name, 'lang'), $this->nameLower);
$this->loadJsonTranslationsFrom(module_path($this->name, 'lang'));
}
}
/**
* Register config.
*/
protected function registerConfig(): void
{
$relativeConfigPath = config('modules.paths.generator.config.path');
$configPath = module_path($this->name, $relativeConfigPath);
if (is_dir($configPath)) {
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($configPath));
foreach ($iterator as $file) {
if ($file->isFile() && $file->getExtension() === 'php') {
$relativePath = str_replace($configPath . DIRECTORY_SEPARATOR, '', $file->getPathname());
$configKey = $this->nameLower . '.' . str_replace([DIRECTORY_SEPARATOR, '.php'], ['.', ''], $relativePath);
$key = ($relativePath === 'config.php') ? $this->nameLower : $configKey;
$this->publishes([$file->getPathname() => config_path($relativePath)], 'config');
$this->mergeConfigFrom($file->getPathname(), $key);
}
}
}
}
/**
* Register views.
*/
public function registerViews(): void
{
$viewPath = resource_path('views/modules/'.$this->nameLower);
$sourcePath = module_path($this->name, 'resources/views');
$this->publishes([$sourcePath => $viewPath], ['views', $this->nameLower.'-module-views']);
$this->loadViewsFrom(array_merge($this->getPublishableViewPaths(), [$sourcePath]), $this->nameLower);
$componentNamespace = $this->module_namespace($this->name, $this->app_path(config('modules.paths.generator.component-class.path')));
Blade::componentNamespace($componentNamespace, $this->nameLower);
}
/**
* Get the services provided by the provider.
*/
public function provides(): array
{
return [];
}
private function getPublishableViewPaths(): array
{
$paths = [];
foreach (config('view.paths') as $path) {
if (is_dir($path.'/modules/'.$this->nameLower)) {
$paths[] = $path.'/modules/'.$this->nameLower;
}
}
return $paths;
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace Modules\Employee\Providers;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event handler mappings for the application.
*
* @var array<string, array<int, string>>
*/
protected $listen = [];
/**
* Indicates if events should be discovered.
*
* @var bool
*/
protected static $shouldDiscoverEvents = true;
/**
* Configure the proper event listeners for email verification.
*/
protected function configureEmailVerification(): void
{
//
}
}

View File

@@ -0,0 +1,50 @@
<?php
namespace Modules\Employee\Providers;
use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
class RouteServiceProvider extends ServiceProvider
{
protected string $name = 'Employee';
/**
* Called before routes are registered.
*
* Register any model bindings or pattern based filters.
*/
public function boot(): void
{
parent::boot();
}
/**
* Define the routes for the application.
*/
public function map(): void
{
$this->mapApiRoutes();
$this->mapWebRoutes();
}
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*/
protected function mapWebRoutes(): void
{
Route::middleware('web')->group(module_path($this->name, '/routes/web.php'));
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*/
protected function mapApiRoutes(): void
{
Route::middleware('api')->prefix('api')->name('api.')->group(module_path($this->name, '/routes/api.php'));
}
}

View File

@@ -0,0 +1,93 @@
<?php
namespace Modules\Employee\Repositories;
use Illuminate\Http\Request;
use Modules\Employee\Interfaces\EmployeeInterface;
use Modules\Employee\Models\Employee;
class EmployeeRepository implements EmployeeInterface
{
public function findAll($request, callable $query = null, bool $paginate = false, int $limit = 10)
{
$baseQuery = Employee::query();
if ($request->filled('search')) {
$baseQuery->whereAny(
[
'first_name',
'middle_name',
'last_name',
],
'LIKE',
"%{$request->search}%"
);
}
if ($request->filled('email')) {
$baseQuery->where('email', 'LIKE', "%{$$request->email}%");
}
if ($query) {
$query($baseQuery);
}
if ($paginate) {
return $baseQuery->paginate($limit);
}
return $baseQuery->get();
}
public function findById($id, callable $query = null)
{
$baseQuery = Employee::query();
if (is_callable($query)) {
$query($baseQuery);
}
return $baseQuery->where('id', $id)->firstOrFail();
}
public function delete($id)
{
$employee = $this->findById($id);
$employee->delete();
return $employee;
}
public function create(array $data)
{
$employee = Employee::create($data);
return $employee;
}
public function update($id, array $data)
{
$employee = $this->findById($id);
$employee->update($data);
return $employee;
}
public function pluck(callable $query = null)
{
$baseQuery = Employee::query();
if (is_callable($query)) {
$query($baseQuery);
}
return $baseQuery->get()->mapWithKeys(function ($employee) {
return [$employee->id => $employee->full_name];
});
}
public function terminate($id){
$employee = $this->findById($id);
$employee->update(["status" => "terminated"]);
return $employee;
}
}

View File

View File

@@ -0,0 +1,67 @@
<?php
namespace Modules\Employee\Services;
use Illuminate\Support\Facades\DB;
use Modules\Employee\Models\Department;
class DepartmentService
{
public function getAllDepartments(Request $request, callable $query = null, $paginate = false, $limit = 10)
{
$baseQuery = Department::query();
if (is_callable($query)) {
$query($baseQuery);
}
if ($paginate) {
return $baseQuery->paginate($limit);
}
return $baseQuery->get();
}
public function storeDepartment(array $departmentData): Department
{
return DB::transaction(function () use ($departmentData) {
$department = Department::create($departmentData);
return $department;
});
}
public function getDepartmentById(int $id)
{
return Department::findOrFail($id);
}
public function updateDepartment(int $id, array $departmentData)
{
$department = $this->getDepartmentById($id);
return DB::transaction(function () use ($department, $departmentData) {
$department->update($departmentData);
return $department;
});
}
public function deleteDepartment(int $id)
{
return DB::transaction(function () use ($id) {
$department = $this->getDepartmentById($id);
$department->delete();
return $department;
});
}
public function pluck(callable $query = null)
{
$baseQuery = Department::query();
if (is_callable($query)) {
$query($baseQuery);
}
return $baseQuery->pluck('title', 'id');
}
}

View File

@@ -0,0 +1,67 @@
<?php
namespace Modules\Employee\Services;
use Illuminate\Support\Facades\DB;
use Modules\Employee\Models\Designation;
class DesignationService
{
public function getAllDesignations(Request $request, callable $query = null, $paginate = false, $limit = 10)
{
$baseQuery = Designation::query();
if (is_callable($query)) {
$query($baseQuery);
}
if ($paginate) {
return $baseQuery->paginate($limit);
}
return $baseQuery->get();
}
public function storeDesignation(array $designationData): Designation
{
return DB::transaction(function () use ($designationData) {
$designation = Designation::create($designationData);
return $designation;
});
}
public function getDesignationById(int $id)
{
return Designation::findOrFail($id);
}
public function updateDesignation(int $id, array $designationData)
{
$designation = $this->getDesignationById($id);
return DB::transaction(function () use ($designation, $designationData) {
$designation->update($designationData);
return $designation;
});
}
public function deleteDesignation(int $id)
{
return DB::transaction(function () use ($id) {
$designation = $this->getDesignationById($id);
$designation->delete();
return $designation;
});
}
public function pluck(callable $query = null)
{
$baseQuery = Designation::query();
if (is_callable($query)) {
$query($baseQuery);
}
return $baseQuery->pluck('title', 'id');
}
}