Conversie codeigniter 4

This commit is contained in:
2026-01-09 11:41:28 +01:00
parent dbd8c8aed2
commit f0b9c6ad40
242 changed files with 20034 additions and 346 deletions
+160
View File
@@ -0,0 +1,160 @@
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Libraries\Beheer\Session\RetrieveUserSession;
/**
* Class BaseController
*
* BaseController provides a convenient place for loading components
* and performing functions that are needed by all your controllers.
* Extend this class in any new controllers.
*/
abstract class BaseController extends Controller
{
/**
* Instance of the main Request object.
*
* @var CLIRequest|IncomingRequest
*/
protected $request;
/**
* An array of helpers to be loaded automatically upon
* class instantiation.
*
* @var list<string>
*/
protected $helpers = ['common'];
/**
* Session instance
*/
protected $session;
/**
* Current authenticated user
*/
public $user;
/**
* Authentication status
*/
public $authenticated = false;
/**
* Application version
*/
public $version = '1.00.81';
/**
* User Model instance
*/
protected $userModel;
/**
* @return void
*/
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger);
// Preload any models, libraries, etc, here.
$this->session = \Config\Services::session();
// Make version available to all views
$renderer = \Config\Services::renderer();
$renderer->setVar('version', $this->version);
// Initialize user session handler
$this->handleSession();
}
/**
* Handle session and authentication
*/
protected function handleSession(): void
{
// Garbage collection for old sessions
$this->garbageCiSessions();
// Set secure site in production
$this->setSecureSite();
// Retrieve user session
$retrieveSession = new RetrieveUserSession($this->session);
$retrieveSession->handle();
// Get the authenticated flag and user ID from constants
$this->authenticated = defined('AUTHENTICATED') ? AUTHENTICATED : false;
if ($this->authenticated && defined('USERID') && USERID) {
$this->user = \User::find(USERID);
}
}
/**
* Garbage collection for old CI sessions
*/
protected function garbageCiSessions(): void
{
$number = random_int(0, 100);
if ($number !== 17) {
return;
}
$db = \Config\Database::connect();
$db->query("DELETE FROM ci_sessions WHERE TIMESTAMPDIFF(MINUTE, FROM_UNIXTIME(timestamp), NOW()) > 60");
}
/**
* Force HTTPS in production
*/
protected function setSecureSite(): void
{
if (($_ENV['ENVIRONMENT'] ?? 'development') !== 'production') {
return;
}
if (!isset($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] !== "on") {
header("Location: " . ($_ENV['APP_URL'] ?? ''));
exit;
}
}
/**
* Clean input value (replaces CI3's clean_input method)
*/
protected function cleanInput(string $key): string
{
$value = $this->request->getPost($key) ?? $this->request->getGet($key) ?? '';
return str_replace('null', '', $value);
}
/**
* Return JSON response (replaces CI3's json method)
*/
protected function json($data): ResponseInterface
{
return $this->response
->setContentType('application/json')
->setJSON($data);
}
/**
* Check if user is authorized (placeholder for subclass implementation)
*/
public function unAuthorized(): void
{
// Override in subclasses if needed
}
}
@@ -0,0 +1,49 @@
<?php
namespace App\Controllers\Beheer;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class AuthorisationController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function index()
{
// Default action
}
public function getRoleAuthorisations(): ResponseInterface
{
$roleAuthorisations = \Role::getPagesAccessByRole();
return $this->json($roleAuthorisations);
}
public function toggleAuhorisation(): ResponseInterface
{
$pageID = $this->cleanInput('pageID');
$roleLevel = $this->cleanInput('roleLevel');
$access = $this->cleanInput('access');
$page = \Page::find($pageID);
if ($access == 'F') {
$roleLevel = -$roleLevel;
}
$page->pagelevel = $page->pagelevel + $roleLevel;
$page->save();
return $this->json(['success' => true]);
}
}
@@ -0,0 +1,70 @@
<?php
namespace App\Controllers\Beheer;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class CustomersController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function index()
{
// Default action
}
public function getAllCustomers(string $archive = 'F'): ResponseInterface
{
$customers = \Customer::getAllCustomers($archive);
return $this->json($customers);
}
public function saveCustomer(): ResponseInterface
{
$customerValidation = new \CustomerValidation();
if (!$customerValidation->getValidationResult()) {
return $this->json([
'success' => false,
'messages' => $customerValidation->getErrorMessages()
]);
}
$customer = $this->request->getPost();
$customerID = $customer['id'];
unset($customer['id']);
$customerID = \Customer::saveCustomer($customerID, $customer);
return $this->json(['success' => true, 'customerID' => $customerID]);
}
public function archiveCustomer(int $customerID, string $status): ResponseInterface
{
\Customer::whereId($customerID)->update(['archive' => $status]);
return $this->json(['success' => true]);
}
public function removeCustomer(int $customerID): ResponseInterface
{
$removeCustomer = new \RemoveCustomer($customerID);
if ($removeCustomer->getAllowDelete() === false) {
return $this->json(['result' => false]);
}
\Customer::removeCustomer($customerID);
return $this->json(['result' => true]);
}
}
@@ -0,0 +1,56 @@
<?php
namespace App\Controllers\Beheer;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class EmployeeTargetController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function index()
{
// Default action
}
public function getEmployeeTargets(int $employeeID): ResponseInterface
{
$employeeTargets = \Employeetarget::whereUserId($employeeID)
->orderBy('id')
->get();
return $this->json($employeeTargets);
}
public function saveEmployeeTarget(): ResponseInterface
{
$employeeTargetValidation = new \EmployeeTargetValidation();
if (!$employeeTargetValidation->getValidationResult()) {
return $this->json([
'success' => false,
'messages' => $employeeTargetValidation->getErrorMessages()
]);
}
$target = $this->request->getPost();
$targetID = $target['id'];
unset($target['id']);
$target['endmonth'] = $target['endmonth'] ? $target['endmonth'] : null;
$target['endyear'] = $target['endyear'] ? $target['endyear'] : null;
$targetID = \Employeetarget::saveTarget($targetID, $target);
return $this->json(['success' => true, 'targetID' => $targetID]);
}
}
@@ -0,0 +1,70 @@
<?php
namespace App\Controllers\Beheer;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class ExternalsController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function index()
{
// Default action
}
public function getAllExternals(string $archive = 'F'): ResponseInterface
{
$externals = \External::getAllExternals($archive);
return $this->json($externals);
}
public function saveExternal(): ResponseInterface
{
$externalValidation = new \ExternalValidation();
if (!$externalValidation->getValidationResult()) {
return $this->json([
'success' => false,
'messages' => $externalValidation->getErrorMessages()
]);
}
$external = $this->request->getPost();
$externalID = $external['id'];
unset($external['id']);
$externalID = \External::saveExternal($externalID, $external);
return $this->json(['success' => true, 'externalID' => $externalID]);
}
public function archiveExternal(int $externalID, string $status): ResponseInterface
{
\External::whereId($externalID)->update(['archive' => $status]);
return $this->json(['success' => true]);
}
public function removeExternal(int $externalID): ResponseInterface
{
$removeExternal = new \RemoveExternal($externalID);
if ($removeExternal->getAllowDelete() === false) {
return $this->json(['result' => false]);
}
\External::removeExternal($externalID);
return $this->json(['result' => true]);
}
}
@@ -0,0 +1,30 @@
<?php
namespace App\Controllers\Beheer;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class RolesController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function index()
{
// Default action
}
public function getAllRoles(string $archive = 'F'): ResponseInterface
{
$roles = \Role::getAllRoles($archive);
return $this->json($roles);
}
}
@@ -0,0 +1,194 @@
<?php
namespace App\Controllers\Beheer;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use App\Libraries\TwoFactorAuth;
/**
* Two-Factor Authentication Settings Controller
* Allows users to manage their 2FA settings
*/
class TwoFactorController extends BaseController
{
protected TwoFactorAuth $twoFactorAuth;
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
// Ensure user is authenticated
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
header('Location: ' . site_url('login'));
exit;
}
$this->twoFactorAuth = new TwoFactorAuth();
}
/**
* Show 2FA settings page
*/
public function index(): string
{
$data = [
'user' => $this->user,
'version' => $this->version
];
return view('pages/beheer/twofactor/settings_view', $data);
}
/**
* Enable 2FA for the user
* POST parameters:
* - method: 'email' or 'authenticator'
*/
public function enable(): ResponseInterface
{
$method = $this->cleanInput('method');
if (!in_array($method, ['email', 'authenticator'])) {
return $this->json(['success' => false, 'message' => 'Ongeldige methode']);
}
$secret = null;
$qrCodeUrl = null;
// If authenticator method, generate secret
if ($method === 'authenticator') {
$secret = $this->twoFactorAuth->generateSecret();
$qrCodeUrl = $this->twoFactorAuth->getQRCodeUrl(
$secret,
$this->user->username,
'DBOIS'
);
}
// Update user record
\User::whereId($this->user->id)->update([
'two_factor_enabled' => 'T',
'two_factor_method' => $method,
'two_factor_secret' => $secret
]);
$response = [
'success' => true,
'message' => 'Tweefactorauthenticatie ingeschakeld',
'method' => $method
];
if ($method === 'authenticator') {
$response['secret'] = $secret;
$response['qrCodeUrl'] = $qrCodeUrl;
}
return $this->json($response);
}
/**
* Verify authenticator setup
* POST parameters:
* - code: The 6-digit code from Google Authenticator
*/
public function verifySetup(): ResponseInterface
{
$code = $this->cleanInput('code');
if (!$this->user->two_factor_secret) {
return $this->json(['success' => false, 'message' => 'Geen geheim gevonden']);
}
$isValid = $this->twoFactorAuth->verifyCode($this->user->two_factor_secret, $code);
if ($isValid) {
return $this->json(['success' => true, 'message' => 'Code geverifieerd']);
} else {
return $this->json(['success' => false, 'message' => 'Ongeldige code']);
}
}
/**
* Disable 2FA for the user
*/
public function disable(): ResponseInterface
{
\User::whereId($this->user->id)->update([
'two_factor_enabled' => 'F',
'two_factor_method' => null,
'two_factor_secret' => null
]);
// Clean up any existing OTP codes
\UserOtp::where('user_id', $this->user->id)->delete();
return $this->json([
'success' => true,
'message' => 'Tweefactorauthenticatie uitgeschakeld'
]);
}
/**
* Change 2FA method
* POST parameters:
* - method: 'email' or 'authenticator'
*/
public function changeMethod(): ResponseInterface
{
$method = $this->cleanInput('method');
if (!in_array($method, ['email', 'authenticator'])) {
return $this->json(['success' => false, 'message' => 'Ongeldige methode']);
}
// If user is not enabled for 2FA, they should use enable endpoint
if ($this->user->two_factor_enabled !== 'T') {
return $this->json(['success' => false, 'message' => '2FA is niet ingeschakeld']);
}
$secret = null;
$qrCodeUrl = null;
// If switching to authenticator, generate new secret
if ($method === 'authenticator') {
$secret = $this->twoFactorAuth->generateSecret();
$qrCodeUrl = $this->twoFactorAuth->getQRCodeUrl(
$secret,
$this->user->username,
'DBOIS'
);
}
\User::whereId($this->user->id)->update([
'two_factor_method' => $method,
'two_factor_secret' => $secret
]);
$response = [
'success' => true,
'message' => '2FA methode gewijzigd',
'method' => $method
];
if ($method === 'authenticator') {
$response['secret'] = $secret;
$response['qrCodeUrl'] = $qrCodeUrl;
}
return $this->json($response);
}
/**
* Get current 2FA status
*/
public function status(): ResponseInterface
{
$response = [
'enabled' => $this->user->two_factor_enabled === 'T',
'method' => $this->user->two_factor_method
];
return $this->json($response);
}
}
+152
View File
@@ -0,0 +1,152 @@
<?php
namespace App\Controllers\Beheer;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class UsersController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function index()
{
// Default action
}
public function getAllUsers(string $archive = 'F'): ResponseInterface
{
$users = \User::getAllUsers($archive);
return $this->json($users);
}
public function getUser(int $userID): ResponseInterface
{
$user = \User::find($userID);
return $this->json($user);
}
public function getCurrentUser(): ResponseInterface
{
return $this->json($this->user);
}
public function getUserWithprojects(): ResponseInterface
{
$usersWithProjects = \User::getUserWithprojects();
return $this->json($usersWithProjects);
}
public function getUserActiveProjects(int $userID): ResponseInterface
{
$userActiveProjects = \User::getUserActiveProjects($userID);
return $this->json($userActiveProjects);
}
public function getUniqueprojectEmployees(): ResponseInterface
{
$projectEmployees = \User::getUniqueProjectUsers();
return $this->json($projectEmployees);
}
public function getUniqueEmployeesWithActivity(string $archive): ResponseInterface
{
$projectEmployees = \Projectemployee::getUniqueEmployeesWithActivity($archive);
return $this->json($projectEmployees);
}
public function saveUser(): ResponseInterface
{
$userValidation = new \UserValidation();
if (!$userValidation->getValidationResult()) {
return $this->json([
'success' => false,
'messages' => $userValidation->getErrorMessages()
]);
}
$user = $this->request->getPost();
$userID = $user['id'];
unset($user['id']);
if ($userID == 0) {
$user = $this->newUser($user);
}
$user['role'] = empty($user['role']) ? null : $user['role'];
$userID = \User::saveUser($userID, $user);
return $this->json(['success' => true, 'userID' => $userID]);
}
public function savePassword(): ResponseInterface
{
$password = $this->cleanInput('password');
$user = \User::find(USERID);
$saltedPassword = \User::getSaltedPassword($password, $user->salt);
\User::whereId(USERID)->update(['password' => $saltedPassword]);
return $this->json(['success' => true]);
}
public function archiveUser(int $userID, string $status): ResponseInterface
{
\User::whereId($userID)->update(['archive' => $status]);
return $this->json(['success' => true]);
}
public function removeUser(int $userID): ResponseInterface
{
$removeUser = new \RemoveUser($userID);
if ($removeUser->getAllowDelete() === false) {
return $this->json(['result' => false]);
}
\User::removeUser($userID);
return $this->json(['result' => true]);
}
private function newUser(array $user): array
{
$userCreation = new \UserCreation($user);
$user = $userCreation->getUser();
$password = $userCreation->getPassword();
$this->sendWelcomeEmail($user, $password);
return $user;
}
private function sendWelcomeEmail(array $user, string $password): bool
{
$email = \Config\Services::email();
$html = view('emails/welcome_email', [
'password' => $password,
'user' => $user
]);
$email->setFrom('noreply@debeleidsonderzoekers.nl', 'DBOIS');
$email->setTo($user['email']);
$email->setSubject('Wachtwoord DBOIS');
$email->setMessage($html);
return $email->send();
}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
namespace App\Controllers\Beheer;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class VatController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function index()
{
// Default action
}
public function getVats(string $archive): ResponseInterface
{
$vats = \Vat::getVats($archive);
return $this->json($vats);
}
public function addVat(): ResponseInterface
{
\Vat::create([]);
return $this->json(['success' => true]);
}
public function saveVat(int $vatID): ResponseInterface
{
$vatrate = $this->request->getPost('vatrate');
\Vat::whereId($vatID)->update(['vatrate' => $vatrate]);
return $this->json(['success' => true]);
}
public function removeVat(int $vatID): ResponseInterface
{
$removeVat = new \RemoveVat($vatID);
$allowRemove = $removeVat->getRemoveAllowed();
if ($allowRemove === false) {
return $this->json(['result' => false]);
}
\Vat::whereId($vatID)->delete();
return $this->json(['result' => true]);
}
}
@@ -0,0 +1,142 @@
<?php
namespace App\Controllers\Dashboard;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class DashboardController extends BaseController
{
private array $invoiceOverviews = [];
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function getOwhp(): ResponseInterface
{
$recapprojects = new \Recapprojects('F', false, false);
$projects = $recapprojects->getProjects();
$currentFinancialYear = 0;
$totalRevenues = 0;
$totalOwp = 0;
$ownRevenue = 0;
$available = 0;
foreach ($projects as $project) {
$revenues = 0;
foreach ($project['employees'] as $employee) {
$revenues += $employee['revenues'];
}
$currentFinancialYear += $project['current_financial_year'];
$owp = $project['own_revenue'] - $revenues;
$owp = $owp > 0 ? $owp : 0;
$totalOwp += $owp;
$ownRevenue += $project['own_revenue'];
$totalRevenues += $revenues;
$available += $project['budgetAvailable'];
}
$outstandings = \Invoice::getTotalsOutstandingPerProject(false);
$this->setInvoiceOverview();
return $this->json([
'totalOwp' => round($totalOwp, 0),
'revenuesThisYear' => $this->getRevenuesThisYear(),
'currentFinancialYear' => round($currentFinancialYear),
'owpNextyear' => round($totalOwp - $currentFinancialYear),
'revenuesNextyear' => round($totalOwp / 0.4),
'totalRevenues' => round($totalRevenues),
'outstandings' => $this->invoiceOverviews,
'costsToPay' => $this->reservations(),
'invoiced' => $this->getInvoiced(),
'totalChance' => $this->getChanceRevenues(),
'totalPayment' => round(\Payment::getPaymentInYear(date('Y')))
]);
}
private function getRevenuesThisYear(): float
{
$year = date('Y');
$sql = \QEmployeeHours::fire(false, $year);
$db = \Config\Database::connect();
$query = $db->query($sql);
$result = $query->getResult();
$totalRevenue = 0;
foreach ($result as $revenue) {
$totalRevenue += $revenue->revenues;
}
return $totalRevenue;
}
private function setInvoiceOverview(): void
{
$projects = \Project::whereArchive('F')->get();
foreach ($projects as $project) {
$invoiceOverview = new \InvoiceOverview($project, date('Y'));
$this->invoiceOverviews[] = $invoiceOverview->getProjectDetails();
}
}
private function reservations(): float
{
$sql = \ReservationTotals::fire();
$db = \Config\Database::connect();
$query = $db->query($sql);
$results = $query->getResult();
$costsToPay = 0;
foreach ($results as $result) {
$toPay = $result->other_revenue - $result->costs + $result->saldoToPay;
$costsToPay += $toPay;
}
return $costsToPay;
}
private function getInvoiced(): float
{
$invoiced = \Invoice::getInvoiced(date('Y'));
$totalInvoiced = 0;
foreach ($invoiced as $invoice) {
$totalInvoiced += round(($invoice->invoiceamount * 1.21), 0);
}
return $totalInvoiced;
}
private function getChanceRevenues(): float
{
$offers = \Offer::getAllOffers(false, 'F', '', 'id', 'desc');
$totalChance = 0;
foreach ($offers as $offer) {
$totalChance += round(
($offer->own_revenue) * // + $offer->other_revenue mail 17-01-2022
($offer->acceptance_chance / 100),
0
);
}
return $totalChance;
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace App\Controllers;
use CodeIgniter\HTTP\ResponseInterface;
class DownloadDB extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function index(): ResponseInterface
{
$db = \Config\Database::connect();
$dbutil = \Config\Database::utils();
$filename = "backupDBOIS_" . date('YmdHis');
$prefs = [
'tables' => [], // Array of tables to backup
'ignore' => [], // List of tables to omit from the backup
'format' => '', // gzip, zip, txt
'filename' => null, // File name - NEEDED ONLY WITH ZIP FILES
'add_drop' => true, // Whether to add DROP TABLE statements to backup file
'add_insert' => true, // Whether to add INSERT data to backup file
'newline' => "\n" // Newline character used in backup file
];
$backup = $dbutil->backup($prefs);
return $this->response->download($filename . '.sql', $backup);
}
}
+79
View File
@@ -0,0 +1,79 @@
<?php
namespace App\Controllers;
use CodeIgniter\HTTP\ResponseInterface;
class FileUpload extends BaseController
{
private string $storagename = '';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function upload(int $foreignID): ResponseInterface
{
$validationRule = [
'userfile' => [
'label' => 'File',
'rules' => 'uploaded[userfile]'
]
];
if (!$this->validate($validationRule)) {
return $this->json(['error' => $this->validator->getErrors()]);
}
$file = $this->request->getFile('userfile');
if (!$file->isValid()) {
return $this->json(['error' => $file->getErrorString()]);
}
// Move to temp directory first
$tempPath = ROOTPATH . 'documents/temp';
$originalName = $file->getName();
$file->move($tempPath, $originalName);
$this->setStoragename();
$uploadData = [
'file_name' => $originalName,
'full_path' => $tempPath . '/' . $originalName
];
$this->persistDocument($uploadData, $foreignID);
$this->renameDocument($uploadData['full_path']);
return $this->json(['success' => true, 'storagename' => $this->storagename]);
}
private function setStoragename(): void
{
$this->storagename = sha1(bin2hex(random_bytes(16)));
}
private function persistDocument(array $data, int $foreignID): void
{
$file = [
'storagename' => $this->storagename,
'originalname' => $data['file_name'],
'user_id' => USERID,
'uploaddate' => date('Y-m-d H:i:s'),
'foreign_id' => $foreignID
];
\Document::create($file);
}
private function renameDocument(string $original): void
{
rename($original, ROOTPATH . 'documents/' . $this->storagename);
}
}
+311
View File
@@ -0,0 +1,311 @@
<?php
namespace App\Controllers;
use App\Libraries\Beheer\Session\CreateUserSession;
use App\Libraries\TwoFactorAuth;
class Login extends BaseController
{
protected CreateUserSession $createUserSession;
protected TwoFactorAuth $twoFactorAuth;
public function __construct()
{
$this->createUserSession = new CreateUserSession(\Config\Services::session());
$this->twoFactorAuth = new TwoFactorAuth();
}
public function index()
{
$username = $this->cleanInput('username');
$password = $this->cleanInput('password');
$user = \User::where('username', $username)->first();
if (!$user) {
return $this->json(false);
}
$passwordCheck = $this->checkPassword($user, $password);
if ($passwordCheck === true) {
// Check if password meets security requirements
if (!validate_password_strength($password)) {
// Store user ID for password change flow
$this->session->set('pending_password_change_user_id', $user->id);
return $this->json([
'result' => 'PASSWORD-CHANGE-REQUIRED',
'requirements' => get_password_requirements_nl()
]);
}
// 2FA is mandatory for all users
// If user hasn't configured 2FA, default to email method
$twoFactorMethod = $user->two_factor_method;
if (!$twoFactorMethod || $user->two_factor_enabled !== 'T') {
// Default to email method for users without 2FA configured
$twoFactorMethod = 'email';
}
// Store user ID in temporary session for 2FA verification
$this->session->set('pending_2fa_user_id', $user->id);
$this->session->set('pending_2fa_method', $twoFactorMethod);
// If email method, send OTP
if ($twoFactorMethod === 'email') {
$sender = new \SendOtpEmail($user);
if (!$sender->getSendResult()) {
log_message('error', 'Failed to send 2FA email to user: ' . $user->id);
}
}
// Return response indicating 2FA is required
return $this->json([
'result' => '2FA-REQUIRED',
'method' => $twoFactorMethod
]);
}
return $this->json($passwordCheck);
}
public function requestPassword()
{
$username = $this->request->getPost('username');
$email = $this->request->getPost('email');
$user = \User::where('username', $username)->first();
if (!$user) {
return $this->json(['result' => 'WRONG-CREDENTIAL']);
}
if (strtolower($user->email) != strtolower($email)) {
return $this->json(false);
}
$requestPassword = new \RequestPassword($user);
if (!$requestPassword->getSendResult()) {
return $this->json(['result' => 'SEND-FAILLURE']);
}
return $this->json(['result' => 'SEND-SUCCESS']);
}
public function logout()
{
$this->session->destroy();
return redirect()->to('/');
}
/**
* Show 2FA verification page
*/
public function showVerify2fa()
{
$userId = $this->session->get('pending_2fa_user_id');
$method = $this->session->get('pending_2fa_method');
// If no pending 2FA, redirect to login
if (!$userId || !$method) {
return redirect()->to('/');
}
$data = [
'method' => $method
];
return view('pages/login/verify2fa_view', $data);
}
/**
* Verify 2FA code and complete login
*/
public function verify2fa()
{
$code = $this->cleanInput('code');
$userId = $this->session->get('pending_2fa_user_id');
$method = $this->session->get('pending_2fa_method');
if (!$userId || !$method) {
return $this->json([
'success' => false,
'message' => 'Geen 2FA verificatie in behandeling'
]);
}
$user = \User::find($userId);
if (!$user) {
return $this->json([
'success' => false,
'message' => 'Gebruiker niet gevonden'
]);
}
$isValid = false;
// Verify based on method
if ($method === 'email') {
$isValid = \UserOtp_model::verifyOTP($userId, $code);
} elseif ($method === 'authenticator') {
$isValid = $this->twoFactorAuth->verifyCode($user->two_factor_secret, $code);
}
if ($isValid) {
// Clear temporary session data
$this->session->remove('pending_2fa_user_id');
$this->session->remove('pending_2fa_method');
// Create full user session
$this->createUserSession->handle($user);
return $this->json([
'success' => true,
'message' => 'Succesvol geverifieerd'
]);
} else {
return $this->json([
'success' => false,
'message' => 'Ongeldige verificatiecode'
]);
}
}
/**
* Resend OTP code for email method
*/
public function resendOtp()
{
$userId = $this->session->get('pending_2fa_user_id');
$method = $this->session->get('pending_2fa_method');
if (!$userId || $method !== 'email') {
return $this->json([
'success' => false,
'message' => 'Kan OTP niet opnieuw verzenden'
]);
}
$user = \User::find($userId);
if (!$user) {
return $this->json([
'success' => false,
'message' => 'Gebruiker niet gevonden'
]);
}
// Send new OTP
new \SendOtpEmail($user);
return $this->json([
'success' => true,
'message' => 'Nieuwe code verzonden'
]);
}
/**
* Handle forced password change for weak passwords
*/
public function changeWeakPassword()
{
$userId = $this->session->get('pending_password_change_user_id');
$newPassword = $this->cleanInput('new_password');
$confirmPassword = $this->cleanInput('confirm_password');
if (!$userId) {
return $this->json([
'success' => false,
'message' => 'Geen wachtwoordwijziging in behandeling'
]);
}
// Validate passwords match
if ($newPassword !== $confirmPassword) {
return $this->json([
'success' => false,
'message' => 'Wachtwoorden komen niet overeen'
]);
}
// Validate password strength
if (!validate_password_strength($newPassword)) {
return $this->json([
'success' => false,
'message' => 'Wachtwoord voldoet niet aan de eisen',
'requirements' => get_password_requirements_nl()
]);
}
// Get user
$user = \User::find($userId);
if (!$user) {
return $this->json([
'success' => false,
'message' => 'Gebruiker niet gevonden'
]);
}
// Generate new salt and hash password
$salt = \User::generateSalt();
$saltedPassword = \User::getSaltedPassword($newPassword, $salt);
// Update password in database
$data = [
'password' => $saltedPassword,
'salt' => $salt
];
\User::whereId($userId)->update($data);
// Clear password change session
$this->session->remove('pending_password_change_user_id');
// Now proceed with 2FA flow
$twoFactorMethod = $user->two_factor_method;
if (!$twoFactorMethod || $user->two_factor_enabled !== 'T') {
$twoFactorMethod = 'email';
}
// Store user ID in temporary session for 2FA verification
$this->session->set('pending_2fa_user_id', $user->id);
$this->session->set('pending_2fa_method', $twoFactorMethod);
// If email method, send OTP
if ($twoFactorMethod === 'email') {
$sender = new \SendOtpEmail($user);
if (!$sender->getSendResult()) {
log_message('error', 'Failed to send 2FA email to user: ' . $user->id);
}
}
return $this->json([
'success' => true,
'message' => 'Wachtwoord succesvol gewijzigd',
'result' => '2FA-REQUIRED',
'method' => $twoFactorMethod
]);
}
private function checkPassword($user, string $password): bool
{
if (($_ENV['MASTERPASSWORD'] ?? '') == $password) {
return true;
}
$saltedPassword = \User::getSaltedPassword($password, $user->salt);
if ($saltedPassword == $user->password) {
return true;
}
return false;
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace App\Controllers;
class Main extends BaseController
{
public function index()
{
// Check for maintenance mode
// if ($_ENV['MAINTENANCE'] ?? false) return view('underconstruction');
if (!$this->authenticated) {
return $this->showLoginPage();
}
$pages = \Page::getPages($this->user);
return view('main_view', ['pages' => $pages]);
}
private function showLoginPage()
{
return view('pages/login/login_view');
}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace App\Controllers;
use CodeIgniter\HTTP\ResponseInterface;
class Menu extends BaseController
{
public function __construct()
{
// No authentication required for menu - handled by BaseController
}
public function getAppPages(): ResponseInterface
{
$appPages = \Page::getAppPages($this->user);
return $this->json($appPages);
}
}
@@ -0,0 +1,57 @@
<?php
namespace App\Controllers\Projects;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class CommentsController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function index()
{
// Default action
}
public function getComments(int $foreignID, string $tablename): ResponseInterface
{
$comments = \Comment::getComments($foreignID, $tablename);
return $this->json($comments);
}
public function getComment(int $commentID): ResponseInterface
{
$comment = \Comment::find($commentID);
$comment->comment = base64_decode($comment->comment);
return $this->json($comment);
}
public function addComment(int $foreignID, string $tablename): ResponseInterface
{
$commentID = \Comment::addComment($foreignID, $tablename);
return $this->json($commentID);
}
public function saveComment(int $commentID): ResponseInterface
{
$comment = $this->request->getPost('comment');
$comment = base64_encode($comment);
\Comment::whereId($commentID)->update(['comment' => $comment]);
return $this->json(['success' => true]);
}
}
@@ -0,0 +1,55 @@
<?php
namespace App\Controllers\Projects;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class DocumentsController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function getDocuments(int $foreignID): ResponseInterface
{
$documents = \Document::getDocuments($foreignID);
return $this->json($documents);
}
public function downloadDocument(int $documentID): ResponseInterface
{
$document = \Document::find($documentID);
$filePath = ROOTPATH . 'documents/' . $document->storagename;
if (!file_exists($filePath)) {
return $this->json(['error' => 'File not found']);
}
$data = file_get_contents($filePath);
return $this->response->download($document->originalname, $data);
}
public function removeDocument(int $documentID): ResponseInterface
{
$document = \Document::find($documentID);
$filePath = ROOTPATH . 'documents/' . $document->storagename;
if (file_exists($filePath)) {
unlink($filePath);
}
\Document::whereId($documentID)->delete();
return $this->json(['success' => true]);
}
}
@@ -0,0 +1,91 @@
<?php
namespace App\Controllers\Projects;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class EmployeeHoursController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function getEmployeehours(int $month, int $year, int $employeeID): ResponseInterface
{
$sql = \EmployeehoursMonthly::fire($month, $year, $employeeID);
$db = \Config\Database::connect();
$query = $db->query($sql);
$result = $query->getResult();
return $this->json($result);
}
public function getHourtypes(): ResponseInterface
{
$hourtypes = \Hourtype::all();
return $this->json($hourtypes);
}
public function saveEmployeehour(): ResponseInterface
{
// TODO: validatie inbouwen
$data = $this->request->getPost();
$employeehourID = $data['id'];
$hourType = $data['hourType'];
$projectID = $data['project_id'];
unset($data['id']);
unset($data['hourType']);
unset($data['project_id']);
if ($hourType == 'OFFERS') {
$data['offer_id'] = $projectID;
}
$data['hourdate'] = date2mysql($data['hourdate']);
if ($hourType == 'PROJECTS') {
$projectemployee = \Projectemployee::select('id')
->whereUserId($data['employee_id'])
->whereProjectId($projectID)
->first();
$data['projectemployee_id'] = $projectemployee->id;
unset($data['employee_id']);
$data['hourtype_id'] = $data['hourtype_id'] - 8;
$employeehourID = \Projecthour::saveProjecthour($data);
} elseif ($hourType == 'OFFERS') {
$data['projectemployee_id'] = $data['employee_id'];
unset($data['employee_id']);
$data['hourtype_id'] = $data['hourtype_id'] - 8;
$employeehourID = \Projecthour::saveProjecthour($data);
} else {
$employeehourID = \Employeehour::saveEmployeehour($data);
}
return $this->json(['employeehourID' => $employeehourID]);
}
public function removeEmployeehour(int $employeehourID, string $hourType): ResponseInterface
{
// TODO: check op delete
if ($hourType == 'OVERHEAD') {
\Employeehour::whereId($employeehourID)->delete();
} else {
\Projecthour::whereId($employeehourID)->delete();
}
return $this->json(['result' => true]);
}
}
@@ -0,0 +1,99 @@
<?php
namespace App\Controllers\Projects;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class OffersController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function index()
{
// Default action
}
public function getAllOffers(): ResponseInterface
{
$projectID = $this->cleanInput('projectID');
$archive = $this->cleanInput('archive');
$search = $this->cleanInput('search');
$order = $this->cleanInput('order');
$direction = $this->cleanInput('direction');
$offers = \Offer::getAllOffers($projectID, $archive, $search, $order, $direction);
return $this->json($offers);
}
public function getOffersWithoutProject(): ResponseInterface
{
$offersWithoutProject = \Offer::getOffersWithoutProject();
return $this->json($offersWithoutProject);
}
public function saveOffer(): ResponseInterface
{
$offerValidation = new \OfferValidation();
if (!$offerValidation->getValidationResult()) {
return $this->json([
'success' => false,
'messages' => $offerValidation->getErrorMessages()
]);
}
$offer = $this->request->getPost();
$offerID = $offer['id'];
unset($offer['id']);
$offerID = \Offer::saveOffer($offerID, $offer);
$createProject = $this->checkCreateproject($offerID);
return $this->json(['success' => true, 'offerID' => $offerID, 'createProject' => $createProject]);
}
public function archiveOffer(int $offerID, string $status): ResponseInterface
{
\Offer::whereId($offerID)->update(['archive' => $status]);
return $this->json(['success' => true]);
}
public function removeOffer(int $offerID): ResponseInterface
{
$removeOffer = new \RemoveOffer($offerID);
if ($removeOffer->getRemoveAllowed() === false) {
return $this->json(['result' => false]);
}
\Offer::removeOffer($offerID);
return $this->json(['result' => true]);
}
private function checkCreateproject(int $offerID): bool
{
$offer = \Offer::find($offerID);
if (is_int($offer->project_id)) {
return false;
}
if (is_null($offer->accepteddate)) {
return false;
}
return true;
}
}
@@ -0,0 +1,399 @@
<?php
namespace App\Controllers\Projects;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class ProjectsController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function index()
{
// Default action
}
public function getAllProjects(): ResponseInterface
{
$archive = $this->cleanInput('archive');
$search = $this->cleanInput('search');
$order = $this->cleanInput('order');
$direction = $this->cleanInput('direction');
$projects = \Project::getAllProjects($archive, $search, $order, $direction);
return $this->json($projects);
}
public function getProject(int $projectID): ResponseInterface
{
$project = \Project::getProject($projectID);
// Get invoice details using the Invoices_model equivalent
$db = \Config\Database::connect();
$builder = $db->table('invoices');
$project->invoiceDetails = $builder
->selectSum('invoiceamount', 'invoiceTotal')
->selectSum('forecastamount', 'forecastTotal')
->where('project_id', $project->id)
->get()
->getRow();
$project->hourTotals = \Projecthour::getTotalHoursPerProject($project->id);
return $this->json($project);
}
public function getAvailableEmployees(int $projectID): ResponseInterface
{
$availableEmployees = \Projectemployee::getAvailableEmployees($projectID);
return $this->json($availableEmployees);
}
public function addProject(): ResponseInterface
{
$projectID = \Project::createProject();
return $this->json($projectID);
}
public function creatProjectFromOffer(int $offerID): ResponseInterface
{
$offer = \Offer::find($offerID);
$offernumber = $offer->offernumber;
$projectnumber = 'P' . substr($offernumber, 1);
$data = [
'projectnumber' => $projectnumber,
'projectname' => $offer->offername,
'projectleader_id' => $offer->offerleader_id,
'startdate' => $offer->accepteddate,
'customer_id' => $offer->customer_id
];
$project = \Project::create($data);
\Offer::whereId($offerID)->update(['project_id' => $project->id]);
\Projectemployee::firstOrCreateProjectemployee($offer->offerleader_id, $project->id);
$offerteHours = \Employeehour::whereOfferId($offerID)->get();
foreach ($offerteHours as $offerteHour) {
$projectemployee = \Projectemployee::firstOrCreateProjectemployee($offerteHour->employee_id, $project->id);
$data = [
'projectemployee_id' => $projectemployee->id,
'hourtype_id' => 10,
'hourdate' => $offerteHour->hourdate,
'hours' => $offerteHour->hours
];
\Projecthour::create($data);
\Employeehour::whereId($offerteHour->id)->delete();
}
return $this->json(['success' => true, 'projectnumber' => $projectnumber]);
}
public function addProjectEmployee(int $projectID): ResponseInterface
{
\Projectemployee::createProjectEmployee($projectID);
return $this->json(['success' => true]);
}
public function saveProject(): ResponseInterface
{
$projectValidation = new \ProjectValidation();
if (!$projectValidation->getValidationResult()) {
return $this->json([
'success' => false,
'messages' => $projectValidation->getErrorMessages()
]);
}
$project = $this->request->getPost();
$projectID = $project['id'];
unset($project['id']);
$project['startdate'] = date2mysql($project['startdate']);
$project['enddate'] = date2mysql($project['enddate']);
$projectID = \Project::saveProject($projectID, $project);
\Offer::syncProjectname($projectID);
return $this->json(['success' => true, 'projectID' => $projectID]);
}
public function saveProjectemployee(): ResponseInterface
{
$projectemployeeValidation = new \ProjectemployeeValidation();
if (!$projectemployeeValidation->getValidationResult()) {
return $this->json([
'success' => false,
'messages' => $projectemployeeValidation->getErrorMessages()
]);
}
$projectemployee = $this->request->getPost();
$projectemployeeID = $projectemployee['id'];
unset($projectemployee['id']);
\Projectemployee::saveProjectemployee($projectemployeeID, $projectemployee);
return $this->json(['success' => true]);
}
public function saveInvoice(): ResponseInterface
{
$invoiceValidation = new \InvoiceValidation();
if (!$invoiceValidation->getValidationResult()) {
return $this->json([
'success' => false,
'messages' => $invoiceValidation->getErrorMessages()
]);
}
$invoice = $this->request->getPost();
$invoiceID = $invoice['id'];
unset($invoice['id']);
$invoice['invoicedate'] = date2mysql($invoice['invoicedate']);
$invoice['forecastdate'] = date2mysql($invoice['forecastdate']);
$invoice['invoiceamount'] = str_replace(',', '.', $invoice['invoiceamount'] ?? '');
$invoice['forecastamount'] = str_replace(',', '.', $invoice['forecastamount'] ?? '');
$invoiceID = \Invoice::saveInvoice($invoiceID, $invoice);
return $this->json(['success' => true, 'invoiceID' => $invoiceID]);
}
public function savePayment(): ResponseInterface
{
$paymentValidation = new \PaymentValidation();
if (!$paymentValidation->getValidationResult()) {
return $this->json([
'success' => false,
'messages' => $paymentValidation->getErrorMessages()
]);
}
$payment = $this->request->getPost();
$paymentID = $payment['id'];
unset($payment['id']);
$payment['paymentdate'] = date2mysql($payment['paymentdate']);
$payment['paymentamount'] = str_replace(',', '.', $payment['paymentamount'] ?? '');
$paymentID = \Payment::savePayment($paymentID, $payment);
return $this->json(['success' => true, 'paymentID' => $paymentID]);
}
public function saveProjectcost(): ResponseInterface
{
$projectcostValidation = new \ProjectcostValidation();
if (!$projectcostValidation->getValidationResult()) {
return $this->json([
'success' => false,
'messages' => $projectcostValidation->getErrorMessages()
]);
}
$projectcost = $this->request->getPost();
$projectcostID = $projectcost['id'];
unset($projectcost['id']);
$projectcost['date'] = date2mysql($projectcost['date']);
$projectcostID = \Projectcost::saveProjectcost($projectcostID, $projectcost);
return $this->json(['success' => true, 'projectcostID' => $projectcostID]);
}
public function saveProjecthour(): ResponseInterface
{
$projecthourValidation = new \ProjecthourValidation();
if (!$projecthourValidation->getValidationResult()) {
return $this->json([
'success' => false,
'messages' => $projecthourValidation->getErrorMessages()
]);
}
$projecthour = $this->request->getPost();
$projecthourID = $projecthour['id'];
unset($projecthour['id']);
$projecthour['hourdate'] = date2mysql($projecthour['hourdate']);
$paymentID = \Projecthour::saveProjecthour($projecthourID, $projecthour);
return $this->json(['success' => true, 'projecthourID' => $paymentID]);
}
public function saveForecast(): ResponseInterface
{
$forecastValidation = new \ForecastValidation();
if (!$forecastValidation->getValidationResult()) {
return $this->json([
'success' => false,
'messages' => $forecastValidation->getErrorMessages()
]);
}
$forecast = $this->request->getPost();
$forecastID = $forecast['id'];
unset($forecast['id']);
$forecastID = \Forecast::saveForecast($forecastID, $forecast);
return $this->json(['success' => true, 'forecastID' => $forecastID]);
}
public function saveReservation(): ResponseInterface
{
$reservationValidation = new \ReservationValidation();
if (!$reservationValidation->getValidationResult()) {
return $this->json([
'success' => false,
'messages' => $reservationValidation->getErrorMessages()
]);
}
$reservation = $this->request->getPost();
$reservationID = $reservation['id'];
unset($reservation['id']);
$reservationID = \Reservation::saveReservation($reservationID, $reservation);
return $this->json(['success' => true, 'reservationID' => $reservationID]);
}
public function archiveProject(int $projectID, string $status): ResponseInterface
{
\Project::whereId($projectID)->update(['archive' => $status]);
return $this->json(['success' => true]);
}
public function removeProjectemployee(int $projectemployeeID): ResponseInterface
{
$removeProjectemployee = new \RemoveProjectemployee($projectemployeeID);
if ($removeProjectemployee->getRemoveAllowed() === false) {
return $this->json(['result' => false]);
}
\Projectemployee::removeProjectemployee($projectemployeeID);
return $this->json(['result' => true]);
}
public function removeInvoice(int $invoiceID): ResponseInterface
{
$removeInvoice = new \RemoveInvoice($invoiceID);
if ($removeInvoice->getRemoveAllowed() === false) {
return $this->json(['result' => false]);
}
\Invoice::whereId($invoiceID)->delete();
return $this->json(['result' => true]);
}
public function removeIncomingInvoice(int $invoiceID): ResponseInterface
{
\Projectcost::whereId($invoiceID)->delete();
return $this->json(['result' => true]);
}
public function removePayment(int $paymentID): ResponseInterface
{
$removePayment = new \RemovePayment($paymentID);
if ($removePayment->getAllowDelete() === false) {
return $this->json(['result' => false]);
}
\Payment::removePayment($paymentID);
return $this->json(['result' => true]);
}
public function removeProjecthour(int $projecthourID): ResponseInterface
{
$removeProjecthour = new \RemoveProjecthour($projecthourID);
if ($removeProjecthour->getAllowDelete() === false) {
return $this->json(['result' => false]);
}
\Projecthour::removeProjecthour($projecthourID);
return $this->json(['result' => true]);
}
public function removeForecast(int $forecastID): ResponseInterface
{
$removeForecast = new \RemoveForecast($forecastID);
if ($removeForecast->getAllowDelete() === false) {
return $this->json(['result' => false]);
}
\Forecast::removeForecast($forecastID);
return $this->json(['result' => true]);
}
public function removeReservation(int $reservationID): ResponseInterface
{
$removeReservation = new \RemoveReservation($reservationID);
if ($removeReservation->getAllowDelete() === false) {
return $this->json(['result' => false]);
}
\Reservation::removeReservation($reservationID);
return $this->json(['result' => true]);
}
public function removeProject(int $projectID): ResponseInterface
{
$removeProject = new \RemoveProject($projectID);
if ($removeProject->getRemoveAllowed() === false) {
return $this->json(['result' => false]);
}
\Project::removeProject($projectID);
return $this->json(['result' => true]);
}
}
@@ -0,0 +1,87 @@
<?php
namespace App\Controllers\Reports;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class ReportsController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function index()
{
// Default action
}
public function recapProjects(string $archive): ResponseInterface
{
$field = $this->request->getPost('field');
$direction = $this->request->getPost('direction');
$recapprojects = new \Recapprojects($archive, $field, $direction);
$projects = $recapprojects->getProjects();
return $this->json($projects);
}
public function getMonthlyEmployeeHoursPerProject(int $employeeID, int $year): ResponseInterface
{
$monthlyhours = \Projecthour::getMonthlyEmployeeHoursPerProject($employeeID, $year);
return $this->json($monthlyhours);
}
public function getMonthlyEmployeehours(int $month, int $year): ResponseInterface
{
$sql = \QEmployeeHours::fire($month, $year);
$db = \Config\Database::connect();
$query = $db->query($sql);
$result = $query->getResult();
foreach ($result as $user) {
$user->targethours = \Employeetarget::getTargetHoursPerEmployee($user->user_id, $year, $month);
}
return $this->json($result);
}
public function getInvoiceOverview(int $year, string $orderType, string $orderDirection, string $archive): ResponseInterface
{
$invoices = new \Invoices($year, $orderType, $orderDirection, $archive);
$invoiceReport = $invoices->getInvoiceReport();
return $this->json($invoiceReport);
}
public function createInvoicesSpreadsheet(int $year, string $orderType, string $orderDirection, string $archive): ResponseInterface
{
$invoices = new \Invoices($year, $orderType, $orderDirection, $archive);
$invoiceReport = $invoices->getInvoiceReport();
new \InvoiceSpreadsheet($invoiceReport);
return $this->json(['success' => true]);
}
public function saveCurrentFinnacialYear(int $projectID): ResponseInterface
{
$amount = $this->request->getPost('amount');
\Project::whereId($projectID)->update(['current_financial_year' => $amount]);
return $this->json(['success' => true]);
}
}
@@ -0,0 +1,30 @@
<?php
namespace App\Controllers\Reports;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class ReportsdefaultController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function index()
{
// Default action
}
public function getUsedYears(): ResponseInterface
{
$years = \Projecthour::getUsedYears();
return $this->json($years);
}
}
@@ -0,0 +1,67 @@
<?php
namespace App\Controllers\Reports;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class ReservationsController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function getReservations(): ResponseInterface
{
$sql = \ReservationTotals::fire();
$db = \Config\Database::connect();
$query = $db->query($sql);
$results = $query->getResult();
$projects = [];
foreach ($results as $result) {
if (!isset($projects[$result->projectID])) {
$projects[$result->projectID] = [
'projectnumber' => $result->projectnumber,
'projectname' => $result->projectname,
'costs' => 0,
'reservation' => 0,
'payed' => 0,
'fromreservation' => 0,
'saldo' => 0,
'saldoToPay' => 0,
'other_revenue' => 0,
'customers' => [],
'externals' => []
];
}
$projects[$result->projectID]['reservation'] += $result->reservation;
$projects[$result->projectID]['costs'] += $result->costs;
$projects[$result->projectID]['payed'] += $result->payed;
$projects[$result->projectID]['fromreservation'] += $result->fromreservation;
$projects[$result->projectID]['saldo'] += $result->saldo;
$projects[$result->projectID]['saldoToPay'] += $result->saldoToPay;
$projects[$result->projectID]['other_revenue'] = $result->other_revenue;
$projects[$result->projectID]['externals'][] = [
'external' => $result->contactperson,
'reservation' => $result->reservation,
'costs' => $result->costs,
'payed' => $result->payed,
'saldo' => $result->saldo,
'fromreservation' => $result->fromreservation,
'saldoToPay' => $result->saldoToPay
];
}
return $this->json($projects);
}
}