Initial commit of testapi

This commit is contained in:
2025-06-20 13:33:07 +02:00
commit a455aba1d5
377 changed files with 30566 additions and 0 deletions
@@ -0,0 +1,49 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Response;
use Illuminate\Http\Request;
class AuthenticationController extends Controller
{
/**
* @unauthenticated
*
* @return "{'status': 'success','token': 'plaintexttoken'}"
*
*
*/
public function authorize(Request $request) {
$request->validate([
'email' => 'required|email',
'password' => 'required|string'
]);
if (!$request->has('email') || !$request->has('password')) {
return json_encode([
'status' => 'invalid',
'message' => 'ingen brukernavn eller passord oppgitt'
], 422);
}
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
$user = Auth::user();
$token = $user->createToken($request->token_name ?? 'default');
return json_encode([
'status' => 'success',
'token' => $token->plainTextToken
], Response::HTTP_ACCEPTED);
}
return json_encode([
'status' => 'invalid',
'message' => 'ugyldig bruker/passord'
], Response::HTTP_UNAUTHORIZED);
}
}
@@ -0,0 +1,53 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\Models\Department;
class DepartmentController extends Controller
{
/**
* GET /Departments
* Query params:
* - departmentName (string)
* - updatedSince (date-time)
*/
public function index(Request $request) {
$q = Department::query();
if ($name = $request->query('departmentName')) {
$q->where('name', $name);
}
if ($since = $request->query('updatedSince')) {
$q->where('updated_at', '>=', Carbon::parse($since));
}
$out = $q->get()->map(function ($d) {
return [
'Id' => $d->id,
'Name' => $d->name,
'Updated' => $d->updated_at->toIso8601String().'Z',
];
});
return response()->json($out);
}
/**
* GET /Departments/{id}
*/
public function show(int $id) {
$d = Department::findOrFail($id);
return response()->json([
'Id' => $d->id,
'Name' => $d->name,
'Updated' => $d->updated_at->toIso8601String().'Z',
]);
}
}
@@ -0,0 +1,68 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\Models\Project;
class ProjectController extends Controller
{
/**
* GET /Projects
* Query params:
* - projectNumber (string)
* - projectName (string)
* - updatedSince (date-time)
* - createdSince (date-time)
*/
public function index(Request $request) {
$q = Project::with(['departments', 'profiles']);
if ($num = $request->query('projectNumber')) {
$q->where('project_number', $num);
}
if ($name = $request->query('projectName')) {
$q->where('project_name', $name);
}
if ($sinceUp = $request->query('updatedSince')) {
$q->where('updated_at', '>=', Carbon::parse($sinceUp));
}
if ($sinceCr = $request->query('createdSince')) {
$q->where('created_at', '>=', Carbon::parse($sinceCr));
}
$out = $q->get()->map(function ($p) {
return [
'Id' => $p->id,
'ProjectName' => $p->project_name,
'ProjectNumber' => $p->project_number,
'Departments' => $p->departments->pluck('id')->all(),
'UserIds' => $p->profiles->pluck('id')->all(),
'Updated' => $p->updated_at->toIso8601String().'Z',
'Created' => $p->created_at->toIso8601String().'Z',
];
});
return response()->json($out);
}
/**
* GET /Projects/{id}
*/
public function show(int $id) {
$p = Project::with(['departments', 'profiles'])->findOrFail($id);
return response()->json([
'Id' => $p->id,
'ProjectName' => $p->project_name,
'ProjectNumber' => $p->project_number,
'Departments' => $p->departments->pluck('id')->all(),
'UserIds' => $p->profiles->pluck('id')->all(),
'Updated' => $p->updated_at->toIso8601String().'Z',
'Created' => $p->created_at->toIso8601String().'Z',
]);
}
}
@@ -0,0 +1,140 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\Models\ApiKeys;
class SmartdokLiveController extends Controller
{
private string $serviceName = 'smartdok';
private string $apiKey;
private string $authToken;
private string $serviceUrl = 'https://api.smartdok.no';
public function __construct() {
$record = ApiKeys::where('category', $this->serviceName)->first();
if (! $record) {
throw new HttpResponseException(
response()->json([
'feil' => "ingen tjenesteoppføring funnet for tjenesten '{$this->serviceName}', som betyr at du ikke har definert en API nøkkel for denne tjenesten enda. Logg inn og legg til en API nøkkel først"
], 404)
);
}
$this->apiKey = $record->key;
$smartdokAuthorizeRequest = Http::withHeaders([
'Content-Type' => 'application/json',
'Accept' => 'application/json'
])->post("{$this->serviceUrl}/Authorize/ApiToken", [
'input' => $this->apiKey
]);
$response = $smartdokAuthorizeRequest->json();
if (!isset($response['Token'])) {
throw new HttpResponseException(
response()->json([
'feil' => "Kunne ikke hente Visma SmartDok autorisasjon ved bruk av den lagrede API nøkkelen i mellomvaren"
], 403)
);
}
$this->authToken = $response['Token'];
}
public function users() {
$smartdokUsersRequest = Http::withHeaders([
'Authorization' => "Bearer {$this->authToken}",
'Accept' => 'application/json'
])->get("{$this->serviceUrl}/Users");
return $smartdokUsersRequest->json();
}
public function user(string $id) {
$smartdokUsersRequest = Http::withHeaders([
'Authorization' => "Bearer {$this->authToken}",
'Accept' => 'application/json'
])->get("{$this->serviceUrl}/Users/{$id}");
return $smartdokUsersRequest->json();
}
public function departments() {
$smartdokDepartmentsRequest = Http::withHeaders([
'Authorization' => "Bearer {$this->authToken}",
'Accept' => 'application/json'
])->get("{$this->serviceUrl}/Departments");
return $smartdokDepartmentsRequest->json();
}
public function department(string $id) {
$smartdokDepartmentsRequest = Http::withHeaders([
'Authorization' => "Bearer {$this->authToken}",
'Accept' => 'application/json'
])->get("{$this->serviceUrl}/Departments/{$id}");
return $smartdokDepartmentsRequest->json();
}
public function projects() {
$smartdokProjectsRequest = Http::withHeaders([
'Authorization' => "Bearer {$this->authToken}",
'Accept' => 'application/json'
])->get("{$this->serviceUrl}/Projects");
return $smartdokProjectsRequest->json();
}
public function project(string $id) {
$smartdokProjectsRequest = Http::withHeaders([
'Authorization' => "Bearer {$this->authToken}",
'Accept' => 'application/json'
])->get("{$this->serviceUrl}/Projects/{$id}");
return $smartdokProjectsRequest->json();
}
public function WorkHours(Request $request) {
$request->validate([
'fromDate' => 'required|date',
'toDate' => 'required|date',
'projectId' => 'nullable|integer',
]);
$from = Carbon::parse($request->query('fromDate'))
->startOfDay()
->toDateTimeString(); // “2025-05-12 00:00:00”
$to = Carbon::parse($request->query('toDate'))
->endOfDay()
->toDateTimeString(); // “2025-05-12 23:59:59”
$query = [
'fromDate' => $from,
'toDate' => $to,
];
if (! is_null($request->input('projectId'))) {
$query['projectId'] = $request->input('projectId');
}
$smartdokWorkHourRequest = Http::withHeaders([
'Authorization' => "Bearer {$this->authToken}",
'Accept' => 'application/json'
])->get("{$this->serviceUrl}/WorkHours", $query);
return $smartdokWorkHourRequest->json();
}
}
@@ -0,0 +1,54 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\SmartdokProfile;
class SmartdokProfileController extends Controller
{
/**
* List all users
*
* Returns a JSON array of all the smartdok users registered on the system
*
* @response \App\Models\SmartdokProfile
*/
public function index() {
$profiles = SmartdokProfile::all()->map(function ($p) {
return [
'Id' => $p->id,
'UserName' => $p->username,
'Name' => $p->name,
];
});
return response()->json($profiles);
}
/**
* Get a user
*
* Returns a JSON array of all the smartdok users registered on the system
*
* @param $id
*
* Example response:
* {
* "Id": "00000000-0000-0000-0000-000000000000",
* "UserName": "string",
* "Name": "string"
* }
*/
public function show(string $id) {
$p = SmartdokProfile::findOrFail($id);
return response()->json([
'Id' => $p->id,
'UserName' => $p->username,
'Name' => $p->name,
]);
}
}
@@ -0,0 +1,70 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\Models\WorkHour;
class WorkHourController extends Controller
{
/**
* GET /WorkHours
*
* Required query params:
* - fromDate : date-time (filters work_date >= fromDate)
* - toDate : date-time (filters work_date <= toDate)
* Optional query param:
* - projectId : integer (filters by associated project)
*
* @response \App\Models\WorkHour
*/
public function index(Request $request) {
$request->validate([
'fromDate' => 'required|date',
'toDate' => 'required|date',
'projectId' => 'nullable|integer',
]);
$from = Carbon::parse($request->query('fromDate'))
->startOfDay()
->toDateTimeString(); // “2025-05-12 00:00:00”
$to = Carbon::parse($request->query('toDate'))
->endOfDay()
->toDateTimeString(); // “2025-05-12 23:59:59”
$q = WorkHour::with('project.departments')
->whereBetween('work_date', [$from, $to]);
if ($pid = $request->query('projectId')) {
// filter directly on the foreign key
$q->where('project_id', $pid);
}
$result = $q->get()->map(function (WorkHour $w) {
$deptIds = $w->project
->departments
->pluck('id')
->unique()
->values()
->all();
return [
'WorkHourID' => $w->id,
'UserID' => $w->user_id,
'ProjectID' => $w->project_id,
'OrdinaryHours' => $w->ordinary_hours,
'Date' => $w->work_date->toDateString(),
'Comment' => $w->comment,
'DepartmentIDsProject' => $deptIds,
'Updated' => $w->updated_at->toIso8601String() . 'Z',
'Created' => $w->created_at->toIso8601String() . 'Z',
];
});
return response()->json($result);
}
}
@@ -0,0 +1,87 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Inertia\Inertia;
use App\Models\ApiAdmins;
use App\Models\ApiKeys;
class ApiAdminController extends Controller
{
public function index(Request $request) {
$userId = Auth::id();
$isAdmin = ApiAdmins::where('user_id', $userId)->exists();
$categories = Apikeys::select('id', 'category')
->orderBy('category')
->get();
return Inertia::render('Dashboard', [
'isAdmin' => $isAdmin,
'categories' => $categories,
]);
}
public function create() {
$userId = Auth::id();
$isAdmin = ApiAdmins::where('user_id', $userId)->exists();
if (! $isAdmin) {
abort(403);
}
$raw = config('api_key_categories', []);
$categories = collect($raw)
->map(fn($desc, $key) => ['key' => $key, 'description' => $desc])
->values()
->all();
return Inertia::render('ApiKeys/Add', [
'categories' => $categories,
]);
}
public function store(Request $request) {
$userId = Auth::id();
$isAdmin = ApiAdmins::where('user_id', $userId)->exists();
if (! $isAdmin) {
abort(403);
}
$data = $request->validate([
'category' => 'required|string|unique:apikeys,category',
'key' => 'required|string',
]);
Apikeys::create([
'category' => $data['category'],
'key' => $data['key'],
]);
return redirect()
->route('dashboard')
->with('success', 'API‐key category added.');
}
public function destroy(int $id) {
$userId = Auth::id();
$isAdmin = ApiAdmins::where('user_id', $userId)->exists();
if (! $isAdmin) {
abort(403);
}
// Attempt to find the record—404 if not found
$apiKey = Apikeys::findOrFail($id);
$apiKey->delete();
return redirect()
->route('dashboard')
->with('success', 'API‐key category removed.');
}
}
@@ -0,0 +1,51 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Inertia\Inertia;
use Inertia\Response;
class AuthenticatedSessionController extends Controller
{
/**
* Show the login page.
*/
public function create(Request $request): Response
{
return Inertia::render('auth/Login', [
'canResetPassword' => Route::has('password.request'),
'status' => $request->session()->get('status'),
]);
}
/**
* Handle an incoming authentication request.
*/
public function store(LoginRequest $request): RedirectResponse
{
$request->authenticate();
$request->session()->regenerate();
return redirect()->intended(route('dashboard', absolute: false));
}
/**
* Destroy an authenticated session.
*/
public function destroy(Request $request): RedirectResponse
{
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}
@@ -0,0 +1,41 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
use Inertia\Inertia;
use Inertia\Response;
class ConfirmablePasswordController extends Controller
{
/**
* Show the confirm password page.
*/
public function show(): Response
{
return Inertia::render('auth/ConfirmPassword');
}
/**
* Confirm the user's password.
*/
public function store(Request $request): RedirectResponse
{
if (! Auth::guard('web')->validate([
'email' => $request->user()->email,
'password' => $request->password,
])) {
throw ValidationException::withMessages([
'password' => __('auth.password'),
]);
}
$request->session()->put('auth.password_confirmed_at', time());
return redirect()->intended(route('dashboard', absolute: false));
}
}
@@ -0,0 +1,24 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
class EmailVerificationNotificationController extends Controller
{
/**
* Send a new email verification notification.
*/
public function store(Request $request): RedirectResponse
{
if ($request->user()->hasVerifiedEmail()) {
return redirect()->intended(route('dashboard', absolute: false));
}
$request->user()->sendEmailVerificationNotification();
return back()->with('status', 'verification-link-sent');
}
}
@@ -0,0 +1,22 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
class EmailVerificationPromptController extends Controller
{
/**
* Show the email verification prompt page.
*/
public function __invoke(Request $request): RedirectResponse|Response
{
return $request->user()->hasVerifiedEmail()
? redirect()->intended(route('dashboard', absolute: false))
: Inertia::render('auth/VerifyEmail', ['status' => $request->session()->get('status')]);
}
}
@@ -0,0 +1,69 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules;
use Illuminate\Validation\ValidationException;
use Inertia\Inertia;
use Inertia\Response;
class NewPasswordController extends Controller
{
/**
* Show the password reset page.
*/
public function create(Request $request): Response
{
return Inertia::render('auth/ResetPassword', [
'email' => $request->email,
'token' => $request->route('token'),
]);
}
/**
* Handle an incoming new password request.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request): RedirectResponse
{
$request->validate([
'token' => 'required',
'email' => 'required|email',
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
// Here we will attempt to reset the user's password. If it is successful we
// will update the password on an actual user model and persist it to the
// database. Otherwise we will parse the error and return the response.
$status = Password::reset(
$request->only('email', 'password', 'password_confirmation', 'token'),
function ($user) use ($request) {
$user->forceFill([
'password' => Hash::make($request->password),
'remember_token' => Str::random(60),
])->save();
event(new PasswordReset($user));
}
);
// If the password was successfully reset, we will redirect the user back to
// the application's home authenticated view. If there is an error we can
// redirect them back to where they came from with their error message.
if ($status == Password::PasswordReset) {
return to_route('login')->with('status', __($status));
}
throw ValidationException::withMessages([
'email' => [__($status)],
]);
}
}
@@ -0,0 +1,41 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Password;
use Inertia\Inertia;
use Inertia\Response;
class PasswordResetLinkController extends Controller
{
/**
* Show the password reset link request page.
*/
public function create(Request $request): Response
{
return Inertia::render('auth/ForgotPassword', [
'status' => $request->session()->get('status'),
]);
}
/**
* Handle an incoming password reset link request.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request): RedirectResponse
{
$request->validate([
'email' => 'required|email',
]);
Password::sendResetLink(
$request->only('email')
);
return back()->with('status', __('A reset link will be sent if the account exists.'));
}
}
@@ -0,0 +1,51 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Inertia\Inertia;
use Inertia\Response;
class RegisteredUserController extends Controller
{
/**
* Show the registration page.
*/
public function create(): Response
{
return Inertia::render('auth/Register');
}
/**
* Handle an incoming registration request.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request): RedirectResponse
{
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|lowercase|email|max:255|unique:'.User::class,
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
event(new Registered($user));
Auth::login($user);
return to_route('dashboard');
}
}
@@ -0,0 +1,29 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Auth\Events\Verified;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
use Illuminate\Http\RedirectResponse;
class VerifyEmailController extends Controller
{
/**
* Mark the authenticated user's email address as verified.
*/
public function __invoke(EmailVerificationRequest $request): RedirectResponse
{
if ($request->user()->hasVerifiedEmail()) {
return redirect()->intended(route('dashboard', absolute: false).'?verified=1');
}
if ($request->user()->markEmailAsVerified()) {
/** @var \Illuminate\Contracts\Auth\MustVerifyEmail $user */
$user = $request->user();
event(new Verified($user));
}
return redirect()->intended(route('dashboard', absolute: false).'?verified=1');
}
}
+8
View File
@@ -0,0 +1,8 @@
<?php
namespace App\Http\Controllers;
abstract class Controller
{
//
}
@@ -0,0 +1,108 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Inertia\Inertia;
use App\Models\Department;
class DepartmentController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index(Request $request) {
$departments = Department::orderBy('name')
->paginate(10)
->through(fn($dept) => [
'id' => $dept->id,
'name' => $dept->name,
]);
return Inertia::render('Department/Index', [
'departments' => $departments,
'filters' => $request->only(['page']),
]);
}
/**
* Show the form for creating a new resource.
*/
public function create() {
return Inertia::render('Department/Create');
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request) {
$data = $request->validate([
'name' => 'required|string|max:255',
]);
Department::create($data);
return redirect()
->route('smartdok.departments.index')
->with('success', 'Department created successfully.');
}
/**
* Display the specified resource.
*/
public function show(string $id) {
$department = Department::findOrFail($id);
return Inertia::render('Department/Show', [
'department' => [
'id' => $department->id,
'name' => $department->name,
],
]);
}
/**
* Show the form for editing the specified resource.
*/
public function edit(string $id) {
$department = Department::findOrFail($id);
return Inertia::render('Department/Edit', [
'department' => [
'id' => $department->id,
'name' => $department->name,
],
]);
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, string $id) {
$department = Department::findOrFail($id);
$data = $request->validate([
'name' => 'required|string|max:255',
]);
$department->update($data);
return redirect()
->route('smartdok.departments.index')
->with('success', 'Department updated successfully.');
}
/**
* Remove the specified resource from storage.
*/
public function destroy(string $id) {
$department = Department::findOrFail($id);
$department->delete();
return redirect()
->route('smartdok.departments.index')
->with('success', 'Department deleted successfully.');
}
}
+171
View File
@@ -0,0 +1,171 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Inertia\Inertia;
use App\Models\Project;
use App\Models\SmartdokProfile;
use App\Models\Department;
class ProjectController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index(Request $request) {
$projects = Project::with(['profiles', 'departments'])
->orderBy('project_name')
->paginate(10)
->through(fn($project) => [
'id' => $project->id,
'project_name' => $project->project_name,
'project_number' => $project->project_number,
'user_ids' => $project->profiles->pluck('id'),
'department_ids' => $project->departments->pluck('id'),
]);
return Inertia::render('Project/Index', [
'projects' => $projects,
'filters' => $request->only(['page']),
]);
}
/**
* Show the form for creating a new resource.
*/
public function create() {
$profiles = SmartdokProfile::orderBy('name')
->get()
->map(fn($p) => ['id' => $p->id, 'name' => $p->name]);
$departments = Department::orderBy('name')
->get()
->map(fn($d) => ['id' => $d->id, 'name' => $d->name]);
return Inertia::render('Project/Create', [
'profiles' => $profiles,
'departments' => $departments,
]);
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request) {
$data = $request->validate([
'project_name' => 'required|string|max:255',
'project_number' => 'required|string|max:255|unique:projects,project_number',
'user_ids' => 'sometimes|array',
'user_ids.*' => 'uuid|exists:smartdok_profiles,id',
'department_ids' => 'sometimes|array',
'department_ids.*' => 'integer|exists:departments,id',
]);
$project = Project::create([
'project_name' => $data['project_name'],
'project_number' => $data['project_number'],
]);
$project->profiles()->sync($data['user_ids'] ?? []);
$project->departments()->sync($data['department_ids'] ?? []);
return redirect()
->route('smartdok.projects.index')
->with('success', 'Project created successfully.');
}
/**
* Display the specified resource.
*/
public function show(string $id) {
$project = Project::with(['profiles', 'departments'])->findOrFail($id);
return Inertia::render('Project/Show', [
'project' => [
'id' => $project->id,
'project_name' => $project->project_name,
'project_number' => $project->project_number,
'profiles' => $project->profiles->map(fn ($p) => [
'id' => $p->id,
'username' => $p->username,
'name' => $p->name,
]),
'departments' => $project->departments->map(fn ($d) => [
'id' => $d->id,
'name' => $d->name,
]),
],
]);
}
/**
* Show the form for editing the specified resource.
*/
public function edit(string $id) {
$project = Project::with(['profiles', 'departments'])
->findOrFail($id);
$profiles = SmartdokProfile::orderBy('name')
->get()
->map(fn($p) => ['id' => $p->id, 'name' => $p->name]);
$departments = Department::orderBy('name')
->get()
->map(fn($d) => ['id' => $d->id, 'name' => $d->name]);
return Inertia::render('Project/Edit', [
'project' => [
'id' => $project->id,
'project_name' => $project->project_name,
'project_number' => $project->project_number,
// ensure these are plain arrays, not Collections
'user_ids' => $project->profiles->pluck('id')->all(),
'department_ids' => $project->departments->pluck('id')->all(),
],
'profiles' => $profiles,
'departments' => $departments,
]);
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, string $id) {
$project = Project::findOrFail($id);
$data = $request->validate([
'project_name' => 'required|string|max:255',
'project_number' => 'required|string|max:255|unique:projects,project_number,' . $project->id,
'user_ids' => 'sometimes|array',
'user_ids.*' => 'uuid|exists:smartdok_profiles,id',
'department_ids' => 'sometimes|array',
'department_ids.*' => 'integer|exists:departments,id',
]);
$project->update([
'project_name' => $data['project_name'],
'project_number' => $data['project_number'],
]);
$project->profiles()->sync($data['user_ids'] ?? []);
$project->departments()->sync($data['department_ids'] ?? []);
return redirect()
->route('smartdok.projects.index')
->with('success', 'Project updated successfully.');
}
/**
* Remove the specified resource from storage.
*/
public function destroy(string $id) {
$project = Project::findOrFail($id);
$project->delete();
return redirect()
->route('smartdok.projects.index')
->with('success', 'Project deleted successfully.');
}
}
@@ -0,0 +1,39 @@
<?php
namespace App\Http\Controllers\Settings;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;
use Inertia\Inertia;
use Inertia\Response;
class PasswordController extends Controller
{
/**
* Show the user's password settings page.
*/
public function edit(): Response
{
return Inertia::render('settings/Password');
}
/**
* Update the user's password.
*/
public function update(Request $request): RedirectResponse
{
$validated = $request->validate([
'current_password' => ['required', 'current_password'],
'password' => ['required', Password::defaults(), 'confirmed'],
]);
$request->user()->update([
'password' => Hash::make($validated['password']),
]);
return back();
}
}
@@ -0,0 +1,63 @@
<?php
namespace App\Http\Controllers\Settings;
use App\Http\Controllers\Controller;
use App\Http\Requests\Settings\ProfileUpdateRequest;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;
use Inertia\Response;
class ProfileController extends Controller
{
/**
* Show the user's profile settings page.
*/
public function edit(Request $request): Response
{
return Inertia::render('settings/Profile', [
'mustVerifyEmail' => $request->user() instanceof MustVerifyEmail,
'status' => $request->session()->get('status'),
]);
}
/**
* Update the user's profile information.
*/
public function update(ProfileUpdateRequest $request): RedirectResponse
{
$request->user()->fill($request->validated());
if ($request->user()->isDirty('email')) {
$request->user()->email_verified_at = null;
}
$request->user()->save();
return to_route('profile.edit');
}
/**
* Delete the user's profile.
*/
public function destroy(Request $request): RedirectResponse
{
$request->validate([
'password' => ['required', 'current_password'],
]);
$user = $request->user();
Auth::logout();
$user->delete();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}
@@ -0,0 +1,116 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Inertia\Inertia;
use App\Models\SmartdokProfile;
class SmartdokProfileController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index(Request $request) {
$profiles = SmartdokProfile::orderBy('name')
->paginate(10)
->through(fn($profile) => [
'id' => $profile->id,
'username' => $profile->username,
'name' => $profile->name,
]);
return Inertia::render('SmartDokProfile/Index', [
'profiles' => $profiles,
'filters' => $request->only(['search', 'page']),
]);
}
/**
* Show the form for creating a new resource.
*/
public function create() {
return Inertia::render('SmartDokProfile/Create');
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request) {
$data = $request->validate([
'username' => 'required|string|max:255|unique:smartdok_profiles,username',
'name' => 'required|string|max:255',
]);
// generate a UUID for the new profile
$data['id'] = (string) Str::uuid();
SmartdokProfile::create($data);
return redirect()
->route('smartdok.profiles.index')
->with('success', 'Profile created successfully.');
}
/**
* Display the specified resource.
*/
public function show(string $id) {
$profile = SmartdokProfile::findOrFail($id);
return Inertia::render('SmartDokProfile/Show', [
'profile' => [
'id' => $profile->id,
'username' => $profile->username,
'name' => $profile->name,
],
]);
}
/**
* Show the form for editing the specified resource.
*/
public function edit(string $id) {
$profile = SmartdokProfile::findOrFail($id);
return Inertia::render('SmartDokProfile/Edit', [
'profile' => [
'id' => $profile->id,
'username' => $profile->username,
'name' => $profile->name,
],
]);
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, string $id) {
$profile = SmartdokProfile::findOrFail($id);
$data = $request->validate([
'username' => 'required|string|max:255|unique:smartdok_profiles,username,' . $profile->id,
'name' => 'required|string|max:255',
]);
$profile->update($data);
return redirect()
->route('smartdok.profiles.index')
->with('success', 'Profile updated successfully.');
}
/**
* Remove the specified resource from storage.
*/
public function destroy(string $id) {
$profile = SmartdokProfile::findOrFail($id);
$profile->delete();
return redirect()
->route('smartdok.profiles.index')
->with('success', 'Profile deleted successfully.');
}
}
+168
View File
@@ -0,0 +1,168 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Inertia\Inertia;
use App\Models\WorkHour;
use App\Models\SmartdokProfile;
use App\Models\Project;
class WorkHourController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index(Request $request) {
$workHours = WorkHour::with(['user', 'project'])
->orderBy('created_at', 'desc')
->paginate(10)
->through(fn($wh) => [
'id' => $wh->id,
'user_id' => $wh->user_id,
'user_name' => $wh->user->name,
'ordinary_hours' => $wh->ordinary_hours,
'work_date' => $wh->work_date->toDateString(),
'comment' => $wh->comment,
'project_id' => $wh->project_id,
'project_name' => $wh->project->project_name,
]);
return Inertia::render('WorkHour/Index', [
'workHours' => $workHours,
'filters' => $request->only(['page']),
]);
}
/**
* Show the form for creating a new resource.
*/
public function create() {
$profiles = SmartdokProfile::orderBy('name')
->get()
->map(fn($p) => ['id' => $p->id, 'name' => $p->name]);
$projects = Project::orderBy('project_name')
->get()
->map(fn($proj) => ['id' => $proj->id, 'project_name' => $proj->project_name]);
return Inertia::render('WorkHour/Create', [
'profiles' => $profiles,
'projects' => $projects,
'today' => now()->toDateString(),
]);
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request) {
$data = $request->validate([
'user_id' => 'required|uuid|exists:smartdok_profiles,id',
'project_id' => 'required|integer|exists:projects,id',
'ordinary_hours' => 'required|numeric|min:0.5|multiple_of:0.5',
'work_date' => 'required|date',
'comment' => 'nullable|string',
]);
WorkHour::create([
'user_id' => $data['user_id'],
'project_id' => $data['project_id'],
'ordinary_hours' => $data['ordinary_hours'],
'work_date' => $data['work_date'],
'comment' => $data['comment'] ?? null,
]);
return redirect()
->route('smartdok.work-hours.index')
->with('success', 'Work hour entry created successfully.');
}
/**
* Display the specified resource.
*/
public function show(string $id) {
$wh = WorkHour::with(['user', 'project'])->findOrFail($id);
return Inertia::render('WorkHour/Show', [
'workHour' => [
'id' => $wh->id,
'user_id' => $wh->user_id,
'user_name' => $wh->user->name,
'ordinary_hours' => $wh->ordinary_hours,
'work_date' => $wh->work_date->toDateString(),
'comment' => $wh->comment,
'project_id' => $wh->project_id,
'project_name' => $wh->project->project_name,
],
]);
}
/**
* Show the form for editing the specified resource.
*/
public function edit(string $id) {
$wh = WorkHour::with(['user', 'project'])->findOrFail($id);
$profiles = SmartdokProfile::orderBy('name')
->get()
->map(fn($p) => ['id' => $p->id, 'name' => $p->name]);
$projects = Project::orderBy('project_name')
->get()
->map(fn($proj) => ['id' => $proj->id, 'project_name' => $proj->project_name]);
return Inertia::render('WorkHour/Edit', [
'workHour' => [
'id' => $wh->id,
'user_id' => $wh->user_id,
'ordinary_hours' => $wh->ordinary_hours,
'work_date' => $wh->work_date->toDateString(),
'comment' => $wh->comment,
'project_id' => $wh->project_id,
],
'profiles' => $profiles,
'projects' => $projects,
]);
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, string $id) {
$wh = WorkHour::findOrFail($id);
$data = $request->validate([
'user_id' => 'required|uuid|exists:smartdok_profiles,id',
'project_id' => 'required|integer|exists:projects,id',
'ordinary_hours' => 'required|numeric|decimal:1|min:0.5',
'work_date' => 'required|date',
'comment' => 'nullable|string',
]);
$wh->update([
'user_id' => $data['user_id'],
'project_id' => $data['project_id'],
'ordinary_hours' => $data['ordinary_hours'],
'work_date' => $data['work_date'],
'comment' => $data['comment'] ?? null,
]);
return redirect()
->route('smartdok.work-hours.index')
->with('success', 'Work hour entry updated successfully.');
}
/**
* Remove the specified resource from storage.
*/
public function destroy(string $id) {
WorkHour::findOrFail($id)->delete();
return redirect()
->route('smartdok.work-hours.index')
->with('success', 'Work hour entry deleted successfully.');
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use Symfony\Component\HttpFoundation\Response;
class HandleAppearance
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
View::share('appearance', $request->cookie('appearance') ?? 'system');
return $next($request);
}
}
@@ -0,0 +1,56 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Inspiring;
use Illuminate\Http\Request;
use Inertia\Middleware;
use Tighten\Ziggy\Ziggy;
class HandleInertiaRequests extends Middleware
{
/**
* The root template that's loaded on the first page visit.
*
* @see https://inertiajs.com/server-side-setup#root-template
*
* @var string
*/
protected $rootView = 'app';
/**
* Determines the current asset version.
*
* @see https://inertiajs.com/asset-versioning
*/
public function version(Request $request): ?string
{
return parent::version($request);
}
/**
* Define the props that are shared by default.
*
* @see https://inertiajs.com/shared-data
*
* @return array<string, mixed>
*/
public function share(Request $request): array
{
[$message, $author] = str(Inspiring::quotes()->random())->explode('-');
return [
...parent::share($request),
'name' => config('app.name'),
'quote' => ['message' => trim($message), 'author' => trim($author)],
'auth' => [
'user' => $request->user(),
],
'ziggy' => [
...(new Ziggy)->toArray(),
'location' => $request->url(),
],
'sidebarOpen' => ! $request->hasCookie('sidebar_state') || $request->cookie('sidebar_state') === 'true',
];
}
}
+85
View File
@@ -0,0 +1,85 @@
<?php
namespace App\Http\Requests\Auth;
use Illuminate\Auth\Events\Lockout;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class LoginRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'email' => ['required', 'string', 'email'],
'password' => ['required', 'string'],
];
}
/**
* Attempt to authenticate the request's credentials.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function authenticate(): void
{
$this->ensureIsNotRateLimited();
if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.failed'),
]);
}
RateLimiter::clear($this->throttleKey());
}
/**
* Ensure the login request is not rate limited.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function ensureIsNotRateLimited(): void
{
if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
return;
}
event(new Lockout($this));
$seconds = RateLimiter::availableIn($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.throttle', [
'seconds' => $seconds,
'minutes' => ceil($seconds / 60),
]),
]);
}
/**
* Get the rate limiting throttle key for the request.
*/
public function throttleKey(): string
{
return Str::transliterate(Str::lower($this->string('email')).'|'.$this->ip());
}
}
@@ -0,0 +1,30 @@
<?php
namespace App\Http\Requests\Settings;
use App\Models\User;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class ProfileUpdateRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'email' => [
'required',
'string',
'lowercase',
'email',
'max:255',
Rule::unique(User::class)->ignore($this->user()->id),
],
];
}
}