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
@@ -0,0 +1,36 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 27/12/2017
* Time: 17:45
*/
class RemoveCustomer {
private $customerID;
private $allowDelete = TRUE;
public function __construct( $userID )
{
$this->setCustomerID( $userID );
$this->handle();
}
public function getAllowDelete()
{
return $this->allowDelete;
}
private function setCustomerID( $customerID )
{
$this->customerID = $customerID;
}
private function handle()
{
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 27/12/2017
* Time: 17:45
*/
class RemoveExternal {
private $externalID;
private $allowDelete = TRUE;
public function __construct( $userID )
{
$this->setExternalID( $userID );
$this->handle();
}
public function getAllowDelete()
{
return $this->allowDelete;
}
private function setExternalID( $externalID )
{
$this->externalID = $externalID;
}
private function handle()
{
}
}
@@ -0,0 +1,42 @@
<?php
namespace App\Libraries\Beheer\Session;
use CodeIgniter\Session\Session;
class CreateUserSession
{
private Session $session;
private object $user;
private array $sessionArray = [];
public function __construct(Session $session)
{
$this->session = $session;
}
public function handle(object $user): void
{
$this->setUser($user);
$this->setSessionArray();
$this->createSession();
}
private function setUser(object $user): void
{
$this->user = $user;
}
private function setSessionArray(): void
{
$this->sessionArray = [
'userID' => $this->user->id,
'role' => $this->user->role
];
}
private function createSession(): void
{
$this->session->set($this->sessionArray);
}
}
@@ -0,0 +1,45 @@
<?php
namespace App\Libraries\Beheer\Session;
use CodeIgniter\Session\Session;
class RetrieveUserSession
{
private Session $session;
public function __construct(Session $session)
{
$this->session = $session;
}
public function handle(): void
{
$this->setUserID();
$this->setRole();
$this->setAuthenticated();
}
private function setUserID(): void
{
$userId = $this->session->get('userID');
if (!defined('USERID')) {
define('USERID', $userId);
}
}
private function setRole(): void
{
$role = $this->session->get('role');
if (!defined('ROLE')) {
define('ROLE', $role);
}
}
private function setAuthenticated(): void
{
if (!defined('AUTHENTICATED')) {
define('AUTHENTICATED', USERID ? true : false);
}
}
}
@@ -0,0 +1,101 @@
<?php
/**
* Send OTP Email Library
* Generates and sends a one-time password via email for two-factor authentication
*/
class SendOtpEmail
{
private $user;
private $otpCode;
private $sendResult = false;
public function __construct($user)
{
$this->user = $user;
$this->handle();
}
/**
* Get the result of the email send operation
* @return bool True if email was sent successfully
*/
public function getSendResult()
{
return $this->sendResult;
}
/**
* Get the generated OTP code (for testing purposes)
* @return string The OTP code
*/
public function getOtpCode()
{
return $this->otpCode;
}
/**
* Main handler for OTP email process
*/
private function handle()
{
$this->generateOTP();
$this->sendOTPEmail();
}
/**
* Generate a new OTP code
*/
private function generateOTP()
{
// Generate OTP valid for 10 minutes
$this->otpCode = \UserOtp_model::generateOTP($this->user->id, 10);
}
/**
* Send the OTP code via email
*/
private function sendOTPEmail()
{
$email = \Config\Services::email();
// Build email configuration directly from environment variables
$config = [
'protocol' => str_replace(',', '', $_ENV['PROTOCOL'] ?? 'smtp'),
'SMTPHost' => str_replace(',', '', $_ENV['SMTP_HOST'] ?? ''),
'SMTPUser' => str_replace(',', '', $_ENV['SMTP_USER'] ?? ''),
'SMTPPass' => str_replace(',', '', $_ENV['SMTP_PASS'] ?? ''),
'SMTPPort' => (int) str_replace(',', '', $_ENV['SMTP_PORT'] ?? 25),
'SMTPCrypto' => 'tls',
'SMTPTimeout' => 30,
'charset' => 'UTF-8',
'mailType' => 'html',
'newline' => "\r\n",
'CRLF' => "\r\n",
'wordWrap' => true,
];
$email->initialize($config);
$data = [
'username' => $this->user->username,
'firstname' => $this->user->firstname,
'middlename' => $this->user->middlename,
'lastname' => $this->user->lastname,
'otp_code' => $this->otpCode
];
$html = view('emails/twofactor_otp_email', ['user' => $data]);
$email->setFrom('noreply@dbois.nl', 'DBOIS');
$email->setTo($this->user->email);
$email->setSubject('DBOIS Tweefactorauthenticatie - Verificatiecode');
$email->setMessage($html);
$this->sendResult = $email->send();
if (!$this->sendResult) {
log_message('error', 'Failed to send 2FA OTP email to ' . $this->user->email . ': ' . $email->printDebugger());
}
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 26/12/2017
* Time: 12:39
*/
class CreateUser {
public function __construct()
{
}
}
@@ -0,0 +1,99 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 26/12/2017
* Time: 12:40
*/
class PasswordRecipe {
private $password = FALSE;
private $salt = FALSE;
private $saltedPassword;
public function __construct()
{
$this->handle();
}
public function getPassword()
{
return $this->password;
}
public function getSalt()
{
return $this->salt;
}
public function getSaltedPassword()
{
return $this->saltedPassword;
}
public function setPassword( $password )
{
$this->password = $password;
}
public function setSalt( $salt )
{
$this->salt = $salt;
}
private function handle()
{
$this->checkPassword();
$this->checkSalt();
$this->setSaltedPassword();
}
private function checkPassword()
{
if ( ! $this->password ) $this->createPassword();
if ( strlen( $this->password ) < 6 ) return;
}
private function checkSalt()
{
if ( ! $this->salt ) $this->createSalt();
}
private function createPassword()
{
$pass = $this->getRandomString( 8 );
$this->password = $pass;
}
private function createSalt()
{
$salt = $this->getRandomString( 18 );
$this->salt = sha1($salt);
}
private function setSaltedPassword()
{
$this->saltedPassword = User::getSaltedPassword( $this->password, $this->salt);
}
private function getRandomString( $length = 8 )
{
$rand = '';
$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$alphaLength = strlen( $alphabet ) - 1; //put the length -1 in cache
for ( $i = 0; $i < $length; $i ++ )
{
$n = rand( 0, $alphaLength );
$rand .= $alphabet[ $n ];
}
return $rand;
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 27/12/2017
* Time: 17:45
*/
class RemoveUser {
private $userID;
private $allowDelete=FALSE;
public function __construct( $userID )
{
$this->setUserID($userID);
$this->handle();
}
public function getAllowDelete()
{
return $this->allowDelete;
}
private function setUserID( $userID )
{
$this->userID = $userID;
}
private function handle()
{
//$this->checkIfUserHasProjects();
}
}
@@ -0,0 +1,104 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 28/07/2018
* Time: 14:31
*/
class RequestPassword {
private $ci;
private $salt;
private $user;
private $password;
private $sendResult;
private $passwordRecipe;
private $saltedPassword;
public function __construct( $user )
{
$this->ci =& get_instance();
$this->user = $user;
$this->ci->load->library( 'email' );
$this->handle();
}
public function getSendResult()
{
return $this->sendResult;
}
private function handle()
{
$this->createPassword();
$this->setPassword();
$this->setSalt();
$this->setSaltedPassword();
$this->persistNewpassword();
$this->sendNewPassword();
}
private function createPassword()
{
$this->passwordRecipe = new PasswordRecipe();
}
private function setPassword()
{
$this->password = $this->passwordRecipe->getPassword();
}
private function setSalt()
{
$this->salt = $this->passwordRecipe->getsalt();
}
private function setSaltedPassword()
{
$this->saltedPassword = $this->passwordRecipe->getSaltedPassword();
}
private function persistNewPassword()
{
$data = [
'password' => $this->saltedPassword,
'salt' => $this->salt
];
User::whereId( $this->user->id )->update( $data );
}
private function sendNewPassword()
{
$data = [
'username' => $this->user->username,
'firstname' => $this->user->firstname,
'middlename' => $this->user->middlename,
'lastname' => $this->user->lastname,
'password' => $this->password
];
$html = $this->ci->load->view( 'emails/requestpassword_email', ['user'=>$data], true );
$this->ci->email->from( 'noreply@dbois.nl', 'DBOIS' );
$this->ci->email->to( $this->user->email );
$this->ci->email->subject( 'Nieuw wachtwoord DBOIS' );
$this->ci->email->message( $html );
$this->ci->email->set_mailtype("html");
$this->ci->email->set_newline("\r\n");
$this->sendResult = $this->ci->email->send();
if( ! $this->sendResult ) log_message( 'error', json_encode($this->ci->email->print_debugger()));
}
}
@@ -0,0 +1,72 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 27/12/2017
* Time: 14:10
*/
class UserCreation {
private $user;
private $passWordRecipe;
private $password;
private $saltedPassword;
private $salt;
public function __construct( $user )
{
$this->setUser( $user );
$this->handle();
}
public function getUser()
{
return $this->user;
}
public function getPassword()
{
return $this->password;
}
private function setUser( $user )
{
$this->user = $user;
}
private function handle()
{
$this->passWordRecipe = new PasswordRecipe();
$this->setPassword();
$this->setSalt();
$this->setSaltedPassword();
$this->enrichUser();
}
private function setPassword()
{
$this->password = $this->passWordRecipe->getPassword();
}
private function setSalt()
{
$this->salt = $this->passWordRecipe->getSalt();
}
private function setSaltedPassword()
{
$this->saltedPassword = $this->passWordRecipe->getSaltedPassword();
}
private function enrichUser()
{
$this->user['password'] = $this->saltedPassword;
$this->user['salt'] = $this->salt;
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 10/06/2018
* Time: 17:06
*/
class RemoveInvoice {
private $invoiceID;
private $payments;
private $removeAllowed;
public function __construct( $invoiceID )
{
$this->setInvoiceID( $invoiceID );
$this->handle();
}
public function getRemoveAllowed()
{
return $this->removeAllowed;
}
private function setInvoiceID( $invoiceID )
{
$this->invoiceID = $invoiceID;
}
private function handle()
{
$this->setPayment();
$this->setRemoveAllowed();
}
private function setPayment()
{
$payments = Payment::whereInvoiceId( $this->invoiceID );
$this->payments = $payments->count() == 0 ? TRUE : FALSE;
}
private function setRemoveAllowed()
{
if ( $this->payments === FALSE ) return $this->removeAllowed = FALSE;
$this->removeAllowed = TRUE;
}
}
@@ -0,0 +1,46 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 10/06/2018
* Time: 15:56
*/
class RemoveInvoices {
private $invoiceID;
private $payments;
private $removeAllowed;
public function __construct( $invoiceID )
{
$this->setInvoiceID($invoiceID);
$this->handle();
}
private function setInvoiceID( $invoiceID )
{
$this->invoiceID = $invoiceID;
}
private function handle()
{
$this->setPayments();
$this->setRemoveAllowed();
}
private function setPayments()
{
$payments = Payment::whereInvoiceId($this->invoiceID);
$this->payments = $payments->count() == 0 ? TRUE : FALSE;
}
private function setRemoveAllowed()
{
$this->removeAllowed = $this->payments;
}
}
+52
View File
@@ -0,0 +1,52 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 10/06/2018
* Time: 16:28
*/
class RemoveOffer {
private $offerID;
private $project;
private $removeAllowed;
public function __construct($offerID)
{
$this->setOfferID($offerID);
$this->handle();
}
public function getRemoveAllowed()
{
return $this->removeAllowed;
}
private function setOfferID( $offerID )
{
$this->offerID = $offerID;
}
private function handle()
{
$this->setProject();
$this->setRemoveAllowed();
}
private function setProject()
{
$offer = Offer::Find($this->offerID);
$this->project = is_null($offer->project_id) ? TRUE : FALSE;
}
private function setRemoveAllowed()
{
if( $this->project === FALSE ) return $this->removeAllowed = FALSE;
$this->removeAllowed = TRUE;
}
}
+97
View File
@@ -0,0 +1,97 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 10/06/2018
* Time: 15:53
*/
class RemoveProject {
private $projectID;
private $forecast;
private $invoices;
private $projectemployees;
private $reservations;
private $removeAllowed;
private $projectcosts;
public function __construct( $projectID )
{
$this->setProjectID( $projectID );
$this->handle();
}
public function getRemoveAllowed()
{
return $this->removeAllowed;
}
private function setProjectID( $projectID )
{
$this->projectID = $projectID;
}
private function handle()
{
$this->setForecast();
$this->setInvoices();
$this->setProjectemployees();
$this->setReservations();
$this->setRemoveAllowed();
$this->setProjectCosts();
}
private function setForecast()
{
$forecast = Forecast::whereProjectId( $this->projectID );
$this->forecast = $forecast->count() == 0 ? TRUE : FALSE;
}
private function setInvoices()
{
$invoices = Invoice::whereProjectId( $this->projectID );
$this->invoices = $invoices->count() == 0 ? TRUE : FALSE;
}
private function setProjectemployees( )
{
$setProjectemployees = Projectemployee::whereProjectId($this->projectID);
$this->projectemployees = $setProjectemployees->count() == 0 ? TRUE : FALSE;
}
private function setReservations( )
{
$reservations = Reservation::whereProjectId($this->projectID);
$this->reservations = $reservations->count() == 0 ? TRUE : FALSE;
}
private function setProjectcosts( )
{
$projectcosts = Projectcost::whereProjectId($this->projectID);
$this->projectcosts = $projectcosts->count() == 0 ? TRUE : FALSE;
}
private function setRemoveAllowed()
{
if( $this->forecast === false ) return $this->removeAllowed = FALSE;
if( $this->invoices === false ) return $this->removeAllowed = FALSE;
if( $this->projectemployees === false ) return $this->removeAllowed = FALSE;
if( $this->reservations === false ) return $this->removeAllowed = FALSE;
if( $this->projectcosts === false ) return $this->removeAllowed = FALSE;
$this->removeAllowed = TRUE;
}
}
@@ -0,0 +1,53 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 27/12/2017
* Time: 17:45
*/
class RemoveProjectemployee {
private $projectemployeeID;
private $removeAllowed;
private $projecthours;
public function __construct( $projectemployeeID )
{
$this->setProjectemployeeID( $projectemployeeID );
$this->handle();
}
public function getRemoveAllowed()
{
return $this->removeAllowed;
}
private function setProjectemployeeID( $projectemployeeID )
{
$this->projectemployeeID = $projectemployeeID;
}
private function handle()
{
$this->setProjectHours();
$this->setRemoveAllowed();
}
private function setProjecthours()
{
$projecthours = Projecthour::whereProjectemployeeId($this->projectemployeeID);
$this->projecthours = $projecthours->count() == 0 ?TRUE : FALSE;
}
private function setRemoveAllowed()
{
if( $this->projecthours === false ) return $this->removeAllowed = FALSE;
$this->removeAllowed = TRUE;
}
}
+65
View File
@@ -0,0 +1,65 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 10/06/2018
* Time: 17:06
*/
class RemoveVat {
private $vatID;
private $projects;
private $invoices;
private $removeAllowed;
public function __construct( $vatID )
{
$this->setVatID( $vatID );
$this->handle();
}
public function getRemoveAllowed()
{
return $this->removeAllowed;
}
private function setVatID( $vatID )
{
$this->vatID = $vatID;
}
private function handle()
{
$this->setProject();
$this->setInvoices();
$this->setRemoveAllowed();
}
private function setProject()
{
$projects = Project::whereVatId( $this->vatID );
$this->projects = $projects->count() == 0 ? TRUE : FALSE;
}
private function setInvoices()
{
$invoices = Invoice::whereVatId( $this->vatID );
$this->invoices = $invoices->count() == 0 ? TRUE : FALSE;
}
private function setRemoveAllowed()
{
if ( $this->projects === FALSE ) return $this->removeAllowed = FALSE;
if ( $this->invoices === FALSE ) return $this->removeAllowed = FALSE;
$this->removeAllowed = TRUE;
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 27/12/2017
* Time: 17:45
*/
class RemoveForecast {
private $forecastID;
private $allowDelete = TRUE;
public function __construct( $forecastID )
{
$this->setForecastID( $forecastID );
$this->handle();
}
public function getAllowDelete()
{
return $this->allowDelete;
}
private function setForecastID( $forecastID )
{
$this->forecastID = $forecastID;
}
private function handle()
{
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 27/12/2017
* Time: 17:45
*/
class RemovePayment {
private $paymentID;
private $allowDelete = TRUE;
public function __construct( $paymentID )
{
$this->setPaymentID( $paymentID );
$this->handle();
}
public function getAllowDelete()
{
return $this->allowDelete;
}
private function setPaymentID( $paymentID )
{
$this->paymentID = $paymentID;
}
private function handle()
{
}
}
@@ -0,0 +1,36 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 27/12/2017
* Time: 17:45
*/
class RemoveProjecthour {
private $projecthourID;
private $allowDelete = TRUE;
public function __construct( $projecthourID )
{
$this->setProjecthourID( $projecthourID );
$this->handle();
}
public function getAllowDelete()
{
return $this->allowDelete;
}
private function setProjecthourID( $projecthourID )
{
$this->projecthourID = $projecthourID;
}
private function handle()
{
}
}
@@ -0,0 +1,36 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 27/12/2017
* Time: 17:45
*/
class RemoveReservation {
private $reservationID;
private $allowDelete = TRUE;
public function __construct( $reservationID )
{
$this->setReservationID( $reservationID );
$this->handle();
}
public function getAllowDelete()
{
return $this->allowDelete;
}
private function setReservationID( $reservationID )
{
$this->reservationID = $reservationID;
}
private function handle()
{
}
}
@@ -0,0 +1,75 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 30/07/2018
* Time: 10:48
*/
class InvoiceForecastSheet {
const HEADERS = [
'A' => 'project',
'B' => 'klant',
'C' => 'Nog te factureren incl. btw',
'D' => 'Nog te factureren incl. btw lopend boekjaar incl. btw',
'E' => 'Nog te factureren na lopend boekjaar inc. btw',
'F' => 'Nog te prognotiseren inc. btw'
];
private $invoiceForecast;
private $sheet;
private $row;
public function __construct( $invoiceForecast, $sheet )
{
$this->invoiceForecast = $invoiceForecast;
$this->sheet = $sheet;
$this->handle();
}
private function handle()
{
$this->setHeader();
$this->setBody();
$this->setTotals();
}
private function setHeader()
{
foreach ( self::HEADERS as $cell => $header )
{
$this->sheet->setCellValue( $cell . '1', $header );
$this->sheet->getColumnDimension( $cell )->setAutoSize( TRUE );
}
}
private function setBody()
{
$this->row = 2;
foreach ( $this->invoiceForecast AS $project )
{
$this->sheet->setCellValue( 'A' . $this->row, $project['projectname'] );
$this->sheet->setCellValue( 'B' . $this->row, $project['customer'] );
$this->sheet->setCellValue( 'C' . $this->row, str_replace( '.', '', $project['needInvoice'] ?? '' ) );
$this->sheet->setCellValue( 'D' . $this->row, str_replace( '.', '', $project['forecastThisYear'] ?? '' ) );
$this->sheet->setCellValue( 'E' . $this->row, str_replace( '.', '', $project['forecastOtherYears'] ?? '' ) );
$this->sheet->setCellValue( 'F' . $this->row, str_replace( '.', '', $project['forecastRemaining'] ?? '' ) );
$this->row ++;
}
}
private function setTotals()
{
$lastRow = $this->row - 1;
$this->sheet->setCellValue( 'C' . $this->row, '=SUM(C2:C' . $lastRow . ')' );
$this->sheet->setCellValue( 'D' . $this->row, '=SUM(D2:D' . $lastRow . ')' );
$this->sheet->setCellValue( 'E' . $this->row, '=SUM(E2:E' . $lastRow . ')' );
$this->sheet->setCellValue( 'F' . $this->row, '=SUM(F2:F' . $lastRow . ')' );
}
}
@@ -0,0 +1,80 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 29/07/2018
* Time: 20:40
*/
class InvoiceOverviewSheet {
const HEADERS = [
'A' => 'project',
'B' => 'klant',
'C' => 'Totaal te factureren excl. btw',
'D' => 'Totaal te factureren incl. btw',
'E' => 'Gefactureerd overige jaren incl. btw',
'F' => 'Gefactureerd lopende boekjaar incl. btw',
'G' => 'Gefactureerd totaal incl. btw',
'H' => 'Nog te factureren incl. btw'
];
private $invoiceOverview;
private $sheet;
private $row;
public function __construct( $invoiceOverview, $sheet )
{
$this->invoiceOverview = $invoiceOverview;
$this->sheet = $sheet;
$this->handle();
}
private function handle()
{
$this->setHeader();
$this->setBody();
$this->setTotals();
}
private function setHeader()
{
foreach ( self::HEADERS as $cell => $header )
{
$this->sheet->setCellValue( $cell . '1', $header );
$this->sheet->getColumnDimension( $cell )->setAutoSize( TRUE );
}
}
private function setBody()
{
$this->row = 2;
foreach ( $this->invoiceOverview AS $project )
{
$this->sheet->setCellValue( 'A' . $this->row, $project['projectname'] );
$this->sheet->setCellValue( 'B' . $this->row, $project['customer'] );
$this->sheet->setCellValue( 'C' . $this->row, str_replace( '.', '', $project['totalToInvoicingExcl'] ?? '' ) );
$this->sheet->setCellValue( 'D' . $this->row, str_replace( '.', '', $project['totalToInvoicingIncl'] ?? '' ) );
$this->sheet->setCellValue( 'E' . $this->row, str_replace( '.', '', $project['totalInvoicedOtherYears'] ?? '' ) );
$this->sheet->setCellValue( 'F' . $this->row, str_replace( '.', '', $project['totalInvoicedThisYear'] ?? '' ) );
$this->sheet->setCellValue( 'G' . $this->row, str_replace( '.', '', $project['invoicesTotal'] ?? '' ) );
$this->sheet->setCellValue( 'H' . $this->row, str_replace( '.', '', $project['needInvoice'] ?? '' ) );
$this->row ++;
}
}
private function setTotals()
{
$lastRow = $this->row - 1;
$this->sheet->setCellValue( 'C' . $this->row, '=SUM(C2:C' . $lastRow . ')' );
$this->sheet->setCellValue( 'D' . $this->row, '=SUM(D2:D' . $lastRow . ')' );
$this->sheet->setCellValue( 'E' . $this->row, '=SUM(E2:E' . $lastRow . ')' );
$this->sheet->setCellValue( 'F' . $this->row, '=SUM(F2:F' . $lastRow . ')' );
$this->sheet->setCellValue( 'G' . $this->row, '=SUM(G2:G' . $lastRow . ')' );
$this->sheet->setCellValue( 'H' . $this->row, '=SUM(H2:H' . $lastRow . ')' );
}
}
@@ -0,0 +1,136 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 29/07/2018
* Time: 20:04
*/
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class InvoiceSpreadsheet {
private $invoiceReport;
private $spreadsheet;
private $invoiceSheet;
private $fullpathname;
private $filename;
private $ci;
public function __construct( $invoiceReport )
{
$this->ci =& get_instance();
$this->invoiceReport = $invoiceReport;
$this->ci->load->helper( 'download' );
$this->handle();
}
private function handle()
{
$this->setSpreadsheet();
$this->setInvoiceOverviewSheet();
$this->setInvoiceForecast();
$this->setMonthForecast();
$this->setMonthPayment();
$this->setInvoiced();
$this->setFilename();
$this->setFullPathname();
$this->createFile();
$this->downloadSpreadsheet();
}
private function setSpreadsheet()
{
$this->spreadsheet = new Spreadsheet();
}
private function setInvoiceOverviewSheet()
{
$invoiceSheet = new Worksheet( $this->spreadsheet, 'Facturen' );
$this->invoiceSheet =
$this->spreadsheet->addSheet( $invoiceSheet );
new InvoiceOverviewSheet( $this->invoiceReport['invoiceOverview'], $this->invoiceSheet );
}
private function setInvoiceForecast()
{
$invoiceSheet = new Worksheet( $this->spreadsheet, 'prognose' );
$this->invoiceSheet =
$this->spreadsheet->addSheet( $invoiceSheet );
new InvoiceForecastSheet( $this->invoiceReport['forecasts'], $this->invoiceSheet );
}
private function setMonthForecast()
{
$invoiceSheet = new Worksheet( $this->spreadsheet, 'maandprognose' );
$this->invoiceSheet =
$this->spreadsheet->addSheet( $invoiceSheet );
new MonthForecastSheet( $this->invoiceReport['monthForecasts'], $this->invoiceSheet );
}
private function setMonthPayment()
{
$invoiceSheet = new Worksheet( $this->spreadsheet, 'maand betalingen' );
$this->invoiceSheet =
$this->spreadsheet->addSheet( $invoiceSheet );
new MonthPaymentSheet( $this->invoiceReport['monthPayments'], $this->invoiceSheet );
}
private function setInvoiced()
{
$invoiceSheet = new Worksheet( $this->spreadsheet, 'verstuurde facturen' );
$this->invoiceSheet =
$this->spreadsheet->addSheet( $invoiceSheet );
new InvoicedSheet( $this->invoiceReport['invoiced'], $this->invoiceSheet );
}
private function setFilename()
{
$this->filename = 'facturen' . date( 'YmdHis' ) . '.xlsx';
}
private function setFullPathname()
{
$this->fullpathname = MYROOTPATH . 'documents/spreadsheets/' . $this->filename;
}
private function createFile()
{
$writer = new Xlsx( $this->spreadsheet );
$writer->save( $this->fullpathname );
}
private function downloadSpreadsheet()
{
$data = file_get_contents( $this->fullpathname );
force_download( $this->filename, $data );
}
}
@@ -0,0 +1,67 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 30/07/2018
* Time: 10:48
*/
class InvoicedSheet {
const HEADERS = [
'A' => 'factuurnummer',
'B' => 'project',
'C' => 'klant',
'D' => 'factuurdatum',
'E' => 'exc btw',
'F' => 'btw',
'G' => 'incl btw'
];
private $invoiced;
private $sheet;
private $row;
public function __construct( $invoiced, $sheet )
{
$this->invoiced = $invoiced;
$this->sheet = $sheet;
$this->handle();
}
private function handle()
{
$this->setHeader();
$this->setBody();
}
private function setHeader()
{
foreach ( self::HEADERS as $cell => $header )
{
$this->sheet->setCellValue( $cell . '1', $header );
$this->sheet->getColumnDimension( $cell )->setAutoSize( TRUE );
}
}
private function setBody()
{
$this->row = 2;
foreach ( $this->invoiced AS $invoice )
{
$vat = ROUND($invoice->invoiceamount * 0.21, 2);
$this->sheet->setCellValue( 'A' . $this->row, $invoice->invoicenumber );
$this->sheet->setCellValue( 'B' . $this->row, ($invoice->projectnumber . ' ' . $invoice['projectname']));
$this->sheet->setCellValue( 'C' . $this->row, $invoice->name );
$this->sheet->setCellValue( 'D' . $this->row, $invoice->invoicenumber );
$this->sheet->setCellValue( 'E' . $this->row, $invoice->invoiceamount );
$this->sheet->setCellValue( 'F' . $this->row, $vat );
$this->sheet->setCellValue( 'G' . $this->row, $invoice->invoiceamount + $vat );
$this->row ++;
}
}
}
@@ -0,0 +1,101 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 30/07/2018
* Time: 10:48
*/
class MonthForecastSheet {
const HEADERS = [
'A' => 'project',
'B' => 'klant',
'C' => 'Nog te factureren incl. btw',
'D' => 'januari',
'E' => 'februari',
'F' => 'maart',
'G' => 'april',
'H' => 'mei',
'I' => 'juni',
'J' => 'juli',
'K' => 'augustus',
'L' => 'september',
'M' => 'oktober',
'N' => 'november',
'O' => 'december',
'P' => 'Nog te factureren na lopend boekjaar inc. btw',
'Q' => 'Nog te prognotiseren inc. btw'
];
const MONTH_COLUMNS = ['D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O'];
private $invoiceForecast;
private $sheet;
private $row;
public function __construct( $invoiceForecast, $sheet )
{
$this->invoiceForecast = $invoiceForecast;
$this->sheet = $sheet;
$this->handle();
}
private function handle()
{
$this->setHeader();
$this->setBody();
$this->setTotals();
}
private function setHeader()
{
foreach ( self::HEADERS as $cell => $header )
{
$this->sheet->setCellValue( $cell . '1', $header );
$this->sheet->getColumnDimension( $cell )->setAutoSize( TRUE );
}
}
private function setBody()
{
$this->row = 2;
foreach ( $this->invoiceForecast AS $project )
{
$this->sheet->setCellValue( 'A' . $this->row, $project['projectname'] );
$this->sheet->setCellValue( 'B' . $this->row, $project['customer'] );
$this->sheet->setCellValue( 'C' . $this->row, str_replace( '.', '', $project['needInvoice'] ?? '' ) );
$columnCount = 0;
foreach ( $project['forecastMonths'] as $month )
{
$column = self::MONTH_COLUMNS[ $columnCount ];
$forecast = $month['forecastamount'];
$this->sheet->setCellValue( $column . $this->row, $forecast );
$columnCount ++;
}
$this->sheet->setCellValue( 'P' . $this->row, str_replace( '.', '', $project['forecastOtherYears'] ?? '' ) );
$this->sheet->setCellValue( 'Q' . $this->row, str_replace( '.', '', $project['forecastRemaining'] ?? '' ) );
$this->row ++;
}
}
private function setTotals()
{
$lastRow = $this->row - 1;
$this->sheet->setCellValue( 'C' . $this->row, '=SUM(C2:C' . $lastRow . ')' );
$this->sheet->setCellValue( 'D' . $this->row, '=SUM(D2:D' . $lastRow . ')' );
foreach ( self::MONTH_COLUMNS as $column )
{
$this->sheet->setCellValue( $column . $this->row, '=SUM(' . $column . '2:' . $column . $lastRow . ')' );
}
$this->sheet->setCellValue( 'P' . $this->row, '=SUM(P2:P' . $lastRow . ')' );
$this->sheet->setCellValue( 'Q' . $this->row, '=SUM(Q2:Q' . $lastRow . ')' );
}
}
@@ -0,0 +1,95 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 30/07/2018
* Time: 10:48
*/
class MonthPaymentSheet {
const HEADERS = [
'A' => 'project',
'B' => 'klant',
'C' => 'januari',
'D' => 'februari',
'E' => 'maart',
'F' => 'april',
'G' => 'mei',
'H' => 'juni',
'I' => 'juli',
'J' => 'augustus',
'K' => 'september',
'L' => 'oktober',
'M' => 'november',
'N' => 'december',
'O' => 'Totaal betaald lopend boekjaar inc. btw'
];
const MONTH_COLUMNS = ['C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N'];
private $invoiceForecast;
private $sheet;
private $row;
public function __construct( $invoiceForecast, $sheet )
{
$this->invoiceForecast = $invoiceForecast;
$this->sheet = $sheet;
$this->handle();
}
private function handle()
{
$this->setHeader();
$this->setBody();
$this->setTotals();
}
private function setHeader()
{
foreach ( self::HEADERS as $cell => $header )
{
$this->sheet->setCellValue( $cell . '1', $header );
$this->sheet->getColumnDimension( $cell )->setAutoSize( TRUE );
}
}
private function setBody()
{
$this->row = 2;
foreach ( $this->invoiceForecast AS $project )
{
$this->sheet->setCellValue( 'A' . $this->row, $project['projectname'] );
$this->sheet->setCellValue( 'B' . $this->row, $project['customer'] );
$columnCount = 0;
foreach ( $project['monthPayments'] as $month )
{
$column = self::MONTH_COLUMNS[ $columnCount ];
$forecast = $month['paymentamount'];
$this->sheet->setCellValue( $column . $this->row, $forecast );
$columnCount ++;
}
$formula = '=SUM(C'.$this->row.':N'.$this->row.')';
$this->sheet->setCellValue( 'O' . $this->row, $formula);
$this->row ++;
}
}
private function setTotals()
{
$lastRow = $this->row - 1;
foreach ( self::MONTH_COLUMNS as $column )
{
$this->sheet->setCellValue( $column . $this->row, '=SUM(' . $column . '2:' . $column . $lastRow . ')' );
}
$this->sheet->setCellValue( 'O' . $this->row, '=SUM(O2:O' . $lastRow . ')' );
}
}
@@ -0,0 +1,125 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 29/07/2018
* Time: 13:14
*/
class InvoiceForecast {
private $year;
private $project;
private $customer;
private $forecast;
private $currentYear;
private $projectname;
private $needInvoice;
private $projectDetails;
private $forecastThisYear = 0;
private $forecastRemaining;
private $forecastOtherYears = 0;
public function __construct( $project, $needInvoice, $year )
{
$this->project = $project;
$this->needInvoice = $needInvoice;
$this->year = $year;
$this->handle();
}
public function getProjectDetails()
{
return $this->projectDetails;
}
public function getNeedInvoice()
{
return $this->needInvoice;
}
public function getForecastOtherYear()
{
return $this->forecastOtherYears;
}
public function getForecastRemaining()
{
return $this->forecastRemaining;
}
private function handle()
{
$this->setCurrentyear();
$this->setProjectname();
$this->setCustomer();
$this->loopForecasts();
$this->setForecastRemaining();
$this->setProjectDetails();
}
private function setCurrentyear()
{
$this->currentYear = date( 'Y' );
}
private function setProjectname()
{
$this->projectname = $this->project->projectname . '(' . $this->project->projectnumber . ')';
}
private function setCustomer()
{
$this->customer = $this->project->customer->name;
}
private function loopForecasts()
{
if ( is_null( $this->project->forecasts ) ) return $this->forecastThisYear = 0;
foreach ( $this->project->forecasts as $this->forecast )
{
$this->setForecastThisYear();
$this->setForecastOtherYears();
}
}
private function setForecastThisYear()
{
if ( $this->forecast->year == $this->year )
$this->forecastThisYear += $this->forecast->forecastamount;
}
private function setForecastOtherYears()
{
if ( $this->forecast->year != $this->year )
$this->forecastOtherYears += $this->forecast->forecastamount;
}
private function setForecastRemaining()
{
$this->forecastRemaining =
$this->needInvoice - $this->forecastThisYear - $this->forecastOtherYears;
}
private function setProjectDetails()
{
$this->projectDetails = [
'projectnumber' => $this->project->projectnumber,
'projectname' => $this->projectname,
'customer' => $this->customer,
'needInvoice' => number_format( $this->needInvoice, 0, ',', '.' ),
'forecastThisYear' => number_format( $this->forecastThisYear, 0, ',', '.' ),
'forecastOtherYears' => number_format( $this->forecastOtherYears, 0, ',', '.' ),
'forecastRemaining' => number_format( $this->forecastRemaining, 0, ',', '.' ),
];
}
}
@@ -0,0 +1,151 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 29/07/2018
* Time: 10:29
*/
class InvoiceOverview {
private $project;
private $year;
private $projectname;
private $customer;
private $totalToInvoicingExcl;
private $totalToInvoicingIncl;
private $totalInvoicedOtherYears;
private $totalInvoicedThisYear;
private $invoicesTotal;
private $needInvoice;
private $projectDetails;
private $projectnumber;
private $projectPayment;
private $invoicesToPay;
public function __construct( $project, $year )
{
$this->project = $project;
$this->year = $year;
$this->handle();
}
public function getProjectDetails()
{
return $this->projectDetails;
}
public function getNeedinvoice()
{
return $this->needInvoice;
}
private function handle()
{
$this->setProjectnumber();
$this->setProjectname();
$this->setCustomer();
$this->setTotalToInvoicingExcl();
$this->setTotalToInvoicingIncl();
$this->setTotalInvoicedOtherYears();
$this->setTotalInvoicedThisYear();
$this->setPaymentPerProject();
$this->setInvoicesTotal();
$this->setInvoicesToPay();
$this->setNeedInvoice();
$this->setProjectDetails();
}
private function setProjectnumber()
{
$this->projectnumber = $this->project->projectnumber;
}
private function setProjectname()
{
$this->projectname = $this->project->projectname;
}
private function setCustomer()
{
$this->customer = $this->project->customer->name;
}
private function setTotalToInvoicingExcl()
{
$offer = $this->project->offer;
$this->totalToInvoicingExcl =
$offer->own_revenue + $offer->other_revenue + $offer->costs;
}
private function setTotalToInvoicingIncl()
{
$this->totalToInvoicingIncl =
$this->totalToInvoicingExcl * ( 1 + ( $this->project->vat->vatrate / 100 ) );
}
private function setTotalInvoicedOtherYears()
{
$this->totalInvoicedOtherYears =
Invoice::invoicePerYear( $this->project->id, $this->year, FALSE );
}
private function setTotalInvoicedThisYear()
{
$this->totalInvoicedThisYear =
Invoice::invoicePerYear( $this->project->id, $this->year, TRUE );
}
private function setPaymentPerProject()
{
$this->projectPayment = Payment::getPaymentPerProject( $this->project->id );
}
private function setInvoicesTotal()
{
$this->invoicesTotal =
$this->totalInvoicedOtherYears + $this->totalInvoicedThisYear;
}
private function setInvoicesToPay()
{
$this->invoicesToPay = $this->invoicesTotal - $this->projectPayment;
}
private function setNeedInvoice()
{
$this->needInvoice =
$this->totalToInvoicingIncl - $this->invoicesTotal;
}
private function setProjectDetails()
{
$this->projectDetails = [
'projectnumber' => $this->projectnumber,
'projectname' => $this->projectname,
'customer' => $this->customer,
'totalToInvoicingExcl' => number_format( $this->totalToInvoicingExcl ?? 0, 0, ',', '.' ),
'totalToInvoicingIncl' => number_format( $this->totalToInvoicingIncl ?? 0, 0, ',', '.' ),
'totalInvoicedOtherYears' => number_format( $this->totalInvoicedOtherYears ?? 0, 0, ',', '.' ),
'totalInvoicedThisYear' => number_format( $this->totalInvoicedThisYear ?? 0, 0, ',', '.' ),
'invoicesTotal' => number_format( $this->invoicesTotal ?? 0, 0, ',', '.' ),
'projectPayment' => number_format( $this->projectPayment ?? 0, 0, ',', '.' ),
'invoiceToPay' => number_format( $this->invoicesToPay ?? 0, 0, ',', '.' ),
'needInvoice' => number_format( $this->needInvoice ?? 0, 0, ',', '.' )
];
}
}
+133
View File
@@ -0,0 +1,133 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 29/07/2018
* Time: 10:19
*/
class Invoices {
private $year;
private $project;
private $projects;
private $monthPayment;
private $monthPayments;
private $monthForecast;
private $monthForecasts;
private $invoiceOverview;
private $invoiceForecast;
private $invoiceForecasts;
private $invoiceOverviews = [];
private $invoiceReport = [];
private $orderType;
private $orderDirection;
private $archive;
private $invoicedYears;
private $invoiced;
public function __construct( $year, $orderType, $orderDirection, $archive )
{
$this->year = $year;
$this->orderType = $orderType;
$this->orderDirection = $orderDirection;
$this->archive = $archive;
$this->handle();
}
public function getInvoiceReport()
{
return $this->invoiceReport;
}
private function handle()
{
$this->setProjects();
$this->loopProjects();
//only projects with payments also archived projects
$this->setMonthPayments();
$this->setInvoicedyears();
$this->setInvoiced();
$this->setInvoiceReport();
}
private function setProjects()
{
$this->projects =
Project::getProjectsForReport( $this->orderType, $this->orderDirection, $this->archive );
}
private function loopProjects()
{
foreach ( $this->projects as $this->project )
{
$this->setInvoiceOverview();
$this->setInvoiceForecasts();
$this->setMonthForecasts();
}
}
private function setInvoiceOverview()
{
$this->invoiceOverview = new InvoiceOverview( $this->project, $this->year );
$this->invoiceOverviews[] = $this->invoiceOverview->getProjectDetails();
}
private function setInvoiceForecasts()
{
$this->invoiceForecast =
new InvoiceForecast( $this->project, $this->invoiceOverview->getNeedinvoice(), $this->year );
$this->invoiceForecasts[] = $this->invoiceForecast->getProjectDetails();
}
public function setMonthForecasts()
{
$this->monthForecast =
new MonthForecast( $this->invoiceForecast, $this->project, $this->year );
$this->monthForecasts[] = $this->monthForecast->getProjectDetails();
}
public function setMonthPayments()
{
$monthPayment = new MonthPayments(
$this->year, $this->orderType, $this->orderDirection );
$this->monthPayments = $monthPayment->getProjectDetails();
}
private function setInvoiced()
{
$this->invoiced = Invoice::getInvoiced( $this->year, $this->orderType, $this->orderDirection );
}
private function setInvoicedYears()
{
$this->invoicedYears = Invoice::selectRaw( 'DATE_FORMAT(invoicedate, "%Y") AS years' )
->distinct()
->orderBy( 'invoicedate' )
->pluck( 'years' );
}
private function setInvoiceReport()
{
$this->invoiceReport = [
'invoiceOverview' => $this->invoiceOverviews,
'forecasts' => $this->invoiceForecasts,
'monthForecasts' => $this->monthForecasts,
'monthPayments' => $this->monthPayments,
'invoicedYears' => $this->invoicedYears,
'invoiced' => $this->invoiced
];
}
}
@@ -0,0 +1,92 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 29/07/2018
* Time: 14:23
*/
class MonthForecast {
private $year;
private $project;
private $forecast;
private $customer;
private $projectname;
private $forecastMonths;
private $projectDetails;
private $invoiceForecast;
public function __construct( InvoiceForecast $invoiceForecast, $project, $year )
{
$this->project = $project;
$this->invoiceForecast = $invoiceForecast;
$this->year = $year;
$this->handle();
}
public function getProjectDetails()
{
return $this->projectDetails;
}
private function handle()
{
$this->setProjectname();
$this->setCustomer();
$this->setInitialsForecastMonths();
$this->loopForecasts();
$this->setProjectDetails();
}
private function setProjectname()
{
$this->projectname = $this->project->projectname . '(' . $this->project->projectnumber . ')';
}
private function setCustomer()
{
$this->customer = $this->project->customer->name;
}
private function setInitialsForecastMonths()
{
for ( $i = 0; $i < 12; $i ++ )
{
$this->forecastMonths[ $i ] = ['forecastamount' => 0];
}
}
private function loopForecasts()
{
foreach ( $this->project->forecasts as $this->forecast )
{
$this->setMonthForecast();
}
}
private function setMonthForecast()
{
if ( $this->forecast->year == $this->year )
$this->forecastMonths[ $this->forecast->month_id ]['forecastamount'] += $this->forecast->forecastamount;
}
private function setProjectDetails()
{
$this->projectDetails = [
'projectnumber' => $this->project->projectnumber,
'projectname' => $this->projectname,
'customer' => $this->customer,
'needInvoice' => number_format( $this->invoiceForecast->getNeedInvoice(), 0, ',', '.' ),
'forecastOtherYears' => number_format( $this->invoiceForecast->getForecastOtherYear(), 0, ',', '.' ),
'forecastRemaining' => number_format( $this->invoiceForecast->getForecastRemaining(), 0, ',', '.' ),
'forecastMonths' => $this->forecastMonths
];
}
}
@@ -0,0 +1,128 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 29/07/2018
* Time: 14:23
*/
class MonthPayments {
private $year;
private $project;
private $payment;
private $customer;
private $projectname;
private $monthPayments;
private $projectDetails;
private $projectsWithPayments;
private $totalProjectPayments;
private $orderType;
private $orderDirection;
public function __construct( $year, $orderType, $orderDirection )
{
$this->year = $year;
$this->orderType = $orderType;
$this->orderDirection = $orderDirection;
$this->handle();
}
public function getProjectDetails()
{
return $this->projectDetails;
}
private function handle()
{
$this->setProjectsWithPayments();
$this->loopProjectsWithPayments();
}
private function setProjectsWithPayments()
{
$projectsArray = Payment::getProjectsWithPayments( $this->year );
$this->projectsWithPayments =
Project::getProjectsForReport(
$this->orderType, $this->orderDirection, FALSE, $projectsArray );
}
private function loopProjectsWithPayments()
{
foreach ( $this->projectsWithPayments as $this->project )
{
$this->setProjectname();
$this->setCustomer();
$this->setInitialsMonthPayments();
$this->loopPayments();
$this->setProjectDetails();
}
}
private function setProjectname()
{
$this->projectname = $this->project->projectname . '(' . $this->project->projectnumber . ')';
}
private function setCustomer()
{
$this->customer = $this->project->customer->name;
}
private function setInitialsMonthPayments()
{
for ( $i = 1; $i <= 12; $i ++ )
{
$this->monthPayments[ $i ] = ['paymentamount' => 0];
}
}
private function loopPayments()
{
$this->totalProjectPayments = 0;
foreach ( $this->project->invoices as $invoice )
{
foreach ( $invoice->payments as $this->payment )
{
$this->setMonthPayments();
$this->setTotalProjectPayments();
}
}
}
private function setMonthPayments()
{
$paymentYear = date( 'Y', strtotime( $this->payment->paymentdate ) );
$paymentMonth = date( 'n', strtotime( $this->payment->paymentdate ) );
if ( $paymentYear == $this->year )
$this->monthPayments[ $paymentMonth ]['paymentamount'] += $this->payment->paymentamount;
}
private function setTotalProjectPayments()
{
$paymentYear = date( 'Y', strtotime( $this->payment->paymentdate ) );
if ( $paymentYear == $this->year )
$this->totalProjectPayments += $this->payment->paymentamount;
}
private function setProjectDetails()
{
$this->projectDetails[] = [
'projectnumber' => $this->project->projectnumber,
'projectname' => $this->projectname,
'customer' => $this->customer,
'monthPayments' => $this->monthPayments,
'totalProjectPayments' => number_format( $this->totalProjectPayments, 0, ',', '.' )
];
}
}
+279
View File
@@ -0,0 +1,279 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 20/02/2018
* Time: 16:49
*/
class Recapprojects {
private $index;
private $field;
private $archive;
private $project;
private $projects;
private $direction;
private $employeeHours;
private $invoicedYears = [];
private $projectTotals;
private $employeeBudget;
private $uniqueEmployee;
private $uniqueEmployees;
private $currentFinancialYear;
private $projectEmployeeDetail;
private $projectEmployeeDetails;
public function __construct( $archive, $field, $direction )
{
$this->archive = $archive;
$this->field = $field;
$this->direction = $direction;
$this->handle();
}
public function getProjects()
{
return $this->projects;
}
private function handle()
{
$this->setProjects();
$this->setUniqueEmployees();
$this->loopProjects();
$this->setInvoicedYears();
$this->loopProjectsForInvoicedYears();
}
private function setProjects()
{
$this->projects = Project::getActiveProjects(
$this->archive, $this->field, $this->direction )->toArray();
}
private function setUniqueEmployees()
{
$this->uniqueEmployees =
Projectemployee::getUniqueEmployeesWithActivity();
}
private function loopProjects()
{
$this->index = 0;
foreach ( $this->projects as $this->project )
{
$this->projectTotals = 0;
$this->setProjectEmployeeDetails();
$this->loopUniqueEmployees();
$this->setBudget();
$this->setProjectCosts();
$this->setBudgetAvailable();
$this->setSaldo();
$this->setInvoiced();
$this->setWorkInProgress();
$this->setCurrentFinancialYear();
$this->index ++;
}
}
private function setProjectEmployeeDetails()
{
$this->projectEmployeeDetails =
Projectemployee::getProjectemployeeDetailsPerProject( $this->project['id'] );
}
private function loopUniqueEmployees()
{
foreach ( $this->uniqueEmployees as $this->uniqueEmployee )
{
$this->setProjectEmployeeDetail();
$this->setEmployeeBudget();
$this->setEmployeeHours();
$this->setEmployeeDetails();
$this->setProjectTotals();
}
}
private function setProjectEmployeeDetail()
{
foreach ( $this->projectEmployeeDetails as $this->projectEmployeeDetail )
{
if ( $this->uniqueEmployee->id == $this->projectEmployeeDetail->id ) return;
}
$this->projectEmployeeDetail = FALSE;
}
private function setEmployeeBudget()
{
if( property_exists($this, 'uniqueEmployee') ) return $this->employeeBudget = 0;
if( is_null($this->projectEmployeeDetail)) return $this->employeeBudget = 0;
$this->employeeBudget =
is_null( $this->projectEmployeeDetail['budget'] ) ? 0 : $this->projectEmployeeDetail['budget'];
}
private function setEmployeeHours()
{
$this->employeeHours =
$this->projectEmployeeDetail ? $this->projectEmployeeDetail->hours : 0;
}
private function setEmployeeDetails()
{
$this->projects[ $this->index ]['employees'][] = [
'id' => $this->uniqueEmployee->id,
'fullname' => $this->uniqueEmployee->fullname,
'hours' => $this->employeeHours,
'revenues' => $this->projectEmployeeDetail ? $this->projectEmployeeDetail->revenues : 0,
'budget' => $this->employeeBudget,
'availableHours' => $this->employeeBudget - $this->employeeHours
];
}
private function setProjectTotals()
{
if ( ! isset( $this->projects[ $this->index ]['projectHours'] ) )
$this->projects[ $this->index ]['projectHours'] = 0;
if ( ! isset( $this->projects[ $this->index ]['projectEuros'] ) )
$this->projects[ $this->index ]['projectEuros'] = 0;
if ( ! isset( $this->projects[ $this->index ]['hoursAvailable'] ) )
$this->projects[ $this->index ]['hoursAvailable'] = 0;
$this->projects[ $this->index ]['projectHours'] +=
$this->projectEmployeeDetail ? $this->projectEmployeeDetail->hours : 0;
$this->projects[ $this->index ]['projectEuros'] +=
$this->projectEmployeeDetail ? $this->projectEmployeeDetail->revenues : 0;
$this->projects[ $this->index ]['hoursAvailable'] +=
$this->employeeBudget - $this->employeeHours;
}
private function setBudget()
{
$this->projects[ $this->index ]['budget'] =
round( ( $this->projects[ $this->index ]['own_revenue'] + $this->projects[ $this->index ]['other_revenue'] ), 0 );
}
private function setProjectCosts()
{
$this->projects[ $this->index ]['projectcosts'] =
Projectcost::getCostsPerPerProject( $this->projects[ $this->index ]['id'] );
}
private function setBudgetAvailable()
{
$this->projects[ $this->index ]['budgetAvailable'] =
$this->projects[ $this->index ]['budget'] - $this->projects[ $this->index ]['projectcosts'];
}
private function setSaldo()
{
$this->projects[ $this->index ]['saldo'] =
$this->projects[ $this->index ]['budgetAvailable'] - $this->projects[ $this->index ]['projectEuros'];
}
private function setInvoiced()
{
$invoiced = \Invoice::getInvoicedPerYearPerProject( $this->projects[ $this->index ]['id'] );
foreach ( $invoiced ? $invoiced : [] as $invoice )
{
$this->projects[ $this->index ]['invoiced'][] = [
'year' => $invoice->invoiceyear,
'invoiced' => $invoice->invoiced
];
$this->setTotalInvoiced( $invoice->invoiced );
}
if ( ! isset( $this->projects[ $this->index ]['invoiced'] ) )
{
$this->projects[ $this->index ]['invoiced'] = [];
$this->projects[ $this->index ]['totalInvoiced'] = 0;
}
}
private function setTotalInvoiced( $invoiced )
{
if ( ! isset( $this->projects[ $this->index ]['totalInvoiced'] ) )
$this->projects[ $this->index ]['totalInvoiced'] = 0;
$this->projects[ $this->index ]['totalInvoiced'] += $invoiced;
}
private function setWorkInProgress()
{
$this->projects[ $this->index ]['workInProgress'] =
$this->projects[ $this->index ]['projectEuros'] +
$this->projects[ $this->index ]['projectcosts'] -
$this->projects[ $this->index ]['totalInvoiced'];
if ( $this->projects[ $this->index ]['workInProgress'] < 0 )
$this->projects[ $this->index ]['workInProgress'] = 0;
}
private function setCurrentFinancialYear()
{
$this->currentFinancialYear = $this->project['current_financial_year'];
}
private function setInvoicedYears()
{
foreach ( $this->projects as $this->project )
{
foreach ( $this->project['invoiced'] as $year )
{
if ( in_array( $year['year'], $this->invoicedYears ) ) continue;
array_push( $this->invoicedYears, $year['year'] );
}
}
}
private function loopProjectsForInvoicedYears()
{
$this->index = 0;
foreach ( $this->projects as $this->project )
{
foreach ( $this->invoicedYears as $invoiceYear )
{
$hasYear = FALSE;
foreach ( $this->project['invoiced'] as $year )
{
if ( $invoiceYear == $year['year'] ) $hasYear = TRUE;
}
if ( ! $hasYear ) $this->projects[ $this->index ]['invoiced'][] = [
'year' => $invoiceYear,
'invoiced' => 0
];
}
usort( $this->projects[ $this->index ]['invoiced'], function ( $a, $b ) {
return $a['year'] - $b['year'];
} );
$this->index ++;
}
}
}
+181
View File
@@ -0,0 +1,181 @@
<?php
namespace App\Libraries;
/**
* Two-Factor Authentication Library
* Implements TOTP (Time-based One-Time Password) for Google Authenticator
* Based on RFC 6238
*/
class TwoFactorAuth
{
protected int $codeLength = 6;
protected int $period = 30; // 30 seconds validity window
public function __construct()
{
// No CI instance needed
}
/**
* Generate a new secret key for TOTP
* @return string Base32 encoded secret
*/
public function generateSecret(int $length = 16): string
{
$secret = '';
$validChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; // Base32 alphabet
for ($i = 0; $i < $length; $i++) {
$secret .= $validChars[random_int(0, 31)];
}
return $secret;
}
/**
* Generate QR code URL for Google Authenticator
* @param string $secret The user's TOTP secret
* @param string $username The username
* @param string $issuer The application name
* @return string QR code URL
*/
public function getQRCodeUrl(string $secret, string $username, string $issuer = 'DBOIS'): string
{
$encodedIssuer = rawurlencode($issuer);
$encodedUsername = rawurlencode($username);
$otpauthUrl = "otpauth://totp/{$encodedIssuer}:{$encodedUsername}?secret={$secret}&issuer={$encodedIssuer}";
// Using Google Charts API for QR code generation
return "https://chart.googleapis.com/chart?chs=200x200&chld=M|0&cht=qr&chl=" . urlencode($otpauthUrl);
}
/**
* Verify a TOTP code
* @param string $secret The user's secret
* @param string $code The code to verify
* @param int $discrepancy Time window (default 1 = +/- 30 seconds)
* @return bool True if code is valid
*/
public function verifyCode(string $secret, string $code, int $discrepancy = 1): bool
{
$currentTimeSlice = floor(time() / $this->period);
for ($i = -$discrepancy; $i <= $discrepancy; $i++) {
$calculatedCode = $this->getCode($secret, (int)($currentTimeSlice + $i));
if ($this->timingSafeEquals($calculatedCode, $code)) {
return true;
}
}
return false;
}
/**
* Generate TOTP code for a given time slice
* @param string $secret The secret key
* @param int|null $timeSlice The time slice (defaults to current)
* @return string The generated code
*/
public function getCode(string $secret, ?int $timeSlice = null): string
{
if ($timeSlice === null) {
$timeSlice = (int)floor(time() / $this->period);
}
$secretKey = $this->base32Decode($secret);
// Pack time into binary string
$time = chr(0) . chr(0) . chr(0) . chr(0) . pack('N*', $timeSlice);
// Hash with secret
$hash = hash_hmac('sha1', $time, $secretKey, true);
// Use last 4 bits as offset
$offset = ord(substr($hash, -1)) & 0x0F;
// Get 4 bytes from offset
$hashPart = substr($hash, $offset, 4);
// Unpack binary value
$value = unpack('N', $hashPart);
$value = $value[1];
// Only 32 bits
$value = $value & 0x7FFFFFFF;
// Get the required digits
$modulo = pow(10, $this->codeLength);
return str_pad($value % $modulo, $this->codeLength, '0', STR_PAD_LEFT);
}
/**
* Decode Base32 string
* @param string $secret Base32 encoded string
* @return string Binary string
*/
protected function base32Decode(string $secret): string
{
if (empty($secret)) {
return '';
}
$base32chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
$base32charsFlipped = array_flip(str_split($base32chars));
$paddingCharCount = substr_count($secret, '=');
$allowedValues = [6, 4, 3, 1, 0];
if (!in_array($paddingCharCount, $allowedValues)) {
return '';
}
for ($i = 0; $i < 4; $i++) {
if (
$paddingCharCount == $allowedValues[$i] &&
substr($secret, -($allowedValues[$i])) != str_repeat('=', $allowedValues[$i])
) {
return '';
}
}
$secret = str_replace('=', '', $secret);
$secret = str_split($secret);
$binaryString = '';
for ($i = 0; $i < count($secret); $i = $i + 8) {
$x = '';
if (!isset($base32charsFlipped[$secret[$i]])) {
return '';
}
for ($j = 0; $j < 8; $j++) {
$char = $secret[$i + $j] ?? '';
$charValue = $base32charsFlipped[$char] ?? 0;
$x .= str_pad(base_convert((string)$charValue, 10, 2), 5, '0', STR_PAD_LEFT);
}
$eightBits = str_split($x, 8);
for ($z = 0; $z < count($eightBits); $z++) {
$y = chr((int)base_convert($eightBits[$z], 2, 10));
$binaryString .= ($y || ord($y) == 48) ? $y : '';
}
}
return $binaryString;
}
/**
* Timing-safe string comparison
* @param string $safeString Known string
* @param string $userString User provided string
* @return bool True if strings match
*/
protected function timingSafeEquals(string $safeString, string $userString): bool
{
return hash_equals($safeString, $userString);
}
}
@@ -0,0 +1,90 @@
<?php
/**
* Created by PhpStorm.
* User: imac-3
* Date: 26/06/16
* Time: 21:17
*/
require_once( APPPATH . 'Libraries/Validation/Validation.php' );
use App\Libraries\Validation\Validation;
class BaseValidation {
protected $validationField;
protected $key;
protected $fieldValue;
protected $errorMessages = [];
protected $validation;
protected $fieldname;
protected $validationResult;
protected $request;
public function __construct()
{
$this->request = \Config\Services::request();
$this->validateInput();
}
public function getValidationResult()
{
return $this->validationResult;
}
public function validateInput()
{
$this->loopFields();
}
public function getErrorMessages()
{
return $this->errorMessages;
}
private function loopFields()
{
foreach ( $this->validationFields as $this->key => $this->validationField )
{
$this->validation = new Validation();
$this->setInputfield();
$this->validateFieldvalue();
$this->setFieldname();
$this->setValidationResult();
$this->setErrorMesagges();
}
}
private function setInputfield()
{
$this->fieldValue = $this->request->getPost($this->key);
}
private function validateFieldvalue()
{
$this->validation->validate( $this->fieldValue, $this->validationField );
}
private function setFieldname()
{
$this->fieldname = $this->validationField['fieldname'];
}
private function setErrorMesagges()
{
$this->errorMessages[ $this->fieldname ] = $this->validation->getErrorMessages();
}
private function setValidationResult()
{
if( $this->validationResult === FALSE ) return;
$this->validationResult = $this->validation->getValidationResult();
}
}
@@ -0,0 +1,30 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 10/07/16
* Time: 13:35
*/
require_once( APPPATH . 'Libraries/Validation/InputValidations/BaseValidation.php' );
class CustomerValidation extends BaseValidation {
protected $validationFields = [
'name' => [
'validations' => 'required|alphaNumericSpaces',
'fieldname' => 'name'
],
'email' => [
'validations' => 'email',
'fieldname' => 'email'
]
];
public function __construct()
{
parent::__construct();
}
}
@@ -0,0 +1,38 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 10/07/16
* Time: 13:35
*/
require_once( APPPATH . 'Libraries/Validation/InputValidations/BaseValidation.php' );
class EmployeeTargetValidation extends BaseValidation {
protected $validationFields = [
'user_id' => [
'validations' => 'required|integer',
'fieldname' => 'gebruiker'
],
'startmonth' => [
'validations' => 'integer',
'fieldname' => 'startmaand'
],
'startyear' => [
'validations' => 'required|integer',
'fieldname' => 'startjaar'
],
'target' =>[
'validations' => 'integer',
'fieldname' => 'uren target'
]
];
public function __construct()
{
parent::__construct();
}
}
@@ -0,0 +1,34 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 10/07/16
* Time: 13:35
*/
require_once( APPPATH . 'Libraries/Validation/InputValidations/BaseValidation.php' );
class ExternalValidation extends BaseValidation {
protected $validationFields = [
'contactperson' => [
'validations' => 'required|alphaNumericSpaces',
'fieldname' => 'contact'
],
'email' => [
'validations' => 'email',
'fieldname' => 'email'
],
'rate' => [
'validations' => 'numeric',
'fieldname' => 'tarief'
]
];
public function __construct()
{
parent::__construct();
}
}
@@ -0,0 +1,38 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 10/07/16
* Time: 13:35
*/
require_once( APPPATH . 'Libraries/Validation/InputValidations/BaseValidation.php' );
class ForecastValidation extends BaseValidation {
protected $validationFields = [
'project_id' => [
'validations' => 'required|integer',
'fieldname' => 'project'
],
'year' => [
'validations' => 'integer',
'fieldname' => 'jaar'
],
'month_id' => [
'validations' => 'integer',
'fieldname' => 'maand'
],
'forecastamount' => [
'validations' => 'number',
'fieldname' => 'bedrag'
]
];
public function __construct()
{
parent::__construct();
}
}
@@ -0,0 +1,42 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 10/07/16
* Time: 13:35
*/
require_once( APPPATH . 'Libraries/Validation/InputValidations/BaseValidation.php' );
class InvoiceValidation extends BaseValidation {
protected $validationFields = [
'project_id' => [
'validations' => 'required|integer',
'fieldname' => 'project'
],
'invoicedate' => [
'validations' => 'date',
'fieldname' => 'factuurdatum'
],
'forecastdate' => [
'validations' => 'date',
'fieldname' => 'prognosedatum'
],
'invoiceamount' => [
'validations' => 'number',
'fieldname' => 'factuurbedrag'
],
'forecastamount' => [
'validations' => 'number',
'fieldname' => 'prognosebedrag'
]
];
public function __construct()
{
parent::__construct();
}
}
@@ -0,0 +1,27 @@
<?php
/**
* Created by PhpStorm.
* User: imac-3
* Date: 26/06/16
* Time: 21:13
*/
class LoginValidation extends BaseValidation {
protected $validationFields = [
'username' => [
'validations' => 'required|alphaNumericSpaces',
'fieldname' => 'gebruikersnaam'
],
'password' => [
'validations' => 'required',
'fieldname' => 'wachtwoord'
]
];
public function __construct()
{
parent::__construct();
}
}
@@ -0,0 +1,42 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 10/07/16
* Time: 13:35
*/
require_once( APPPATH . 'Libraries/Validation/InputValidations/BaseValidation.php' );
class OfferValidation extends BaseValidation {
protected $validationFields = [
'customer_id' => [
'validations' => 'required|numeric',
'fieldname' => 'klant'
],
'startdate' => [
'validations' => 'required|date',
'fieldname' => 'offertedatum'
],
'acceptdate' => [
'validations' => 'date',
'fieldname' => 'acceptatiedatum'
],
'rejectdate' => [
'validations' => 'date',
'fieldname' => 'afwijsdatum'
],
'acceptance_chance' => [
'validations' => 'numeric',
'fieldname' => 'afwijsdatum|minvalue-0|maxvalue-100'
]
];
public function __construct()
{
parent::__construct();
}
}
@@ -0,0 +1,42 @@
<?php
/**
* Created by Pensare Software
* User: Theo Weijmer
* Date: 26/06/16
* Time: 20:39
*/
class OrganisationValidation extends BaseValidation {
protected $validationFields = [
'brin' => [
'validations' => 'required|alphaNumeric',
'fieldname' => 'brinnummer'
],
'naam' => [
'validations' => 'required',
'fieldname' => 'Organisatienaam'
],
'naamkort' => [
'validations' => 'required',
'fieldname' => 'Organisatienaam (kort)'
],
'vestiging' => [
'validations' => 'required|alphaNumeric|unique',
'fieldname' => 'vestigingsnummer',
'model' => 'organisations_model',
'field' => 'vestiging'
],
'email' => [
'validations' => 'email',
'fieldname' => 'email'
]
];
public function __construct()
{
parent::__construct();
}
}
@@ -0,0 +1,28 @@
<?php
/**
* Created by PhpStorm.
* User: imac-3
* Date: 26/06/16
* Time: 21:13
*/
require_once( APPPATH . 'Libraries/Validation/InputValidations/BaseValidation.php' );
class PasswordRequestValidation extends BaseValidation {
protected $validationFields = [
'username' => [
'validations' => 'required|alphaNumericSpaces',
'fieldname' => 'gebruikersnaam'
],
'email' => [
'validations' => 'required|email',
'fieldname' => 'email'
]
];
public function __construct()
{
parent::__construct();
}
}
@@ -0,0 +1,34 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 10/07/16
* Time: 13:35
*/
require_once( APPPATH . 'Libraries/Validation/InputValidations/BaseValidation.php' );
class PaymentValidation extends BaseValidation {
protected $validationFields = [
'invoice_id' => [
'validations' => 'required|integer',
'fieldname' => 'factuur'
],
'paymentdate' => [
'validations' => 'date',
'fieldname' => 'betaaldatum'
],
'paymentamount' => [
'validations' => 'number',
'fieldname' => 'bedrag'
]
];
public function __construct()
{
parent::__construct();
}
}
@@ -0,0 +1,34 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 10/07/16
* Time: 13:35
*/
require_once( APPPATH . 'Libraries/Validation/InputValidations/BaseValidation.php' );
class ProjectValidation extends BaseValidation {
protected $validationFields = [
'customer_id' => [
'validations' => 'required|integer',
'fieldname' => 'klant'
],
'startdate' => [
'validations' => 'required|date',
'fieldname' => 'start project'
],
'enddate' => [
'validations' => 'date',
'fieldname' => 'eind project'
]
];
public function __construct()
{
parent::__construct();
}
}
@@ -0,0 +1,42 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 10/07/16
* Time: 13:35
*/
require_once( APPPATH . 'Libraries/Validation/InputValidations/BaseValidation.php' );
class ProjectcostValidation extends BaseValidation {
protected $validationFields = [
'project_id' => [
'validations' => 'required|integer',
'fieldname' => 'project'
],
'external_id' => [
'validations' => 'required|integer',
'fieldname' => 'externe'
],
'date' => [
'validations' => 'date',
'fieldname' => 'datum'
],
'costs' => [
'validations' => 'number',
'fieldname' => 'kosten'
],
'payed' => [
'validations' => 'number',
'fieldname' => 'betaald'
]
];
public function __construct()
{
parent::__construct();
}
}
@@ -0,0 +1,41 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 10/07/16
* Time: 13:35
*/
require_once( APPPATH . 'Libraries/Validation/InputValidations/BaseValidation.php' );
class ProjectemployeeValidation extends BaseValidation {
protected $validationFields = [
'user_id' => [
'validations' => 'integer',
'fieldname' => 'klant'
],
'startdate' => [
'validations' => 'date',
'fieldname' => 'start project'
],
'enddate' => [
'validations' => 'date',
'fieldname' => 'eind project'
]
];
public function __construct()
{
parent::__construct();
$this->handleSpecificValidations();
}
protected function handleSpecificValidations()
{
}
}
@@ -0,0 +1,34 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 10/07/16
* Time: 13:35
*/
require_once( APPPATH . 'Libraries/Validation/InputValidations/BaseValidation.php' );
class ProjecthourValidation extends BaseValidation {
protected $validationFields = [
'projectemployee_id' => [
'validations' => 'required|integer',
'fieldname' => 'projectmedewerker'
],
'hourdate' => [
'validations' => 'date',
'fieldname' => 'datum'
],
'hours' => [
'validations' => 'number',
'fieldname' => 'uren'
]
];
public function __construct()
{
parent::__construct();
}
}
@@ -0,0 +1,34 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 10/07/16
* Time: 13:35
*/
require_once( APPPATH . 'Libraries/Validation/InputValidations/BaseValidation.php' );
class ReservationValidation extends BaseValidation {
protected $validationFields = [
'project_id' => [
'validations' => 'required|integer',
'fieldname' => 'project'
],
'external_id' =>[
'validations' => 'required|integer',
'fieldname' => 'onderaannemer'
],
'reservationamount' => [
'validations' => 'number',
'fieldname' => 'bedrag'
]
];
public function __construct()
{
parent::__construct();
}
}
@@ -0,0 +1,46 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 10/07/16
* Time: 13:35
*/
require_once( APPPATH . 'Libraries/Validation/InputValidations/BaseValidation.php' );
class UserValidation extends BaseValidation {
protected $validationFields = [
'firstname' => [
'validations' => 'required|alphaNumericSpaces',
'fieldname' => 'firstname'
],
'lastname' => [
'validations' => 'required|alphaNumericSpaces',
'fieldname' => 'lastname'
],
'email' => [
'validations' => 'required|email|unique',
'fieldname' => 'email',
'model' => 'User_model',
'field' => 'email'
],
'username' => [
'validations' => 'required|alphanumeric|minlength-4|unique',
'fieldname' => 'username',
'model' => 'User_model',
'field' => 'username'
],
'hourlyrate' =>[
'validations' => 'decimal',
'fieldname' => 'uurtarief'
]
];
public function __construct()
{
parent::__construct();
}
}
+209
View File
@@ -0,0 +1,209 @@
<?php
namespace App\Libraries\Validation;
use CodeIgniter\HTTP\IncomingRequest;
/**
* Custom Validation Library
* Migrated from CodeIgniter 3 to CodeIgniter 4
*/
class Validation
{
private $fieldValue;
private $validations;
private $validation;
private $validationResult;
private array $errorMessages = [];
private $validationField;
protected IncomingRequest $request;
public function __construct()
{
$this->request = \Config\Services::request();
}
public function validate($fieldValue, $validationField = false): void
{
$this->setValidationField($validationField);
$this->setFieldValue($fieldValue);
$this->handle();
}
public function setValidationField($validationfield): void
{
$this->validationField = $validationfield;
}
public function getErrorMessages(): array
{
return $this->errorMessages;
}
public function getValidationResult(): bool
{
return $this->validationResult;
}
private function handle(): void
{
$this->setValidations();
$this->checkValidations();
$this->setValidationResult();
}
private function setValidations(): void
{
$this->validations = explode('|', $this->validationField['validations']);
}
private function setFieldValue($fieldValue): void
{
$this->fieldValue = $fieldValue;
}
private function setValidationResult(): void
{
if (count($this->errorMessages) == 0) {
$this->validationResult = true;
return;
}
$this->validationResult = false;
}
private function checkValidations(): void
{
foreach ($this->validations as $this->validation) {
if ($this->validation == 'required') $this->checkRequired();
if ($this->validation == 'alpha') $this->checkAlfa();
if ($this->validation == 'alphaNumeric') $this->checkAlfanumeric();
if ($this->validation == 'alphaNumericSpaces') $this->checkAlphaNumericSpaces();
if ($this->validation == 'alphaDash') $this->checkAlphaDash();
if ($this->validation == 'numeric') $this->checkNumeric();
if ($this->validation == 'integer') $this->checkInteger();
if ($this->validation == 'decimal') $this->checkDecimal();
if ($this->validation == 'email') $this->checkEmail();
if ($this->validation == 'unique') $this->checkUnique();
if ($this->validation == 'date') $this->checkDate();
if (substr($this->validation, 0, 9) == 'minlength') $this->checkMinlength();
if (substr($this->validation, 0, 9) == 'maxlength') $this->checkMaxlength();
if (substr($this->validation, 0, 8) == 'minvalue') $this->checkMinvalue();
if (substr($this->validation, 0, 8) == 'maxvalue') $this->checkMaxvalue();
}
}
public function checkRequired(): void
{
if (!$this->fieldValue || empty($this->fieldValue) || strlen($this->fieldValue) == 0)
$this->errorMessages[] = 'veld is verplicht';
}
public function checkAlfa(): void
{
$value = ctype_alpha($this->fieldValue);
if (!$value) $this->errorMessages[] = 'alleen letters toegestaan';
}
public function checkAlfaNumeric(): bool
{
$value = ctype_alnum((string)$this->fieldValue);
if (!$value) $this->errorMessages[] = 'alleen letters en cijfers toegestaan';
return $value;
}
public function checkAlphaNumericSpaces(): void
{
$value = (bool)preg_match('/^[A-Z0-9 ]+$/i', $this->fieldValue);
if (!$value) $this->errorMessages[] = 'alleen letters, cijfers en spaties toegestaan';
}
public function checkAlphaDash(): void
{
$value = (bool)preg_match('/^[a-z0-9_-]+$/i', $this->fieldValue);
if (!$value) $this->errorMessages[] = 'alleen letters, cijfers en streepjes toegestaan';
}
public function checkNumeric(): void
{
$value = (bool)preg_match('/^[\-+]?[0-9]*\.?[0-9]+$/', $this->fieldValue);
if (!$value) $this->errorMessages[] = 'alleen getallen toegestaan';
}
public function checkInteger(): void
{
$value = (bool)preg_match('/^[\-+]?[0-9]+$/', $this->fieldValue);
if (!$value) $this->errorMessages[] = 'alleen gehele getallen toegestaan';
}
public function checkDecimal(): void
{
$value = is_numeric($this->fieldValue);
if (!$value) $this->errorMessages[] = 'alleen getallen toegestaan';
}
public function checkEmail(): void
{
if (!$this->fieldValue || empty($this->fieldValue) || strlen($this->fieldValue) == 0) return;
$value = (bool)filter_var($this->fieldValue, FILTER_VALIDATE_EMAIL);
if (!$value) $this->errorMessages[] = 'ongeldig emailadres';
}
public function checkUnique(): void
{
$recordID = $this->request->getPost('id');
$model = $this->validationField['model'];
$field = $this->validationField['field'];
// For Eloquent models, we can call the static method directly
$value = $model::checkUnique($recordID, $field, $this->fieldValue);
if (!$value) $this->errorMessages[] = 'invoer moet uniek zijn';
}
public function checkDate(): void
{
if (empty($this->fieldValue)) return;
$dateParts = explode('-', $this->fieldValue);
if (count($dateParts) != 3) $dateParts = explode('/', $this->fieldValue);
if (count($dateParts) != 3) {
$this->errorMessages[] = 'invoer is geen datum';
return;
}
if (!checkdate((int)$dateParts[1], (int)$dateParts[0], (int)$dateParts[2]))
$this->errorMessages[] = 'invoer is geen datum';
}
private function checkMinlength(): void
{
$length = explode('-', $this->validation);
if (strlen($this->fieldValue) < (int)$length[1])
$this->errorMessages[] = 'moet minimaal uit ' . $length[1] . ' karakters bestaan';
}
private function checkMaxlength(): void
{
$length = explode('-', $this->validation);
if (strlen($this->fieldValue) > (int)$length[1])
$this->errorMessages[] = 'mag maximaal uit ' . $length[1] . ' karakters bestaan';
}
private function checkMinValue(): void
{
$value = explode('-', $this->validation);
if ($this->fieldValue < (float)$value[1])
$this->errorMessages[] = 'moet minimaal ' . $value[1] . ' zijn';
}
private function checkMaxValue(): void
{
$value = explode('-', $this->validation);
if ($this->fieldValue > (float)$value[1])
$this->errorMessages[] = 'mag maximaal ' . $value[1] . ' zijn';
}
}