Start Point al 2026

This commit is contained in:
mirko.aletto committed 2026-05-06 11:04:41 +02:00
commit 8a76e1db3b
371 files changed
+160283

No files matched your search

+112
View File
@@ -0,0 +1,112 @@
#--------------------------------------------------------------------
# Example Environment Configuration file
#
# This file can be used as a starting point for your own
# custom .env files, and contains most of the possible settings
# available in a default install.
#
# By default, all of the settings are commented out. If you want
# to override the setting, you must un-comment it by removing the '#'
# at the beginning of the line.
#--------------------------------------------------------------------
#--------------------------------------------------------------------
# ENVIRONMENT
#--------------------------------------------------------------------
CI_ENVIRONMENT = production
# CI_ENVIRONMENT = development
#--------------------------------------------------------------------
# MRK
#--------------------------------------------------------------------
MRK_FILE_PATH = '/opt/bitnami/projects/CSiCoDB2/writable/uploads/'
# MRK_FILE_PATH = ''
#--------------------------------------------------------------------
# APP
#--------------------------------------------------------------------
# app.baseURL = 'https://82.62.81.71:33330/'
app.baseURL = 'https://87.15.102.60:33330/'
# app.baseURL = 'http://localhost/'
# app.forceGlobalSecureRequests = false
# app.sessionDriver = 'CodeIgniter\Session\Handlers\FileHandler'
app.sessionCookieName = 'csicodb2_session'
app.sessionExpiration = 3600;
# app.sessionSavePath = NULL
# app.sessionMatchIP = false
# app.sessionTimeToUpdate = 300
# app.sessionRegenerateDestroy = false
# app.cookiePrefix = ''
# app.cookieDomain = ''
# app.cookiePath = '/'
# app.cookieSecure = false
# app.cookieHTTPOnly = false
# app.CSRFProtection = false
# app.CSRFTokenName = 'csrf_test_name'
# app.CSRFCookieName = 'csrf_cookie_name'
# app.CSRFExpire = 7200
# app.CSRFRegenerate = true
# app.CSRFExcludeURIs = []
# app.CSPEnabled = false
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------
database.default.hostname = localhost
database.default.database = CSiCoDB2
database.default.username = CSiCoUser
database.default.password = Fe69Ti66Tr67
database.default.DBDriver = MySQLi
# database.tests.hostname = localhost
# database.tests.database = ci4
# database.tests.username = root
# database.tests.password = root
# database.tests.DBDriver = MySQLi
#--------------------------------------------------------------------
# CONTENT SECURITY POLICY
#--------------------------------------------------------------------
# contentsecuritypolicy.reportOnly = false
# contentsecuritypolicy.defaultSrc = 'none'
# contentsecuritypolicy.scriptSrc = 'self'
# contentsecuritypolicy.styleSrc = 'self'
# contentsecuritypolicy.imageSrc = 'self'
# contentsecuritypolicy.base_uri = null
# contentsecuritypolicy.childSrc = null
# contentsecuritypolicy.connectSrc = 'self'
# contentsecuritypolicy.fontSrc = null
# contentsecuritypolicy.formAction = null
# contentsecuritypolicy.frameAncestors = null
# contentsecuritypolicy.mediaSrc = null
# contentsecuritypolicy.objectSrc = null
# contentsecuritypolicy.pluginTypes = null
# contentsecuritypolicy.reportURI = null
# contentsecuritypolicy.sandbox = false
# contentsecuritypolicy.upgradeInsecureRequests = false
#--------------------------------------------------------------------
# ENCRYPTION
#--------------------------------------------------------------------
# encryption.key =
# encryption.driver = OpenSSL
#--------------------------------------------------------------------
# HONEYPOT
#--------------------------------------------------------------------
# honeypot.hidden = 'true'
# honeypot.label = 'Fill This Field'
# honeypot.name = 'honeypot'
# honeypot.template = '<label>{label}</label><input type="text" name="{name}" value=""/>'
# honeypot.container = '<div style="display:none">{template}</div>'
+127
View File
@@ -0,0 +1,127 @@
#-------------------------
# Operating Specific Junk Files
#-------------------------
# OS X
.DS_Store
.AppleDouble
.LSOverride
# OS X Thumbnails
._*
# Windows image file caches
Thumbs.db
ehthumbs.db
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msm
*.msp
# Windows shortcuts
*.lnk
# Linux
*~
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
#-------------------------
# Environment Files
#-------------------------
# These should never be under version control,
# as it poses a security risk.
.env
.vagrant
Vagrantfile
#-------------------------
# Temporary Files
#-------------------------
writable/cache/*
!writable/cache/index.html
writable/logs/*
!writable/logs/index.html
writable/session/*
!writable/session/index.html
writable/uploads/*
!writable/uploads/index.html
writable/debugbar/*
php_errors.log
#-------------------------
# User Guide Temp Files
#-------------------------
user_guide_src/build/*
user_guide_src/cilexer/build/*
user_guide_src/cilexer/dist/*
user_guide_src/cilexer/pycilexer.egg-info/*
#-------------------------
# Test Files
#-------------------------
tests/coverage*
# Don't save phpunit under version control.
phpunit
#-------------------------
# Composer
#-------------------------
vendor/
#-------------------------
# IDE / Development Files
#-------------------------
# Modules Testing
_modules/*
# phpenv local config
.php-version
# Jetbrains editors (PHPStorm, etc)
.idea/
*.iml
# Netbeans
nbproject/
build/
nbbuild/
dist/
nbdist/
nbactions.xml
nb-configuration.xml
.nb-gradle/
# Sublime Text
*.tmlanguage.cache
*.tmPreferences.cache
*.stTheme.cache
*.sublime-workspace
*.sublime-project
.phpintel
/api/
# Visual Studio Code
.vscode/
/results/
/phpunit*.xml
/.phpunit.*.cache
+64
View File
@@ -0,0 +1,64 @@
# CodeIgniter 4 Application Starter
## What is CodeIgniter?
CodeIgniter is a PHP full-stack web framework that is light, fast, flexible, and secure.
More information can be found at the [official site](http://codeigniter.com).
This repository holds a composer-installable app starter.
It has been built from the
[development repository](https://github.com/codeigniter4/CodeIgniter4).
More information about the plans for version 4 can be found in [the announcement](http://forum.codeigniter.com/thread-62615.html) on the forums.
The user guide corresponding to this version of the framework can be found
[here](https://codeigniter4.github.io/userguide/).
## Installation & updates
`composer create-project codeigniter4/appstarter` then `composer update` whenever
there is a new release of the framework.
When updating, check the release notes to see if there are any changes you might need to apply
to your `app` folder. The affected files can be copied or merged from
`vendor/codeigniter4/framework/app`.
## Setup
Copy `env` to `.env` and tailor for your app, specifically the baseURL
and any database settings.
## Important Change with index.php
`index.php` is no longer in the root of the project! It has been moved inside the *public* folder,
for better security and separation of components.
This means that you should configure your web server to "point" to your project's *public* folder, and
not to the project root. A better practice would be to configure a virtual host to point there. A poor practice would be to point your web server to the project root and expect to enter *public/...*, as the rest of your logic and the
framework are exposed.
**Please** read the user guide for a better explanation of how CI4 works!
The user guide updating and deployment is a bit awkward at the moment, but we are working on it!
## Repository Management
We use Github issues, in our main repository, to track **BUGS** and to track approved **DEVELOPMENT** work packages.
We use our [forum](http://forum.codeigniter.com) to provide SUPPORT and to discuss
FEATURE REQUESTS.
This repository is a "distribution" one, built by our release preparation script.
Problems with it can be raised on our forum, or as issues in the main repository.
## Server Requirements
PHP version 7.2 or higher is required, with the following extensions installed:
- [intl](http://php.net/manual/en/intl.requirements.php)
- [libcurl](http://php.net/manual/en/curl.requirements.php) if you plan to use the HTTP\CURLRequest library
Additionally, make sure that the following extensions are enabled in your PHP:
- json (enabled by default - don't turn it off)
- [mbstring](http://php.net/manual/en/mbstring.installation.php)
- [mysqlnd](http://php.net/manual/en/mysqlnd.install.php)
- xml (enabled by default - don't turn it off)
+6
View File
@@ -0,0 +1,6 @@
<IfModule authz_core_module>
Require all denied
</IfModule>
<IfModule !authz_core_module>
Deny from all
</IfModule>
+15
View File
@@ -0,0 +1,15 @@
<?php
/**
* The goal of this file is to allow developers a location
* where they can overwrite core procedural functions and
* replace them with their own. This file is loaded during
* the bootstrap process and is called during the frameworks
* execution.
*
* This can be looked at as a `master helper` file that is
* loaded early on, and may also contain additional functions
* that you'd like to use throughout your entire application
*
* @link: https://codeigniter4.github.io/CodeIgniter4/
*/
+268
View File
@@ -0,0 +1,268 @@
<?php namespace Config;
use CodeIgniter\Config\BaseConfig;
class App extends BaseConfig
{
/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
| http://example.com/
|
| If this is not set then CodeIgniter will try guess the protocol, domain
| and path to your installation. However, you should always configure this
| explicitly and never rely on auto-guessing, especially in production
| environments.
|
*/
public $baseURL = 'http://localhost:8080/';
/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/
public $indexPage = 'index.php';
/*
|--------------------------------------------------------------------------
| URI PROTOCOL
|--------------------------------------------------------------------------
|
| This item determines which getServer global should be used to retrieve the
| URI string. The default setting of 'REQUEST_URI' works for most servers.
| If your links do not seem to work, try one of the other delicious flavors:
|
| 'REQUEST_URI' Uses $_SERVER['REQUEST_URI']
| 'QUERY_STRING' Uses $_SERVER['QUERY_STRING']
| 'PATH_INFO' Uses $_SERVER['PATH_INFO']
|
| WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded!
*/
public $uriProtocol = 'REQUEST_URI';
/*
|--------------------------------------------------------------------------
| Default Locale
|--------------------------------------------------------------------------
|
| The Locale roughly represents the language and location that your visitor
| is viewing the site from. It affects the language strings and other
| strings (like currency markers, numbers, etc), that your program
| should run under for this request.
|
*/
public $defaultLocale = 'en';
/*
|--------------------------------------------------------------------------
| Negotiate Locale
|--------------------------------------------------------------------------
|
| If true, the current Request object will automatically determine the
| language to use based on the value of the Accept-Language header.
|
| If false, no automatic detection will be performed.
|
*/
public $negotiateLocale = false;
/*
|--------------------------------------------------------------------------
| Supported Locales
|--------------------------------------------------------------------------
|
| If $negotiateLocale is true, this array lists the locales supported
| by the application in descending order of priority. If no match is
| found, the first locale will be used.
|
*/
public $supportedLocales = ['en'];
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| The default timezone that will be used in your application to display
| dates with the date helper, and can be retrieved through app_timezone()
|
*/
public $appTimezone = 'America/Chicago';
/*
|--------------------------------------------------------------------------
| Default Character Set
|--------------------------------------------------------------------------
|
| This determines which character set is used by default in various methods
| that require a character set to be provided.
|
| See http://php.net/htmlspecialchars for a list of supported charsets.
|
*/
public $charset = 'UTF-8';
/*
|--------------------------------------------------------------------------
| URI PROTOCOL
|--------------------------------------------------------------------------
|
| If true, this will force every request made to this application to be
| made via a secure connection (HTTPS). If the incoming request is not
| secure, the user will be redirected to a secure version of the page
| and the HTTP Strict Transport Security header will be set.
*/
public $forceGlobalSecureRequests = false;
/*
|--------------------------------------------------------------------------
| Session Variables
|--------------------------------------------------------------------------
|
| 'sessionDriver'
|
| The storage driver to use: files, database, redis, memcached
| - CodeIgniter\Session\Handlers\FileHandler
| - CodeIgniter\Session\Handlers\DatabaseHandler
| - CodeIgniter\Session\Handlers\MemcachedHandler
| - CodeIgniter\Session\Handlers\RedisHandler
|
| 'sessionCookieName'
|
| The session cookie name, must contain only [0-9a-z_-] characters
|
| 'sessionExpiration'
|
| The number of SECONDS you want the session to last.
| Setting to 0 (zero) means expire when the browser is closed.
|
| 'sessionSavePath'
|
| The location to save sessions to, driver dependent.
|
| For the 'files' driver, it's a path to a writable directory.
| WARNING: Only absolute paths are supported!
|
| For the 'database' driver, it's a table name.
| Please read up the manual for the format with other session drivers.
|
| IMPORTANT: You are REQUIRED to set a valid save path!
|
| 'sessionMatchIP'
|
| Whether to match the user's IP address when reading the session data.
|
| WARNING: If you're using the database driver, don't forget to update
| your session table's PRIMARY KEY when changing this setting.
|
| 'sessionTimeToUpdate'
|
| How many seconds between CI regenerating the session ID.
|
| 'sessionRegenerateDestroy'
|
| Whether to destroy session data associated with the old session ID
| when auto-regenerating the session ID. When set to FALSE, the data
| will be later deleted by the garbage collector.
|
| Other session cookie settings are shared with the rest of the application,
| except for 'cookie_prefix' and 'cookie_httponly', which are ignored here.
|
*/
public $sessionDriver = 'CodeIgniter\Session\Handlers\FileHandler';
public $sessionCookieName = 'ci_session';
public $sessionExpiration = 7200;
public $sessionSavePath = WRITEPATH . 'session';
public $sessionMatchIP = false;
public $sessionTimeToUpdate = 300;
public $sessionRegenerateDestroy = false;
/*
|--------------------------------------------------------------------------
| Cookie Related Variables
|--------------------------------------------------------------------------
|
| 'cookiePrefix' = Set a cookie name prefix if you need to avoid collisions
| 'cookieDomain' = Set to .your-domain.com for site-wide cookies
| 'cookiePath' = Typically will be a forward slash
| 'cookieSecure' = Cookie will only be set if a secure HTTPS connection exists.
| 'cookieHTTPOnly' = Cookie will only be accessible via HTTP(S) (no javascript)
|
| Note: These settings (with the exception of 'cookie_prefix' and
| 'cookie_httponly') will also affect sessions.
|
*/
public $cookiePrefix = '';
public $cookieDomain = '';
public $cookiePath = '/';
public $cookieSecure = false;
public $cookieHTTPOnly = false;
/*
|--------------------------------------------------------------------------
| Reverse Proxy IPs
|--------------------------------------------------------------------------
|
| If your server is behind a reverse proxy, you must whitelist the proxy
| IP addresses from which CodeIgniter should trust headers such as
| HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP in order to properly identify
| the visitor's IP address.
|
| You can use both an array or a comma-separated list of proxy addresses,
| as well as specifying whole subnets. Here are a few examples:
|
| Comma-separated: '10.0.1.200,192.168.5.0/24'
| Array: array('10.0.1.200', '192.168.5.0/24')
*/
public $proxyIPs = '';
/*
|--------------------------------------------------------------------------
| Cross Site Request Forgery
|--------------------------------------------------------------------------
| Enables a CSRF cookie token to be set. When set to TRUE, token will be
| checked on a submitted form. If you are accepting user data, it is strongly
| recommended CSRF protection be enabled.
|
| CSRFTokenName = The token name
| CSRFHeaderName = The header name
| CSRFCookieName = The cookie name
| CSRFExpire = The number in seconds the token should expire.
| CSRFRegenerate = Regenerate token on every submission
| CSRFRedirect = Redirect to previous page with error on failure
*/
public $CSRFTokenName = 'csrf_test_name';
public $CSRFHeaderName = 'X-CSRF-TOKEN';
public $CSRFCookieName = 'csrf_cookie_name';
public $CSRFExpire = 7200;
public $CSRFRegenerate = true;
public $CSRFRedirect = true;
/*
|--------------------------------------------------------------------------
| Content Security Policy
|--------------------------------------------------------------------------
| Enables the Response's Content Secure Policy to restrict the sources that
| can be used for images, scripts, CSS files, audio, video, etc. If enabled,
| the Response object will populate default values for the policy from the
| ContentSecurityPolicy.php file. Controllers can always add to those
| restrictions at run time.
|
| For a better understanding of CSP, see these documents:
| - http://www.html5rocks.com/en/tutorials/security/content-security-policy/
| - http://www.w3.org/TR/CSP/
*/
public $CSPEnabled = false;
}
+66
View File
@@ -0,0 +1,66 @@
<?php
namespace Config;
use CodeIgniter\Config\AutoloadConfig;
/**
* -------------------------------------------------------------------
* AUTO-LOADER
* -------------------------------------------------------------------
* This file defines the namespaces and class maps so the Autoloader
* can find the files as needed.
*
* NOTE: If you use an identical key in $psr4 or $classmap, then
* the values in this file will overwrite the framework's values.
*/
class Autoload extends AutoloadConfig
{
/**
* -------------------------------------------------------------------
* Namespaces
* -------------------------------------------------------------------
* This maps the locations of any namespaces in your application to
* their location on the file system. These are used by the autoloader
* to locate files the first time they have been instantiated.
*
* The '/app' and '/system' directories are already mapped for you.
* you may change the name of the 'App' namespace if you wish,
* but this should be done prior to creating any namespaced classes,
* else you will need to modify all of those classes for this to work.
*
* Prototype:
*
* $psr4 = [
* 'CodeIgniter' => SYSTEMPATH,
* 'App' => APPPATH
* ];
*
* @var array
*/
public $psr4 = [
APP_NAMESPACE => APPPATH, // For custom app namespace
'Config' => APPPATH . 'Config',
];
/**
* -------------------------------------------------------------------
* Class Map
* -------------------------------------------------------------------
* The class map provides a map of class names and their exact
* location on the drive. Classes loaded in this manner will have
* slightly faster performance because they will not have to be
* searched for within one or more directories as they would if they
* were being autoloaded through a namespace.
*
* Prototype:
*
* $classmap = [
* 'MyClass' => '/path/to/class/file.php'
* ];
*
* @var array
*/
public $classmap = [];
}
+32
View File
@@ -0,0 +1,32 @@
<?php
/*
|--------------------------------------------------------------------------
| ERROR DISPLAY
|--------------------------------------------------------------------------
| In development, we want to show as many errors as possible to help
| make sure they don't make it to production. And save us hours of
| painful debugging.
*/
error_reporting(-1);
ini_set('display_errors', '1');
/*
|--------------------------------------------------------------------------
| DEBUG BACKTRACES
|--------------------------------------------------------------------------
| If true, this constant will tell the error screens to display debug
| backtraces along with the other error information. If you would
| prefer to not see this, set this value to false.
*/
defined('SHOW_DEBUG_BACKTRACE') || define('SHOW_DEBUG_BACKTRACE', true);
/*
|--------------------------------------------------------------------------
| DEBUG MODE
|--------------------------------------------------------------------------
| Debug mode is an experimental flag that can allow changes throughout
| the system. This will control whether Kint is loaded, and a few other
| items. It can always be used within your own application too.
*/
defined('CI_DEBUG') || define('CI_DEBUG', true);
+22
View File
@@ -0,0 +1,22 @@
<?php
/*
|--------------------------------------------------------------------------
| ERROR DISPLAY
|--------------------------------------------------------------------------
| Don't show ANY in production environments. Instead, let the system catch
| it and display a generic error message.
*/
ini_set('display_errors', '0');
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED);
/*
|--------------------------------------------------------------------------
| DEBUG MODE
|--------------------------------------------------------------------------
| Debug mode is an experimental flag that can allow changes throughout
| the system. It's not widely used currently, and may not survive
| release of the framework.
*/
defined('CI_DEBUG') || define('CI_DEBUG', false);
+33
View File
@@ -0,0 +1,33 @@
<?php
/*
|--------------------------------------------------------------------------
| ERROR DISPLAY
|--------------------------------------------------------------------------
| In development, we want to show as many errors as possible to help
| make sure they don't make it to production. And save us hours of
| painful debugging.
*/
error_reporting(-1);
ini_set('display_errors', '1');
/*
|--------------------------------------------------------------------------
| DEBUG BACKTRACES
|--------------------------------------------------------------------------
| If true, this constant will tell the error screens to display debug
| backtraces along with the other error information. If you would
| prefer to not see this, set this value to false.
*/
defined('SHOW_DEBUG_BACKTRACE') || define('SHOW_DEBUG_BACKTRACE', true);
/*
|--------------------------------------------------------------------------
| DEBUG MODE
|--------------------------------------------------------------------------
| Debug mode is an experimental flag that can allow changes throughout
| the system. It's not widely used currently, and may not survive
| release of the framework.
*/
defined('CI_DEBUG') || define('CI_DEBUG', true);
+120
View File
@@ -0,0 +1,120 @@
<?php namespace Config;
use CodeIgniter\Config\BaseConfig;
class Cache extends BaseConfig
{
/*
|--------------------------------------------------------------------------
| Primary Handler
|--------------------------------------------------------------------------
|
| The name of the preferred handler that should be used. If for some reason
| it is not available, the $backupHandler will be used in its place.
|
*/
public $handler = 'file';
/*
|--------------------------------------------------------------------------
| Backup Handler
|--------------------------------------------------------------------------
|
| The name of the handler that will be used in case the first one is
| unreachable. Often, 'file' is used here since the filesystem is
| always available, though that's not always practical for the app.
|
*/
public $backupHandler = 'dummy';
/*
|--------------------------------------------------------------------------
| Cache Directory Path
|--------------------------------------------------------------------------
|
| The path to where cache files should be stored, if using a file-based
| system.
|
*/
public $storePath = WRITEPATH . 'cache/';
/*
|--------------------------------------------------------------------------
| Cache Include Query String
|--------------------------------------------------------------------------
|
| Whether to take the URL query string into consideration when generating
| output cache files. Valid options are:
|
| false = Disabled
| true = Enabled, take all query parameters into account.
| Please be aware that this may result in numerous cache
| files generated for the same page over and over again.
| array('q') = Enabled, but only take into account the specified list
| of query parameters.
|
*/
public $cacheQueryString = false;
/*
|--------------------------------------------------------------------------
| Key Prefix
|--------------------------------------------------------------------------
|
| This string is added to all cache item names to help avoid collisions
| if you run multiple applications with the same cache engine.
|
*/
public $prefix = '';
/*
| -------------------------------------------------------------------------
| Memcached settings
| -------------------------------------------------------------------------
| Your Memcached servers can be specified below, if you are using
| the Memcached drivers.
|
| See: https://codeigniter.com/user_guide/libraries/caching.html#memcached
|
*/
public $memcached = [
'host' => '127.0.0.1',
'port' => 11211,
'weight' => 1,
'raw' => false,
];
/*
| -------------------------------------------------------------------------
| Redis settings
| -------------------------------------------------------------------------
| Your Redis server can be specified below, if you are using
| the Redis or Predis drivers.
|
*/
public $redis = [
'host' => '127.0.0.1',
'password' => null,
'port' => 6379,
'timeout' => 0,
'database' => 0,
];
/*
|--------------------------------------------------------------------------
| Available Cache Handlers
|--------------------------------------------------------------------------
|
| This is an array of cache engine alias' and class names. Only engines
| that are listed here are allowed to be used.
|
*/
public $validHandlers = [
'dummy' => \CodeIgniter\Cache\Handlers\DummyHandler::class,
'file' => \CodeIgniter\Cache\Handlers\FileHandler::class,
'memcached' => \CodeIgniter\Cache\Handlers\MemcachedHandler::class,
'predis' => \CodeIgniter\Cache\Handlers\PredisHandler::class,
'redis' => \CodeIgniter\Cache\Handlers\RedisHandler::class,
'wincache' => \CodeIgniter\Cache\Handlers\WincacheHandler::class,
];
}
+77
View File
@@ -0,0 +1,77 @@
<?php
//--------------------------------------------------------------------
// App Namespace
//--------------------------------------------------------------------
// This defines the default Namespace that is used throughout
// CodeIgniter to refer to the Application directory. Change
// this constant to change the namespace that all application
// classes should use.
//
// NOTE: changing this will require manually modifying the
// existing namespaces of App\* namespaced-classes.
//
defined('APP_NAMESPACE') || define('APP_NAMESPACE', 'App');
/*
|--------------------------------------------------------------------------
| Composer Path
|--------------------------------------------------------------------------
|
| The path that Composer's autoload file is expected to live. By default,
| the vendor folder is in the Root directory, but you can customize that here.
*/
defined('COMPOSER_PATH') || define('COMPOSER_PATH', ROOTPATH . 'vendor/autoload.php');
/*
|--------------------------------------------------------------------------
| Timing Constants
|--------------------------------------------------------------------------
|
| Provide simple ways to work with the myriad of PHP functions that
| require information to be in seconds.
*/
defined('SECOND') || define('SECOND', 1);
defined('MINUTE') || define('MINUTE', 60);
defined('HOUR') || define('HOUR', 3600);
defined('DAY') || define('DAY', 86400);
defined('WEEK') || define('WEEK', 604800);
defined('MONTH') || define('MONTH', 2592000);
defined('YEAR') || define('YEAR', 31536000);
defined('DECADE') || define('DECADE', 315360000);
/*
|--------------------------------------------------------------------------
| Exit Status Codes
|--------------------------------------------------------------------------
|
| Used to indicate the conditions under which the script is exit()ing.
| While there is no universal standard for error codes, there are some
| broad conventions. Three such conventions are mentioned below, for
| those who wish to make use of them. The CodeIgniter defaults were
| chosen for the least overlap with these conventions, while still
| leaving room for others to be defined in future versions and user
| applications.
|
| The three main conventions used for determining exit status codes
| are as follows:
|
| Standard C/C++ Library (stdlibc):
| http://www.gnu.org/software/libc/manual/html_node/Exit-Status.html
| (This link also contains other GNU-specific conventions)
| BSD sysexits.h:
| http://www.gsp.com/cgi-bin/man.cgi?section=3&topic=sysexits
| Bash scripting:
| http://tldp.org/LDP/abs/html/exitcodes.html
|
*/
defined('EXIT_SUCCESS') || define('EXIT_SUCCESS', 0); // no errors
defined('EXIT_ERROR') || define('EXIT_ERROR', 1); // generic error
defined('EXIT_CONFIG') || define('EXIT_CONFIG', 3); // configuration error
defined('EXIT_UNKNOWN_FILE') || define('EXIT_UNKNOWN_FILE', 4); // file not found
defined('EXIT_UNKNOWN_CLASS') || define('EXIT_UNKNOWN_CLASS', 5); // unknown class
defined('EXIT_UNKNOWN_METHOD') || define('EXIT_UNKNOWN_METHOD', 6); // unknown class member
defined('EXIT_USER_INPUT') || define('EXIT_USER_INPUT', 7); // invalid user input
defined('EXIT_DATABASE') || define('EXIT_DATABASE', 8); // database error
defined('EXIT__AUTO_MIN') || define('EXIT__AUTO_MIN', 9); // lowest automatically-assigned error code
defined('EXIT__AUTO_MAX') || define('EXIT__AUTO_MAX', 125); // highest automatically-assigned error code
+48
View File
@@ -0,0 +1,48 @@
<?php namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Class ContentSecurityPolicyConfig
*
* Stores the default settings for the ContentSecurityPolicy, if you
* choose to use it. The values here will be read in and set as defaults
* for the site. If needed, they can be overridden on a page-by-page basis.
*
* Suggested reference for explanations:
* https://www.html5rocks.com/en/tutorials/security/content-security-policy/
*
* @package Config
*/
class ContentSecurityPolicy extends BaseConfig
{
// broadbrush CSP management
public $reportOnly = false; // default CSP report context
public $reportURI = null; // URL to send violation reports to
public $upgradeInsecureRequests = false; // toggle for forcing https
// sources allowed; string or array of strings
// Note: once you set a policy to 'none', it cannot be further restricted
public $defaultSrc = null; // will default to self if not over-ridden
public $scriptSrc = 'self';
public $styleSrc = 'self';
public $imageSrc = 'self';
public $baseURI = null; // will default to self if not over-ridden
public $childSrc = 'self';
public $connectSrc = 'self';
public $fontSrc = null;
public $formAction = 'self';
public $frameAncestors = null;
public $mediaSrc = null;
public $objectSrc = 'self';
public $manifestSrc = null;
// mime types allowed; string or array of strings
public $pluginTypes = null;
// list of actions allowed; string or array of strings
public $sandbox = null;
}
+114
View File
@@ -0,0 +1,114 @@
<?php namespace Config;
/**
* Database Configuration
*
* @package Config
*/
class Database extends \CodeIgniter\Database\Config
{
/**
* The directory that holds the Migrations
* and Seeds directories.
*
* @var string
*/
public $filesPath = APPPATH . 'Database/';
/**
* Lets you choose which connection group to
* use if no other is specified.
*
* @var string
*/
public $defaultGroup = 'default';
/**
* The default database connection.
*
* @var array
*/
public $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => '',
'password' => '',
'database' => '',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => (ENVIRONMENT !== 'production'),
'cacheOn' => false,
'cacheDir' => '',
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
];
/**
* This database connection is used when
* running PHPUnit database tests.
*
* @var array
*/
public $tests = [
'DSN' => '',
'hostname' => '127.0.0.1',
'username' => '',
'password' => '',
'database' => ':memory:',
'DBDriver' => 'SQLite3',
'DBPrefix' => 'db_', // Needed to ensure we're working correctly with prefixes live. DO NOT REMOVE FOR CI DEVS
'pConnect' => false,
'DBDebug' => (ENVIRONMENT !== 'production'),
'cacheOn' => false,
'cacheDir' => '',
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
];
//--------------------------------------------------------------------
public function __construct()
{
parent::__construct();
// Ensure that we always set the database group to 'tests' if
// we are currently running an automated test suite, so that
// we don't overwrite live data on accident.
if (ENVIRONMENT === 'testing')
{
$this->defaultGroup = 'tests';
// Under Travis-CI, we can set an ENV var named 'DB_GROUP'
// so that we can test against multiple databases.
if ($group = getenv('DB'))
{
if (is_file(TESTPATH . 'travis/Database.php'))
{
require TESTPATH . 'travis/Database.php';
if (! empty($dbconfig) && array_key_exists($group, $dbconfig))
{
$this->tests = $dbconfig[$group];
}
}
}
}
}
//--------------------------------------------------------------------
}
+33
View File
@@ -0,0 +1,33 @@
<?php namespace Config;
/**
* DocTypes
*
* @package Config
*/
class DocTypes
{
public $list =
[
'xhtml11' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">',
'xhtml1-strict' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
'xhtml1-trans' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
'xhtml1-frame' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">',
'xhtml-basic11' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">',
'html5' => '<!DOCTYPE html>',
'html4-strict' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">',
'html4-trans' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
'html4-frame' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">',
'mathml1' => '<!DOCTYPE math SYSTEM "http://www.w3.org/Math/DTD/mathml1/mathml.dtd">',
'mathml2' => '<!DOCTYPE math PUBLIC "-//W3C//DTD MathML 2.0//EN" "http://www.w3.org/Math/DTD/mathml2/mathml2.dtd">',
'svg10' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">',
'svg11' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">',
'svg11-basic' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1 Basic//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd">',
'svg11-tiny' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1 Tiny//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd">',
'xhtml-math-svg-xh' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">',
'xhtml-math-svg-sh' => '<!DOCTYPE svg:svg PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">',
'xhtml-rdfa-1' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">',
'xhtml-rdfa-2' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.1//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-2.dtd">',
];
}
+171
View File
@@ -0,0 +1,171 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Email extends BaseConfig
{
/**
* @var string
*/
public $fromEmail;
/**
* @var string
*/
public $fromName;
/**
* @var string
*/
public $recipients;
/**
* The "user agent"
*
* @var string
*/
public $userAgent = 'CodeIgniter';
/**
* The mail sending protocol: mail, sendmail, smtp
*
* @var string
*/
public $protocol = 'mail';
/**
* The server path to Sendmail.
*
* @var string
*/
public $mailPath = '/usr/sbin/sendmail';
/**
* SMTP Server Address
*
* @var string
*/
public $SMTPHost;
/**
* SMTP Username
*
* @var string
*/
public $SMTPUser;
/**
* SMTP Password
*
* @var string
*/
public $SMTPPass;
/**
* SMTP Port
*
* @var integer
*/
public $SMTPPort = 25;
/**
* SMTP Timeout (in seconds)
*
* @var integer
*/
public $SMTPTimeout = 5;
/**
* Enable persistent SMTP connections
*
* @var boolean
*/
public $SMTPKeepAlive = false;
/**
* SMTP Encryption. Either tls or ssl
*
* @var string
*/
public $SMTPCrypto = 'tls';
/**
* Enable word-wrap
*
* @var boolean
*/
public $wordWrap = true;
/**
* Character count to wrap at
*
* @var integer
*/
public $wrapChars = 76;
/**
* Type of mail, either 'text' or 'html'
*
* @var string
*/
public $mailType = 'text';
/**
* Character set (utf-8, iso-8859-1, etc.)
*
* @var string
*/
public $charset = 'UTF-8';
/**
* Whether to validate the email address
*
* @var boolean
*/
public $validate = false;
/**
* Email Priority. 1 = highest. 5 = lowest. 3 = normal
*
* @var integer
*/
public $priority = 3;
/**
* Newline character. (Use “\r\n” to comply with RFC 822)
*
* @var string
*/
public $CRLF = "\r\n";
/**
* Newline character. (Use “\r\n” to comply with RFC 822)
*
* @var string
*/
public $newline = "\r\n";
/**
* Enable BCC Batch Mode.
*
* @var boolean
*/
public $BCCBatchMode = false;
/**
* Number of emails in each BCC batch
*
* @var integer
*/
public $BCCBatchSize = 200;
/**
* Enable notify message from server
*
* @var boolean
*/
public $DSN = false;
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Encryption configuration.
*
* These are the settings used for encryption, if you don't pass a parameter
* array to the encrypter for creation/initialization.
*/
class Encryption extends BaseConfig
{
/*
|--------------------------------------------------------------------------
| Encryption Key Starter
|--------------------------------------------------------------------------
|
| If you use the Encryption class you must set an encryption key (seed).
| You need to ensure it is long enough for the cipher and mode you plan to use.
| See the user guide for more info.
*/
public $key = '';
/*
|--------------------------------------------------------------------------
| Encryption driver to use
|--------------------------------------------------------------------------
|
| One of the supported drivers, eg 'OpenSSL' or 'Sodium'.
| The default driver, if you don't specify one, is 'OpenSSL'.
*/
public $driver = 'OpenSSL';
}
+52
View File
@@ -0,0 +1,52 @@
<?php namespace Config;
use CodeIgniter\Events\Events;
use CodeIgniter\Exceptions\FrameworkException;
/*
* --------------------------------------------------------------------
* Application Events
* --------------------------------------------------------------------
* Events allow you to tap into the execution of the program without
* modifying or extending core files. This file provides a central
* location to define your events, though they can always be added
* at run-time, also, if needed.
*
* You create code that can execute by subscribing to events with
* the 'on()' method. This accepts any form of callable, including
* Closures, that will be executed when the event is triggered.
*
* Example:
* Events::on('create', [$myInstance, 'myMethod']);
*/
Events::on('pre_system', function () {
if (ENVIRONMENT !== 'testing')
{
if (ini_get('zlib.output_compression'))
{
throw FrameworkException::forEnabledZlibOutputCompression();
}
while (ob_get_level() > 0)
{
ob_end_flush();
}
ob_start(function ($buffer) {
return $buffer;
});
}
/*
* --------------------------------------------------------------------
* Debug Toolbar Listeners.
* --------------------------------------------------------------------
* If you delete, they will no longer be collected.
*/
if (ENVIRONMENT !== 'production')
{
Events::on('DBQuery', 'CodeIgniter\Debug\Toolbar\Collectors\Database::collect');
Services::toolbar()->respond();
}
});
+42
View File
@@ -0,0 +1,42 @@
<?php namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Setup how the exception handler works.
*
* @package Config
*/
class Exceptions extends BaseConfig
{
/*
|--------------------------------------------------------------------------
| LOG EXCEPTIONS?
|--------------------------------------------------------------------------
| If true, then exceptions will be logged
| through Services::Log.
|
| Default: true
*/
public $log = true;
/*
|--------------------------------------------------------------------------
| DO NOT LOG STATUS CODES
|--------------------------------------------------------------------------
| Any status codes here will NOT be logged if logging is turned on.
| By default, only 404 (Page Not Found) exceptions are ignored.
*/
public $ignoreCodes = [ 404 ];
/*
|--------------------------------------------------------------------------
| Error Views Path
|--------------------------------------------------------------------------
| This is the path to the directory that contains the 'cli' and 'html'
| directories that hold the views used to generate errors.
|
| Default: APPPATH.'Views/errors'
*/
public $errorViewPath = APPPATH . 'Views/errors';
}
+36
View File
@@ -0,0 +1,36 @@
<?php namespace Config;
use CodeIgniter\Config\BaseConfig;
class Filters extends BaseConfig
{
// Makes reading things below nicer,
// and simpler to change out script that's used.
public $aliases = [
'csrf' => \CodeIgniter\Filters\CSRF::class,
'toolbar' => \CodeIgniter\Filters\DebugToolbar::class,
'honeypot' => \CodeIgniter\Filters\Honeypot::class,
];
// Always applied before every request
public $globals = [
'before' => [
//'honeypot'
// 'csrf',
],
'after' => [
'toolbar',
//'honeypot'
],
];
// Works on all of a particular HTTP method
// (GET, POST, etc) as BEFORE filters only
// like: 'post' => ['CSRF', 'throttle'],
public $methods = [];
// List filter aliases and any before/after uri patterns
// that they should run on, like:
// 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']],
public $filters = [];
}
+6
View File
@@ -0,0 +1,6 @@
<?php namespace Config;
class ForeignCharacters extends \CodeIgniter\Config\ForeignCharacters
{
}
+85
View File
@@ -0,0 +1,85 @@
<?php namespace Config;
use CodeIgniter\Config\BaseConfig;
class Format extends BaseConfig
{
/*
|--------------------------------------------------------------------------
| Available Response Formats
|--------------------------------------------------------------------------
|
| When you perform content negotiation with the request, these are the
| available formats that your application supports. This is currently
| only used with the API\ResponseTrait. A valid Formatter must exist
| for the specified format.
|
| These formats are only checked when the data passed to the respond()
| method is an array.
|
*/
public $supportedResponseFormats = [
'application/json',
'application/xml', // machine-readable XML
'text/xml', // human-readable XML
];
/*
|--------------------------------------------------------------------------
| Formatters
|--------------------------------------------------------------------------
|
| Lists the class to use to format responses with of a particular type.
| For each mime type, list the class that should be used. Formatters
| can be retrieved through the getFormatter() method.
|
*/
public $formatters = [
'application/json' => \CodeIgniter\Format\JSONFormatter::class,
'application/xml' => \CodeIgniter\Format\XMLFormatter::class,
'text/xml' => \CodeIgniter\Format\XMLFormatter::class,
];
/*
|--------------------------------------------------------------------------
| Formatters Options
|--------------------------------------------------------------------------
|
| Additional Options to adjust default formatters behaviour.
| For each mime type, list the additional options that should be used.
|
*/
public $formatterOptions = [
'application/json' => JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
'application/xml' => 0,
'text/xml' => 0,
];
//--------------------------------------------------------------------
/**
* A Factory method to return the appropriate formatter for the given mime type.
*
* @param string $mime
*
* @return \CodeIgniter\Format\FormatterInterface
*/
public function getFormatter(string $mime)
{
if (! array_key_exists($mime, $this->formatters))
{
throw new \InvalidArgumentException('No Formatter defined for mime type: ' . $mime);
}
$class = $this->formatters[$mime];
if (! class_exists($class))
{
throw new \BadMethodCallException($class . ' is not a valid Formatter.');
}
return new $class();
}
//--------------------------------------------------------------------
}
+42
View File
@@ -0,0 +1,42 @@
<?php namespace Config;
use CodeIgniter\Config\BaseConfig;
class Honeypot extends BaseConfig
{
/**
* Makes Honeypot visible or not to human
*
* @var boolean
*/
public $hidden = true;
/**
* Honeypot Label Content
*
* @var string
*/
public $label = 'Fill This Field';
/**
* Honeypot Field Name
*
* @var string
*/
public $name = 'honeypot';
/**
* Honeypot HTML Template
*
* @var string
*/
public $template = '<label>{label}</label><input type="text" name="{name}" value=""/>';
/**
* Honeypot container
*
* @var string
*/
public $container = '<div style="display:none">{template}</div>';
}
+31
View File
@@ -0,0 +1,31 @@
<?php namespace Config;
use CodeIgniter\Config\BaseConfig;
class Images extends BaseConfig
{
/**
* Default handler used if no other handler is specified.
*
* @var string
*/
public $defaultHandler = 'gd';
/**
* The path to the image library.
* Required for ImageMagick, GraphicsMagick, or NetPBM.
*
* @var string
*/
public $libraryPath = '/usr/local/bin/convert';
/**
* The available handler classes.
*
* @var \CodeIgniter\Images\Handlers\BaseHandler[]
*/
public $handlers = [
'gd' => \CodeIgniter\Images\Handlers\GDHandler::class,
'imagick' => \CodeIgniter\Images\Handlers\ImageMagickHandler::class,
];
}
+62
View File
@@ -0,0 +1,62 @@
<?php namespace Config;
use CodeIgniter\Config\BaseConfig;
use Kint\Renderer\Renderer;
class Kint extends BaseConfig
{
/*
|--------------------------------------------------------------------------
| Kint
|--------------------------------------------------------------------------
|
| We use Kint's RichRenderer and CLIRenderer. This area contains options
| that you can set to customize how Kint works for you.
|
| For details on these settings, see Kint's docs:
| https://kint-php.github.io/kint/
|
*/
/*
|--------------------------------------------------------------------------
| Global Settings
|--------------------------------------------------------------------------
*/
public $plugins = null;
public $maxDepth = 6;
public $displayCalledFrom = true;
public $expanded = false;
/*
|--------------------------------------------------------------------------
| RichRenderer Settings
|--------------------------------------------------------------------------
*/
public $richTheme = 'aante-light.css';
public $richFolder = false;
public $richSort = Renderer::SORT_FULL;
public $richObjectPlugins = null;
public $richTabPlugins = null;
/*
|--------------------------------------------------------------------------
| CLI Settings
|--------------------------------------------------------------------------
*/
public $cliColors = true;
public $cliForceUTF8 = false;
public $cliDetectWidth = true;
public $cliMinWidth = 40;
}
+132
View File
@@ -0,0 +1,132 @@
<?php namespace Config;
use CodeIgniter\Config\BaseConfig;
class Logger extends BaseConfig
{
/*
|--------------------------------------------------------------------------
| Error Logging Threshold
|--------------------------------------------------------------------------
|
| You can enable error logging by setting a threshold over zero. The
| threshold determines what gets logged. Any values below or equal to the
| threshold will be logged. Threshold options are:
|
| 0 = Disables logging, Error logging TURNED OFF
| 1 = Emergency Messages - System is unusable
| 2 = Alert Messages - Action Must Be Taken Immediately
| 3 = Critical Messages - Application component unavailable, unexpected exception.
| 4 = Runtime Errors - Don't need immediate action, but should be monitored.
| 5 = Warnings - Exceptional occurrences that are not errors.
| 6 = Notices - Normal but significant events.
| 7 = Info - Interesting events, like user logging in, etc.
| 8 = Debug - Detailed debug information.
| 9 = All Messages
|
| You can also pass an array with threshold levels to show individual error types
|
| array(1, 2, 3, 8) = Emergency, Alert, Critical, and Debug messages
|
| For a live site you'll usually enable Critical or higher (3) to be logged otherwise
| your log files will fill up very fast.
|
*/
public $threshold = 3;
/*
|--------------------------------------------------------------------------
| Date Format for Logs
|--------------------------------------------------------------------------
|
| Each item that is logged has an associated date. You can use PHP date
| codes to set your own date formatting
|
*/
public $dateFormat = 'Y-m-d H:i:s';
/*
|--------------------------------------------------------------------------
| Log Handlers
|--------------------------------------------------------------------------
|
| The logging system supports multiple actions to be taken when something
| is logged. This is done by allowing for multiple Handlers, special classes
| designed to write the log to their chosen destinations, whether that is
| a file on the getServer, a cloud-based service, or even taking actions such
| as emailing the dev team.
|
| Each handler is defined by the class name used for that handler, and it
| MUST implement the CodeIgniter\Log\Handlers\HandlerInterface interface.
|
| The value of each key is an array of configuration items that are sent
| to the constructor of each handler. The only required configuration item
| is the 'handles' element, which must be an array of integer log levels.
| This is most easily handled by using the constants defined in the
| Psr\Log\LogLevel class.
|
| Handlers are executed in the order defined in this array, starting with
| the handler on top and continuing down.
|
*/
public $handlers = [
//--------------------------------------------------------------------
// File Handler
//--------------------------------------------------------------------
'CodeIgniter\Log\Handlers\FileHandler' => [
/*
* The log levels that this handler will handle.
*/
'handles' => [
'critical',
'alert',
'emergency',
'debug',
'error',
'info',
'notice',
'warning',
],
/*
* The default filename extension for log files.
* An extension of 'php' allows for protecting the log files via basic
* scripting, when they are to be stored under a publicly accessible directory.
*
* Note: Leaving it blank will default to 'log'.
*/
'fileExtension' => '',
/*
* The file system permissions to be applied on newly created log files.
*
* IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal
* integer notation (i.e. 0700, 0644, etc.)
*/
'filePermissions' => 0644,
/*
* Logging Directory Path
*
* By default, logs are written to WRITEPATH . 'logs/'
* Specify a different destination here, if desired.
*/
'path' => '',
],
/**
* The ChromeLoggerHandler requires the use of the Chrome web browser
* and the ChromeLogger extension. Uncomment this block to use it.
*/
// 'CodeIgniter\Log\Handlers\ChromeLoggerHandler' => [
// /*
// * The log levels that this handler will handle.
// */
// 'handles' => ['critical', 'alert', 'emergency', 'debug',
// 'error', 'info', 'notice', 'warning'],
// ]
];
}
+50
View File
@@ -0,0 +1,50 @@
<?php namespace Config;
use CodeIgniter\Config\BaseConfig;
class Migrations extends BaseConfig
{
/*
|--------------------------------------------------------------------------
| Enable/Disable Migrations
|--------------------------------------------------------------------------
|
| Migrations are enabled by default for security reasons.
| You should enable migrations whenever you intend to do a schema migration
| and disable it back when you're done.
|
*/
public $enabled = true;
/*
|--------------------------------------------------------------------------
| Migrations table
|--------------------------------------------------------------------------
|
| This is the name of the table that will store the current migrations state.
| When migrations runs it will store in a database table which migration
| level the system is at. It then compares the migration level in this
| table to the $config['migration_version'] if they are not the same it
| will migrate up. This must be set.
|
*/
public $table = 'migrations';
/*
|--------------------------------------------------------------------------
| Timestamp Format
|--------------------------------------------------------------------------
|
| This is the format that will be used when creating new migrations
| using the cli command:
| > php spark migrate:create
|
| Typical formats:
| YmdHis_
| Y-m-d-His_
| Y_m_d_His_
|
*/
public $timestampFormat = 'Y-m-d-His_';
}
+530
View File
@@ -0,0 +1,530 @@
<?php namespace Config;
/*
| -------------------------------------------------------------------
| MIME TYPES
| -------------------------------------------------------------------
| This file contains an array of mime types. It is used by the
| Upload class to help identify allowed file types.
|
| When more than one variation for an extension exist (like jpg, jpeg, etc)
| the most common one should be first in the array to aid the guess*
| methods. The same applies when more than one mime-type exists for a
| single extension.
|
*/
class Mimes
{
/**
* Map of extensions to mime types.
*
* @var array
*/
public static $mimes = [
'hqx' => [
'application/mac-binhex40',
'application/mac-binhex',
'application/x-binhex40',
'application/x-mac-binhex40',
],
'cpt' => 'application/mac-compactpro',
'csv' => [
'text/csv',
'text/x-comma-separated-values',
'text/comma-separated-values',
'application/octet-stream',
'application/vnd.ms-excel',
'application/x-csv',
'text/x-csv',
'application/csv',
'application/excel',
'application/vnd.msexcel',
'text/plain',
],
'bin' => [
'application/macbinary',
'application/mac-binary',
'application/octet-stream',
'application/x-binary',
'application/x-macbinary',
],
'dms' => 'application/octet-stream',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'exe' => [
'application/octet-stream',
'application/x-msdownload',
],
'class' => 'application/octet-stream',
'psd' => [
'application/x-photoshop',
'image/vnd.adobe.photoshop',
],
'so' => 'application/octet-stream',
'sea' => 'application/octet-stream',
'dll' => 'application/octet-stream',
'oda' => 'application/oda',
'pdf' => [
'application/pdf',
'application/force-download',
'application/x-download',
'binary/octet-stream',
],
'ai' => [
'application/pdf',
'application/postscript',
],
'eps' => 'application/postscript',
'ps' => 'application/postscript',
'smi' => 'application/smil',
'smil' => 'application/smil',
'mif' => 'application/vnd.mif',
'xls' => [
'application/vnd.ms-excel',
'application/msexcel',
'application/x-msexcel',
'application/x-ms-excel',
'application/x-excel',
'application/x-dos_ms_excel',
'application/xls',
'application/x-xls',
'application/excel',
'application/download',
'application/vnd.ms-office',
'application/msword',
],
'ppt' => [
'application/vnd.ms-powerpoint',
'application/powerpoint',
'application/vnd.ms-office',
'application/msword',
],
'pptx' => [
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/x-zip',
'application/zip',
],
'wbxml' => 'application/wbxml',
'wmlc' => 'application/wmlc',
'dcr' => 'application/x-director',
'dir' => 'application/x-director',
'dxr' => 'application/x-director',
'dvi' => 'application/x-dvi',
'gtar' => 'application/x-gtar',
'gz' => 'application/x-gzip',
'gzip' => 'application/x-gzip',
'php' => [
'application/x-php',
'application/x-httpd-php',
'application/php',
'text/php',
'text/x-php',
'application/x-httpd-php-source',
],
'php4' => 'application/x-httpd-php',
'php3' => 'application/x-httpd-php',
'phtml' => 'application/x-httpd-php',
'phps' => 'application/x-httpd-php-source',
'js' => [
'application/x-javascript',
'text/plain',
],
'swf' => 'application/x-shockwave-flash',
'sit' => 'application/x-stuffit',
'tar' => 'application/x-tar',
'tgz' => [
'application/x-tar',
'application/x-gzip-compressed',
],
'z' => 'application/x-compress',
'xhtml' => 'application/xhtml+xml',
'xht' => 'application/xhtml+xml',
'zip' => [
'application/x-zip',
'application/zip',
'application/x-zip-compressed',
'application/s-compressed',
'multipart/x-zip',
],
'rar' => [
'application/x-rar',
'application/rar',
'application/x-rar-compressed',
],
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mpga' => 'audio/mpeg',
'mp2' => 'audio/mpeg',
'mp3' => [
'audio/mpeg',
'audio/mpg',
'audio/mpeg3',
'audio/mp3',
],
'aif' => [
'audio/x-aiff',
'audio/aiff',
],
'aiff' => [
'audio/x-aiff',
'audio/aiff',
],
'aifc' => 'audio/x-aiff',
'ram' => 'audio/x-pn-realaudio',
'rm' => 'audio/x-pn-realaudio',
'rpm' => 'audio/x-pn-realaudio-plugin',
'ra' => 'audio/x-realaudio',
'rv' => 'video/vnd.rn-realvideo',
'wav' => [
'audio/x-wav',
'audio/wave',
'audio/wav',
],
'bmp' => [
'image/bmp',
'image/x-bmp',
'image/x-bitmap',
'image/x-xbitmap',
'image/x-win-bitmap',
'image/x-windows-bmp',
'image/ms-bmp',
'image/x-ms-bmp',
'application/bmp',
'application/x-bmp',
'application/x-win-bitmap',
],
'gif' => 'image/gif',
'jpg' => [
'image/jpeg',
'image/pjpeg',
],
'jpeg' => [
'image/jpeg',
'image/pjpeg',
],
'jpe' => [
'image/jpeg',
'image/pjpeg',
],
'jp2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'j2k' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpf' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpg2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpx' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpm' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'mj2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'mjp2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'png' => [
'image/png',
'image/x-png',
],
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'css' => [
'text/css',
'text/plain',
],
'html' => [
'text/html',
'text/plain',
],
'htm' => [
'text/html',
'text/plain',
],
'shtml' => [
'text/html',
'text/plain',
],
'txt' => 'text/plain',
'text' => 'text/plain',
'log' => [
'text/plain',
'text/x-log',
],
'rtx' => 'text/richtext',
'rtf' => 'text/rtf',
'xml' => [
'application/xml',
'text/xml',
'text/plain',
],
'xsl' => [
'application/xml',
'text/xsl',
'text/xml',
],
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpe' => 'video/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
'avi' => [
'video/x-msvideo',
'video/msvideo',
'video/avi',
'application/x-troff-msvideo',
],
'movie' => 'video/x-sgi-movie',
'doc' => [
'application/msword',
'application/vnd.ms-office',
],
'docx' => [
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/zip',
'application/msword',
'application/x-zip',
],
'dot' => [
'application/msword',
'application/vnd.ms-office',
],
'dotx' => [
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/zip',
'application/msword',
],
'xlsx' => [
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/zip',
'application/vnd.ms-excel',
'application/msword',
'application/x-zip',
],
'word' => [
'application/msword',
'application/octet-stream',
],
'xl' => 'application/excel',
'eml' => 'message/rfc822',
'json' => [
'application/json',
'text/json',
],
'pem' => [
'application/x-x509-user-cert',
'application/x-pem-file',
'application/octet-stream',
],
'p10' => [
'application/x-pkcs10',
'application/pkcs10',
],
'p12' => 'application/x-pkcs12',
'p7a' => 'application/x-pkcs7-signature',
'p7c' => [
'application/pkcs7-mime',
'application/x-pkcs7-mime',
],
'p7m' => [
'application/pkcs7-mime',
'application/x-pkcs7-mime',
],
'p7r' => 'application/x-pkcs7-certreqresp',
'p7s' => 'application/pkcs7-signature',
'crt' => [
'application/x-x509-ca-cert',
'application/x-x509-user-cert',
'application/pkix-cert',
],
'crl' => [
'application/pkix-crl',
'application/pkcs-crl',
],
'der' => 'application/x-x509-ca-cert',
'kdb' => 'application/octet-stream',
'pgp' => 'application/pgp',
'gpg' => 'application/gpg-keys',
'sst' => 'application/octet-stream',
'csr' => 'application/octet-stream',
'rsa' => 'application/x-pkcs7',
'cer' => [
'application/pkix-cert',
'application/x-x509-ca-cert',
],
'3g2' => 'video/3gpp2',
'3gp' => [
'video/3gp',
'video/3gpp',
],
'mp4' => 'video/mp4',
'm4a' => 'audio/x-m4a',
'f4v' => [
'video/mp4',
'video/x-f4v',
],
'flv' => 'video/x-flv',
'webm' => 'video/webm',
'aac' => 'audio/x-acc',
'm4u' => 'application/vnd.mpegurl',
'm3u' => 'text/plain',
'xspf' => 'application/xspf+xml',
'vlc' => 'application/videolan',
'wmv' => [
'video/x-ms-wmv',
'video/x-ms-asf',
],
'au' => 'audio/x-au',
'ac3' => 'audio/ac3',
'flac' => 'audio/x-flac',
'ogg' => [
'audio/ogg',
'video/ogg',
'application/ogg',
],
'kmz' => [
'application/vnd.google-earth.kmz',
'application/zip',
'application/x-zip',
],
'kml' => [
'application/vnd.google-earth.kml+xml',
'application/xml',
'text/xml',
],
'ics' => 'text/calendar',
'ical' => 'text/calendar',
'zsh' => 'text/x-scriptzsh',
'7zip' => [
'application/x-compressed',
'application/x-zip-compressed',
'application/zip',
'multipart/x-zip',
],
'cdr' => [
'application/cdr',
'application/coreldraw',
'application/x-cdr',
'application/x-coreldraw',
'image/cdr',
'image/x-cdr',
'zz-application/zz-winassoc-cdr',
],
'wma' => [
'audio/x-ms-wma',
'video/x-ms-asf',
],
'jar' => [
'application/java-archive',
'application/x-java-application',
'application/x-jar',
'application/x-compressed',
],
'svg' => [
'image/svg+xml',
'application/xml',
'text/xml',
],
'vcf' => 'text/x-vcard',
'srt' => [
'text/srt',
'text/plain',
],
'vtt' => [
'text/vtt',
'text/plain',
],
'ico' => [
'image/x-icon',
'image/x-ico',
'image/vnd.microsoft.icon',
],
];
//--------------------------------------------------------------------
/**
* Attempts to determine the best mime type for the given file extension.
*
* @param string $extension
*
* @return string|null The mime type found, or none if unable to determine.
*/
public static function guessTypeFromExtension(string $extension)
{
$extension = trim(strtolower($extension), '. ');
if (! array_key_exists($extension, static::$mimes))
{
return null;
}
return is_array(static::$mimes[$extension]) ? static::$mimes[$extension][0] : static::$mimes[$extension];
}
//--------------------------------------------------------------------
/**
* Attempts to determine the best file extension for a given mime type.
*
* @param string $type
* @param string $proposed_extension - default extension (in case there is more than one with the same mime type)
*
* @return string|null The extension determined, or null if unable to match.
*/
public static function guessExtensionFromType(string $type, ?string $proposed_extension = null)
{
$type = trim(strtolower($type), '. ');
$proposed_extension = trim(strtolower($proposed_extension));
if (! is_null($proposed_extension) && array_key_exists($proposed_extension, static::$mimes) && in_array($type, is_string(static::$mimes[$proposed_extension]) ? [static::$mimes[$proposed_extension]] : static::$mimes[$proposed_extension]))
{
return $proposed_extension;
}
foreach (static::$mimes as $ext => $types)
{
if ((is_string($types) && $types === $type) || (is_array($types) && in_array($type, $types)))
{
return $ext;
}
}
return null;
}
//--------------------------------------------------------------------
}
+45
View File
@@ -0,0 +1,45 @@
<?php
namespace Config;
use CodeIgniter\Modules\Modules as CoreModules;
class Modules extends CoreModules
{
/*
|--------------------------------------------------------------------------
| Auto-Discovery Enabled?
|--------------------------------------------------------------------------
|
| If true, then auto-discovery will happen across all elements listed in
| $activeExplorers below. If false, no auto-discovery will happen at all,
| giving a slight performance boost.
*/
public $enabled = true;
/*
|--------------------------------------------------------------------------
| Auto-Discovery Within Composer Packages Enabled?
|--------------------------------------------------------------------------
|
| If true, then auto-discovery will happen across all namespaces loaded
| by Composer, as well as the namespaces configured locally.
*/
public $discoverInComposer = true;
/*
|--------------------------------------------------------------------------
| Auto-discover Rules
|--------------------------------------------------------------------------
|
| Aliases list of all discovery classes that will be active and used during
| the current application request.
| If it is not listed, only the base application elements will be used.
*/
public $aliases = [
'events',
'registrars',
'routes',
'services',
];
}
+35
View File
@@ -0,0 +1,35 @@
<?php namespace Config;
use CodeIgniter\Config\BaseConfig;
class Pager extends BaseConfig
{
/*
|--------------------------------------------------------------------------
| Templates
|--------------------------------------------------------------------------
|
| Pagination links are rendered out using views to configure their
| appearance. This array contains aliases and the view names to
| use when rendering the links.
|
| Within each view, the Pager object will be available as $pager,
| and the desired group as $pagerGroup;
|
*/
public $templates = [
'default_full' => 'CodeIgniter\Pager\Views\default_full',
'default_simple' => 'CodeIgniter\Pager\Views\default_simple',
'default_head' => 'CodeIgniter\Pager\Views\default_head',
];
/*
|--------------------------------------------------------------------------
| Items Per Page
|--------------------------------------------------------------------------
|
| The default number of results shown in a single page.
|
*/
public $perPage = 20;
}
+77
View File
@@ -0,0 +1,77 @@
<?php namespace Config;
/**
* Holds the paths that are used by the system to
* locate the main directories, app, system, etc.
* Modifying these allows you to re-structure your application,
* share a system folder between multiple applications, and more.
*
* All paths are relative to the project's root folder.
*/
class Paths
{
/*
*---------------------------------------------------------------
* SYSTEM FOLDER NAME
*---------------------------------------------------------------
*
* This variable must contain the name of your "system" folder.
* Include the path if the folder is not in the same directory
* as this file.
*/
public $systemDirectory = __DIR__ . '/../../vendor/codeigniter4/framework/system';
/*
*---------------------------------------------------------------
* APPLICATION FOLDER NAME
*---------------------------------------------------------------
*
* If you want this front controller to use a different "app"
* folder than the default one you can set its name here. The folder
* can also be renamed or relocated anywhere on your getServer. If
* you do, use a full getServer path. For more info please see the user guide:
* http://codeigniter.com/user_guide/general/managing_apps.html
*
* NO TRAILING SLASH!
*/
public $appDirectory = __DIR__ . '/..';
/*
* ---------------------------------------------------------------
* WRITABLE DIRECTORY NAME
* ---------------------------------------------------------------
*
* This variable must contain the name of your "writable" directory.
* The writable directory allows you to group all directories that
* need write permission to a single place that can be tucked away
* for maximum security, keeping it out of the app and/or
* system directories.
*/
public $writableDirectory = __DIR__ . '/../../writable';
/*
* ---------------------------------------------------------------
* TESTS DIRECTORY NAME
* ---------------------------------------------------------------
*
* This variable must contain the name of your "tests" directory.
* The writable directory allows you to group all directories that
* need write permission to a single place that can be tucked away
* for maximum security, keeping it out of the app and/or
* system directories.
*/
public $testsDirectory = __DIR__ . '/../../tests';
/*
* ---------------------------------------------------------------
* VIEW DIRECTORY NAME
* ---------------------------------------------------------------
*
* This variable must contain the name of the directory that
* contains the view files used by your application. By
* default this is in `app/Views`. This value
* is used when no value is provided to `Services::renderer()`.
*/
public $viewDirectory = __DIR__ . '/../Views';
}
+51
View File
@@ -0,0 +1,51 @@
<?php namespace Config;
// Create a new instance of our RouteCollection class.
$routes = Services::routes();
// Load the system's routing file first, so that the app and ENVIRONMENT
// can override as needed.
if (file_exists(SYSTEMPATH . 'Config/Routes.php'))
{
require SYSTEMPATH . 'Config/Routes.php';
}
/**
* --------------------------------------------------------------------
* Router Setup
* --------------------------------------------------------------------
*/
$routes->setDefaultNamespace('App\Controllers');
$routes->setDefaultController('Dashboard');
$routes->setDefaultMethod('index');
$routes->setTranslateURIDashes(false);
$routes->set404Override();
$routes->setAutoRoute(true);
/**
* --------------------------------------------------------------------
* Route Definitions
* --------------------------------------------------------------------
*/
// We get a performance increase by specifying the default
// route since we don't have to scan directories.
$routes->get('/', 'Dashboard::index');
/**
* --------------------------------------------------------------------
* Additional Routing
* --------------------------------------------------------------------
*
* There will often be times that you need additional routing and you
* need it to be able to override any defaults in this file. Environment
* based routes is one such time. require() additional route files here
* to make that happen.
*
* You will have access to the $routes object within that file without
* needing to reload it.
*/
if (file_exists(APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php'))
{
require APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php';
}
+30
View File
@@ -0,0 +1,30 @@
<?php namespace Config;
use CodeIgniter\Config\Services as CoreServices;
/**
* Services Configuration file.
*
* Services are simply other classes/libraries that the system uses
* to do its job. This is used by CodeIgniter to allow the core of the
* framework to be swapped out easily without affecting the usage within
* the rest of your application.
*
* This file holds any application-specific services, or service overrides
* that you might need. An example has been included with the general
* method format you should use for your service methods. For more examples,
* see the core Services file at system/Config/Services.php.
*/
class Services extends CoreServices
{
// public static function example($getShared = true)
// {
// if ($getShared)
// {
// return static::getSharedInstance('example');
// }
//
// return new \CodeIgniter\Example();
// }
}
+68
View File
@@ -0,0 +1,68 @@
<?php namespace Config;
use CodeIgniter\Config\BaseConfig;
class Toolbar extends BaseConfig
{
/*
|--------------------------------------------------------------------------
| Debug Toolbar
|--------------------------------------------------------------------------
| The Debug Toolbar provides a way to see information about the performance
| and state of your application during that page display. By default it will
| NOT be displayed under production environments, and will only display if
| CI_DEBUG is true, since if it's not, there's not much to display anyway.
|
| toolbarMaxHistory = Number of history files, 0 for none or -1 for unlimited
|
*/
public $collectors = [
\CodeIgniter\Debug\Toolbar\Collectors\Timers::class,
\CodeIgniter\Debug\Toolbar\Collectors\Database::class,
\CodeIgniter\Debug\Toolbar\Collectors\Logs::class,
\CodeIgniter\Debug\Toolbar\Collectors\Views::class,
// \CodeIgniter\Debug\Toolbar\Collectors\Cache::class,
\CodeIgniter\Debug\Toolbar\Collectors\Files::class,
\CodeIgniter\Debug\Toolbar\Collectors\Routes::class,
\CodeIgniter\Debug\Toolbar\Collectors\Events::class,
];
/*
|--------------------------------------------------------------------------
| Max History
|--------------------------------------------------------------------------
| The Toolbar allows you to view recent requests that have been made to
| the application while the toolbar is active. This allows you to quickly
| view and compare multiple requests.
|
| $maxHistory sets a limit on the number of past requests that are stored,
| helping to conserve file space used to store them. You can set it to
| 0 (zero) to not have any history stored, or -1 for unlimited history.
|
*/
public $maxHistory = 20;
/*
|--------------------------------------------------------------------------
| Toolbar Views Path
|--------------------------------------------------------------------------
| The full path to the the views that are used by the toolbar.
| MUST have a trailing slash.
|
*/
public $viewsPath = SYSTEMPATH . 'Debug/Toolbar/Views/';
/*
|--------------------------------------------------------------------------
| Max Queries
|--------------------------------------------------------------------------
| If the Database Collector is enabled, it will log every query that the
| the system generates so they can be displayed on the toolbar's timeline
| and in the query log. This can lead to memory issues in some instances
| with hundreds of queries.
|
| $maxQueries defines the maximum amount of queries that will be stored.
|
*/
public $maxQueries = 100;
}
+218
View File
@@ -0,0 +1,218 @@
<?php namespace Config;
use CodeIgniter\Config\BaseConfig;
class UserAgents extends BaseConfig
{
/*
| -------------------------------------------------------------------
| USER AGENT TYPES
| -------------------------------------------------------------------
| This file contains four arrays of user agent data. It is used by the
| User Agent Class to help identify browser, platform, robot, and
| mobile device data. The array keys are used to identify the device
| and the array values are used to set the actual name of the item.
*/
public $platforms = [
'windows nt 10.0' => 'Windows 10',
'windows nt 6.3' => 'Windows 8.1',
'windows nt 6.2' => 'Windows 8',
'windows nt 6.1' => 'Windows 7',
'windows nt 6.0' => 'Windows Vista',
'windows nt 5.2' => 'Windows 2003',
'windows nt 5.1' => 'Windows XP',
'windows nt 5.0' => 'Windows 2000',
'windows nt 4.0' => 'Windows NT 4.0',
'winnt4.0' => 'Windows NT 4.0',
'winnt 4.0' => 'Windows NT',
'winnt' => 'Windows NT',
'windows 98' => 'Windows 98',
'win98' => 'Windows 98',
'windows 95' => 'Windows 95',
'win95' => 'Windows 95',
'windows phone' => 'Windows Phone',
'windows' => 'Unknown Windows OS',
'android' => 'Android',
'blackberry' => 'BlackBerry',
'iphone' => 'iOS',
'ipad' => 'iOS',
'ipod' => 'iOS',
'os x' => 'Mac OS X',
'ppc mac' => 'Power PC Mac',
'freebsd' => 'FreeBSD',
'ppc' => 'Macintosh',
'linux' => 'Linux',
'debian' => 'Debian',
'sunos' => 'Sun Solaris',
'beos' => 'BeOS',
'apachebench' => 'ApacheBench',
'aix' => 'AIX',
'irix' => 'Irix',
'osf' => 'DEC OSF',
'hp-ux' => 'HP-UX',
'netbsd' => 'NetBSD',
'bsdi' => 'BSDi',
'openbsd' => 'OpenBSD',
'gnu' => 'GNU/Linux',
'unix' => 'Unknown Unix OS',
'symbian' => 'Symbian OS',
];
// The order of this array should NOT be changed. Many browsers return
// multiple browser types so we want to identify the sub-type first.
public $browsers = [
'OPR' => 'Opera',
'Flock' => 'Flock',
'Edge' => 'Spartan',
'Chrome' => 'Chrome',
// Opera 10+ always reports Opera/9.80 and appends Version/<real version> to the user agent string
'Opera.*?Version' => 'Opera',
'Opera' => 'Opera',
'MSIE' => 'Internet Explorer',
'Internet Explorer' => 'Internet Explorer',
'Trident.* rv' => 'Internet Explorer',
'Shiira' => 'Shiira',
'Firefox' => 'Firefox',
'Chimera' => 'Chimera',
'Phoenix' => 'Phoenix',
'Firebird' => 'Firebird',
'Camino' => 'Camino',
'Netscape' => 'Netscape',
'OmniWeb' => 'OmniWeb',
'Safari' => 'Safari',
'Mozilla' => 'Mozilla',
'Konqueror' => 'Konqueror',
'icab' => 'iCab',
'Lynx' => 'Lynx',
'Links' => 'Links',
'hotjava' => 'HotJava',
'amaya' => 'Amaya',
'IBrowse' => 'IBrowse',
'Maxthon' => 'Maxthon',
'Ubuntu' => 'Ubuntu Web Browser',
'Vivaldi' => 'Vivaldi',
];
public $mobiles = [
// legacy array, old values commented out
'mobileexplorer' => 'Mobile Explorer',
// 'openwave' => 'Open Wave',
// 'opera mini' => 'Opera Mini',
// 'operamini' => 'Opera Mini',
// 'elaine' => 'Palm',
'palmsource' => 'Palm',
// 'digital paths' => 'Palm',
// 'avantgo' => 'Avantgo',
// 'xiino' => 'Xiino',
'palmscape' => 'Palmscape',
// 'nokia' => 'Nokia',
// 'ericsson' => 'Ericsson',
// 'blackberry' => 'BlackBerry',
// 'motorola' => 'Motorola'
// Phones and Manufacturers
'motorola' => 'Motorola',
'nokia' => 'Nokia',
'palm' => 'Palm',
'iphone' => 'Apple iPhone',
'ipad' => 'iPad',
'ipod' => 'Apple iPod Touch',
'sony' => 'Sony Ericsson',
'ericsson' => 'Sony Ericsson',
'blackberry' => 'BlackBerry',
'cocoon' => 'O2 Cocoon',
'blazer' => 'Treo',
'lg' => 'LG',
'amoi' => 'Amoi',
'xda' => 'XDA',
'mda' => 'MDA',
'vario' => 'Vario',
'htc' => 'HTC',
'samsung' => 'Samsung',
'sharp' => 'Sharp',
'sie-' => 'Siemens',
'alcatel' => 'Alcatel',
'benq' => 'BenQ',
'ipaq' => 'HP iPaq',
'mot-' => 'Motorola',
'playstation portable' => 'PlayStation Portable',
'playstation 3' => 'PlayStation 3',
'playstation vita' => 'PlayStation Vita',
'hiptop' => 'Danger Hiptop',
'nec-' => 'NEC',
'panasonic' => 'Panasonic',
'philips' => 'Philips',
'sagem' => 'Sagem',
'sanyo' => 'Sanyo',
'spv' => 'SPV',
'zte' => 'ZTE',
'sendo' => 'Sendo',
'nintendo dsi' => 'Nintendo DSi',
'nintendo ds' => 'Nintendo DS',
'nintendo 3ds' => 'Nintendo 3DS',
'wii' => 'Nintendo Wii',
'open web' => 'Open Web',
'openweb' => 'OpenWeb',
// Operating Systems
'android' => 'Android',
'symbian' => 'Symbian',
'SymbianOS' => 'SymbianOS',
'elaine' => 'Palm',
'series60' => 'Symbian S60',
'windows ce' => 'Windows CE',
// Browsers
'obigo' => 'Obigo',
'netfront' => 'Netfront Browser',
'openwave' => 'Openwave Browser',
'mobilexplorer' => 'Mobile Explorer',
'operamini' => 'Opera Mini',
'opera mini' => 'Opera Mini',
'opera mobi' => 'Opera Mobile',
'fennec' => 'Firefox Mobile',
// Other
'digital paths' => 'Digital Paths',
'avantgo' => 'AvantGo',
'xiino' => 'Xiino',
'novarra' => 'Novarra Transcoder',
'vodafone' => 'Vodafone',
'docomo' => 'NTT DoCoMo',
'o2' => 'O2',
// Fallback
'mobile' => 'Generic Mobile',
'wireless' => 'Generic Mobile',
'j2me' => 'Generic Mobile',
'midp' => 'Generic Mobile',
'cldc' => 'Generic Mobile',
'up.link' => 'Generic Mobile',
'up.browser' => 'Generic Mobile',
'smartphone' => 'Generic Mobile',
'cellphone' => 'Generic Mobile',
];
// There are hundreds of bots but these are the most common.
public $robots = [
'googlebot' => 'Googlebot',
'msnbot' => 'MSNBot',
'baiduspider' => 'Baiduspider',
'bingbot' => 'Bing',
'slurp' => 'Inktomi Slurp',
'yahoo' => 'Yahoo',
'ask jeeves' => 'Ask Jeeves',
'fastcrawler' => 'FastCrawler',
'infoseek' => 'InfoSeek Robot 1.0',
'lycos' => 'Lycos',
'yandex' => 'YandexBot',
'mediapartners-google' => 'MediaPartners Google',
'CRAZYWEBCRAWLER' => 'Crazy Webcrawler',
'adsbot-google' => 'AdsBot Google',
'feedfetcher-google' => 'Feedfetcher Google',
'curious george' => 'Curious George',
'ia_archiver' => 'Alexa Crawler',
'MJ12bot' => 'Majestic-12',
'Uptimebot' => 'Uptimebot',
];
}
+36
View File
@@ -0,0 +1,36 @@
<?php namespace Config;
class Validation
{
//--------------------------------------------------------------------
// Setup
//--------------------------------------------------------------------
/**
* Stores the classes that contain the
* rules that are available.
*
* @var array
*/
public $ruleSets = [
\CodeIgniter\Validation\Rules::class,
\CodeIgniter\Validation\FormatRules::class,
\CodeIgniter\Validation\FileRules::class,
\CodeIgniter\Validation\CreditCardRules::class,
];
/**
* Specifies the views that are used to display the
* errors.
*
* @var array
*/
public $templates = [
'list' => 'CodeIgniter\Validation\Views\list',
'single' => 'CodeIgniter\Validation\Views\single',
];
//--------------------------------------------------------------------
// Rules
//--------------------------------------------------------------------
}
+34
View File
@@ -0,0 +1,34 @@
<?php namespace Config;
class View extends \CodeIgniter\Config\View
{
/**
* When false, the view method will clear the data between each
* call. This keeps your data safe and ensures there is no accidental
* leaking between calls, so you would need to explicitly pass the data
* to each view. You might prefer to have the data stick around between
* calls so that it is available to all views. If that is the case,
* set $saveData to true.
*/
public $saveData = true;
/**
* Parser Filters map a filter name with any PHP callable. When the
* Parser prepares a variable for display, it will chain it
* through the filters in the order defined, inserting any parameters.
* To prevent potential abuse, all filters MUST be defined here
* in order for them to be available for use within the Parser.
*
* Examples:
* { title|esc(js) }
* { created_on|date(Y-m-d)|esc(attr) }
*/
public $filters = [];
/**
* Parser Plugins provide a way to extend the functionality provided
* by the core Parser by creating aliases that will be replaced with
* any callable. Can be single or tag pair.
*/
public $plugins = [];
}
+93
View File
@@ -0,0 +1,93 @@
<?php namespace App\Controllers;
use App\Models\Lavoratori_Model;
use App\Models\Clienti_Model;
class Admin extends BaseController{
//--------------------------------------------------------------------
// visualizza e permette il CRUD della tabella indicata:
public function crud($tab = 'Clienti'){
$data['title'] = "CRUD della tabella: $tab";
helper(['tools','form']);
return view('test', $data);
}//function clienti()
//--------------------------------------------------------------------
// visualizza e permette il CRUD della tabella Clienti:
public function clienti($order_field = null, $order_direction = null) {
// Tab: Clienti = ['clIDcliente', 'clNome', 'clInfo', 'clCreatedAt', 'clUpdatedAt', 'clDeletedAt'];
helper(['tools','form']);
$data['tab'] = 'admin';
// Verifico sessione e livello:
if (!CheckLevel(3)) { return redirect()->to('/dashboard'); }
// gestisco ordinamento:
if (null==$order_field){ $order_field = 'clIDcliente'; }
if (null==$order_direction){ $order_direction = 'DESC'; }
// Imposto i parametri per la pagina parametrica:
$data['title'] = 'Elenco clienti della CSiCo:'; // titolo della pagina
$data['cmd_tab'] = [ // Elenco dei comandi per l'intera tabella
'add' => 'clienti/add', // - inserimento nuovo record
'exp_csv' => 'clienti/export_csv', // - esportazione in csv dei records
];
$data['cmd_rec'] = [ // Elenco dei comandi per ciascun records
'edit' => 'clienti/edit', // - editazione del record
'delete' => 'clienti/delete', // - cancellazione del record
//'select' => 'clienti/select', // - selezione del record
];
$data['fields'] = [ // campi che voglio riportare sulla tabella (nell'ordine voluto)
'clIDcliente' => 'ID', // - coppia Key -> Label dove key è l'identificativo del campo sul database, e label è il testo che vogliamo visualizzare.
'clNome' => 'Nome', // - coppia Key -> Label
'clInfo' => 'Info', // - coppia Key -> Label
'clCreatedAt' => 'CreatedAt', // - coppia Key -> Label
'clUpdatedAt' => 'UpdatedAt', // - coppia Key -> Label
'clDeletedAt' => 'DeletedAt' // - coppia Key -> Label
];
$data['id'] = 'clIDcliente'; // identificativo del campo che fa ta ID della tabella
$data['sort'] = [ // ordinamento della tabella
'calbck' => 'admin/clienti', // funzione di call back per il riordino
'field' => $order_field, // Colonna utilizzata per l'ordinamento
'val' => $order_direction, // Tipo di ordinamento (ascendente o discendente)
];
// Ricavo i dati da visualizzare:
$model = new Clienti_Model();
// imposto l'ordinamento selezionato
if (isset($data['sort'])){
$order_field = $data['sort']['field'];
$order_direction =$data['sort']['val'];
$model->orderBy($order_field, $order_direction);
}
// eseguo la query con paginazione:
$data['dataset'] = $model->paginate(session()->get('pager_num'));
$data['pager'] = $model->pager;
return view('pages/crud', $data);
}//function clienti()
//--------------------------------------------------------------------
}//class Admin
+86
View File
@@ -0,0 +1,86 @@
<?php namespace App\Controllers;
use App\Libraries\Crud;
class Articoli extends CRUDController {
// Tab: Articoli = ['arIDarticolo', 'arCode', 'arIDcategoria', 'arIDplace', 'arNome', 'arDescrizione', 'arDataAcquisto', 'arEuro', 'arCreatedAt', 'arUpdatedAt', 'arDeletedAt'];
protected $crud;
function __construct() {
$params = [
'table' => 'Articoli',
'dev' => false,
'fields' => $this->field_options(),
'form_title_add' => 'Add Articolo',
'form_title_update' => 'Edit Articolo',
'form_submit' => 'Add',
'table_title' => 'Pagina per la tabella Articoli',
'form_submit_update' => 'Update',
'base' => '',
'UpdatedAt' => 'arUpdatedAt',
'DeletedAt' => 'arDeletedAt',
];
$this->crud = new Crud($params, service('request'));
}// __construct
protected function field_options() {
$fields = [];
$fields['arIDarticolo'] = ['label' => 'ID', 'helper' => 'Identificativo univoco del record nel database'];
$fields['arCode'] = ['label' => 'Codice', 'helper' => 'Codice identificativo dell\'articolo (5 caratteri)', 'required' => true, 'unique' => [true, 'arCode']];
$fields['arIDcategoria'] = [
'label' => 'Categoria',
'required' => true,
'type' => 'dropdown',
'relation' => [
'table'=> 'Categorie',
'primary_key' => 'caIDcategoria',
'display' => ['caCode', 'caNome'],
'order_by' => 'caCode',
'order' => 'ASC'
]
];
$fields['arIDplace'] = [
'label' => 'Posizione',
'required' => true,
'type' => 'dropdown',
'relation' => [
'table'=> 'Posizioni',
'primary_key' => 'psIDplace',
'display' => ['psCode', 'psDescrizione'],
'order_by' => 'psCode',
'order' => 'ASC'
]
];
$fields['arNome'] = ['label' => 'Nome', 'helper' => 'Nome dell\'articolo (max 32 caratteri)', 'required' => true];
$fields['arDescrizione'] = ['label' => 'Descrizione', 'helper' => 'Descrizione esaustiva dell\'articolo', 'required' => true];
$fields['arDataAcquisto'] = ['label' => 'Data Acquisto', 'helper' => 'Data di acquisto dell\'articolo', 'required' => true, 'type' => 'date'];
$fields['arEuro'] = ['label' => 'Valore', 'helper' => 'Valore stimato dell\'articolo in €', 'required' => true];
$fields['arCreatedAt'] = ['label' => 'Created At', 'helper' => 'Data di creazione del record relativo nel database', 'only_edit'=> true];
$fields['arUpdatedAt'] = ['label' => 'Updated At', 'helper' => 'Timestamp dell\'ultimo aggiornamento del record nel database', 'type' => 'unset'];
$fields['arDeletedAt'] = ['label' => 'Deleted At', 'helper' => 'Data di cancellazione del record relativo nel database', 'type' => 'unset'];
return $fields;
}// field_options
public function index() { return $this->CRUD_view(['arIDarticolo', 'arCode', 'arIDcategoria', 'arIDplace', 'arNome', 'arDescrizione', 'arDataAcquisto', 'arEuro', 'arCreatedAt', 'arUpdatedAt', 'arDeletedAt']); }
//--------------------------------------------------------------------
// Auto CRUD terminato
//--------------------------------------------------------------------
}
+83
View File
@@ -0,0 +1,83 @@
<?php namespace App\Controllers;
use App\Libraries\Crud;
class ArticoloEvents extends CRUDController {
// Tab: ArticoloEvents = ['earIDarticoloEvent', 'earIDarticolo', 'earIDlavoratore', 'earDescrizione', 'earData', 'earTipologia'];
protected $crud;
function __construct() {
$params = [
'table' => 'ArticoloEvents',
'dev' => false,
'fields' => $this->field_options(),
'form_title_add' => 'Add Evento',
'form_title_update' => 'Edit Evento',
'form_submit' => 'Add',
'table_title' => 'Pagina per la tabella ArticoloEvents',
'form_submit_update' => 'Update',
'base' => '',
'UpdatedAt' => '',
'DeletedAt' => '',
];
$this->crud = new Crud($params, service('request'));
}// __construct
protected function field_options() {
$fields = [];
$fields['earIDarticoloEvent'] = ['label' => 'ID', 'helper' => 'Identificativo univoco del record nel database'];
$fields['earIDarticolo'] = [
'label' => 'Articolo',
'required' => true,
'type' => 'dropdown',
'helper' => 'Articolo a cui si riferisce l\'evento',
'relation' => [
'table'=> 'Articoli',
'primary_key' => 'arIDarticolo',
'display' => ['arCode', 'arNome'],
'order_by' => 'arCode',
'order' => 'ASC'
]
];
$fields['earIDlavoratore'] = [
'label' => 'Lavoratore',
'required' => true,
'type' => 'dropdown',
'helper' => 'Lavoratore a cui si riferisce l\'evento',
'relation' => [
'table'=> 'Lavoratori',
'primary_key' => 'lvIDlavoratore',
'display' => ['lvNickname', 'lvNome', 'lvCognome'], //'display' => ['lvNickname'],
'order_by' => 'lvNickname',
'order' => 'ASC'
]
];
$fields['earDescrizione'] = ['label' => 'Descrizione', 'helper' => 'Descrizione esaustiva dell\'evento', 'required' => true];
$fields['earData'] = ['label' => 'Timestamp', 'helper' => 'Timestamp dell\'evento', 'required' => true, 'type' => 'date'];
$fields['earTipologia'] = ['label' => 'Tipo', 'helper' => 'Tipologia di evento', 'required' => true];
return $fields;
}// field_options
public function index() { return $this->CRUD_view(['earIDarticoloEvent', 'earIDarticolo', 'earIDlavoratore', 'earDescrizione', 'earData', 'earTipologia']); }
//--------------------------------------------------------------------
// Auto CRUD terminato
//--------------------------------------------------------------------
}
+49
View File
@@ -0,0 +1,49 @@
<?php
namespace App\Controllers;
/**
* 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:
* class Home extends BaseController
*
* For security be sure to declare any new methods as protected or private.
*
* @package CodeIgniter
*/
use CodeIgniter\Controller;
class BaseController extends Controller
{
/**
* An array of helpers to be loaded automatically upon
* class instantiation. These helpers will be available
* to all other controllers that extend BaseController.
*
* @var array
*/
protected $helpers = [];
/**
* Constructor.
*/
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger);
//--------------------------------------------------------------------
// Preload any models, libraries, etc, here.
//--------------------------------------------------------------------
// E.g.:
// $this->session = \Config\Services::session();
date_default_timezone_set('Europe/Rome'); // Imposto il timestamp voluto e sono a posto.
}
}
+168
View File
@@ -0,0 +1,168 @@
<?php namespace App\Controllers;
use App\Libraries\Crud;
class CRUDController extends BaseController {
protected $crud;
public function CRUD_view($cols) {
helper(['tools','form']);
$data['tab'] = 'admin';
$page = 1;
if (isset($_GET['page'])) {
$page = (int) $_GET['page'];
$page = max(1, $page);
}
$data['title'] = $this->crud->getTableTitle();
$per_page = session()->get('pager_num');
$columns = $cols;
$where = null;//['DeletedAt =' => 'null'];
// imposto l'ordinamento richiesto:
CheckSort( $this->crud->getTable(), true);
$data['sortCol'] = session()->get('sort')['col'];
$data['sortDir'] = session()->get('sort')['dir'];
$order = [
[$data['sortCol'], $data['sortDir']]
];
$data['order']=$order;
$data['table'] = $this->crud->MRK_view($page, $per_page, $columns, $where, $order);
return view('pages/crud_table', $data);
}//function CRUD_view
public function CRUD_viewSelect($cols) {
helper(['tools','form']);
$data['tab'] = 'admin';
$page = 1;
if (isset($_GET['page'])) {
$page = (int) $_GET['page'];
$page = max(1, $page);
}
$data['title'] = $this->crud->getTableTitle();
$per_page = session()->get('pager_num');
$columns = $cols;
$where = null;//['DeletedAt =' => 'null'];
// imposto l'ordinamento richiesto:
CheckSort( $this->crud->getTable(), true);
$data['sortCol'] = session()->get('sort')['col'];
$data['sortDir'] = session()->get('sort')['dir'];
$order = [
[$data['sortCol'], $data['sortDir']]
];
$data['order']=$order;
$data['table'] = $this->crud->mrk_viewSelectCommessa($page, $per_page, $columns, $where, $order);
return view('pages/crud_table', $data);
}//function CRUD_view
public function CRUD_add() {
helper(['tools','form']);
// Verifico sessione e livello:
if (!CheckLevel(3)) {
session()->setFlashdata('warning', 'L\'utente non ha i permessi per inserire un nuovo record');
$pg = $this->crud->getTable();
return redirect()->to("/$pg");
}
$data['tab'] = 'admin';
$data['form'] = $form = $this->crud->form();
$data['title'] = $this->crud->getAddTitle();
if(is_array($form) && isset($form['redirect']))
return redirect()->to($form['redirect']);
return view('pages/crud_form', $data);
}//function CRUD_add
public function CRUD_edit($id) {
helper(['tools','form']);
// Verifico sessione e livello:
if (!CheckLevel(3)) {
session()->setFlashdata('warning', 'L\'utente non ha i permessi per editare un record');
$pg = $this->crud->getTable();
return redirect()->to("/$pg");
}
$data['tab'] = 'admin';
if(!$this->crud->current_values($id))
return redirect()->to($this->crud->getBase() . '/' . $this->crud->getTable());
$data['item_id'] = $id;
$data['form'] = $form = $this->crud->form();
$data['title'] = $this->crud->getEditTitle();
if (is_array($form) && isset($form['redirect']))
return redirect()->to($form['redirect']);
return view('pages/crud_form', $data);
}//function CRUD_edit
function CRUD_delete($id) {
$data = [];
helper(['tools','form']);
// Verifico sessione e livello:
if (!CheckLevel(3)) {
session()->setFlashdata('warning', 'L\'utente non ha i permessi per eliminare un record');
} else {
// Debug
//$data['form'] = $this->crud->MRK_deleteItem($id);
//return view('test', $data);
// Elimino il record:
if ($this->crud->MRK_deleteItem($id)) {
session()->setFlashdata('success', 'Recors cancellato correttamente.');
} else {
session()->setFlashdata('warning', 'Errore durante la cancellazione del record.');
}
}
$pg = $this->crud->getTable();
return redirect()->to("/$pg");
}//function CRUD_delete
function CRUD_sort($col, $dir){
helper(['tools']);
SetSort($this->crud->getTable(), $col, $dir);
//return $this->CRUD_view();
$pg = $this->crud->getTable();
return redirect()->to("/$pg");
}//function CRUD_sort
function CRUD_exp(){
helper(['tools']);
session()->setFlashdata('warning', 'Esportazione dei record, per ora non abilitata.');
$pg = $this->crud->getTable();
return redirect()->to("/$pg");
}//function CRUD_exp
//--------------------------------------------------------------------
// Auto CRUD terminato
//--------------------------------------------------------------------
}
+545
View File
@@ -0,0 +1,545 @@
<?php namespace App\Controllers;
use App\Libraries\Crud;
use App\Models\Lavoratori_Model;
use App\Models\CSiCoCars_Model;
use App\Models\CSiCoCarEvents_Model;
class CSiCoCarEvents extends CRUDController {
// Tab: CSiCoCarEvents = ['ecaIDcarEvent', 'ecaIDcar', 'ecaIDlavoratore', 'ecaDescrizione', 'ecaStato', 'ecaData', 'ecaKm', 'ecaTipologia'];
protected $crud;
function __construct() {
$params = [
'table' => 'CSiCoCarEvents',
'dev' => false,
'fields' => $this->field_options(),
'form_title_add' => 'Add Evento',
'form_title_update' => 'Edit Evento',
'form_submit' => 'Add',
'table_title' => 'Pagina per la tabella CSiCoCarEvents',
'form_submit_update' => 'Update',
'base' => '',
'UpdatedAt' => '',
'DeletedAt' => '',
];
$this->crud = new Crud($params, service('request'));
}// __construct
protected function field_options() {
$fields = [];
$fields['ecaIDcarEvent'] = ['label' => 'ID', 'helper' => 'Identificativo univoco del record nel database'];
$fields['ecaIDcar'] = [
'label' => 'CSiCoCar',
'required' => true,
'type' => 'dropdown',
'helper' => 'CSiCoCar a cui si riferisce l\'evento',
'relation' => [
'table'=> 'CSiCoCars',
'primary_key' => 'caIDcar',
'display' => ['caTarga', 'caDescrizione'],
'order_by' => 'caTarga',
'order' => 'ASC'
]
];
$fields['ecaIDlavoratore'] = [
'label' => 'Lavoratore',
'required' => true,
'type' => 'dropdown',
'helper' => 'Lavoratore a cui si riferisce l\'evento',
'relation' => [
'table'=> 'Lavoratori',
'primary_key' => 'lvIDlavoratore',
'display' => ['lvNickname', 'lvNome', 'lvCognome'], //'display' => ['lvNickname'],
'order_by' => 'lvNickname',
'order' => 'ASC'
]
];
$fields['ecaDescrizione'] = ['label' => 'Descrizione', 'helper' => 'Descrizione esaustiva dell\'evento', 'required' => true];
$fields['ecaStato'] = ['label' => 'Stato', 'helper' => 'Descrizione esaustiva dello stato attuale della macchina', 'required' => true];
$fields['ecaKm'] = ['label' => 'Km', 'helper' => 'Totale Km percorsi (valore del totalizzatore dell\'auto)', 'required' => true];
$fields['ecaData'] = ['label' => 'Timestamp', 'helper' => 'Timestamp dell\'evento', 'required' => true, 'type' => 'date'];
$fields['ecaTipologia'] = ['label' => 'Tipo', 'helper' => 'Tipologia di evento', 'required' => true];
return $fields;
}// field_options
public function index() { return $this->CRUD_view(['ecaIDcarEvent', 'ecaIDcar', 'ecaIDlavoratore', 'ecaDescrizione', 'ecaStato', 'ecaData', 'ecaKm', 'ecaTipologia']); }
//--------------------------------------------------------------------
// Auto CRUD terminato
//--------------------------------------------------------------------
public function show() {
helper(['tools','form']);
$data['tab'] = 'cars';
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CSiCoCarEvents/show -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Ricavo la macchina selezionata (se vi è una selezione):
$IDcar = session()->get('filter_car');
if ((null !== $IDcar) && ($IDcar!=-1)) {
$mcc = new CSiCoCars_Model();
$data['car'] = $mcc->where('caIDcar', $IDcar)->first();
}
// Ricavo i relativi eventi:
$mev = new CSiCoCarEvents_Model();
$mev->join('Lavoratori', 'CSiCoCarEvents.ecaIDlavoratore = Lavoratori.lvIDlavoratore');
$mev->join('CSiCoCars', 'CSiCoCarEvents.ecaIDcar = CSiCoCars.caIDcar');
// Per ora niente filtro, poi in futuro forse
$mev->where('ecaIDcar', $IDcar);
// imposto l'ordinamento richiesto:
CheckSort('evncar',true);
$data['sortCol'] = session()->get('sort')['col'];
$data['sortDir'] = session()->get('sort')['dir'];
$mev->orderBy($data['sortCol'], $data['sortDir']);
// eseguo la query con paginazione:
$data['dataset'] = $mev->paginate(session()->get('pager_num'));
$data['pager'] = $mev->pager;
return view('/pages/events/CSiCoCarEvents', $data);
}//function select
//--------------------------------------------------------------------
public function add() {
helper(['tools','form']);
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CSiCoCarEvents/add -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Ricavo livello del lavoratore (solo amministratori o superiori, possono editare tutti i campi)
$data['enable'] = $enable = CheckLevel(3, false);
// Ricavo la macchina selezionata (se vi è una selezione):
$IDcar = session()->get('filter_car');
if ((null == $IDcar) || ($IDcar==-1)) {
return redirect()->to('/dashboard/cars');
}
$mcc = new CSiCoCars_Model();
$data['car'] = $mcc->where('caIDcar', $IDcar)->first();
if ($data['car']==null) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CSiCoCarEvents/add -> Error code 002'); }
return redirect()->to('/dashboard/cars');
}
// preparo i dati
$data['tab'] = 'credit';
$data['add'] = true;
$data['title'] = 'Dettagli nuova evento della macchina: ' . $data['car']->ccNumero;
// Gestione POST
if ($this->request->getMethod() == 'post') {
// Regole per validare i campi introdotti nel form:
$rules = [
'Data' => 'trim|required',
'Km' => 'trim|required',
'Tipologia' => 'trim|required',
'Descrizione' => 'trim|required|min_length[8]',
'Stato' => 'trim|required|min_length[8]',
];
if ($enable){
$rules['IDlavoratore'] = 'trim|required';
}
// analisi della validazione
if (! $this->validate($rules)) {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', $data['validation']->listErrors());
} else {
// validazione passata
// Preparo i dati per l'inserimento
// Tab: CSiCoCarEvents = ['ecaIDcarEvent', 'ecaIDcar', 'ecaIDlavoratore', 'ecaDescrizione', 'ecaStato', 'ecaData', 'ecaKm', 'ecaTipologia'];
// Tab: CSiCoCars = ['caIDcar', 'caTarga', 'caDescrizione', 'caDataAssicurazione', 'caTipoGomme', 'caCreatedAt', 'caUpdatedAt', 'caStato', 'caDeletedAt'];
$newData = [
'ecaIDcar' => $data['car']->caIDcar,
'ecaDescrizione' => $this->request->getVar('Descrizione'),
'ecaStato' => $this->request->getVar('Stato'),
'ecaData' => $this->request->getVar('Data'),
'ecaKm' => $this->request->getVar('Km'),
'ecaTipologia' => $this->request->getVar('Tipologia'),
];
if ($enable){
$newData['ecaIDlavoratore'] = $this->request->getVar('IDlavoratore');
} else {
$newData['ecaIDlavoratore'] = session()->get('lavoratore')->lvIDlavoratore;
}
$model = new CSiCoCarEvents_Model();
if ($model->save($newData)) {
// evento inserito con successo, aggiorno lo stato della carta
if ($this->updateCarStato($data['car']->caIDcar)) {
// update dello stato nella carta di credito riuscito
session()->setFlashdata('success', 'Evento inserito con successo');
} else {
// update dello stato nella carta di credito fallito
session()->setFlashdata('danger', 'Evento inserito ma stato della carta non aggiornato correttamente');
}
// apro la pagina desiderata in base al pulsante utilizzato:
if(isset($_POST['crea_continua'])) {
// è stato premuto il secondo pulsante, quindi inserisco un secondo valore:
//return redirect()->to('/dashboard/orari');
} else {
return redirect()->to('/CSiCoCarEvents/show');
}
} else {
// errore durante l'inserimento dell'evento
session()->setFlashdata('danger', 'Errore durante l\'inserimento del record nel DB.');
}
}// analisi validazione
}// Gestione POST
// Ricavo i dati per il select dei lavoratori:
$modelLavoratori = new Lavoratori_Model();
$data['select_lavoratori'] = $modelLavoratori->get_select();
// Show form
echo view('pages/form/CSiCoCarEvents_form_add_edit', $data);
}//function add
//--------------------------------------------------------------------
public function edit($IDevent = null) {
helper(['tools','form']);
// Verifico dato introdotto:
if ($IDevent==null) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CSiCoCarEvents/edit -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CSiCoCarEvents/edit -> Error code 002'); }
return redirect()->to('/dashboard');
}
// Ricavo livello del lavoratore (solo amministratori o superiori, possono editare tutti i campi)
$data['enable'] = $enable = CheckLevel(3, false);
// Ricavo l'evento selezionato, completo di tutti i particolari:
// Tab: CSiCoCarEvents = ['ecaIDcarEvent', 'ecaIDcar', 'ecaIDlavoratore', 'ecaDescrizione', 'ecaStato', 'ecaData', 'ecaKm', 'ecaTipologia'];
// Tab: CSiCoCars = ['caIDcar', 'caTarga', 'caDescrizione', 'caDataAssicurazione', 'caTipoGomme', 'caCreatedAt', 'caUpdatedAt', 'caStato', 'caDeletedAt'];
// Tab: Lavoratori = ['lvIDlavoratore', 'lvNome', 'lvCognome', 'lvMail', 'lvLevel', 'lvRimborsoKm', 'lvNickname', 'lvPassword', 'lvCreatedAt', 'lvUpdatedAt', 'caStato', 'lvDeletedAt'];
$model = new CSiCoCarEvents_Model();
$model->join('CSiCoCars', 'CSiCoCarEvents.ecaIDcar = CSiCoCars.caIDcar');
$model->join('Lavoratori', 'CSiCoCarEvents.ecaIDlavoratore = Lavoratori.lvIDlavoratore');
$data['evnt'] = $model->where('ecaIDcarEvent', $IDevent)
->first();
// Verifico che esista il record:
if (null==$data['evnt']) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CSiCoCarEvents/edit -> Error code 003'); }
return redirect()->to('/dashboard');
}
// ricavo la macchina a cui l'evento si riferisce
$mcc = new CSiCoCars_Model();
$data['car'] = $mcc->where('caIDcar', $data['evnt']->ecaIDcar)->first();
// Verifico che esista il record:
if ($data['car']==null) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CSiCoCarEvents/edit -> Error code 004'); }
return redirect()->to('/dashboard/cars');
}
// preparo i dati
$data['tab'] = 'credit';
$data['add'] = false;
$data['title'] = 'Dettagli evento: ' . $data['evnt']->caTarga;
// Gestione POST
if ($this->request->getMethod() == 'post') {
// Regole per validare i campi introdotti nel form:
$rules = [
'Data' => 'trim|required',
'Km' => 'trim|required',
'Tipologia' => 'trim|required',
'Descrizione' => 'trim|required|min_length[8]',
'Stato' => 'trim|required|min_length[8]',
];
if ($enable){
$rules['IDlavoratore'] = 'trim|required';
}
// analisi della validazione
if (! $this->validate($rules)) {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', $data['validation']->listErrors());
}else{
// validazione passata
// Preparo i dati per l'inserimento
$newData = [
'ecaIDcarEvent' => $IDevent,
'ecaDescrizione' => $this->request->getVar('Descrizione'),
'ecaStato' => $this->request->getVar('Stato'),
'ecaData' => $this->request->getVar('Data'),
'ecaKm' => $this->request->getVar('Km'),
'ecaTipologia' => $this->request->getVar('Tipologia'),
];
if ($enable){
$newData['ecaIDlavoratore'] = $this->request->getVar('IDlavoratore');
}
if ($model->save($newData)) {
// evento inserito con successo, aggiorno lo stato della carta
if ($this->updateCarStato($data['car']->caIDcar)) {
// update dello stato nella carta di credito riuscito
session()->setFlashdata('success', 'Evento aggiornato con successo');
} else {
// update dello stato nella carta di credito fallito
session()->setFlashdata('danger', 'Evento inserito ma stato della carta non aggiornato correttamente');
}
// apro la pagina desiderata in base al pulsante utilizzato:
if(isset($_POST['crea_continua'])) {
// è stato premuto il secondo pulsante, quindi inserisco un secondo valore:
//return redirect()->to('/dashboard/orari');
} else {
return redirect()->to('/CSiCoCarEvents/show');
}
} else {
// errore durante l'inserimento dell'evento
session()->setFlashdata('danger', 'Errore durante l\'inserimento del record nel DB.');
}
}// analisi validazione
}// Gestione POST
// Ricavo i dati per il select dei lavoratori:
$modelLavoratori = new Lavoratori_Model();
$data['select_lavoratori'] = $modelLavoratori->get_select();
// Show form
echo view('pages/form/CSiCoCarEvents_form_add_edit', $data);
}//function edit
//--------------------------------------------------------------------
public function delete($IDevent = null){
helper(['tools']);
$data = [];
// Ricavo l'evento selezionato, completo di tutti i particolari:
// Tab: CSiCoCarEvents = ['ecaIDcarEvent', 'ecaIDcar', 'ecaIDlavoratore', 'ecaDescrizione', 'ecaStato', 'ecaData', 'ecaKm', 'ecaTipologia'];
// Tab: CSiCoCars = ['caIDcar', 'caTarga', 'caDescrizione', 'caDataAssicurazione', 'caTipoGomme', 'caCreatedAt', 'caUpdatedAt', 'caStato', 'caDeletedAt'];
// Tab: Lavoratori = ['lvIDlavoratore', 'lvNome', 'lvCognome', 'lvMail', 'lvLevel', 'lvRimborsoKm', 'lvNickname', 'lvPassword', 'lvCreatedAt', 'lvUpdatedAt', 'lvDeletedAt'];
$model = new CSiCoCarEvents_Model();
$model->join('CSiCoCars', 'CSiCoCarEvents.ecaIDcar = CSiCoCars.caIDcar');
$model->join('Lavoratori', 'CSiCoCarEvents.ecaIDlavoratore = Lavoratori.lvIDlavoratore');
$evnt = $model->where('ecaIDcarEvent', $IDevent)
->first();
// Verifico che esista il record:
if (null==$evnt) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CSiCoCarEvents/delete -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Verifico sessione e livello:
if (!(CheckLevel(3) || session()->get('lavoratore')->lvIDlavoratore==$evnt->ecaIDlavoratore)) {
session()->setFlashdata('warning', 'Non si hanno i permessi per cancellare un evento inserito da altri lavoratori.');
return redirect()->to('/CSiCoCarEvents/show');
}
// Elimino il record:
if ($model->delete($IDevent)) {
// Evento cancellato, aggiorno stato della macchina relativa
if ($this->updateCarStato($evnt->ecaIDcar)) {
// update dello stato nella macchina riuscito
session()->setFlashdata('success', 'Recors cancellato correttamente.');
} else {
// update dello stato nella macchina fallito
session()->setFlashdata('danger', 'Errore durante la cancellazione del record.');
}
} else {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', 'Errore durante la cancellazione del record.');
}
// Show profile
return redirect()->to('/CSiCoCarEvents/show');
} // function delete($id)
//--------------------------------------------------------------------
public function export_csv(){
helper(['tools','form']);
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CSiCoCars/export_csv -> Error code 001'); }
return redirect()->to('/CSiCoCarEvents/show');
}
// Ricavo gli eventi della carta di credito:
// Tab: CSiCoCarEvents = ['ecaIDcarEvent', 'ecaIDcar', 'ecaIDlavoratore', 'ecaDescrizione', 'ecaStato', 'ecaData', 'ecaKm', 'ecaTipologia'];
// Tab: CSiCoCars = ['caIDcar', 'caTarga', 'caDescrizione', 'caDataAssicurazione', 'caTipoGomme', 'caCreatedAt', 'caUpdatedAt', 'caStato', 'caDeletedAt'];
// Tab: Lavoratori = ['lvIDlavoratore', 'lvNome', 'lvCognome', 'lvMail', 'lvLevel', 'lvRimborsoKm', 'lvNickname', 'lvPassword', 'lvCreatedAt', 'lvUpdatedAt', 'lvDeletedAt'];
$mev = new CSiCoCarEvents_Model();
$mev->join('Lavoratori', 'CSiCoCarEvents.ecaIDlavoratore = Lavoratori.lvIDlavoratore');
$mev->join('CSiCoCars', 'CSiCoCarEvents.ecaIDcar = CSiCoCars.caIDcar');
// Per ora niente filtro, poi in futuro forse
$mev->where('ecaIDcar', session()->get('filter_car'));
// imposto l'ordinamento richiesto:
CheckSort('evncar',true);
$data['sortCol'] = session()->get('sort')['col'];
$data['sortDir'] = session()->get('sort')['dir'];
$mev->orderBy($data['sortCol'], $data['sortDir']);
// eseguo la query:
$data['dataset'] = $mev->asArray()
->findAll();
// Imposto il nome del file da downloadare:
$filepath = $_SERVER['MRK_FILE_PATH'];
$filename = 'CSiCoDB_Eventi_CSiCoCar_il_' . date('Y-m-d_H-i-s') . '.csv';
// file creation
$file = fopen($filepath . $filename,"w");
// Esport header
fputcsv($file,['Auto aziendale selezionata:']);
fputcsv($file,['ID car', 'Targa', 'Descrizione', 'Scadenza Assicurazione', 'Tipo Gomme', 'Created At', 'Updated At', 'Stato']);
$head = [];
$head['caIDcar'] = $data['dataset'][0]['caIDcar'];
$head['caTarga'] = $data['dataset'][0]['caTarga'];
$head['caDescrizione'] = $data['dataset'][0]['caDescrizione'];
$head['caDataAssicurazione'] = $data['dataset'][0]['caDataAssicurazione'];
$head['caTipoGomme'] = $data['dataset'][0]['caTipoGomme'];
$head['caCreatedAt'] = $data['dataset'][0]['caCreatedAt'];
$head['caUpdatedAt'] = $data['dataset'][0]['caUpdatedAt'];
$head['caStato'] = $data['dataset'][0]['caStato'];
fputcsv($file,$head);
fputcsv($file,[' ']);
fputcsv($file,[' ']);
fputcsv($file,[' ']);
fputcsv($file,['Eventi dell\'auto aziendale:']);
fputcsv($file,['ID evento', 'ID Lavoratore', 'Nickname', 'Descrizione Evento', 'Stato Auto', 'Data', 'Totale Km', 'Tipologia']);
foreach ($data['dataset'] as $line){
//fputcsv($file,$line);
// Seleziono le colonne da esportare:
$record = [];
$record['ecaIDcarEvent'] = $line['ecaIDcarEvent'];
$record['ecaIDlavoratore'] = $line['ecaIDlavoratore'];
$record['lvNickname'] = $line['lvNickname'];
$record['ecaDescrizione'] = $line['ecaDescrizione'];
$record['ecaStato'] = $line['ecaStato'];
$record['ecaData'] = $line['ecaData'];
$record['ecaKm'] = $line['ecaKm'];
$record['ecaTipologia'] = $line['ecaTipologia'];
fputcsv($file,$record);
}
// Chiudo il file
fclose($file);
// download
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=".$filename);
header("Content-Type: application/csv; ");
readfile($filepath . $filename);
// deleting file
unlink($filepath . $filename);
exit();
} // function export_csv
//--------------------------------------------------------------------
/**
* Eseguo l'aggiornamento dello stato della macchina indicata, in base alla cronologia degli eventi
*/
private function updateCarStato($IDcar){
try {
// verifico la tipologia dell'ultimo evento inserito:
// Tab: CSiCoCarEvents = ['ecaIDcarEvent', 'ecaIDcar', 'ecaIDlavoratore', 'ecaDescrizione', 'ecaStato', 'ecaData', 'ecaKm', 'ecaTipologia'];
// Tab: CSiCoCars = ['caIDcar', 'caTarga', 'caDescrizione', 'caDataAssicurazione', 'caTipoGomme', 'caCreatedAt', 'caUpdatedAt', 'caStato', 'caDeletedAt'];
$mev = new CSiCoCarEvents_Model();
$evnt = $mev->where('ecaIDcar', $IDcar)
->orderBy('ecaData', 'DESC')->orderBy('ecaIDcarEvent', 'DESC')->first();
// Preparo i dati per aggiornare la carta:
$updCar['caIDcar'] = $IDcar;
// determino lo stato attuale della carta dalla tipologia dell'evento:
switch ($evnt->ecaTipologia) {
case 'Dismessa':
$updCar['caStato'] = 'Dismessa';
break;
case 'Presa':
$updCar['caStato'] = 'Occupata';
break;
case 'Restituita':
default:
$updCar['caStato'] = 'Disponibile';
break;
}
// Aggiorno la carta:
$model_car = new CSiCoCars_Model();
if ($model_car->save($updCar)) {
// carta aggiornata con successo
return true;
} else {
// aggiornamento fallito
return false;
}
} catch (Throwable $th) {
//throw $th;
return false;
}
}
//--------------------------------------------------------------------
}
+351
View File
@@ -0,0 +1,351 @@
<?php namespace App\Controllers;
use App\Libraries\Crud;
use App\Models\CSiCoCars_Model;
use App\Models\CSiCoCarEvents_Model;
class CSiCoCars extends CRUDController {
// Tab: CSiCoCars = ['caIDcar', 'caTarga', 'caDescrizione', 'caDataAssicurazione', 'caTipoGomme', 'caCreatedAt', 'caUpdatedAt', 'caStato', 'caDeletedAt'];
protected $crud;
function __construct() {
$params = [
'table' => 'CSiCoCars',
'dev' => false,
'fields' => $this->field_options(),
'form_title_add' => 'Add CSiCoCar',
'form_title_update' => 'Edit CSiCoCar',
'form_submit' => 'Add',
'table_title' => 'Pagina per la tabella CSiCoCars',
'form_submit_update' => 'Update',
'base' => '',
'UpdatedAt' => 'caUpdatedAt',
'DeletedAt' => 'caDeletedAt',
];
$this->crud = new Crud($params, service('request'));
}// __construct
protected function field_options() {
$fields = [];
$fields['caIDcar'] = ['label' => 'ID', 'helper' => 'Identificativo univoco del record nel database'];
$fields['caTarga'] = ['label' => 'Targa', 'helper' => 'Targa dell\'auto (max 10 caratteri)', 'required' => true];
$fields['caDescrizione'] = ['label' => 'Descrizione', 'helper' => 'Descrizione esaustiva della CSiCoCar', 'required' => true];
$fields['caDataAssicurazione'] = ['label' => 'Scadenza Assicurazione', 'helper' => 'Data di scadenza dell\'assicurazione', 'required' => true];
$fields['caTipoGomme'] = ['label' => 'Tipo Gomme', 'helper' => 'Tipologia delle gomme in uso', 'required' => true];
$fields['caStato'] = ['label' => 'Stato', 'helper' => 'Stato di disponibilità della CSiCoCar', 'required' => true];
$fields['caCreatedAt'] = ['label' => 'Created At', 'helper' => 'Data di creazione del record relativo nel database', 'only_edit'=> true];
$fields['caUpdatedAt'] = ['label' => 'Updated At', 'helper' => 'Timestamp dell\'ultimo aggiornamento del record nel database', 'type' => 'unset'];
$fields['caDeletedAt'] = ['label' => 'Deleted At', 'helper' => 'Data di cancellazione del record relativo nel database', 'type' => 'unset'];
return $fields;
}// field_options
public function index() { return $this->CRUD_view(['caIDcar', 'caTarga', 'caDescrizione', 'caDataAssicurazione', 'caTipoGomme', 'caStato', 'caCreatedAt', 'caUpdatedAt', 'caDeletedAt']); }
//--------------------------------------------------------------------
// Auto CRUD terminato
//--------------------------------------------------------------------
public function select($IDcar = null) {
helper(['tools','form']);
$data['tab'] = 'cars';
$model = new CSiCoCars_Model();
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CSiCoCars/select -> Error code 001'); }
return redirect()->to('/dashboard');
}
// memorizzo la selezione
session()->set('filter_car', $IDcar);
// visualizzo gli eventi della carta selezionata:
return redirect()->to('/CSiCoCarEvents/show');
}//function select
//--------------------------------------------------------------------
public function add() {
helper(['tools','form']);
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CSiCoCars/add -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Ricavo livello del lavoratore (solo amministratori o superiori, possono editare tutti i campi)
$data['enable'] = $enable = CheckLevel(3, false);
// Solo amministratori possono inserire una nuova sim:
if (!$enable){
session()->setFlashdata('warning', 'Non si hanno i permessi per inserire una nuova auto aziendale.');
return redirect()->to('/dashboard/cars');
}
// preparo i dati
$data['tab'] = 'cars';
$data['add'] = true;
$data['title'] = 'Dettagli nuova Auto';
// Gestione POST
if ($this->request->getMethod() == 'post') {
// Regole per validare i campi introdotti nel form:
$rules = [
'Targa' => 'trim|required|min_length[7]|max_length[9]',
'DataAssicurazione' => 'trim|required',
'TipoGomme' => 'trim|required',
'Descrizione' => 'trim|required|min_length[8]',
//'Stato' => 'trim|required',
];
// analisi della validazione
if (! $this->validate($rules)) {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', $data['validation']->listErrors());
}else{
// validazione passata
// Preparo i dati per l'inserimento
// Tab: CSiCoCars = ['caIDcar', 'caTarga', 'caDescrizione', 'caDataAssicurazione', 'caTipoGomme', 'caCreatedAt', 'caUpdatedAt', 'caStato', 'caDeletedAt'];
$newData = [
'caTarga' => $this->request->getVar('Targa'),
'caDataAssicurazione' => $this->request->getVar('DataAssicurazione'),
'caTipoGomme' => $this->request->getVar('TipoGomme'),
'caDescrizione' => $this->request->getVar('Descrizione'),
'caStato' => 'Disponibile',
];
$model = new CSiCoCars_Model();
if ($model->save($newData)) {
session()->setFlashdata('success', 'Record inserito con successo sul DB');
if(isset($_POST['crea_continua'])) {
// è stato premuto il secondo pulsante, quindi inserisco un secondo valore:
//return redirect()->to('/dashboard/orari');
} else {
return redirect()->to('/dashboard/cars');
}
} else {
session()->setFlashdata('danger', 'Errore durante l\'inserimento del record nel DB.');
}
}// analisi validazione
}// Gestione POST
// Show form
echo view('pages/form/CSiCoCars_form_add_edit', $data);
}//function add
//--------------------------------------------------------------------
public function edit($IDcar = null) {
helper(['tools','form']);
// Verifico dato introdotto:
if ($IDcar==null) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CSiCoCars/edit -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CSiCoCars/edit -> Error code 002'); }
return redirect()->to('/dashboard');
}
// Ricavo livello del lavoratore (solo amministratori o superiori, possono editare tutti i campi)
$data['enable'] = $enable = CheckLevel(3, false);
// Solo amministratori possono editare una carta:
if (!$enable){
session()->setFlashdata('warning', 'Non si hanno i permessi per editare i dati di una carta di credito aziendale.');
return redirect()->to('/dashboard/cars');
}
// preparo i dati
$data['tab'] = 'cars';
$data['add'] = false;
$data['title'] = 'Dettagli dell\'auto aziendale';
// Ricavo il profilo dell'orario da editare
// Tab: CSiCoCars = ['caIDcar', 'caTarga', 'caDescrizione', 'caDataAssicurazione', 'caTipoGomme', 'caCreatedAt', 'caUpdatedAt', 'caStato', 'caDeletedAt'];
$model = new CSiCoCars_Model();
$data['car'] = $model->where('caIDcar', $IDcar)
->first();
// Verifico che esista il record dell'orario:
if (null==$data['car']) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CSiCoCars/edit -> Error code 003'); }
return redirect()->to('/dashboard');
}
// Gestione POST
if ($this->request->getMethod() == 'post') {
// Regole per validare i campi introdotti nel form:
$rules = [
'Targa' => 'trim|required|min_length[7]|max_length[9]',
'DataAssicurazione' => 'trim|required',
'TipoGomme' => 'trim|required',
'Descrizione' => 'trim|required|min_length[8]',
'Stato' => 'trim|required',
];
// analisi della validazione
if (! $this->validate($rules)) {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', $data['validation']->listErrors());
}else{
// validazione passata
// Preparo i dati per l'aggiornamento
// Tab: CSiCoCars = ['caIDcar', 'caTarga', 'caDescrizione', 'caDataAssicurazione', 'caTipoGomme', 'caCreatedAt', 'caUpdatedAt', 'caStato', 'caDeletedAt'];
$newData = [
'caIDcar' => $this->request->getVar('IDcar'),
'caTarga' => $this->request->getVar('Targa'),
'caDataAssicurazione' => $this->request->getVar('DataAssicurazione'),
'caTipoGomme' => $this->request->getVar('TipoGomme'),
'caDescrizione' => $this->request->getVar('Descrizione'),
'caStato' => $this->request->getVar('Stato'),
];
$model = new CSiCoCars_Model();
if ($model->save($newData)) {
session()->setFlashdata('success', 'Successfuly Updated');
return redirect()->to('/dashboard/cars');
} else {
session()->setFlashdata('danger', 'Errore durante l\'update del record nel DB.');
}
}// analisi validazione
}// Gestione POST
// Show form
echo view('pages/form/CSiCoCars_form_add_edit', $data);
}//function select
//--------------------------------------------------------------------
public function delete($IDcar = null){
helper(['tools']);
$data = [];
$model = new CSiCoCars_Model();
// Verifico sessione e livello:
if (!CheckLevel(3)) {
session()->setFlashdata('warning', 'Non si hanno i permessi per cancellare un\'auto aziendale.');
return redirect()->to('/dashboard/cars');
}
// Verifico dato introdotto:
if ($IDcar==null) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CSiCoCars/delete -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Elimino il record:
if ($model->delete($IDcar)) {
session()->setFlashdata('success', 'Recors cancellato correttamente.');
} else {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', 'Errore durante la cancellazione del record.');
}
// Show profile
return redirect()->to('/dashboard/cars');
} // function delete($id)
//--------------------------------------------------------------------
public function export_csv(){
helper(['tools','form']);
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CSiCoCars/export_csv -> Error code 001'); }
return redirect()->to('/Lavoratori/login');
}
// Ricavo le ore dell'utente:
// Tab: CSiCoCars = ['caIDcar', 'caTarga', 'caDescrizione', 'caDataAssicurazione', 'caTipoGomme', 'caCreatedAt', 'caUpdatedAt', 'caStato', 'caDeletedAt'];
$model = new CSiCoCars_Model();
// Costruisco la query per selezionare le ore da esportare:
// - applico eventuale filtro per lo stato:
// imposto l'ordinamento richiesto:
CheckSort('csicocars',true);
$data['sortCol'] = session()->get('sort')['col'];
$data['sortDir'] = session()->get('sort')['dir'];
$model->orderBy($data['sortCol'], $data['sortDir']);
// eseguo la query:
$data['dataset'] = $model->asArray()
->findAll();
// Imposto il nome del file da downloadare:
$filepath = $_SERVER['MRK_FILE_PATH'];
$filename = 'CSiCoDB_CSiCoCars_il_' . date('Y-m-d_H-i-s') . '.csv';
// file creation
$file = fopen($filepath . $filename,"w");
// Esport header
fputcsv($file,['ID Car', 'Targa', 'Descrizione', 'Data Assicurazione', 'Tipo Gomme', 'CreatedAt', 'UpdatedAt', 'Stato']);
foreach ($data['dataset'] as $line){
fputcsv($file,$line);
}
// Chiudo il file
fclose($file);
// download
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=".$filename);
header("Content-Type: application/csv; ");
readfile($filepath . $filename);
// deleting file
unlink($filepath . $filename);
exit();
} // function export_csv
//--------------------------------------------------------------------
}//class CSiCoCars
+57
View File
@@ -0,0 +1,57 @@
<?php namespace App\Controllers;
use App\Libraries\Crud;
class Categorie extends CRUDController {
// Tab: Categorie = ['caIDcategoria', 'caCode', 'caNome', 'caDescrizione'];
protected $crud;
function __construct() {
$params = [
'table' => 'Categorie',
'dev' => false,
'fields' => $this->field_options(),
'form_title_add' => 'Add Categoria',
'form_title_update' => 'Edit Categoria',
'form_submit' => 'Add',
'table_title' => 'Pagina per la tabella Categorie',
'form_submit_update' => 'Update',
'base' => '',
'UpdatedAt' => '',
'DeletedAt' => '',
];
$this->crud = new Crud($params, service('request'));
}// __construct
protected function field_options() {
$fields = [];
$fields['caIDcategoria'] = ['label' => 'ID', 'helper' => 'Identificativo univoco del record nel database'];
$fields['caCode'] = ['label' => 'Code', 'helper' => 'Codice della categoria (2 caratteri)', 'required' => true];
$fields['caNome'] = ['label' => 'Nome', 'helper' => 'Nome della categoria (max 32 caratteri)', 'required' => true];
$fields['caDescrizione'] = ['label' => 'Descrizione', 'helper' => 'Descrizione esaustiva della categoria','required' => true];
return $fields;
}// field_options
public function index() { return $this->CRUD_view(['caIDcategoria', 'caCode', 'caNome', 'caDescrizione']); }
//--------------------------------------------------------------------
// Auto CRUD terminato
//--------------------------------------------------------------------
}
+60
View File
@@ -0,0 +1,60 @@
<?php namespace App\Controllers;
use App\Libraries\Crud;
class Clienti extends CRUDController {
// Tab: Clienti = ['clIDcliente', 'clNome', 'clInfo', 'clCreatedAt', 'clUpdatedAt', 'clDeletedAt'];
protected $crud;
function __construct() {
$params = [
'table' => 'Clienti',
'dev' => false,
'fields' => $this->field_options(),
'form_title_add' => 'Add Cliente',
'form_title_update' => 'Edit Cliente',
'form_submit' => 'Add',
'table_title' => 'Pagina per la tabella Clienti',
'form_submit_update' => 'Update',
'base' => '',
'UpdatedAt' => 'clUpdatedAt',
'DeletedAt' => 'clDeletedAt',
];
$this->crud = new Crud($params, service('request'));
}// __construct
protected function field_options() {
$fields = [];
$fields['clIDcliente'] = ['label' => 'ID Cliente', 'helper' => 'Identificativo univoco del record nel database'];
$fields['clNome'] = ['label' => 'Nome', 'helper' => 'Nome identificativo del cliente (max 32 caratteri)', 'required' => true, 'unique' => [true, 'clNome']];
$fields['clInfo'] = ['label' => 'Info relative', 'helper' => 'Descrizione del cliente o altre informazioni utili ad esso relative', 'required' => true];
$fields['clCreatedAt'] = ['label' => 'Created at', 'helper' => 'Data di creazione del record relativo nel database', 'only_edit'=> true];
$fields['clUpdatedAt'] = ['label' => 'Updated at', 'helper' => 'Timestamp dell\'ultimo aggiornamento del record nel database', 'type' => 'unset'];
$fields['clDeletedAt'] = ['label' => 'Deleted at', 'helper' => 'Data di cancellazione del record relativo nel database', 'type' => 'unset'];
return $fields;
}// field_options
public function index() { return $this->CRUD_view(['clIDcliente', 'clNome', 'clInfo', 'clCreatedAt', 'clUpdatedAt', 'clDeletedAt']); }
//--------------------------------------------------------------------
// Auto CRUD terminato
//--------------------------------------------------------------------
}
+237
View File
@@ -0,0 +1,237 @@
<?php namespace App\Controllers;
use App\Libraries\Crud;
use App\Models\Commesse_Model;
use App\Models\Stime_Model;
use App\Models\Orari_Model;
class Commesse extends CRUDController {
// Tab: Commesse = ['coIDcommessa', 'coNome', 'coIDcliente', 'coDescrizione', 'coIDstatoCommessa', 'coCreatedAt', 'coUpdatedAt', 'coDeletedAt'];
protected $crud;
function __construct() {
$params = [
'table' => 'Commesse',
'dev' => false,
'fields' => $this->field_options(),
'form_title_add' => 'Add Commessa',
'form_title_update' => 'Edit Commessa',
'form_submit' => 'Add',
'table_title' => 'Pagina per la tabella Commesse',
'form_submit_update' => 'Update',
'base' => '',
'UpdatedAt' => 'coUpdatedAt',
'DeletedAt' => 'coDeletedAt',
];
$this->crud = new Crud($params, service('request'));
}// __construct
protected function field_options() {
$fields = [];
$fields['coIDcommessa'] = ['label' => 'ID', 'helper' => 'Identificativo univoco del record nel database'];
$fields['coNome'] = ['label' => 'Nome', 'helper' => 'Nome della commessa (max 32 caratteri)', 'required' => true];
$fields['coIDcliente'] = [
'label' => 'Cliente',
'required' => true,
'type' => 'dropdown',
'helper' => 'Cliente a cui si riferisce la commessa',
'relation' => [
'table'=> 'Clienti',
'primary_key' => 'clIDcliente',
'display' => ['clNome'],
'order_by' => 'clNome',
'order' => 'ASC'
]
];
$fields['coDescrizione'] = ['label' => 'Descrizione', 'helper' => 'Descrizione esaustiva della commessa','required' => true];
$fields['coIDstatoCommessa'] = [
'label' => 'Stato',
'required' => true,
'type' => 'dropdown',
'helper' => 'Stato della commessa',
'relation' => [
'table'=> 'StatiCommessa',
'primary_key' => 'stIDstatoCommessa',
'display' => ['stIDstatoCommessa'],
'order_by' => 'stIDstatoCommessa',
'order' => 'ASC'
]
];
$fields['coCreatedAt'] = ['label' => 'Created At', 'helper' => 'Data di creazione del record relativo nel database', 'only_edit'=> true];
$fields['coUpdatedAt'] = ['label' => 'Updated At', 'helper' => 'Timestamp dell\'ultimo aggiornamento del record nel database', 'type' => 'unset'];
$fields['coDeletedAt'] = ['label' => 'Deleted At', 'helper' => 'Data di cancellazione del record relativo nel database', 'type' => 'unset'];
$fields['coMRK'] = ['label' => 'Usate', 'helper' => 'Ore lavorate per lo svolgimento della commessa','required' => false];
return $fields;
}// field_options
//public function index() { return $this->CRUD_view(['coIDcommessa', 'coNome', 'coIDcliente', 'coDescrizione', 'coIDstatoCommessa', 'coCreatedAt', 'coUpdatedAt', 'coDeletedAt']); }
public function index() {
$colums = [
'coIDcommessa',
'coNome',
'coIDcliente',
'coDescrizione',
[
'label' => 'Stima',
'callback' => 'callback_OreStimate',
],
[
'label' => 'Usate',
'callback' => 'callback_OreLavorate',
],
'coIDstatoCommessa',
'coCreatedAt',
'coUpdatedAt',
'coDeletedAt'];
//return $this->CRUD_view($colums);
return $this->CRUD_viewSelect($colums);
}
// Visualizzo il report della commessa:
public function CRUD_select($id) {
helper(['tools','form']);
$data['tab'] = 'admin'; //$data['tab'] = 'amministrazione';
// Verifico sessione e livello:
if (!CheckLevel(1)) { return redirect()->to('/dashboard'); }
// // imposto l'ordinamento richiesto:
// CheckSort('ReportCommessa',true);
// $data['sortCol'] = session()->get('sort')['col'];
// $data['sortDir'] = session()->get('sort')['dir'];
// $model->orderBy($data['sortCol'], $data['sortDir']);
// Ricavo il dataset per il riepilogo della Commessa:
$model = new Commesse_Model();
$data['datasetCommessa'] = $model->get_ReportByCommessa($id);
// Ricavo il dataset per il riepilogo delle Stime:
$model = new Stime_Model();
$data['datasetStime'] = $model->get_ReportByCommessa($id);
// Ricavo il dataset per il riepilogo delle Ore:
$model = new Orari_Model();
$data['datasetOre'] = $model->get_ReportByCommessa($id);
$data['title'] = "Analisi della commessa selezionata: " . $id;
$data['id'] = $id;
//return view('test_ReportCommessa', $data);
return view('pages/reportCommessa', $data);
}//function CRUD_edit
//--------------------------------------------------------------------
// Auto CRUD terminato
//--------------------------------------------------------------------
//--------------------------------------------------------------------
// Methods
//--------------------------------------------------------------------
public function export_report_csv($id){
helper(['tools','form']);
$data['tab'] = 'admin'; //$data['tab'] = 'amministrazione';
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Commesse/export_report_csv -> Error code 001'); }
return redirect()->to('/Commesse/CRUD_select');
}
// Ricavo il dataset per il riepilogo della Commessa:
$model = new Commesse_Model();
$data['datasetCommessa'] = $model->get_ReportByCommessa($id);
// Ricavo il dataset per il riepilogo delle Stime:
$model = new Stime_Model();
$data['datasetStime'] = $model->get_ReportByCommessa($id);
// Ricavo il dataset per il riepilogo delle Ore:
$model = new Orari_Model();
$data['datasetOre'] = $model->get_ReportByCommessa($id);
$data['title'] = "Analisi della commessa selezionata: " . $id;
// Imposto il nome del file da downloadare:
$filepath = $_SERVER['MRK_FILE_PATH'];
$filename = 'CSiCoDB_Report_Commessa_' . $id . '_il_' . date('Y-m-d_H-i-s') . '.csv';
// file creation
$file = fopen($filepath . $filename,"w");
// Esport header
fputcsv($file,['Analisi della commessa selezionata: ', $id]);
fputcsv($file,['', '']);
// Export report commessa:
// fputcsv($file,['','','ID','Nome','Cliente','Descrizione','Stima','Usate','Delta','Stato','Created At','Updated At','Deleted At']);
// foreach ($data['datasetCommessa'] as $line){
// //fputcsv($file,$line);
// // Seleziono le colonne da esportare:
// $record = [];
// $record['A'] = '';
// $record['B'] = '';
// $record['ID'] = $line['ID'];
// $record['Nome'] = $line['Nome'];
// $record['Cliente'] = $line['Cliente'];
// $record['Descrizione'] = $line['Descrizione'];
// $record['Stima'] = $line['Stima'];
// $record['Usate'] = $line['Usate'];
// $record['Delta'] = $line['Stima']-$line['Usate'];
// $record['Stato'] = $line['Stato'];
// $record['CreatedAt'] = $line['CreatedAt'];
// $record['UpdatedAt'] = $line['UpdatedAt'];
// $record['DeletedAt'] = $line['DeletedAt'];
// fputcsv($file,$record);
// }
// fputcsv($file,['', '']);
// Export report stime:
// Export report ore:
// Chiudo il file
fclose($file);
// download
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=".$filename);
header("Content-Type: application/csv; ");
readfile($filepath . $filename);
// deleting file
unlink($filepath . $filename);
exit();
} // function export_report_csv
//--------------------------------------------------------------------
}
+541
View File
@@ -0,0 +1,541 @@
<?php namespace App\Controllers;
use App\Libraries\Crud;
use App\Models\Lavoratori_Model;
use App\Models\CreditCards_Model;
use App\Models\CreditCardEvents_Model;
class CreditCardEvents extends CRUDController {
// Tab: CreditCardEvents = ['eccIDcreditEvent', 'eccIDcard', 'eccIDlavoratore', 'eccDescrizione', 'eccData', 'eccCredito', 'eccTipologia'];
protected $crud;
function __construct() {
$params = [
'table' => 'CreditCardEvents',
'dev' => false,
'fields' => $this->field_options(),
'form_title_add' => 'Add Evento',
'form_title_update' => 'Edit Evento',
'form_submit' => 'Add',
'table_title' => 'Pagina per la tabella CreditCardEvents',
'form_submit_update' => 'Update',
'base' => '',
'UpdatedAt' => '',
'DeletedAt' => '',
];
$this->crud = new Crud($params, service('request'));
}// __construct
protected function field_options() {
$fields = [];
$fields['eccIDcreditEvent'] = ['label' => 'ID', 'helper' => 'Identificativo univoco del record nel database'];
$fields['eccIDcard'] = [
'label' => 'CSiCoCard',
'required' => true,
'type' => 'dropdown',
'helper' => 'Carta di credito a cui si riferisce l\'evento',
'relation' => [
'table'=> 'CreditCards',
'primary_key' => 'ccIDcard',
'display' => ['ccNumero'],
'order_by' => 'ccNumero',
'order' => 'ASC'
]
];
$fields['eccIDlavoratore'] = [
'label' => 'Lavoratore',
'required' => true,
'type' => 'dropdown',
'helper' => 'Lavoratore a cui si riferisce l\'evento',
'relation' => [
'table'=> 'Lavoratori',
'primary_key' => 'lvIDlavoratore',
'display' => ['lvNickname', 'lvNome', 'lvCognome'], //'display' => ['lvNickname'],
'order_by' => 'lvNickname',
'order' => 'ASC'
]
];
$fields['eccDescrizione'] = ['label' => 'Descrizione', 'helper' => 'Descrizione esaustiva dell\'evento', 'required' => true];
$fields['eccData'] = ['label' => 'Timestamp', 'helper' => 'Timestamp dell\'evento', 'required' => true, 'type' => 'date'];
$fields['eccCredito'] = ['label' => 'Credito Residuo', 'helper' => 'Stima del credito residuo sulla carta', 'required' => true];
$fields['eccTipologia'] = ['label' => 'Tipo', 'helper' => 'Tipologia di evento', 'required' => true];
return $fields;
}// field_options
public function index() { return $this->CRUD_view(['eccIDcreditEvent', 'eccIDcard', 'eccIDlavoratore', 'eccDescrizione', 'eccData', 'eccCredito', 'eccTipologia']); }
//--------------------------------------------------------------------
// Auto CRUD terminato
//--------------------------------------------------------------------
public function show() {
helper(['tools','form']);
$data['tab'] = 'credit';
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CreditCardEvents/show -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Ricavo la carta di credito selezionata (se vi è una selezione):
// Tab: CreditCards = ['ccIDcard', 'ccNumero', 'ccDescrizione', 'ccScadeIl', 'ccPIN', 'ccCreatedAt', 'ccUpdatedAt', 'ccDeletedAt'];
$IDcard = session()->get('filter_cc');
if ((null !== $IDcard) && ($IDcard!=-1)) {
$mcc = new CreditCards_Model();
$data['card'] = $mcc->where('ccIDcard', $IDcard)->first();
}
// Ricavo i relativi eventi:
// Tab: CreditCardEvents = ['eccIDcreditEvent', 'eccIDcard', 'eccIDlavoratore', 'eccDescrizione', 'eccData', 'eccCredito', 'eccTipologia'];
$mev = new CreditCardEvents_Model();
$mev->join('Lavoratori', 'CreditCardEvents.eccIDlavoratore = Lavoratori.lvIDlavoratore');
$mev->join('CreditCards', 'CreditCardEvents.eccIDcard = CreditCards.ccIDcard');
// Per ora niente filtro, poi in futuro forse
$mev->where('eccIDcard', $IDcard);
// imposto l'ordinamento richiesto:
CheckSort('evncredit',true);
$data['sortCol'] = session()->get('sort')['col'];
$data['sortDir'] = session()->get('sort')['dir'];
$mev->orderBy($data['sortCol'], $data['sortDir']);
// eseguo la query con paginazione:
$data['dataset'] = $mev->paginate(session()->get('pager_num'));
$data['pager'] = $mev->pager;
return view('/pages/events/CreditCardEvents', $data);
}//function select
//--------------------------------------------------------------------
public function add() {
helper(['tools','form']);
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CreditCardEvents/add -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Ricavo livello del lavoratore (solo amministratori o superiori, possono editare tutti i campi)
$data['enable'] = $enable = CheckLevel(3, false);
// Ricavo la carta di credito selezionata (se vi è una selezione):
// Tab: CreditCards = ['ccIDcard', 'ccNumero', 'ccDescrizione', 'ccScadeIl', 'ccPIN', 'ccCreatedAt', 'ccUpdatedAt', 'ccDeletedAt'];
$IDcard = session()->get('filter_cc');
if ((null == $IDcard) || ($IDcard==-1)) {
return redirect()->to('/dashboard/credit');
}
$mcc = new CreditCards_Model();
$data['card'] = $mcc->where('ccIDcard', $IDcard)->first();
if ($data['card']==null) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CreditCardEvents/add -> Error code 002'); }
return redirect()->to('/dashboard/credit');
}
// preparo i dati
$data['tab'] = 'credit';
$data['add'] = true;
$data['title'] = 'Dettagli nuova evento della carta: ' . $data['card']->ccNumero;
// Gestione POST
if ($this->request->getMethod() == 'post') {
// Regole per validare i campi introdotti nel form:
$rules = [
'Data' => 'trim|required',
'Credito' => 'trim|required',
'Tipologia' => 'trim|required',
'Descrizione' => 'trim|required|min_length[8]',
];
if ($enable){
$rules['IDlavoratore'] = 'trim|required';
}
// analisi della validazione
if (! $this->validate($rules)) {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', $data['validation']->listErrors());
}else{
// validazione passata
// Preparo i dati per l'inserimento
// Tab: CreditCardEvents = ['eccIDcreditEvent', 'eccIDcard', 'eccIDlavoratore', 'eccDescrizione', 'eccData', 'eccCredito', 'eccTipologia'];
$newData = [
'eccIDcard' => $data['card']->ccIDcard,
'eccDescrizione' => $this->request->getVar('Descrizione'),
'eccData' => $this->request->getVar('Data'),
'eccCredito' => $this->request->getVar('Credito'),
'eccTipologia' => $this->request->getVar('Tipologia'),
];
if ($enable){
$newData['eccIDlavoratore'] = $this->request->getVar('IDlavoratore');
} else {
$newData['eccIDlavoratore'] = session()->get('lavoratore')->lvIDlavoratore;
}
$model = new CreditCardEvents_Model();
if ($model->save($newData)) {
// evento inserito con successo, aggiorno lo stato della carta
if ($this->updateCardStato($data['card']->ccIDcard)) {
// update dello stato nella carta di credito riuscito
session()->setFlashdata('success', 'Evento inserito con successo');
} else {
// update dello stato nella carta di credito fallito
session()->setFlashdata('danger', 'Evento inserito ma stato della carta non aggiornato correttamente');
}
// apro la pagina desiderata in base al pulsante utilizzato:
if(isset($_POST['crea_continua'])) {
// è stato premuto il secondo pulsante, quindi inserisco un secondo valore:
//return redirect()->to('/dashboard/orari');
} else {
return redirect()->to('/CreditCardEvents/show');
}
} else {
// errore durante l'inserimento dell'evento
session()->setFlashdata('danger', 'Errore durante l\'inserimento del record nel DB.');
}
}// analisi validazione
}// Gestione POST
// Ricavo i dati per il select dei lavoratori:
$modelLavoratori = new Lavoratori_Model();
$data['select_lavoratori'] = $modelLavoratori->get_select();
// Show form
echo view('pages/form/creditcardevents_form_add_edit', $data);
}//function add
//--------------------------------------------------------------------
public function edit($IDevent = null) {
helper(['tools','form']);
// Verifico dato introdotto:
if ($IDevent==null) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CreditCardEvents/edit -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CreditCardEvents/edit -> Error code 002'); }
return redirect()->to('/dashboard');
}
// Ricavo livello del lavoratore (solo amministratori o superiori, possono editare tutti i campi)
$data['enable'] = $enable = CheckLevel(3, false);
// Ricavo l'evento selezionato, completo di tutti i particolari:
// Tab: CreditCardEvents = ['eccIDcreditEvent', 'eccIDcard', 'eccIDlavoratore', 'eccDescrizione', 'eccData', 'eccCredito', 'eccTipologia'];
// Tab: CreditCards = ['ccIDcard', 'ccNumero', 'ccDescrizione', 'ccScadeIl', 'ccPIN', 'ccCreatedAt', 'ccUpdatedAt', 'ccDeletedAt'];
// Tab: Lavoratori = ['lvIDlavoratore', 'lvNome', 'lvCognome', 'lvMail', 'lvLevel', 'lvRimborsoKm', 'lvNickname', 'lvPassword', 'lvCreatedAt', 'lvUpdatedAt', 'ccStato', 'lvDeletedAt'];
$model = new CreditCardEvents_Model();
$model->join('CreditCards', 'CreditCardEvents.eccIDcard = CreditCards.ccIDcard');
$model->join('Lavoratori', 'CreditCardEvents.eccIDlavoratore = Lavoratori.lvIDlavoratore');
$data['evnt'] = $model->where('eccIDcreditEvent', $IDevent)
->first();
// Verifico che esista il record:
if (null==$data['evnt']) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CreditCardEvents/edit -> Error code 003'); }
return redirect()->to('/dashboard');
}
// ricavo la carta a cui l'evento si riferisce
$mcc = new CreditCards_Model();
$data['card'] = $mcc->where('ccIDcard', $data['evnt']->eccIDcard)->first();
// Verifico che esista il record:
if ($data['card']==null) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CreditCardEvents/edit -> Error code 004'); }
return redirect()->to('/dashboard/credit');
}
// preparo i dati
$data['tab'] = 'credit';
$data['add'] = false;
$data['title'] = 'Dettagli evento: ' . $data['evnt']->ccNumero;
// Gestione POST
if ($this->request->getMethod() == 'post') {
// Regole per validare i campi introdotti nel form:
$rules = [
'Data' => 'trim|required',
'Credito' => 'trim|required',
'Tipologia' => 'trim|required',
'Descrizione' => 'trim|required|min_length[8]',
];
if ($enable){
$rules['IDlavoratore'] = 'trim|required';
}
// analisi della validazione
if (! $this->validate($rules)) {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', $data['validation']->listErrors());
}else{
// validazione passata
// Preparo i dati per l'inserimento
$newData = [
'eccIDcreditEvent' => $IDevent,
'eccDescrizione' => $this->request->getVar('Descrizione'),
'eccData' => $this->request->getVar('Data'),
'eccCredito' => $this->request->getVar('Credito'),
'eccTipologia' => $this->request->getVar('Tipologia'),
];
if ($enable){
$newData['eccIDlavoratore'] = $this->request->getVar('IDlavoratore');
}
if ($model->save($newData)) {
// evento inserito con successo, aggiorno lo stato della carta
if ($this->updateCardStato($data['card']->ccIDcard)) {
// update dello stato nella carta di credito riuscito
session()->setFlashdata('success', 'Evento aggiornato con successo');
} else {
// update dello stato nella carta di credito fallito
session()->setFlashdata('danger', 'Evento inserito ma stato della carta non aggiornato correttamente');
}
// apro la pagina desiderata in base al pulsante utilizzato:
if(isset($_POST['crea_continua'])) {
// è stato premuto il secondo pulsante, quindi inserisco un secondo valore:
//return redirect()->to('/dashboard/orari');
} else {
return redirect()->to('/CreditCardEvents/show');
}
} else {
// errore durante l'inserimento dell'evento
session()->setFlashdata('danger', 'Errore durante l\'inserimento del record nel DB.');
}
}// analisi validazione
}// Gestione POST
// Ricavo i dati per il select dei lavoratori:
$modelLavoratori = new Lavoratori_Model();
$data['select_lavoratori'] = $modelLavoratori->get_select();
// Show form
echo view('pages/form/creditcardevents_form_add_edit', $data);
}//function edit
//--------------------------------------------------------------------
public function delete($IDevent = null){
helper(['tools']);
$data = [];
// Ricavo l'evento selezionato, completo di tutti i particolari:
// Tab: CreditCardEvents = ['eccIDcreditEvent', 'eccIDcard', 'eccIDlavoratore', 'eccDescrizione', 'eccData', 'eccCredito', 'eccTipologia'];
// Tab: CreditCards = ['ccIDcard', 'ccNumero', 'ccDescrizione', 'ccScadeIl', 'ccPIN', 'ccCreatedAt', 'ccUpdatedAt', 'ccDeletedAt'];
// Tab: Lavoratori = ['lvIDlavoratore', 'lvNome', 'lvCognome', 'lvMail', 'lvLevel', 'lvRimborsoKm', 'lvNickname', 'lvPassword', 'lvCreatedAt', 'lvUpdatedAt', 'ccStato', 'lvDeletedAt'];
$model = new CreditCardEvents_Model();
$model->join('CreditCards', 'CreditCardEvents.eccIDcard = CreditCards.ccIDcard');
$model->join('Lavoratori', 'CreditCardEvents.eccIDlavoratore = Lavoratori.lvIDlavoratore');
$evnt = $model->where('eccIDcreditEvent', $IDevent)
->first();
// Verifico che esista il record:
if (null==$evnt) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CreditCardEvents/delete -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Verifico sessione e livello:
if (!(CheckLevel(3) || session()->get('lavoratore')->lvIDlavoratore==$evnt->eccIDlavoratore)) {
session()->setFlashdata('warning', 'Non si hanno i permessi per cancellare un evento inserito da altri lavoratori.');
return redirect()->to('/CreditCardEvents/show');
}
// Elimino il record:
if ($model->delete($IDevent)) {
// Evento cancellato, aggiorno stato della carta di credito relativa
if ($this->updateCardStato($evnt->eccIDcard)) {
// update dello stato nella carta di credito riuscito
session()->setFlashdata('success', 'Recors cancellato correttamente.');
} else {
// update dello stato nella carta di credito fallito
session()->setFlashdata('danger', 'Errore durante la cancellazione del record.');
}
} else {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', 'Errore durante la cancellazione del record.');
}
// Show profile
return redirect()->to('/CreditCardEvents/show');
} // function delete($id)
//--------------------------------------------------------------------
public function export_csv(){
helper(['tools','form']);
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CreditCards/export_csv -> Error code 001'); }
return redirect()->to('/CreditCardEvents/show');
}
// Ricavo gli eventi della carta di credito:
// Tab: CreditCardEvents = ['eccIDcreditEvent', 'eccIDcard', 'eccIDlavoratore', 'eccDescrizione', 'eccData', 'eccCredito', 'eccTipologia'];
// Tab: CreditCards = ['ccIDcard', 'ccNumero', 'ccDescrizione', 'ccScadeIl', 'ccPIN', 'ccCreatedAt', 'ccUpdatedAt', 'ccDeletedAt', 'ccStato'];
// Tab: Lavoratori = ['lvIDlavoratore', 'lvNome', 'lvCognome', 'lvMail', 'lvLevel', 'lvRimborsoKm', 'lvNickname', 'lvPassword', 'lvCreatedAt', 'lvUpdatedAt', 'lvDeletedAt'];
$mev = new CreditCardEvents_Model();
$mev->join('Lavoratori', 'CreditCardEvents.eccIDlavoratore = Lavoratori.lvIDlavoratore');
$mev->join('CreditCards', 'CreditCardEvents.eccIDcard = CreditCards.ccIDcard');
// Per ora niente filtro, poi in futuro forse
$mev->where('eccIDcard', session()->get('filter_cc'));
// imposto l'ordinamento richiesto:
CheckSort('evncredit',true);
$data['sortCol'] = session()->get('sort')['col'];
$data['sortDir'] = session()->get('sort')['dir'];
$mev->orderBy($data['sortCol'], $data['sortDir']);
// eseguo la query:
$data['dataset'] = $mev->asArray()
->findAll();
// Imposto il nome del file da downloadare:
$filepath = $_SERVER['MRK_FILE_PATH'];
$filename = 'CSiCoDB_Eventi_Credit_Card_il_' . date('Y-m-d_H-i-s') . '.csv';
// file creation
$file = fopen($filepath . $filename,"w");
// Esport header
fputcsv($file,['Carta di credito selezionata:']);
fputcsv($file,['ID card', 'Numero', 'Descrizione', 'ScadeIl', 'PIN', 'CreatedAt', 'UpdatedAt', 'Stato']);
$head = [];
$head['eccIDcard'] = $data['dataset'][0]['eccIDcard'];
$head['ccNumero'] = $data['dataset'][0]['ccNumero'];
$head['ccDescrizione'] = $data['dataset'][0]['ccDescrizione'];
$head['ccScadeIl'] = $data['dataset'][0]['ccScadeIl'];
$head['ccPIN'] = $data['dataset'][0]['ccPIN'];
$head['ccCreatedAt'] = $data['dataset'][0]['ccCreatedAt'];
$head['ccUpdatedAt'] = $data['dataset'][0]['ccUpdatedAt'];
$head['ccStato'] = $data['dataset'][0]['ccStato'];
fputcsv($file,$head);
fputcsv($file,[' ']);
fputcsv($file,[' ']);
fputcsv($file,[' ']);
fputcsv($file,['Eventi della carta di credito:']);
fputcsv($file,['ID evento', 'ID Lavoratore', 'Nickname', 'Descrizione Evento', 'Data', 'Credito', 'Tipologia']);
foreach ($data['dataset'] as $line){
//fputcsv($file,$line);
// Seleziono le colonne da esportare:
$record = [];
$record['eccIDcreditEvent'] = $line['eccIDcreditEvent'];
$record['eccIDlavoratore'] = $line['eccIDlavoratore'];
$record['lvNickname'] = $line['lvNickname'];
$record['eccDescrizione'] = $line['eccDescrizione'];
$record['eccData'] = $line['eccData'];
$record['eccCredito'] = $line['eccCredito'];
$record['eccTipologia'] = $line['eccTipologia'];
fputcsv($file,$record);
}
// Chiudo il file
fclose($file);
// download
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=".$filename);
header("Content-Type: application/csv; ");
readfile($filepath . $filename);
// deleting file
unlink($filepath . $filename);
exit();
} // function export_csv
//--------------------------------------------------------------------
/**
* Eseguo l'aggiornamento dello stato della carta di credito indicata, in base alla cronologia degli eventi
*/
private function updateCardStato($IDcard){
try {
// verifico la tipologia dell'ultimo evento inserito:
// Tab: CreditCards = ['ccIDcard', 'ccNumero', 'ccDescrizione', 'ccScadeIl', 'ccPIN', 'ccCreatedAt', 'ccUpdatedAt', 'ccDeletedAt'];
// Tab: CreditCardEvents = ['eccIDcreditEvent', 'eccIDcard', 'eccIDlavoratore', 'eccDescrizione', 'eccData', 'eccCredito', 'eccTipologia'];
$mev = new CreditCardEvents_Model();
$evnt = $mev->where('eccIDcard', $IDcard)
->orderBy('eccData', 'DESC')->orderBy('eccIDcreditEvent', 'DESC')->first();
// Preparo i dati per aggiornare la carta:
$updCard['ccIDcard'] = $IDcard;
// determino lo stato attuale della carta dalla tipologia dell'evento:
switch ($evnt->eccTipologia) {
case 'Dismessa':
$updCard['ccStato'] = 'Dismessa';
break;
case 'Presa':
$updCard['ccStato'] = 'Occupata';
break;
case 'Restituita':
default:
$updCard['ccStato'] = 'Disponibile';
break;
}
// Aggiorno la carta:
$model_card = new CreditCards_Model();
if ($model_card->save($updCard)) {
// carta aggiornata con successo
return true;
} else {
// aggiornamento fallito
return false;
}
} catch (Throwable $th) {
//throw $th;
return false;
}
}
//--------------------------------------------------------------------
}//class CreditCardEvents
+350
View File
@@ -0,0 +1,350 @@
<?php namespace App\Controllers;
use App\Libraries\Crud;
use App\Models\Lavoratori_Model;
use App\Models\CreditCards_Model;
use App\Models\CreditCardEvents_Model;
class CreditCards extends CRUDController {
// Tab: CreditCards = ['ccIDcard', 'ccNumero', 'ccDescrizione', 'ccScadeIl', 'ccPIN', 'ccStato', 'ccCreatedAt', 'ccUpdatedAt', 'ccDeletedAt'];
protected $crud;
function __construct() {
$params = [
'table' => 'CreditCards',
'dev' => false,
'fields' => $this->field_options(),
'form_title_add' => 'Add CreditCard',
'form_title_update' => 'Edit CreditCard',
'form_submit' => 'Add',
'table_title' => 'Pagina per la tabella CreditCards',
'form_submit_update' => 'Update',
'base' => '',
'UpdatedAt' => 'ccUpdatedAt',
'DeletedAt' => 'ccDeletedAt',
];
$this->crud = new Crud($params, service('request'));
}// __construct
protected function field_options() {
$fields = [];
$fields['ccIDcard'] = ['label' => 'ID', 'helper' => 'Identificativo univoco del record nel database'];
$fields['ccNumero'] = ['label' => 'Numero', 'helper' => 'Numero della carta di credito (max 20 caratteri)', 'required' => true];
$fields['ccDescrizione'] = ['label' => 'Descrizione', 'helper' => 'Descrizione esaustiva carta di credito', 'required' => true];
$fields['ccScadeIl'] = ['label' => 'Data Scadenza', 'helper' => 'Data di scadenza della carta di credito', 'required' => true];
$fields['ccPIN'] = ['label' => 'PIN', 'helper' => 'PIN della carta di credito (max 6 caratteri)', 'required' => true];
$fields['ccStato'] = ['label' => 'Stato', 'helper' => 'Stato di disponmibilità della carta di credito', 'required' => true];
$fields['ccCreatedAt'] = ['label' => 'Created At', 'helper' => 'Data di creazione del record relativo nel database', 'only_edit'=> true];
$fields['ccUpdatedAt'] = ['label' => 'Updated At', 'helper' => 'Timestamp dell\'ultimo aggiornamento del record nel database', 'type' => 'unset'];
$fields['ccDeletedAt'] = ['label' => 'Deleted At', 'helper' => 'Data di cancellazione del record relativo nel database', 'type' => 'unset'];
return $fields;
}// field_options
public function index() { return $this->CRUD_view(['ccIDcard', 'ccNumero', 'ccDescrizione', 'ccScadeIl', 'ccPIN', 'ccStato', 'ccCreatedAt', 'ccUpdatedAt', 'ccDeletedAt']); }
//--------------------------------------------------------------------
// Auto CRUD terminato
//--------------------------------------------------------------------
public function select($IDcard = null) {
helper(['tools','form']);
$data['tab'] = 'credit';
$model = new CreditCards_Model();
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CreditCards/select -> Error code 001'); }
return redirect()->to('/dashboard');
}
// memorizzo la selezione
session()->set('filter_cc', $IDcard);
// visualizzo gli eventi della carta selezionata:
return redirect()->to('/CreditCardEvents/show');
}//function select
//--------------------------------------------------------------------
public function add() {
helper(['tools','form']);
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CreditCards/add -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Ricavo livello del lavoratore (solo amministratori o superiori, possono editare tutti i campi)
$data['enable'] = $enable = CheckLevel(3, false);
// Solo amministratori possono inserire una nuova carta:
if (!$enable){
session()->setFlashdata('warning', 'Non si hanno i permessi per inserire una nuova carta di credito aziendale.');
return redirect()->to('/dashboard/credit');
}
// preparo i dati
$data['tab'] = 'credit';
$data['add'] = true;
$data['title'] = 'Dettagli nuova carta di credito';
// Gestione POST
if ($this->request->getMethod() == 'post') {
// Regole per validare i campi introdotti nel form:
//
$rules = [
'Numero' => 'trim|required|min_length[8]|max_length[20]',
'ScadeIl' => 'trim|required',
'PIN' => 'trim|required|min_length[3]|max_length[6]',
'Descrizione' => 'trim|required|min_length[8]',
//'Stato' => 'trim|required',
];
// analisi della validazione
if (! $this->validate($rules)) {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', $data['validation']->listErrors());
}else{
// validazione passata
// Preparo i dati per l'inserimento
// Tab: CreditCards = ['ccIDcard', 'ccNumero', 'ccDescrizione', 'ccScadeIl', 'ccPIN', 'ccCreatedAt', 'ccUpdatedAt', 'ccStato', 'ccDeletedAt'];
$newData = [
'ccNumero' => $this->request->getVar('Numero'),
'ccScadeIl' => $this->request->getVar('ScadeIl'),
'ccPIN' => $this->request->getVar('PIN'),
'ccDescrizione' => $this->request->getVar('Descrizione'),
'ccStato' => 'Disponibile',
];
$model = new CreditCards_Model();
if ($model->save($newData)) {
session()->setFlashdata('success', 'Record inserito con successo sul DB');
if(isset($_POST['crea_continua'])) {
// è stato premuto il secondo pulsante, quindi inserisco un secondo valore:
//return redirect()->to('/dashboard/orari');
} else {
return redirect()->to('/dashboard/credit');
}
} else {
session()->setFlashdata('danger', 'Errore durante l\'inserimento del record nel DB.');
}
}// analisi validazione
}// Gestione POST
// Show form
echo view('pages/form/creditcards_form_add_edit', $data);
}//function select
//--------------------------------------------------------------------
public function edit($IDcard = null) {
helper(['tools','form']);
// Verifico dato introdotto:
if ($IDcard==null) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CreditCards/edit -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CreditCards/add -> Error code 002'); }
return redirect()->to('/dashboard');
}
// Ricavo livello del lavoratore (solo amministratori o superiori, possono editare tutti i campi)
$data['enable'] = $enable = CheckLevel(3, false);
// Solo amministratori possono editare una carta:
if (!$enable){
session()->setFlashdata('warning', 'Non si hanno i permessi per editare i dati di una carta di credito aziendale.');
return redirect()->to('/dashboard/credit');
}
// preparo i dati
$data['tab'] = 'credit';
$data['add'] = false;
$data['title'] = 'Dettagli della carta di credito';
// Ricavo il profilo dell'orario da editare
$model = new CreditCards_Model();
$data['card'] = $model->where('ccIDcard', $IDcard)
->first();
// Verifico che esista il record dell'orario:
if (null==$data['card']) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CreditCards/edit -> Error code 003'); }
return redirect()->to('/dashboard');
}
// Gestione POST
if ($this->request->getMethod() == 'post') {
// Regole per validare i campi introdotti nel form:
$rules = [
'Numero' => 'trim|required|min_length[8]|max_length[20]',
'ScadeIl' => 'trim|required',
'PIN' => 'trim|required|min_length[3]|max_length[6]',
'Descrizione' => 'trim|required|min_length[8]',
'Stato' => 'trim|required',
];
// analisi della validazione
if (! $this->validate($rules)) {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', $data['validation']->listErrors());
}else{
// validazione passata
// Preparo i dati per l'aggiornamento
// Tab: CreditCards = ['ccIDcard', 'ccNumero', 'ccDescrizione', 'ccScadeIl', 'ccPIN', 'ccCreatedAt', 'ccUpdatedAt', 'ccStato', 'ccDeletedAt'];
$newData = [
'ccIDcard' => $this->request->getVar('IDcard'),
'ccNumero' => $this->request->getVar('Numero'),
'ccScadeIl' => $this->request->getVar('ScadeIl'),
'ccPIN' => $this->request->getVar('PIN'),
'ccDescrizione' => $this->request->getVar('Descrizione'),
'ccStato' => $this->request->getVar('Stato'),
];
$model = new CreditCards_Model();
if ($model->save($newData)) {
session()->setFlashdata('success', 'Successfuly Updated');
return redirect()->to('/dashboard/credit');
} else {
session()->setFlashdata('danger', 'Errore durante l\'update del record nel DB.');
}
}// analisi validazione
}// Gestione POST
// Show form
echo view('pages/form/creditcards_form_add_edit', $data);
}//function select
//--------------------------------------------------------------------
public function delete($IDcard = null){
helper(['tools']);
$data = [];
$model = new CreditCards_Model();
// Verifico sessione e livello:
if (!CheckLevel(3)) {
session()->setFlashdata('warning', 'Non si hanno i permessi per cancellare una carta di credito aziendale.');
return redirect()->to('/dashboard/credit');
}
// Verifico dato introdotto:
if ($IDcard==null) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CreditCards/delete -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Elimino il record:
if ($model->delete($IDcard)) {
session()->setFlashdata('success', 'Recors cancellato correttamente.');
} else {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', 'Errore durante la cancellazione del record.');
}
// Show profile
return redirect()->to('/dashboard/credit');
} // function delete($id)
//--------------------------------------------------------------------
public function export_csv(){
helper(['tools','form']);
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/CreditCards/export_csv -> Error code 001'); }
return redirect()->to('/Lavoratori/login');
}
// Ricavo le ore dell'utente:
// Tab: CreditCards = ['ccIDcard', 'ccNumero', 'ccDescrizione', 'ccScadeIl', 'ccPIN', 'ccCreatedAt', 'ccUpdatedAt', 'ccStato', 'ccDeletedAt'];
$model = new CreditCards_Model();
// Costruisco la query per selezionare le ore da esportare:
// - applico eventuale filtro per lo stato:
// imposto l'ordinamento richiesto:
CheckSort('credit',true);
$data['sortCol'] = session()->get('sort')['col'];
$data['sortDir'] = session()->get('sort')['dir'];
$model->orderBy($data['sortCol'], $data['sortDir']);
// eseguo la query:
$data['dataset'] = $model->asArray()
->findAll();
// Imposto il nome del file da downloadare:
$filepath = $_SERVER['MRK_FILE_PATH'];
$filename = 'CSiCoDB_CarteDiCredito_il_' . date('Y-m-d_H-i-s') . '.csv';
// file creation
$file = fopen($filepath . $filename,"w");
// Esport header
fputcsv($file,['ID card', 'Numero', 'Descrizione', 'ScadeIl', 'PIN', 'CreatedAt', 'UpdatedAt', 'Stato']);
foreach ($data['dataset'] as $line){
fputcsv($file,$line);
}
// Chiudo il file
fclose($file);
// download
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=".$filename);
header("Content-Type: application/csv; ");
readfile($filepath . $filename);
// deleting file
unlink($filepath . $filename);
exit();
} // function export_csv
//--------------------------------------------------------------------
}//class CreditCards
+556
View File
@@ -0,0 +1,556 @@
<?php namespace App\Controllers;
use App\Models\Lavoratori_Model;
use App\Models\TipoOre_Model;
use App\Models\TipiWork_Model;
use App\Models\Orari_Model;
use App\Models\Spese_Model;
use App\Models\Commesse_Model;
use App\Models\CreditCardEvents_Model;
use App\Models\CreditCards_Model;
use App\Models\CSiCoCars_Model;
use App\Models\CSiCoCarEvents_Model;
use App\Models\SIMs_Model;
use App\Models\SIMEvents_Model;
class Dashboard extends BaseController {
//--------------------------------------------------------------------
public function index() {
return $this->home();
}//function index
//--------------------------------------------------------------------
public function home() {
helper(['tools','form']);
$data['tab'] = 'home';
// Verifico sessione e livello:
if (!CheckLevel(0)) { return redirect()->to('/Lavoratori/login'); }
$lav = session()->get('lavoratore');
// // Gli utenti Guest non possono inserire valori e per sicurezza visualizzo una pagina apposta.
// if ($lav->lvLevel==1){ return redirect()->to('/dashboard/home'); }
// Gli utenti guest non possono inserire ore, quindi per loro non gestisco le
// Gestione POST
if ($this->request->getMethod() == 'post') {
// verifico chi ha fatto il POST (ore o spese):
if(isset($_POST['PBinsetrOraPOST'])) {
// POST di aggiunta dell'orario e quindi verifico i dati dell'orario e se validi lo inserisco.
// Regole per validare i campi introdotti nel form:
$rules = [
'o_IDcommessa' => 'trim|required',
'o_Data' => 'trim|required',
'o_Ore' => 'trim|required',
'o_IDTipoOre' => 'trim|required',
'o_Descrizione' => 'trim|required|min_length[8]',
];
// analisi della validazione
if (! $this->validate($rules)) {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', $data['validation']->listErrors());
}else{
// validazione passata
// Preparo i dati per l'inserimento
$newData = [
'orIDcommessa' => $this->request->getVar('o_IDcommessa'),
'orIDlavoratore' => $lav->lvIDlavoratore,
'orData' => $this->request->getVar('o_Data'),
'orOre' => $this->request->getVar('o_Ore'),
'orIDTipoOre' => $this->request->getVar('o_IDTipoOre'),
'orDescrizione' => $this->request->getVar('o_Descrizione'),
];
$modelOrari = new Orari_Model();
if ($modelOrari->save($newData)) {
session()->setFlashdata('success', 'Record inserito con successo sul DB');
UpdateCommessa($newData['orIDcommessa']);
//return redirect()->to('/dashboard/home');
} else {
session()->setFlashdata('danger', 'Errore durante l\'inserimento del record nel DB.');
}
}// analisi validazione
} // if PBinsetrOraPOST
if(isset($_POST['PBinsetrSpesaPOST'])) {
// POST di aggiunta della spesa e quindi verifico i dati della spesa e se validi lo inserisco.
// Regole per validare i campi introdotti nel form:
$rules = [
's_IDcommessa' => 'trim|required',
's_Data' => 'trim|required',
's_Importo' => 'trim|required',
's_DaRimborsare' => 'trim|required',
's_Descrizione' => 'trim|required|min_length[8]',
];
// analisi della validazione
if (! $this->validate($rules)) {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', $data['validation']->listErrors());
}else{
// validazione passata
// Preparo i dati per l'inserimento
$newData = [
'spIDcommessa' => $this->request->getVar('s_IDcommessa'),
'spIDlavoratore' => $lav->lvIDlavoratore,
'spData' => $this->request->getVar('s_Data'),
'spImporto' => $this->request->getVar('s_Importo'),
'spDaRimborsare' => $this->request->getVar('s_DaRimborsare'),
'spDescrizione' => $this->request->getVar('s_Descrizione'),
];
$modelOrari = new Spese_Model();
if ($modelOrari->save($newData)) {
session()->setFlashdata('success', 'Record inserito con successo sul DB');
UpdateCommessa($newData['spIDcommessa']);
//return redirect()->to('/dashboard/home');
} else {
session()->setFlashdata('danger', 'Errore durante l\'inserimento del record nel DB.');
}
}// analisi validazione
} // if PBinsetrSpesaPOST
}// Gestione POST
// Ricavo riepilogo ultimi orari inseriti
$modelCommesse = new Commesse_Model();
$data['orari'] = $modelCommesse->join('Orari', 'Commesse.coIDcommessa = Orari.orIDcommessa')
->where('orIDlavoratore', $lav->lvIDlavoratore)
->orderBy('orIDorario', 'DESC')
->findAll(3);
// Ricavo ultime spese inserite
$data['spese'] = $modelCommesse->join('Spese', 'Commesse.coIDcommessa = Spese.spIDcommessa')
->where('spIDlavoratore', $lav->lvIDlavoratore)
->orderBy('spIDspesa', 'DESC')
->findAll(3);
// Ricavo i dati per il select delle tipologie di orario:
$modelTipoOre = new TipoOre_Model();
$data['select_tipo_ore'] = $modelTipoOre->get_select();
// Ricavo i dati per il select delle commesse:
$data['select_commesse'] = $modelCommesse->get_select();
// Ricavo i dati per il select dei lavoratori:
$modelLavoratori = new Lavoratori_Model();
$data['select_lavoratori'] = $modelLavoratori->get_select();
return view('pages/home', $data);
}//function home
//--------------------------------------------------------------------
public function orari() {
helper(['tools','form']);
$data['tab'] = 'orari';
// Verifico sessione e livello:
if (!CheckLevel(1)) { return redirect()->to('/dashboard'); }
// Ricavo le ore dell'utente:
// Tab: Orari = ['orIDorario', 'orIDcommessa', 'orIDlavoratore', 'orData', 'orOre', 'orIDTipoOre', 'orIDTipoWork', 'orDescrizione'];
// Tab: Lavoratori = ['lvIDlavoratore', 'lvNome', 'lvCognome', 'lvMail', 'lvLevel', 'lvRimborsoKm', 'lvNickname', 'lvPassword', 'lvCreatedAt', 'lvUpdatedAt', 'lvDeletedAt'];
// Tab: Commesse = ['coIDcommessa', 'coNome', 'coIDcliente', 'coDescrizione', 'coIDstatoCommessa', 'coModificatoIl', 'coCreatedAt', 'coUpdatedAt', 'coDeletedAt'];
$model = new Orari_Model();
$model->join('Lavoratori', 'Lavoratori.lvIDlavoratore = Orari.orIDlavoratore');
$model->join('Commesse', 'Commesse.coIDcommessa = Orari.orIDcommessa');
// Costruisco la query per selezionare le ore da mostrare:
// - applico il filtro sull'intervallo temporale:
$model->where('orData >=', session()->get('filter_dal'))
->where('orData <=', session()->get('filter_al') . " 23:59:59");
// - applico eventuale filtro per lavoratore
if (session()->filter_lavoratore!='-1') { $model->where('orIDlavoratore', session()->get('filter_lavoratore')); }
// - applico eventuale filtro per commessa
if (session()->filter_commessa!='-1') { $model->where('orIDcommessa', session()->get('filter_commessa')); }
// - applico eventuale filtro per tipologia di ora:
if (session()->filter_tipo_ore!='-1') { $model->where('orIDTipoOre', session()->get('filter_tipo_ore')); }
// imposto l'ordinamento richiesto:
CheckSort('orari',true);
$data['sortCol'] = session()->get('sort')['col'];
$data['sortDir'] = session()->get('sort')['dir'];
$model->orderBy($data['sortCol'], $data['sortDir']);
// eseguo la query con paginazione:
$data['dataset'] = $model->paginate(session()->get('pager_num'));
$data['pager'] = $model->pager;
// Ricavo i dati per il select delle commesse:
$modelCommesse = new Commesse_Model();
$data['select_commesse'] = $modelCommesse->get_select_on_orari();
// Ricavo i dati per il select delle tipologie di orario:
$modelTipoOre = new TipoOre_Model();
$data['select_tipo_ore'] = $modelTipoOre->get_select_on_orari();
// Ricavo i dati per il select dei lavoratori:
$modelLavoratori = new Lavoratori_Model();
$data['select_lavoratori'] = $modelLavoratori->get_select_on_orari();
// Ricavo i dati per il select delle tipologie di lavoro:
$modelTipoWork = new TipiWork_Model();
$data['select_tipo_work'] = $modelTipoWork->get_select_on_orari();
return view('pages/orari', $data);
}//function orari
//--------------------------------------------------------------------
public function spese() {
helper(['tools','form']);
$data['tab'] = 'spese';
// Verifico sessione e livello:
if (!CheckLevel(1)) { return redirect()->to('/dashboard'); }
// Ricavo le ore dell'utente:
// Tab: Spese = ['spIDspesa', 'spIDcommessa', 'spIDlavoratore', 'spImporto', 'spDaRimborsare', 'spDescrizione', 'spData'];
// Tab: Lavoratori = ['lvIDlavoratore', 'lvNome', 'lvCognome', 'lvMail', 'lvLevel', 'lvRimborsoKm', 'lvNickname', 'lvPassword', 'lvCreatedAt', 'lvUpdatedAt', 'lvDeletedAt'];
// Tab: Commesse = ['coIDcommessa', 'coNome', 'coIDcliente', 'coDescrizione', 'coIDstatoCommessa', 'coModificatoIl', 'coCreatedAt', 'coUpdatedAt', 'coDeletedAt'];
$model = new Spese_Model();
$model->join('Lavoratori', 'Lavoratori.lvIDlavoratore = Spese.spIDlavoratore');
$model->join('Commesse', 'Commesse.coIDcommessa = Spese.spIDcommessa');
// Costruisco la query per selezionare le ore da mostrare:
// - applico il filtro sull'intervallo temporale:
$model->where('spData >=', session()->get('filter_dal'))
->where('spData <=', session()->get('filter_al') . " 23:59:59");
// - applico eventuale filtro per lavoratore
if (session()->filter_lavoratore!='-1') { $model->where('spIDlavoratore', session()->get('filter_lavoratore')); }
// - applico eventuale filtro per commessa
if (session()->filter_commessa!='-1') { $model->where('coIDcommessa', session()->get('filter_commessa')); }
// - applico eventuale filtro per rimborso:
if (session()->filter_rimborso!='-1') { $model->where('spDaRimborsare', session()->get('filter_rimborso')); }
// imposto l'ordinamento richiesto:
CheckSort('spese',true);
$data['sortCol'] = session()->get('sort')['col'];
$data['sortDir'] = session()->get('sort')['dir'];
$model->orderBy($data['sortCol'], $data['sortDir']);
// eseguo la query con paginazione:
$data['dataset'] = $model->paginate(session()->get('pager_num'));
$data['pager'] = $model->pager;
// Ricavo i dati per il select delle commesse:
$modelCommesse = new Commesse_Model();
$data['select_commesse'] = $modelCommesse->get_select_on_spese();
// Ricavo i dati per il select dei lavoratori:
$modelLavoratori = new Lavoratori_Model();
$data['select_lavoratori'] = $modelLavoratori->get_select_on_spese();
return view('pages/spese', $data);
}//function spese
//--------------------------------------------------------------------
public function archivio() {
helper(['tools','form']);
$data['tab'] = 'archivio';
// Verifico sessione e livello:
if (!CheckLevel(1)) { return redirect()->to('/dashboard'); }
return view('pages/archivio', $data);
}//function archivio
//--------------------------------------------------------------------
public function cars() {
helper(['tools','form']);
$data['tab'] = 'cars';
// Verifico sessione e livello:
if (!CheckLevel(1)) { return redirect()->to('/dashboard'); }
// Ricavo le car:
// Tab: CSiCoCars = ['caIDcar', 'caTarga', 'caDescrizione', 'caDataAssicurazione', 'caTipoGomme', 'caCreatedAt', 'caUpdatedAt', 'caStato', 'caDeletedAt'];
$model = new CSiCoCars_Model();
// Costruisco la query per selezionare le macchine da mostrare:
// - applico il filtro sullo stato:
if (session()->filter_caStato!='-1') { $model->where('caStato', session()->get('filter_caStato')); }
// imposto l'ordinamento richiesto:
CheckSort('cars',true);
$data['sortCol'] = session()->get('sort')['col'];
$data['sortDir'] = session()->get('sort')['dir'];
$model->orderBy($data['sortCol'], $data['sortDir']);
// eseguo la query con paginazione:
$data['dataset'] = $model->paginate(session()->get('pager_num'));
$data['pager'] = $model->pager;
return view('pages/cars', $data);
}//function cars
//--------------------------------------------------------------------
public function credit() {
helper(['tools','form']);
$data['tab'] = 'credit';
// Verifico sessione e livello:
if (!CheckLevel(1)) { return redirect()->to('/dashboard'); }
// Ricavo le carte:
// Tab: CreditCards = ['ccIDcard', 'ccNumero', 'ccDescrizione', 'ccScadeIl', 'ccPIN', 'ccCreatedAt', 'ccUpdatedAt', ', 'ccStato', 'ccDeletedAt'];
$model = new CreditCards_Model();
// Costruisco la query per selezionare le ore da mostrare:
// - applico il filtro sullo stato:
if (session()->filter_ccStato!='-1') { $model->where('ccStato', session()->get('filter_ccStato')); }
// imposto l'ordinamento richiesto:
CheckSort('credit',true);
$data['sortCol'] = session()->get('sort')['col'];
$data['sortDir'] = session()->get('sort')['dir'];
$model->orderBy($data['sortCol'], $data['sortDir']);
// eseguo la query con paginazione:
$data['dataset'] = $model->paginate(session()->get('pager_num'));
$data['pager'] = $model->pager;
return view('pages/credit', $data);
}//function credit
//--------------------------------------------------------------------
public function sims() {
helper(['tools','form']);
$data['tab'] = 'sims';
// Verifico sessione e livello:
if (!CheckLevel(1)) { return redirect()->to('/dashboard'); }
// Ricavo le sim:
// SIMs = ['smIDsim', 'smNumero', 'smPIN', 'smPUK', 'smDescrizione', 'smCredito', 'smCreatedAt', 'smUpdatedAt', 'smStato', 'smDeletedAt'];
$model = new SIMs_Model();
// Costruisco la query per selezionare le macchine da mostrare:
// - applico il filtro sullo stato:
if (session()->filter_smStato!='-1') { $model->where('smStato', session()->get('filter_smStato')); }
// imposto l'ordinamento richiesto:
CheckSort('sims',true);
$data['sortCol'] = session()->get('sort')['col'];
$data['sortDir'] = session()->get('sort')['dir'];
$model->orderBy($data['sortCol'], $data['sortDir']);
// eseguo la query con paginazione:
$data['dataset'] = $model->paginate(session()->get('pager_num'));
$data['pager'] = $model->pager;
return view('pages/sims', $data);
}//function sims
//--------------------------------------------------------------------
public function admin() {
helper(['tools','form']);
$data['tab'] = 'admin';
// Verifico sessione e livello:
if (!CheckLevel(1)) { return redirect()->to('/dashboard'); }
return view('pages/admin', $data);
}//function admin
//--------------------------------------------------------------------
public function set_order($tab, $col, $dir){
helper(['tools','form']);
// Verifico sessione e livello:
if (!CheckLevel(0)) { return redirect()->to('/dashboard'); }
if (SetSort($tab, $col, $dir)) {
if ($tab=='anagrafica') return redirect()->to('/Lavoratori/anagrafica');
if ($tab=='evncredit') return redirect()->to('/CreditCardEvents/show');
if ($tab=='evncar') return redirect()->to('/CSiCoCarEvents/show');
if ($tab=='Issues') return redirect()->to('/Issues/View');
return redirect()->to('/dashboard/' . $tab);
} else {
// ordinamento non riuscito, avviso l'utente e torno alla home
session()->setFlashdata('warning', 'Errore durante il riordino dei records');
return redirect()->to('/dashboard');
}
}
//--------------------------------------------------------------------
public function set_filter($page, $new_filter_dal, $new_filter_al, $new_option, $new_filter_commessa, $new_filter_lavoratore) {
helper(['tools','form']);
// Verifico sessione e livello:
if (!CheckLevel(0)) { return redirect()->to('/dashboard'); }
// Questi filtri sono indipendenti dalla tabella
session()->set('filter_dal', $new_filter_dal);
session()->set('filter_al', $new_filter_al);
session()->set('filter_commessa', $new_filter_commessa);
// Questo filtro dipende dal tipo di tabella:
if ($page=='orari'){
session()->set('filter_tipo_ore', $new_option);
}
if ($page=='spese'){
session()->set('filter_rimborso', $new_option);
}
// solo gli amministratori possono vedere tutto e quindi cambiare il filtro del lavoratore:
if (CheckLevel(3, false)) {
session()->set('filter_lavoratore', $new_filter_lavoratore);
} else {
session()->set('filter_lavoratore', session()->get('lavoratore')->lvIDlavoratore);
}
return redirect()->to("/dashboard/$page");
}
//--------------------------------------------------------------------
public function set_filter1($page, $new_option) {
helper(['tools','form']);
// Verifico sessione e livello:
if (!CheckLevel(0)) { return redirect()->to('/dashboard'); }
// Questo filtro dipende dal tipo di tabella:
if ($page=='cars'){
session()->set('filter_caStato', $new_option);
return redirect()->to("/dashboard/$page");
}
if ($page=='credit'){
session()->set('filter_ccStato', $new_option);
return redirect()->to("/dashboard/$page");
}
if ($page=='sims'){
session()->set('filter_smStato', $new_option);
return redirect()->to("/dashboard/$page");
}
if ($page=='Stime'){
session()->set('filter_commessa', $new_option);
return redirect()->to("/Stime");
}
}
//--------------------------------------------------------------------
public function reset_filter($page) {
helper(['tools','form']);
// Verifico sessione e livello:
if (!CheckLevel(0)) { return redirect()->to('/dashboard'); }
// Questi filtri sono indipendenti dalla tabella
session()->set('filter_dal', date("Y-m-d", strtotime("first day of this month")));
session()->set('filter_al', date("Y-m-d", strtotime("last day of this month")));
session()->set('filter_commessa', '-1');
// Questo filtro dipende dal tipo di tabella:
if ($page=='orari'){
session()->set('filter_tipo_ore', '-1');
}
if ($page=='spese'){
session()->set('filter_rimborso', '-1');
}
if ($page=='cars'){
session()->set('filter_caStato', '-1');
}
if ($page=='credit'){
session()->set('filter_ccStato', '-1');
}
if ($page=='sims'){
session()->set('filter_smStato', '-1');
}
// solo gli amministratori possono vedere tutto e quindi cambiare il filtro del lavoratore:
if (CheckLevel(3, false)) {
session()->set('filter_lavoratore', '-1');
} else {
session()->set('filter_lavoratore', session()->get('lavoratore')->lvIDlavoratore);
}
if ($page=='Stime'){
return redirect()->to("/Stime");
}
return redirect()->to("/dashboard/$page");
}
}//class Dashboard
+388
View File
@@ -0,0 +1,388 @@
<?php namespace App\Controllers;
use App\Libraries\Crud;
use App\Models\Issues_Model;
use App\Models\Lavoratori_Model;
class Issues extends CRUDController {
// Tab: Issues = ['isIDissue', 'isTipologia', 'isStato', 'isIDlavoratore', 'isTesto', 'isCreatedAt', 'isUpdatedAt', 'isDeletedAt'];
protected $crud;
function __construct() {
$params = [
'table' => 'Issues',
'dev' => false,
'fields' => $this->field_options(),
'form_title_add' => 'Add Issue',
'form_title_update' => 'Edit Issue',
'form_submit' => 'Add',
'table_title' => 'Pagina per la tabella Issues',
'form_submit_update' => 'Update',
'base' => '',
'UpdatedAt' => 'isUpdatedAt',
'DeletedAt' => 'isDeletedAt',
];
$this->crud = new Crud($params, service('request'));
}// __construct
protected function field_options() {
$fields = [];
$fields['isIDissue'] = ['label' => 'ID', 'helper' => 'Identificativo univoco del record nel database'];
$fields['isTipologia'] = ['label' => 'Tipologia', 'helper' => 'Tipologia dell\'issue', 'required' => true];
$fields['isStato'] = ['label' => 'Stato', 'helper' => 'Stato dell\'issue', 'required' => true];
$fields['isIDlavoratore'] = [
'label' => 'Lavoratore',
'required' => true,
'type' => 'dropdown',
'helper' => 'Lavoratore che inserisce l\'issue',
'relation' => [
'table'=> 'Lavoratori',
'primary_key' => 'lvIDlavoratore',
'display' => ['lvNickname', 'lvNome', 'lvCognome'], //'display' => ['lvNickname'],
'order_by' => 'lvNickname',
'order' => 'ASC'
]
];
$fields['isTesto'] = ['label' => 'Testo', 'helper' => 'Testo descrittivo della issue','required' => true];
$fields['isCreatedAt'] = ['label' => 'Created At', 'helper' => 'Data di creazione del record relativo nel database', 'only_edit'=> true];
$fields['isUpdatedAt'] = ['label' => 'Updated At', 'helper' => 'Timestamp dell\'ultimo aggiornamento del record nel database', 'type' => 'unset'];
$fields['isDeletedAt'] = ['label' => 'Deleted At', 'helper' => 'Data di cancellazione del record relativo nel database', 'type' => 'unset'];
return $fields;
}// field_options
public function index() { return $this->CRUD_view(['isIDissue', 'isTipologia', 'isStato', 'isIDlavoratore', 'isTesto', 'isCreatedAt', 'isUpdatedAt', 'isDeletedAt']); }
//--------------------------------------------------------------------
// Auto CRUD terminato
//--------------------------------------------------------------------
public function View() {
helper(['tools','form']);
$data['tab'] = 'admin';
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Issues/show -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Ricavo i relativi eventi:
$mev = new Issues_Model();
$mev->join('Lavoratori', 'Lavoratori.lvIDlavoratore = Issues.isIDlavoratore');
// Per ora niente filtro, poi in futuro forse
// imposto l'ordinamento richiesto:
CheckSort('Issues',true);
$data['sortCol'] = session()->get('sort')['col'];
$data['sortDir'] = session()->get('sort')['dir'];
$mev->orderBy($data['sortCol'], $data['sortDir']);
// eseguo la query con paginazione:
$data['dataset'] = $mev->paginate(session()->get('pager_num'));
$data['pager'] = $mev->pager;
return view('/pages/issues', $data);
}//function select
//--------------------------------------------------------------------
public function add() {
helper(['tools','form']);
$data['tab'] = 'admin';
$data['add'] = true;
$data['title'] = 'Dettagli dell\'Issue:';
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Issues/add -> Error code 001'); }
return redirect()->to('/Lavoratori/login');
}
// Ricavo livello del lavoratore (solo amministratori o superiori, possono editare tutti i campi)
$data['enable'] = $enable = CheckLevel(3, false);
// Gestione POST
if ($this->request->getMethod() == 'post') {
// Regole per validare i campi introdotti nel form:
$rules = [
'Tipologia' => 'trim|required',
'Stato' => 'trim|required',
'Descrizione' => 'trim|required|min_length[8]',
];
if ($enable){
$rules['IDlavoratore'] = 'trim|required';
}
// analisi della validazione
if (! $this->validate($rules)) {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', $data['validation']->listErrors());
} else {
// validazione passata
// Preparo i dati per l'inserimento
$newData = [
//isIDissue' => $this->request->getVar('IDlavoratore'),
'isTipologia' => $this->request->getVar('Tipologia'),
'isStato' => $this->request->getVar('Stato'),
'isTesto' => $this->request->getVar('Descrizione'),
];
if ($enable){
$newData['isIDlavoratore'] = $this->request->getVar('IDlavoratore');
} else {
$newData['isIDlavoratore'] = session()->get('lavoratore')->lvIDlavoratore;
}
$model = new Issues_Model();
if ($model->save($newData)) {
// issue inserito con successo, aggiorno lo stato della SIM
session()->setFlashdata('success', 'issue inserito con successo');
// apro la pagina desiderata in base al pulsante utilizzato:
if(isset($_POST['crea_continua'])) {
// è stato premuto il secondo pulsante, quindi inserisco un secondo valore:
//return redirect()->to('/dashboard/orari');
} else {
return redirect()->to('/Issues/View');
}
} else {
// errore durante l'inserimento dell'issue
session()->setFlashdata('danger', 'Errore durante l\'inserimento del record nel DB.');
}
}// analisi validazione
}// Gestione POST
// Ricavo i dati per il select dei lavoratori:
$modelLavoratori = new Lavoratori_Model();
$data['select_lavoratori'] = $modelLavoratori->get_select();
// Show form
echo view('pages/form/Issues_form_add_edit', $data);
}//function add
//--------------------------------------------------------------------
public function edit($IDissue = null) {
helper(['tools','form']);
$data['tab'] = 'admin';
$data['add'] = false;
$data['title'] = 'Dettagli dell\'Issue:';
// Verifico dato introdotto:
if ($IDissue==null) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Issues/edit -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Ricavo livello del lavoratore (solo amministratori o superiori, possono editare tutti i campi)
$data['enable'] = $enable = CheckLevel(3, false);
// Ricavo l'issue selezionato, completo di tutti i particolari:
$model = new Issues_Model();
$model->join('Lavoratori', 'Issues.isIDlavoratore = Lavoratori.lvIDlavoratore');
$data['issue'] = $model->where('isIDissue', $IDissue)
->first();
// Verifico che esista il record:
if (null==$data['issue']) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Issues/edit -> Error code 003'); }
return redirect()->to('/dashboard');
}
// Gestione POST
if ($this->request->getMethod() == 'post') {
// Regole per validare i campi introdotti nel form:
$rules = [
'Tipologia' => 'trim|required',
'Stato' => 'trim|required',
'Descrizione' => 'trim|required|min_length[8]',
];
if ($enable){
$rules['IDlavoratore'] = 'trim|required';
}
// analisi della validazione
if (! $this->validate($rules)) {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', $data['validation']->listErrors());
}else{
// validazione passata
// Preparo i dati per l'inserimento
$newData = [
'isIDissue' => $IDissue,
'isTipologia' => $this->request->getVar('Tipologia'),
'isStato' => $this->request->getVar('Stato'),
'isTesto' => $this->request->getVar('Descrizione'),
];
if ($enable){
$newData['isIDlavoratore'] = $this->request->getVar('IDlavoratore');
}
if ($model->save($newData)) {
// issue inserito con successo, aggiorno lo stato della carta
session()->setFlashdata('success', 'issue aggiornato con successo');
// apro la pagina desiderata in base al pulsante utilizzato:
if(isset($_POST['crea_continua'])) {
// è stato premuto il secondo pulsante, quindi inserisco un secondo valore:
//return redirect()->to('/dashboard/orari');
} else {
return redirect()->to('/Issues/View');
}
} else {
// errore durante l'inserimento dell'issue
session()->setFlashdata('danger', 'Errore durante l\'inserimento del record nel DB.');
}
}// analisi validazione
}// Gestione POST
// Ricavo i dati per il select dei lavoratori:
$modelLavoratori = new Lavoratori_Model();
$data['select_lavoratori'] = $modelLavoratori->get_select();
// Show form
echo view('pages/form/Issues_form_add_edit', $data);
}//function edit
//--------------------------------------------------------------------
public function delete($IDissue = null){
helper(['tools']);
$data = [];
// Ricavo l'issue selezionato, completo di tutti i particolari:
$model = new Issues_Model();
$model->join('Lavoratori', 'Issues.isIDlavoratore = Lavoratori.lvIDlavoratore');
$issue = $model->where('isIDissue', $IDissue)
->first();
// Verifico che esista il record:
if (null==$issue) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Issues/delete -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Verifico sessione e livello:
if (!(CheckLevel(3) || session()->get('lavoratore')->lvIDlavoratore==$issue->isIDlavoratore)) {
session()->setFlashdata('warning', 'Non si hanno i permessi per cancellare un issue inserito da altri lavoratori.');
return redirect()->to('/Issues/show');
}
// Elimino il record:
if ($model->delete($IDissue)) {
// issue cancellato, aggiorno stato della macchina relativa
session()->setFlashdata('success', 'Record cancellato correttamente.');
} else {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', 'Errore durante la cancellazione del record.');
}
// Show profile
return redirect()->to('/Issues/View');
} // function delete($id)
//--------------------------------------------------------------------
public function export_csv(){
helper(['tools','form']);
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/SIMs/export_csv -> Error code 001'); }
return redirect()->to('/Issues/show');
}
// Ricavo gli eventi della sim:
// Tab: Issues = ['isIDissue', 'isTipologia', 'isStato', 'isIDlavoratore', 'isTesto', 'isCreatedAt', 'isUpdatedAt', 'isDeletedAt'];
$mev = new Issues_Model();
$mev->join('Lavoratori', 'Issues.isIDlavoratore = Lavoratori.lvIDlavoratore');
// Per ora niente filtro, poi in futuro forse
// imposto l'ordinamento richiesto:
CheckSort('Issues',true);
$data['sortCol'] = session()->get('sort')['col'];
$data['sortDir'] = session()->get('sort')['dir'];
$mev->orderBy($data['sortCol'], $data['sortDir']);
// eseguo la query:
$data['dataset'] = $mev->asArray()
->findAll();
// Imposto il nome del file da downloadare:
$filepath = $_SERVER['MRK_FILE_PATH'];
$filename = 'CSiCoDB_Issues_il_' . date('Y-m-d_H-i-s') . '.csv';
// file creation
$file = fopen($filepath . $filename,"w");
// Esport header
fputcsv($file,['Issue della web app:']);
fputcsv($file,['ID issue', 'Tipologia', 'Stato', 'Descrizione issue', 'ID Lavoratore', 'Nickname', 'Created At', 'Updated At']);
foreach ($data['dataset'] as $line){
//fputcsv($file,$line);
// Seleziono le colonne da esportare:
$record = [];
$record['isIDissue'] = $line['isIDissue'];
$record['isTipologia'] = $line['isTipologia'];
$record['isStato'] = $line['isStato'];
$record['isTesto'] = $line['isTesto'];
$record['isIDlavoratore'] = $line['isIDlavoratore'];
$record['lvNickname'] = $line['lvNickname'];
$record['isCreatedAt'] = $line['isCreatedAt'];
$record['isUpdatedAt'] = $line['isUpdatedAt'];
fputcsv($file,$record);
}
// Chiudo il file
fclose($file);
// download
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=".$filename);
header("Content-Type: application/csv; ");
readfile($filepath . $filename);
// deleting file
unlink($filepath . $filename);
exit();
} // function export_csv
//--------------------------------------------------------------------
}
+493
View File
@@ -0,0 +1,493 @@
<?php namespace App\Controllers;
use App\Libraries\Crud;
use App\Models\Lavoratori_Model;
class Lavoratori extends CRUDController {
// Tab: Lavoratori = ['lvIDlavoratore', 'lvNome', 'lvCognome', 'lvMail', 'lvLevel', 'lvRimborsoKm', 'lvNickname', 'lvPassword', 'lvCreatedAt', 'lvUpdatedAt', 'lvDeletedAt'];
protected $crud;
function __construct() {
$params = [
'table' => 'Lavoratori',
'dev' => false,
'fields' => $this->field_options(),
'form_title_add' => 'Add Issue',
'form_title_update' => 'Edit Issue',
'form_submit' => 'Add',
'table_title' => 'Pagina per la tabella Lavoratori',
'form_submit_update' => 'Update',
'base' => '',
'UpdatedAt' => 'lvUpdatedAt',
'DeletedAt' => 'lvDeletedAt',
];
$this->crud = new Crud($params, service('request'));
}// __construct
protected function field_options() {
$fields = [];
$fields['lvIDlavoratore'] = ['label' => 'ID Lavoratore'];
$fields['lvNome'] = ['label' => 'Nome', 'helper' => 'Nome del lavoratore (max 64 caratteri)', 'required' => true];
$fields['lvCognome'] = ['label' => 'Cognome', 'helper' => 'Cognome del lavoratore (max 64 caratteri)', 'required' => true];
$fields['lvMail'] = ['label' => 'email', 'helper' => 'Indirizzo mail del lavoratore (max 128 caratteri)', 'required' => true, 'unique' => [true, 'lvMail']];
$fields['lvLevel'] = ['label' => 'Livello', 'helper' => 'Livello di accesso alla webapp: 0=Guest; 1=Oper; 2=Inven; 3=Admin; 4=Root', 'required' => true];
$fields['lvRimborsoKm'] = ['label' => '€/Km', 'helper' => 'Rimborso chilometrico riconosciuto al lavoratore', 'required' => true];
$fields['lvNickname'] = ['label' => 'Nickname', 'helper' => 'Nickname del lavoratore nella forma CSiCoCCN', 'required' => true, 'unique' => [true, 'lvNickname']];
$fields['lvPassword'] = [
'label' => 'Password',
'required' => true,
'only_add' => true,
'type' => 'password',
'confirm' => true,
'password_hash' => true,
'helper' => 'Password per il riconoscimento del lavoratore (min 8 caratteri)'
];
$fields['lvCreatedAt'] = ['label' => 'Created at', 'helper' => 'Data di creazione del record relativo nel database', 'only_edit'=> true];
$fields['lvUpdatedAt'] = ['label' => 'Updated at', 'helper' => 'Timestamp dell\'ultimo aggiornamento del record nel database', 'type' => 'unset'];
$fields['lvDeletedAt'] = ['label' => 'Deleted at', 'helper' => 'Data di cancellazione del record relativo nel database', 'type' => 'unset'];
return $fields;
}// field_options
public function index() { return $this->CRUD_view(['lvIDlavoratore', 'lvNickname', 'lvNome', 'lvCognome', 'lvMail', 'lvLevel', 'lvRimborsoKm', 'lvCreatedAt', 'lvUpdatedAt', 'lvDeletedAt']); }
//--------------------------------------------------------------------
// Auto CRUD terminato
//--------------------------------------------------------------------
// funzione per reinizializzare un utente senza loggarsi, utile in caso di problemi per avere un nuovo amministratore e potersi collegare.
// http://localhost/Lavoratori/reinizzializza/CSiCoAlm/4/password/127
public function Reinizzializza($Nickname = 'CSiCoZZZ', $Level = '0', $Password = 'password', $CheckId = 0){
if ($CheckId<>127) {
// Se non siamo loggati
session()->setFlashdata('danger', 'Reinizzializzazione del lavoratore non autorizzata.');
return redirect()->to('/dashboard');
}
// Ricavo l'ID del lavoratore indicato:
$model = new Lavoratori_Model();
$lav = $model->where('lvNickname', $Nickname)
->first();
if (!isset($lav)) {
// Lavoratore non trovato
session()->setFlashdata('danger', 'Lavoratore da reinizzializzare non trovato.');
return redirect()->to('/dashboard');
}
// Preparo i dati per l'aggiornamento
$newData = [
'lvIDlavoratore' => $lav->lvIDlavoratore,
'lvLevel' => $Level,
'lvPassword' => $Password,
];
// Eseguo update del record
if ($model->save($newData)) {
session()->setFlashdata('success', 'Lavoratore reinizzializzato correttamente.');
return redirect()->to('/dashboard');
} else {
session()->setFlashdata('warning', 'Reinizzializzazione non riuscita.');
return redirect()->to('/dashboard');
}
} // function Reinizzializza
//--------------------------------------------------------------------
public function logout(){
session()->destroy();
return redirect()->to('/Lavoratori/login');
}//function logout
//--------------------------------------------------------------------
public function login (){
$data = [];
helper(['tools','form']);
// Gestione POST data dal form
if ($this->request->getMethod() == 'post') {
// Regole per validare i campi introdotti nel form:
$rules = [
'Nickname' => 'required|min_length[8]|max_length[8]',
'Password' => 'required|min_length[8]|max_length[255]',
];
// analisi della validazione
if (! $this->validate($rules)) {
// Validazione non passata, mostro errori sulla flash di warning
$data['validation'] = $this->validator;
session()->setFlashdata('warning', $data['validation']->listErrors());
} else {
// validazione passata
// ricavo il lavoratore dai dati inseriti
$model = new Lavoratori_Model();
$lav = $model->where('lvNickname', $this->request->getVar('Nickname'))
->first();
if (isset($lav) && (password_verify($this->request->getVar('Password'), $lav->lvPassword))) {
// Verifico se lavoratore abilitato:
if (password_verify($this->request->getVar('Password'), $lav->lvPassword)){
// Utente riconosciuto, inizio la sessione di lavoro
if (setUserSession($lav)){
session()->setFlashdata('success', 'Utente abilitato correttamente');
return redirect()->to('/dashboard');
} else {
session()->setFlashdata('warning', 'Errore durante la creazione della sessione di lavoro.<br> Riprovare e se l\'errore si ripete, contattare l\'amministratore.');
}
} else {
// utente non riconosciuto, ritorno al login
session()->setFlashdata('warning', 'Errore, lavoratore non riconosciuto.<br> Riprovare e se l\'errore si ripete, contattare l\'amministratore.');
}
} else {
// Coppia nickname/password non corretta.
session()->setFlashdata('warning', 'Errore, lavoratore non riconosciuto.<br> Riprovare e se l\'errore si ripete, contattare l\'amministratore.');
}
}// analisi della validazione
}// Gestione POST data dal form
// Show login page
echo view('pages/lavoratori/lavoratori_form_login', $data);
}//function login
//--------------------------------------------------------------------
public function profile($id = null){
$data = [];
helper(['tools','form']);
$model = new Lavoratori_Model();
// Verifico sessione e livello:
if (!CheckLevel(0)) { return redirect()->to('/dashboard'); }
// Ricavo livello del lavoratore (solo amministratori o superiori, possono editare tutte del lavoratore)
$enable = CheckLevel(3,false);
// Ricavo l'ID del lavoratore di cui editare il profilo:
if (!isset($id)) {
$id = session()->get('lavoratore')->lvIDlavoratore;
}
// Ricavo il profilo del lavoratore da editare
$lav = $model->where('lvIDlavoratore', $id)
->first();
// Gestione POST
if ($this->request->getMethod() == 'post') {
// Regole per validare i campi introdotti nel form:
//
// L'utente normale può editare solo nome, cognome e quando vuole anche la password.
// L'utente amministratore o superiore, può editare tutto dell'utente.
$rules = [
//'IDlavoratore' => '',
'Nome' => 'trim|required|min_length[3]|max_length[64]',
'Cognome' => 'trim|required|min_length[3]|max_length[64]',
];
if ($enable){
$rules['Mail'] = 'required|min_length[6]|max_length[50]|valid_email';
$rules['Nickname'] = 'trim|required|min_length[8]|max_length[8]';
$rules['RimborsoKm'] = 'required';
}
if($this->request->getPost('NewPassword') != ''){
$rules['NewPassword'] = 'required|min_length[8]|max_length[255]';
$rules['ConfirmNewPassword'] = 'matches[NewPassword]';
}
// analisi della validazione
if (! $this->validate($rules)) {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', $data['validation']->listErrors());
}else{
// validazione passata
// Preparo i dati per l'aggiornamento
$newData = [
'lvIDlavoratore' => $lav->lvIDlavoratore,
'lvNome' => $this->request->getVar('Nome'),
'lvCognome' => $this->request->getVar('Cognome'),
];
if ($enable){
$newData['lvLevel'] = $this->request->getVar('Livello');
$newData['lvMail'] = $this->request->getVar('Mail');
$newData['lvNickname'] = $this->request->getVar('Nickname');
$newData['lvRimborsoKm'] = $this->request->getVar('RimborsoKm');
}
if($this->request->getPost('NewPassword') != ''){
$newData['lvPassword'] = $this->request->getPost('NewPassword');
}
if ($model->save($newData)) {
session()->setFlashdata('success', 'Successfuly Updated');
return redirect()->to('/dashboard');
} else {
session()->setFlashdata('danger', 'Errore durante l\'update del record nel DB.');
}
}// analisi validazione
}// Gestione POST
// Rileggo i dati dal DB
$data['lavoratore'] = $lav;
$data['enable'] = $enable;
// Show profile
echo view('pages/lavoratori/lavoratori_form_profile', $data);
} // function profile
//--------------------------------------------------------------------
public function delete($id = null){
$data = [];
helper(['tools','form']);
// Verifico sessione e livello:
if (!CheckLevel(3,false)) { return redirect()->to('/Lavoratori/anagrafica'); }
// Verifico di non cancellare me stesso:
if (session()->get('lavoratore')->lvIDlavoratore==$id) {
session()->setFlashdata('warning', 'L\'utente non può cancellare se stesso.');
return redirect()->to('/Lavoratori/anagrafica');
}
// Elimino il record:
$model = new Lavoratori_Model();
if ($model->delete($id)) {
session()->setFlashdata('success', 'Recors cancellato correttamente.');
} else {
session()->setFlashdata('warning', 'Errore durante la cancellazione del record.');
}
return redirect()->to('/Lavoratori/anagrafica');
} // function delete
//--------------------------------------------------------------------
public function register(){
$data = [];
helper(['tools','form']);
// // Verifico sessione e livello:
// if (CheckLevel(0,false)) { return redirect()->to('/dashboard'); } // non faccio il test così lo uso anche per creare nuovo utente dalla pagina anagrafica
// Gestione POST data dal form
if ($this->request->getMethod() == 'post') {
// Regole per validare i campi introdotti nel form:
$rules = [
'Nome' => 'required|min_length[3]|max_length[64]',
'Cognome' => 'required|min_length[3]|max_length[64]',
'Password' => 'required|min_length[8]|max_length[255]',
'PasswordConfirm' => 'matches[Password]',
];
// analisi della validazione
if (! $this->validate($rules)) {
// Validazione non passata, mostro errori sulla flash di warning
$data['validation'] = $this->validator;
session()->setFlashdata('warning', $data['validation']->listErrors());
}else{
// validazione passata
$model = new Lavoratori_Model();
$nom = $this->request->getVar('Nome');
$cogn = $this->request->getVar('Cognome');
// Preparo i dati del nuovo record
$newData = [
'lvNome' => $nom,
'lvCognome' => $cogn,
'lvMail' => strtolower($nom) . "." . strtolower($cogn) . "@csico.it",
'lvLevel' => 0,
'lvRimborsoKm' => 0.0,
'lvNickname' => 'CSiCo'.(substr(strtoupper($cogn), 0, 1)).(substr(strtolower($cogn), 1, 1)).(substr(strtolower($nom), 0, 1)),
'lvPassword' => $this->request->getVar('Password'),
];
// Inserisco il nuovo record
if ($model->save($newData)){
session()->setFlashdata('success', 'Dati acquisiti, attendere la mail di conferma per l\'abilitazione completa');
//return redirect()->to('/dashboard');
return redirect()->to('/Lavoratori/anagrafica'); // uso register anche nell'anagrafica
} else {
session()->setFlashdata('danger', 'Errore durante l\'inserimento del record nel DB.');
}
}// analisi validazione
}// Gestione POST
echo view('pages/lavoratori/lavoratori_form_register', $data);
} // function register
//--------------------------------------------------------------------
public function anagrafica(){
$data['tab'] = 'amministrazione';
helper(['tools','form']);
// Verifico sessione e livello:
if (!CheckLevel(1)) { return redirect()->to('/dashboard'); }
$model = new Lavoratori_Model();
// imposto l'ordinamento richiesto:
CheckSort('anagrafica',true);
$data['sortCol'] = session()->get('sort')['col'];
$data['sortDir'] = session()->get('sort')['dir'];
$model->orderBy($data['sortCol'], $data['sortDir']);
// // imposto l'ordinamento richiesto:
// $order_field = session()->get('sort_lavoratori_field');
// $order_direction = session()->get('sort_lavoratori_val');
// $model->orderBy($order_field, $order_direction);
$data['dataset'] = $model->paginate(session()->get('pager_num'));
$data['pager'] = $model->pager;
// Show anagrafica
echo view('pages/lavoratori/lavoratori_anagrafica', $data);
} // function anagrafica
//--------------------------------------------------------------------
// Funzione per resettare la password dell'utente indicato con la standard password.
// TODO Deve inviare mail di conferma all'utente.
public function reset($id){
$data = [];
helper(['tools','form']);
// Verifico sessione e livello:
if (!CheckLevel(0)) { return redirect()->to('/Lavoratori/login'); }
// Se non abbiamo il livello amministrativo non posso resettare la password a meno che non sia la mia.
$lav = session()->get('lavoratore');
if ((CheckLevel(3, false)) || ($lav->lvIDlavoratore==$id)){
//Resetto password con quella standard: password
// Preparo i dati per l'aggiornamento
$newData = [
'lvIDlavoratore' => $id,
'lvPassword' => 'password',
];
// Eseguo update del record
$model = new Lavoratori_Model();
if ($model->save($newData)) {
session()->setFlashdata('success', 'Password resettata correttamente.');
} else {
session()->setFlashdata('warning', 'Reset password non riuscito.');
}
} else{
// non resetto la password
session()->setFlashdata('warning', 'Reset password non consentito.');
}
return redirect()->to('/Lavoratori/anagrafica');
} // function reset
//--------------------------------------------------------------------
public function export_csv(){
helper(['tools']);
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Lavoratori/export_csv -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Ricavo le ore dell'utente:
// Tab: Lavoratori = ['lvIDlavoratore', 'lvNome', 'lvCognome', 'lvMail', 'lvLevel', 'lvRimborsoKm', 'lvNickname', 'lvPassword', 'lvCreatedAt', 'lvUpdatedAt', 'lvDeletedAt'];
$model = new Lavoratori_Model();
// imposto l'ordinamento richiesto:
CheckSort('anagrafica',true);
$sortCol = session()->get('sort')['col'];
$sortDir = session()->get('sort')['dir'];
$model->orderBy($sortCol, $sortDir);
// eseguo la query:
$data['dataset'] = $model->asArray()
->findAll();
// Imposto il nome del file da downloadare:
$filepath = $_SERVER['MRK_FILE_PATH'];
$filename = 'CSiCoDB_Lavoratori_il_' . date('Y-m-d_H-i-s') . '.csv';
// file creation
$file = fopen($filepath . $filename,"w");
// Esport header
fputcsv($file,['ID','Nome','Cognome','Mail','Level','RimborsoKm','Nickname','Hash Password','CreatedAt','UpdatedAt','DeletedAt']);
foreach ($data['dataset'] as $line){
fputcsv($file,$line);
}
// Chiudo il file
// download
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=".$filename);
header("Content-Type: application/csv; ");
readfile($filepath . $filename);
// deleting file
unlink($filepath . $filename);
exit();
}//function export_csv
//--------------------------------------------------------------------
}//class Lavoratori
+471
View File
@@ -0,0 +1,471 @@
<?php namespace App\Controllers;
use App\Libraries\Crud;
use App\Models\Lavoratori_Model;
use App\Models\Commesse_Model;
use App\Models\TipoOre_Model;
use App\Models\TipiWork_Model;
use App\Models\Orari_Model;
use App\Models\Spese_Model;
class Orari extends CRUDController {
// Tab: Orari = ['orIDorario', 'orIDcommessa', 'orIDlavoratore', 'orData', 'orOre', 'orIDTipoOre', 'orIDTipoWork', 'orDescrizione'];
protected $crud;
function __construct() {
$params = [
'table' => 'Orari',
'dev' => false,
'fields' => $this->field_options(),
'form_title_add' => 'Add Orario',
'form_title_update' => 'Edit Orario',
'form_submit' => 'Add',
'table_title' => 'Pagina per la tabella Orari',
'form_submit_update' => 'Update',
'base' => '',
'UpdatedAt' => '',
'DeletedAt' => '',
];
$this->crud = new Crud($params, service('request'));
}// __construct
protected function field_options() {
$fields = [];
$fields['orIDorario'] = ['label' => 'ID', 'helper' => 'Identificativo univoco del record nel database'];
$fields['orIDcommessa'] = [
'label' => 'Commessa',
'required' => true,
'type' => 'dropdown',
'helper' => 'Commessa a cui si riferisce l\'orario',
'relation' => [
'table'=> 'Commesse',
'primary_key' => 'coIDcommessa',
'display' => ['coNome'],
'order_by' => 'coUpdatedAt',
'order' => 'DESC'
]
];
$fields['orIDlavoratore'] = [
'label' => 'Lavoratore',
'required' => true,
'type' => 'dropdown',
'helper' => 'Lavoratore a cui si riferisce l\'orario',
'relation' => [
'table'=> 'Lavoratori',
'primary_key' => 'lvIDlavoratore',
'display' => ['lvNickname', 'lvNome', 'lvCognome'], //'display' => ['lvNickname'],
'order_by' => 'lvNickname',
'order' => 'ASC'
]
];
$fields['orData'] = ['label' => 'Data', 'helper' => 'Data dell\'orario','required' => true];
$fields['orOre'] = ['label' => 'Durata', 'helper' => 'Durata dell\'orario di lavoro. Approssimare al quarto d\'ora (0.25)', 'required' => true];
$fields['orIDTipoOre'] = [
'label' => 'Tipologia',
'required' => true,
'type' => 'dropdown',
'helper' => 'Tipologia dell\'orario',
'relation' => [
'table'=> 'TipoOre',
'primary_key' => 'toIDTipoOre',
'display' => ['toDescrizione'],
'order_by' => 'toOrdinamento',
'order' => 'ASC'
]
];
$fields['orDescrizione'] = ['label' => 'Descrizione', 'helper' => 'Descrizione esaustiva di quanto fatto durante l\'orario inserito','required' => true];
return $fields;
}// field_options
public function index() { return $this->CRUD_view(['orIDorario', 'orIDcommessa', 'orIDlavoratore', 'orData', 'orOre', 'orIDTipoOre', 'orIDTipoWork', 'orDescrizione']); }
//--------------------------------------------------------------------
// Auto CRUD terminato
//--------------------------------------------------------------------
//--------------------------------------------------------------------
public function add(){
helper(['tools','form']);
$data['Data'] = date('Y-m-d');
$model = new Orari_Model();
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Orari/add -> Error code 001'); }
return redirect()->to('/Lavoratori/login');
}
// Ricavo livello del lavoratore (solo amministratori o superiori, possono editare tutti i campi)
$enable = CheckLevel(3, false);
// Gestione POST
if ($this->request->getMethod() == 'post') {
// Regole per validare i campi introdotti nel form:
//
$rules = [
'IDcommessa' => 'trim|required',
'Data' => 'trim|required',
'Durata' => 'trim|required',
'IDTipoOre' => 'trim|required',
'IDTipoWork' => 'trim|required',
'Descrizione' => 'trim|required|min_length[8]',
];
if ($enable){
$rules['IDlavoratore'] = 'trim|required';
}
// analisi della validazione
if (! $this->validate($rules)) {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', $data['validation']->listErrors());
}else{
// validazione passata
// Preparo i dati per l'inserimento
// Tab: Orari = ['orIDorario', 'orIDcommessa', 'orIDlavoratore', 'orData', 'orOre', 'orIDTipoOre', 'orIDTipoWork', 'orDescrizione'];
$newData = [
'orIDcommessa' => $this->request->getVar('IDcommessa'),
'orData' => $this->request->getVar('Data'),
'orOre' => $this->request->getVar('Durata'),
'orIDTipoOre' => $this->request->getVar('IDTipoOre'),
'orIDTipoWork' => $this->request->getVar('IDTipoWork'),
'orDescrizione' => $this->request->getVar('Descrizione'),
];
if ($enable){
$newData['orIDlavoratore'] = $this->request->getVar('IDlavoratore');
} else {
$newData['orIDlavoratore'] = session()->get('lavoratore')->lvIDlavoratore;
}
if ($model->save($newData)) {
session()->setFlashdata('success', 'Record inserito con successo sul DB');
UpdateCommessa($newData['orIDcommessa']);
if(isset($_POST['crea_continua'])) {
// è stato premuto il secondo pulsante, quindi inserisco un secondo valore:
//return redirect()->to('/dashboard/orari');
} else {
return redirect()->to('/dashboard/orari');
}
} else {
session()->setFlashdata('danger', 'Errore durante l\'inserimento del record nel DB.');
}
}// analisi validazione
}// Gestione POST
// Rileggo i dati dal DB
$data['enable'] = $enable;
// Ricavo i dati per il select delle commesse:
$modelCommesse = new Commesse_Model();
$data['select_commesse'] = $modelCommesse->get_select();
// Ricavo i dati per il select dei lavoratori:
$modelLavoratori = new Lavoratori_Model();
$data['select_lavoratori'] = $modelLavoratori->get_select();
// Ricavo i dati per il select deila tipologia di ore:
$modelTipoOre = new TipoOre_Model();
$data['select_tipo_ore'] = $modelTipoOre->get_select();
// Ricavo i dati per il select deila tipologia di lavoro:
$modelTipiWork = new TipiWork_Model();
$data['select_tipi_work'] = $modelTipiWork->get_select();
// Show profile
echo view('pages/orari/orari_form_add', $data);
} // function add($id)
//--------------------------------------------------------------------
public function edit($IDorario = null){
helper(['tools','form']);
$data = [];
$model = new Orari_Model();
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Orari/edit -> Error code 001'); }
return redirect()->to('/Lavoratori/login');
}
// Ricavo livello del lavoratore (solo amministratori o superiori, possono editare tutti i campi)
$enable = CheckLevel(3, false);
// Verifico dato introdotto:
if ($IDorario==null) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Orari/edit -> Error code 002'); }
return redirect()->to('/dashboard');
}
// Ricavo il profilo dell'orario da editare
$orario = $model->where('orIDorario', $IDorario)
->first();
// Verifico che esista il record dell'orario:
if (null==$orario) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Orari/edit -> Error code 003'); }
return redirect()->to('/dashboard');
}
// Verifico se posso editare il campo:
// - utente amministratore o superiore, può editare tutti i campi
// - utente normale può editare solo i propi orari
$lav = session()->get('lavoratore');
if ((!$enable) && ($lav->lvIDlavoratore<>$orario->orIDlavoratore)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Orari/edit -> Error code 004'); }
return redirect()->to('/dashboard');
}
// Gestione POST
if ($this->request->getMethod() == 'post') {
// Regole per validare i campi introdotti nel form:
//
$rules = [
'IDorario' => 'trim|required',
'IDcommessa' => 'trim|required',
'Data' => 'trim|required',
'Durata' => 'trim|required',
'IDTipoOre' => 'trim|required',
'IDTipoWork' => 'trim|required',
'Descrizione' => 'trim|required',
];
if ($enable){
//$rules['Level'] = 'trim|required|min_length[8]|max_length[255]';
$rules['IDlavoratore'] = 'trim|required';
}
// analisi della validazione
if (! $this->validate($rules)) {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', $data['validation']->listErrors());
}else{
// validazione passata
// Preparo i dati per l'aggiornamento
$newData = [
'orIDorario' => $orario->orIDorario,
'orIDcommessa' => $this->request->getVar('IDcommessa'),
'orData' => $this->request->getVar('Data'),
'orOre' => $this->request->getVar('Durata'),
'orIDTipoOre' => $this->request->getVar('IDTipoOre'),
'orIDTipoWork' => $this->request->getVar('IDTipoWork'),
'orDescrizione' => $this->request->getVar('Descrizione'),
];
if ($enable){
$newData['orIDlavoratore'] = $this->request->getVar('IDlavoratore');
}
if ($model->save($newData)) {
session()->setFlashdata('success', 'Successfuly Updated');
UpdateCommessa($newData['orIDcommessa']);
return redirect()->to('/dashboard/orari');
} else {
session()->setFlashdata('danger', 'Errore durante l\'update del record nel DB.');
}
}// analisi validazione
}// Gestione POST
// Rileggo i dati dal DB
$data['orario'] = $orario;
$data['enable'] = $enable;
// Ricavo i dati per il select delle commesse:
$modelCommesse = new Commesse_Model();
$data['select_commesse'] = $modelCommesse->get_select();
// Ricavo i dati per il select dei lavoratori:
$modelLavoratori = new Lavoratori_Model();
$data['select_lavoratori'] = $modelLavoratori->get_select();
// Ricavo i dati per il select deila tipologia di ore:
$modelTipoOre = new TipoOre_Model();
$data['select_tipo_ore'] = $modelTipoOre->get_select();
// Ricavo i dati per il select deila tipologia di lavoro:
$modelTipiWork = new TipiWork_Model();
$data['select_tipi_work'] = $modelTipiWork->get_select();
// Show profile
echo view('pages/orari/orari_form_edit', $data);
} // function edit($id)
//--------------------------------------------------------------------
public function delete($IDorario = null){
helper(['tools']);
$data = [];
$model = new Orari_Model();
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Orari/delete -> Error code 001'); }
return redirect()->to('/Lavoratori/login');
}
// Ricavo livello del lavoratore (solo amministratori o superiori, possono editare tutti i campi)
$enable = CheckLevel(3, false);
// Verifico dato introdotto:
if ($IDorario==null) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Orari/delete -> Error code 002'); }
return redirect()->to('/dashboard');
}
// Ricavo il record dell'orario da editare
$orario = $model->where('orIDorario', $IDorario)
->first();
// Verifico che esista il record dell'orario:
//if (null==$orario) { return redirect()->to('/dashboard'); }
if (!isset($orario)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Orari/delete -> Error code 003'); }
return redirect()->to('/dashboard');
}
// Verifico se posso editare il record:
// - utente amministratore o superiore, cancellare qualunque orario
// - utente normale può cancellare solo i propi orari
$lav = session()->get('lavoratore');
if ((!$enable) && ($lav->IDlavoratore<>$orario->IDlavoratore)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Orari/delete -> Error code 004'); }
return redirect()->to('/dashboard');
}
// Elimino il record:
if ($model->delete($IDorario)) {
session()->setFlashdata('success', 'Recors cancellato correttamente.');
} else {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', 'Errore durante la cancellazione del record.');
}
// Show profile
return redirect()->to('/dashboard/orari');
} // function delete($id)
//--------------------------------------------------------------------
public function export_csv(){
helper(['tools','form']);
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Orari/export_csv -> Error code 001'); }
return redirect()->to('/Lavoratori/login');
}
// Ricavo le ore dell'utente:
// Tab: Orari = ['orIDorario', 'orIDcommessa', 'orIDlavoratore', 'orData', 'orOre', 'orIDTipoOre', 'orDescrizione'];
// Tab: Lavoratori = ['lvIDlavoratore', 'lvNome', 'lvCognome', 'lvMail', 'lvLevel', 'lvRimborsoKm', 'lvNickname', 'lvPassword', 'lvCreatedAt', 'lvUpdatedAt', 'lvDeletedAt'];
// Tab: Commesse = ['coIDcommessa', 'coNome', 'coIDcliente', 'coDescrizione', 'coIDstatoCommessa', 'coModificatoIl', 'coCreatedAt', 'coUpdatedAt', 'coDeletedAt'];
$model = new Orari_Model();
$model->join('Lavoratori', 'Lavoratori.lvIDlavoratore = Orari.orIDlavoratore');
$model->join('Commesse', 'Commesse.coIDcommessa = Orari.orIDcommessa');
$model->join('TipoOre', 'TipoOre.toIDTipoOre = Orari.orIDTipoOre');
// Costruisco la query per selezionare le ore da esportare:
// - applico il filtro sull'intervallo temporale:
$model->where('orData >=', session()->get('filter_dal'))
->where('orData <=', session()->get('filter_al') . " 23:59:59");
// - applico eventuale filtro per lavoratore
if (session()->filter_lavoratore!='-1') { $model->where('orIDlavoratore', session()->get('filter_lavoratore')); }
// - applico eventuale filtro per commessa
if (session()->filter_commessa!='-1') { $model->where('orIDcommessa', session()->get('filter_commessa')); }
// - applico eventuale filtro per tipologia di ora:
if (session()->filter_tipo_ore!='-1') { $model->where('orIDTipoOre', session()->get('filter_tipo_ore')); }
// imposto l'ordinamento richiesto:
CheckSort('orari',true);
$data['sortCol'] = session()->get('sort')['col'];
$data['sortDir'] = session()->get('sort')['dir'];
$model->orderBy($data['sortCol'], $data['sortDir']);
// eseguo la query:
$data['dataset'] = $model->asArray()
->findAll();
// Imposto il nome del file da downloadare:
$filepath = $_SERVER['MRK_FILE_PATH'];
$filename = 'CSiCoDB_Orari_il_' . date('Y-m-d_H-i-s') . '.csv';
// file creation
$file = fopen($filepath . $filename,"w");
// Esport header
fputcsv($file,['IDorario','IDcommessa','Commessa','IDlavoratore','Lavoratore','Il','Durata','IDTipoOre','Tipologia','IDTipoWork','Descrizione']);
foreach ($data['dataset'] as $line){
//fputcsv($file,$line);
// Seleziono le colonne da esportare:
$record = [];
$record['orIDorario'] = $line['orIDorario'];
$record['orIDcommessa'] = $line['orIDcommessa'];
$record['coNome'] = $line['coNome'];
$record['orIDlavoratore'] = $line['orIDlavoratore'];
$record['lvNickname'] = $line['lvNickname'];
$record['orData'] = $line['orData'];
$record['orOre'] = $line['orOre'];
$record['orIDTipoOre'] = $line['orIDTipoOre'];
$record['toDescrizione'] = $line['toDescrizione'];
$record['orIDTipoWork'] = $line['orIDTipoWork'];
$record['orDescrizione'] = $line['orDescrizione'];
fputcsv($file,$record);
}
// Chiudo il file
fclose($file);
// download
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=".$filename);
header("Content-Type: application/csv; ");
readfile($filepath . $filename);
// deleting file
unlink($filepath . $filename);
exit();
} // function export_csv
//--------------------------------------------------------------------
}//class Orari
+56
View File
@@ -0,0 +1,56 @@
<?php namespace App\Controllers;
use App\Libraries\Crud;
class Posizioni extends CRUDController {
// Tab: Posizioni = ['psIDplace', 'psCode', 'psDescrizione'];
protected $crud;
function __construct() {
$params = [
'table' => 'Posizioni',
'dev' => false,
'fields' => $this->field_options(),
'form_title_add' => 'Add Posizione',
'form_title_update' => 'Edit Posizione',
'form_submit' => 'Add',
'table_title' => 'Pagina per la tabella Posizioni',
'form_submit_update' => 'Update',
'base' => '',
'UpdatedAt' => '',
'DeletedAt' => '',
];
$this->crud = new Crud($params, service('request'));
}// __construct
protected function field_options() {
$fields = [];
$fields['psIDplace'] = ['label' => 'ID', 'helper' => 'Identificativo univoco della posizione'];
$fields['psCode'] = ['label' => 'Code', 'helper' => 'Codice della posizione (max 16 caratteri)', 'required' => true, 'unique' => [true, 'psCode']];
$fields['psDescrizione'] = ['label' =>'Descrizione', 'helper' => 'Descrizione della posizione', 'required' => true];
return $fields;
}// field_options
public function index() { return $this->CRUD_view(['psIDplace', 'psCode', 'psDescrizione']); }
//--------------------------------------------------------------------
// Auto CRUD terminato
//--------------------------------------------------------------------
}
+534
View File
@@ -0,0 +1,534 @@
<?php namespace App\Controllers;
use App\Libraries\Crud;
use App\Models\SIMs_Model;
use App\Models\SIMEvents_Model;
use App\Models\Lavoratori_Model;
class SIMEvents extends CRUDController {
// Tab: SIMEvents = ['esmIDsimEvent', 'esmIDsim', 'esmIDlavoratore', 'esmDescrizione', 'esmData', 'esmTipologia'];
protected $crud;
function __construct() {
$params = [
'table' => 'SIMEvents',
'dev' => false,
'fields' => $this->field_options(),
'form_title_add' => 'Add Evento',
'form_title_update' => 'Edit Evento',
'form_submit' => 'Add',
'table_title' => 'Pagina per la tabella SIMEvents',
'form_submit_update' => 'Update',
'base' => '',
'UpdatedAt' => '',
'DeletedAt' => '',
];
$this->crud = new Crud($params, service('request'));
}// __construct
protected function field_options() {
$fields = [];
$fields['esmIDsimEvent'] = ['label' => 'ID', 'helper' => 'Identificativo univoco del record nel database'];
$fields['esmIDsim'] = [
'label' => 'SIM',
'required' => true,
'type' => 'dropdown',
'helper' => 'SIM a cui si riferisce l\'evento',
'relation' => [
'table'=> 'SIMs',
'primary_key' => 'smIDsim',
'display' => ['smIDsim', 'smNumero'],
'order_by' => 'smNumero',
'order' => 'ASC'
]
];
$fields['esmIDlavoratore'] = [
'label' => 'Lavoratore',
'required' => true,
'type' => 'dropdown',
'helper' => 'Lavoratore a cui si riferisce l\'evento',
'relation' => [
'table'=> 'Lavoratori',
'primary_key' => 'lvIDlavoratore',
'display' => ['lvNickname', 'lvNome', 'lvCognome'], //'display' => ['lvNickname'],
'order_by' => 'lvNickname',
'order' => 'ASC'
]
];
$fields['esmDescrizione'] = ['label' => 'Descrizione', 'helper' => 'Descrizione esaustiva dell\'evento', 'required' => true];
$fields['esmData'] = ['label' => 'Timestamp', 'helper' => 'Timestamp dell\'evento', 'required' => true, 'type' => 'date'];
$fields['esmTipologia'] = ['label' => 'Tipo', 'helper' => 'Tipologia di evento', 'required' => true];
return $fields;
}// field_options
public function index() { return $this->CRUD_view(['esmIDsimEvent', 'esmIDsim', 'esmIDlavoratore', 'esmDescrizione', 'esmData', 'esmTipologia']); }
//--------------------------------------------------------------------
// Auto CRUD terminato
//--------------------------------------------------------------------
public function show() {
helper(['tools','form']);
$data['tab'] = 'sims';
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/SIMEvents/show -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Ricavo la macchina selezionata (se vi è una selezione):
$IDsim = session()->get('filter_sim');
if ((null !== $IDsim) && ($IDsim!=-1)) {
$mcc = new SIMs_Model();
$data['sim'] = $mcc->where('smIDsim', $IDsim)->first();
}
// Ricavo i relativi eventi:
$mev = new SIMEvents_Model();
$mev->join('Lavoratori', 'SIMEvents.esmIDlavoratore = Lavoratori.lvIDlavoratore');
$mev->join('SIMs', 'SIMEvents.esmIDsim = SIMs.smIDsim');
// Per ora niente filtro, poi in futuro forse
$mev->where('esmIDsim', $IDsim);
// imposto l'ordinamento richiesto:
CheckSort('evnsim',true);
$data['sortCol'] = session()->get('sort')['col'];
$data['sortDir'] = session()->get('sort')['dir'];
$mev->orderBy($data['sortCol'], $data['sortDir']);
// eseguo la query con paginazione:
$data['dataset'] = $mev->paginate(session()->get('pager_num'));
$data['pager'] = $mev->pager;
return view('/pages/events/SIMEvents', $data);
}//function select
//--------------------------------------------------------------------
public function add() {
helper(['tools','form']);
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/SIMEvents/add -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Ricavo livello del lavoratore (solo amministratori o superiori, possono editare tutti i campi)
$data['enable'] = $enable = CheckLevel(3, false);
// Ricavo la macchina selezionata (se vi è una selezione):
$IDsim = session()->get('filter_sim');
if ((null == $IDsim) || ($IDsim==-1)) {
return redirect()->to('/dashboard/sim');
}
$mcc = new SIMs_Model();
$data['sim'] = $mcc->where('smIDsim', $IDsim)->first();
if ($data['sim']==null) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/SIMEvents/add -> Error code 002'); }
return redirect()->to('/dashboard/sim');
}
// preparo i dati
$data['tab'] = 'sims';
$data['add'] = true;
$data['title'] = 'Dettagli nuova evento della SIM: ' . $data['sim']->ccNumero;
// Gestione POST
if ($this->request->getMethod() == 'post') {
// Regole per validare i campi introdotti nel form:
$rules = [
'Data' => 'trim|required',
'Tipologia' => 'trim|required',
'Descrizione' => 'trim|required|min_length[8]',
];
if ($enable){
$newData['ecaIDlavoratore'] = $this->request->getVar('IDlavoratore');
}
// analisi della validazione
if (! $this->validate($rules)) {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', $data['validation']->listErrors());
} else {
// validazione passata
// Preparo i dati per l'inserimento
// Tab: SIMs = ['smIDsim', 'smNumero', 'smPIN', 'smPUK', 'smDescrizione', 'smCredito', 'smStato', 'smCreatedAt', 'smUpdatedAt', 'smDeletedAt'];
// Tab: SIMEvents = ['esmIDsimEvent', 'esmIDsim', 'esmIDlavoratore', 'esmDescrizione', 'esmData', 'esmTipologia'];
$newData = [
'esmIDsim' => $data['sim']->smIDsim,
'esmDescrizione' => $this->request->getVar('Descrizione'),
'esmData' => $this->request->getVar('Data'),
'esmTipologia' => $this->request->getVar('Tipologia'),
];
if ($enable){
$newData['esmIDlavoratore'] = $this->request->getVar('IDlavoratore');
} else {
$newData['esmIDlavoratore'] = session()->get('lavoratore')->lvIDlavoratore;
}
$model = new SIMEvents_Model();
if ($model->save($newData)) {
// evento inserito con successo, aggiorno lo stato della SIM
if ($this->updateSimStato($data['sim']->smIDsim)) {
// update dello stato nella SIM riuscito
session()->setFlashdata('success', 'Evento inserito con successo');
} else {
// update dello stato nella SIM fallito
session()->setFlashdata('danger', 'Evento inserito ma stato della SIM non aggiornato correttamente');
}
// apro la pagina desiderata in base al pulsante utilizzato:
if(isset($_POST['crea_continua'])) {
// è stato premuto il secondo pulsante, quindi inserisco un secondo valore:
//return redirect()->to('/dashboard/orari');
} else {
return redirect()->to('/SIMEvents/show');
}
} else {
// errore durante l'inserimento dell'evento
session()->setFlashdata('danger', 'Errore durante l\'inserimento del record nel DB.');
}
}// analisi validazione
}// Gestione POST
// Ricavo i dati per il select dei lavoratori:
$modelLavoratori = new Lavoratori_Model();
$data['select_lavoratori'] = $modelLavoratori->get_select();
// Show form
echo view('pages/form/SIMEvents_form_add_edit', $data);
}//function add
//--------------------------------------------------------------------
public function edit($IDevent = null) {
helper(['tools','form']);
// Verifico dato introdotto:
if ($IDevent==null) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/SIMEvents/edit -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/SIMEvents/edit -> Error code 002'); }
return redirect()->to('/dashboard');
}
// Ricavo livello del lavoratore (solo amministratori o superiori, possono editare tutti i campi)
$data['enable'] = $enable = CheckLevel(3, false);
// Ricavo l'evento selezionato, completo di tutti i particolari:
// Tab: SIMs = ['smIDsim', 'smNumero', 'smPIN', 'smPUK', 'smDescrizione', 'smCredito', 'smStato', 'smCreatedAt', 'smUpdatedAt', 'smDeletedAt'];
// Tab: SIMEvents = ['esmIDsimEvent', 'esmIDsim', 'esmIDlavoratore', 'esmDescrizione', 'esmData', 'esmTipologia'];
// Tab: Lavoratori = ['lvIDlavoratore', 'lvNome', 'lvCognome', 'lvMail', 'lvLevel', 'lvRimborsoKm', 'lvNickname', 'lvPassword', 'lvCreatedAt', 'lvUpdatedAt', 'smStato', 'lvDeletedAt'];
$model = new SIMEvents_Model();
$model->join('SIMs', 'SIMEvents.esmIDsim = SIMs.smIDsim');
$model->join('Lavoratori', 'SIMEvents.esmIDlavoratore = Lavoratori.lvIDlavoratore');
$data['evnt'] = $model->where('esmIDsimEvent', $IDevent)
->first();
// Verifico che esista il record:
if (null==$data['evnt']) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/SIMEvents/edit -> Error code 003'); }
return redirect()->to('/dashboard');
}
// ricavo la macchina a cui l'evento si riferisce
$mcc = new SIMs_Model();
$data['sim'] = $mcc->where('smIDsim', $data['evnt']->esmIDsim)->first();
// Verifico che esista il record:
if ($data['sim']==null) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/SIMEvents/edit -> Error code 004'); }
return redirect()->to('/dashboard/cars');
}
// preparo i dati
$data['tab'] = 'sims';
$data['add'] = false;
$data['title'] = 'Dettagli evento: ' . $data['evnt']->smNumero;
// Gestione POST
if ($this->request->getMethod() == 'post') {
// Regole per validare i campi introdotti nel form:
$rules = [
'Data' => 'trim|required',
'Tipologia' => 'trim|required',
'Descrizione' => 'trim|required|min_length[8]',
];
if ($enable){
$newData['ecaIDlavoratore'] = $this->request->getVar('IDlavoratore');
}
// analisi della validazione
if (! $this->validate($rules)) {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', $data['validation']->listErrors());
}else{
// validazione passata
// Preparo i dati per l'inserimento
$newData = [
'esmIDsimEvent' => $IDevent,
'esmDescrizione' => $this->request->getVar('Descrizione'),
'esmData' => $this->request->getVar('Data'),
'esmTipologia' => $this->request->getVar('Tipologia'),
];
if ($enable){
$newData['esmIDlavoratore'] = $this->request->getVar('IDlavoratore');
}
if ($model->save($newData)) {
// evento inserito con successo, aggiorno lo stato della carta
if ($this->updateSimStato($data['sim']->smIDsim)) {
// update dello stato nella sim riuscito
session()->setFlashdata('success', 'Evento aggiornato con successo');
} else {
// update dello stato nella sim fallito
session()->setFlashdata('danger', 'Evento inserito ma stato della SIM non aggiornato correttamente');
}
// apro la pagina desiderata in base al pulsante utilizzato:
if(isset($_POST['crea_continua'])) {
// è stato premuto il secondo pulsante, quindi inserisco un secondo valore:
//return redirect()->to('/dashboard/orari');
} else {
return redirect()->to('/SIMEvents/show');
}
} else {
// errore durante l'inserimento dell'evento
session()->setFlashdata('danger', 'Errore durante l\'inserimento del record nel DB.');
}
}// analisi validazione
}// Gestione POST
// Ricavo i dati per il select dei lavoratori:
$modelLavoratori = new Lavoratori_Model();
$data['select_lavoratori'] = $modelLavoratori->get_select();
// Show form
echo view('pages/form/SIMEvents_form_add_edit', $data);
}//function edit
//--------------------------------------------------------------------
public function delete($IDevent = null){
helper(['tools']);
$data = [];
// Ricavo l'evento selezionato, completo di tutti i particolari:
// Tab: SIMs = ['smIDsim', 'smNumero', 'smPIN', 'smPUK', 'smDescrizione', 'smCredito', 'smStato', 'smCreatedAt', 'smUpdatedAt', 'smDeletedAt'];
// Tab: SIMEvents = ['esmIDsimEvent', 'esmIDsim', 'esmIDlavoratore', 'esmDescrizione', 'esmData', 'esmTipologia'];
// Tab: Lavoratori = ['lvIDlavoratore', 'lvNome', 'lvCognome', 'lvMail', 'lvLevel', 'lvRimborsoKm', 'lvNickname', 'lvPassword', 'lvCreatedAt', 'lvUpdatedAt', 'lvDeletedAt'];
$model = new SIMEvents_Model();
$model->join('SIMs', 'SIMEvents.esmIDsim = SIMs.smIDsim');
$model->join('Lavoratori', 'SIMEvents.esmIDlavoratore = Lavoratori.lvIDlavoratore');
$evnt = $model->where('esmIDsimEvent', $IDevent)
->first();
// Verifico che esista il record:
if (null==$evnt) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/SIMEvents/delete -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Verifico sessione e livello:
if (!(CheckLevel(3) || session()->get('lavoratore')->lvIDlavoratore==$evnt->esmIDlavoratore)) {
session()->setFlashdata('warning', 'Non si hanno i permessi per cancellare un evento inserito da altri lavoratori.');
return redirect()->to('/SIMEvents/show');
}
// Elimino il record:
if ($model->delete($IDevent)) {
// Evento cancellato, aggiorno stato della macchina relativa
if ($this->updateSimStato($evnt->esmIDsim)) {
// update dello stato nella macchina riuscito
session()->setFlashdata('success', 'Recors cancellato correttamente.');
} else {
// update dello stato nella macchina fallito
session()->setFlashdata('danger', 'Errore durante la cancellazione del record.');
}
} else {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', 'Errore durante la cancellazione del record.');
}
// Show profile
return redirect()->to('/SIMEvents/show');
} // function delete($id)
//--------------------------------------------------------------------
public function export_csv(){
helper(['tools','form']);
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/SIMs/export_csv -> Error code 001'); }
return redirect()->to('/SIMEvents/show');
}
// Ricavo gli eventi della sim:
// Tab: SIMs = ['smIDsim', 'smNumero', 'smPIN', 'smPUK', 'smDescrizione', 'smCredito', 'smStato', 'smCreatedAt', 'smUpdatedAt', 'smDeletedAt'];
// Tab: SIMEvents = ['esmIDsimEvent', 'esmIDsim', 'esmIDlavoratore', 'esmDescrizione', 'esmData', 'esmTipologia'];
// Tab: Lavoratori = ['lvIDlavoratore', 'lvNome', 'lvCognome', 'lvMail', 'lvLevel', 'lvRimborsoKm', 'lvNickname', 'lvPassword', 'lvCreatedAt', 'lvUpdatedAt', 'lvDeletedAt'];
$mev = new SIMEvents_Model();
$mev->join('Lavoratori', 'SIMEvents.esmIDlavoratore = Lavoratori.lvIDlavoratore');
$mev->join('SIMs', 'SIMEvents.esmIDsim = SIMs.smIDsim');
// Per ora niente filtro, poi in futuro forse
$mev->where('esmIDsim', session()->get('filter_sim'));
// imposto l'ordinamento richiesto:
CheckSort('evnsim',true);
$data['sortCol'] = session()->get('sort')['col'];
$data['sortDir'] = session()->get('sort')['dir'];
$mev->orderBy($data['sortCol'], $data['sortDir']);
// eseguo la query:
$data['dataset'] = $mev->asArray()
->findAll();
// Imposto il nome del file da downloadare:
$filepath = $_SERVER['MRK_FILE_PATH'];
$filename = 'CSiCoDB_Eventi_CSiCoSIMs_il_' . date('Y-m-d_H-i-s') . '.csv';
// file creation
$file = fopen($filepath . $filename,"w");
// Esport header
fputcsv($file,['SIM aziendale selezionata:']);
fputcsv($file,['ID sim', 'Numero', 'PIN', 'PUK', 'Descrizione', 'Credito Residuo', 'Stato', 'Created At', 'Updated At']);
$head = [];
$head['smIDsim'] = $data['dataset'][0]['smIDsim'];
$head['smNumero'] = $data['dataset'][0]['smNumero'];
$head['smPIN'] = $data['dataset'][0]['smPIN'];
$head['smPUK'] = $data['dataset'][0]['smPUK'];
$head['smDescrizione'] = $data['dataset'][0]['smDescrizione'];
$head['smCredito'] = $data['dataset'][0]['smCredito'];
$head['smStato'] = $data['dataset'][0]['smStato'];
$head['smCreatedAt'] = $data['dataset'][0]['smCreatedAt'];
$head['smUpdatedAt'] = $data['dataset'][0]['smUpdatedAt'];
fputcsv($file,$head);
fputcsv($file,[' ']);
fputcsv($file,[' ']);
fputcsv($file,[' ']);
fputcsv($file,['Eventi della SIM aziendale:']);
fputcsv($file,['ID evento', 'ID Lavoratore', 'Nickname', 'Descrizione Evento', 'Data', 'Tipologia']);
foreach ($data['dataset'] as $line){
//fputcsv($file,$line);
// Seleziono le colonne da esportare:
$record = [];
$record['esmIDsimEvent'] = $line['esmIDsimEvent'];
$record['esmIDlavoratore'] = $line['esmIDlavoratore'];
$record['lvNickname'] = $line['lvNickname'];
$record['esmDescrizione'] = $line['esmDescrizione'];
$record['esmData'] = $line['esmData'];
$record['esmTipologia'] = $line['esmTipologia'];
fputcsv($file,$record);
}
// Chiudo il file
fclose($file);
// download
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=".$filename);
header("Content-Type: application/csv; ");
readfile($filepath . $filename);
// deleting file
unlink($filepath . $filename);
exit();
} // function export_csv
//--------------------------------------------------------------------
/**
* Eseguo l'aggiornamento dello stato della macchina indicata, in base alla cronologia degli eventi
*/
private function updateSimStato($IDsim){
try {
// verifico la tipologia dell'ultimo evento inserito:
// Tab: SIMEvents = ['esmIDsimEvent', 'esmIDsim', 'esmIDlavoratore', 'esmDescrizione', 'esmStato', 'esmData', 'ecaKm', 'esmTipologia'];
// Tab: SIMs = ['smIDsim', 'smNumero', 'smDescrizione', 'caDataAssicurazione', 'caTipoGomme', 'caCreatedAt', 'caUpdatedAt', 'smStato', 'caDeletedAt'];
$mev = new SIMEvents_Model();
$evnt = $mev->where('esmIDsim', $IDsim)
->orderBy('esmData', 'DESC')->orderBy('esmIDsimEvent', 'DESC')->first();
// Preparo i dati per aggiornare la carta:
$updCar['smIDsim'] = $IDsim;
// determino lo stato attuale della carta dalla tipologia dell'evento:
switch ($evnt->esmTipologia) {
case 'Dismessa':
$updCar['smStato'] = 'Dismessa';
break;
case 'Presa':
$updCar['smStato'] = 'Occupata';
break;
case 'Restituita':
default:
$updCar['smStato'] = 'Disponibile';
break;
}
// Aggiorno la carta:
$model_car = new SIMs_Model();
if ($model_car->save($updCar)) {
// carta aggiornata con successo
return true;
} else {
// aggiornamento fallito
return false;
}
} catch (Throwable $th) {
//throw $th;
return false;
}
}
//--------------------------------------------------------------------
}
+355
View File
@@ -0,0 +1,355 @@
<?php namespace App\Controllers;
use App\Libraries\Crud;
use App\Models\SIMs_Model;
use App\Models\SIMEvents_Model;
class Sims extends CRUDController {
// Tab: SIMs = ['smIDsim', 'smNumero', 'smPIN', 'smPUK', 'smDescrizione', 'smCredito', 'smStato', 'smCreatedAt', 'smUpdatedAt', 'smDeletedAt'];
protected $crud;
function __construct() {
$params = [
'table' => 'SIMs',
'dev' => false,
'fields' => $this->field_options(),
'form_title_add' => 'Add SIM',
'form_title_update' => 'Edit SIM',
'form_submit' => 'Add',
'table_title' => 'Pagina per la tabella SIMs',
'form_submit_update' => 'Update',
'base' => '',
'UpdatedAt' => 'smUpdatedAt',
'DeletedAt' => 'smDeletedAt',
];
$this->crud = new Crud($params, service('request'));
}// __construct
protected function field_options() {
$fields = [];
$fields['smIDsim'] = ['label' => 'ID', 'helper' => 'Identificativo univoco del record nel database'];
$fields['smNumero'] = ['label' => 'Numero', 'helper' => 'Numero telefonico (max 16 caratteri)', 'required' => true];
$fields['smPIN'] = ['label' => 'PIN', 'helper' => 'PIN della SIM (max 16 caratteri)', 'required' => true];
$fields['smPUK'] = ['label' => 'PUK', 'helper' => 'PUK della SIM (max 16 caratteri)', 'required' => true];
$fields['smDescrizione'] = ['label' => 'Descrizione', 'helper' => 'Descrizione esaustiva della SIM', 'required' => true];
$fields['smCredito'] = ['label' => 'Credito', 'helper' => 'Credito stimato sulla SIM', 'required' => true];
$fields['smStato'] = ['label' => 'Stato', 'helper' => 'Stato di disponmibilità della SIM', 'required' => true];
$fields['smCreatedAt'] = ['label' => 'Created At', 'helper' => 'Data di creazione del record relativo nel database', 'only_edit'=> true];
$fields['smUpdatedAt'] = ['label' => 'Updated At', 'helper' => 'Timestamp dell\'ultimo aggiornamento del record nel database', 'type' => 'unset'];
$fields['smDeletedAt'] = ['label' => 'Deleted At', 'helper' => 'Data di cancellazione del record relativo nel database', 'type' => 'unset'];
return $fields;
}// field_options
public function index() { return $this->CRUD_view(['smIDsim', 'smNumero', 'smPIN', 'smPUK', 'smDescrizione', 'smCredito', 'smStato', 'smCreatedAt', 'smUpdatedAt', 'smDeletedAt']); }
//--------------------------------------------------------------------
// Auto CRUD terminato
//--------------------------------------------------------------------
public function select($IDsim = null) {
helper(['tools','form']);
$data['tab'] = 'sims';
$model = new SIMs_Model();
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/SIMs/select -> Error code 001'); }
return redirect()->to('/dashboard');
}
// memorizzo la selezione
session()->set('filter_sim', $IDsim);
// visualizzo gli eventi della carta selezionata:
return redirect()->to('/SIMEvents/show');
}//function select
//--------------------------------------------------------------------
public function add() {
helper(['tools','form']);
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/SIMs/add -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Ricavo livello del lavoratore (solo amministratori o superiori, possono editare tutti i campi)
$data['enable'] = $enable = CheckLevel(3, false);
// Solo amministratori possono inserire una nuova sim:
if (!$enable){
session()->setFlashdata('warning', 'Non si hanno i permessi per inserire una nuova SIM aziendale.');
return redirect()->to('/dashboard/sims');
}
// preparo i dati
$data['tab'] = 'sims';
$data['add'] = true;
$data['title'] = 'Dettagli nuova SIM';
// Gestione POST
if ($this->request->getMethod() == 'post') {
// Regole per validare i campi introdotti nel form:
//
$rules = [
'Numero' => 'trim|required|min_length[8]|max_length[20]',
'PIN' => 'trim|required|min_length[4]|max_length[16]',
'PUK' => 'trim|required|min_length[4]|max_length[16]',
'Credito' => 'trim|required',
'Descrizione' => 'trim|required|min_length[8]',
//'Stato' => 'trim|required',
];
// analisi della validazione
if (! $this->validate($rules)) {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', $data['validation']->listErrors());
}else{
// validazione passata
// Preparo i dati per l'inserimento
// SIMs = ['smIDsim', 'smNumero', 'smPIN', 'smPUK', 'smDescrizione', 'smCredito', 'smCreatedAt', 'smUpdatedAt', 'smStato', 'smDeletedAt'];
$newData = [
'smNumero' => $this->request->getVar('Numero'),
'smPIN' => $this->request->getVar('PIN'),
'smPUK' => $this->request->getVar('PUK'),
'smCredito' => $this->request->getVar('Credito'),
'smDescrizione' => $this->request->getVar('Descrizione'),
'smStato' => 'Disponibile',
];
$model = new Sims_Model();
if ($model->save($newData)) {
session()->setFlashdata('success', 'Record inserito con successo sul DB');
if(isset($_POST['crea_continua'])) {
// è stato premuto il secondo pulsante, quindi inserisco un secondo valore:
//return redirect()->to('/dashboard/orari');
} else {
return redirect()->to('/dashboard/sims');
}
} else {
session()->setFlashdata('danger', 'Errore durante l\'inserimento del record nel DB.');
}
}// analisi validazione
}// Gestione POST
// Show form
echo view('pages/form/sims_form_add_edit', $data);
}//function add
//--------------------------------------------------------------------
public function edit($IDsim = null) {
helper(['tools','form']);
// Verifico dato introdotto:
if ($IDsim==null) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/SIMs/edit -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/SIMs/add -> Error code 002'); }
return redirect()->to('/dashboard');
}
// Ricavo livello del lavoratore (solo amministratori o superiori, possono editare tutti i campi)
$data['enable'] = $enable = CheckLevel(3, false);
// Solo amministratori possono editare una carta:
if (!$enable){
session()->setFlashdata('warning', 'Non si hanno i permessi per editare i dati di una carta di credito aziendale.');
return redirect()->to('/dashboard/sims');
}
// preparo i dati
$data['tab'] = 'sims';
$data['add'] = false;
$data['title'] = 'Dettagli della SIM telefonica';
// Ricavo il profilo dell'orario da editare
// SIMs = ['smIDsim', 'smNumero', 'smPIN', 'smPUK', 'smDescrizione', 'smCredito', 'smCreatedAt', 'smUpdatedAt', 'smStato', 'smDeletedAt'];
$model = new Sims_Model();
$data['sim'] = $model->where('smIDsim', $IDsim)
->first();
// Verifico che esista il record dell'orario:
if (null==$data['sim']) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/SIMs/edit -> Error code 003'); }
return redirect()->to('/dashboard');
}
// Gestione POST
if ($this->request->getMethod() == 'post') {
// Regole per validare i campi introdotti nel form:
$rules = [
'Numero' => 'trim|required|min_length[8]|max_length[20]',
'PIN' => 'trim|required|min_length[4]|max_length[16]',
'PUK' => 'trim|required|min_length[4]|max_length[16]',
'Credito' => 'trim|required',
'Descrizione' => 'trim|required|min_length[8]',
'Stato' => 'trim|required',
];
// analisi della validazione
if (! $this->validate($rules)) {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', $data['validation']->listErrors());
}else{
// validazione passata
// Preparo i dati per l'aggiornamento
// Tab: sims = ['smIDsim', 'ccNumero', 'ccDescrizione', 'ccScadeIl', 'ccPIN', 'ccCreatedAt', 'ccUpdatedAt', 'ccStato', 'ccDeletedAt'];
$newData = [
'smIDsim' => $this->request->getVar('IDsim'),
'smNumero' => $this->request->getVar('Numero'),
'smPIN' => $this->request->getVar('PIN'),
'smPUK' => $this->request->getVar('PUK'),
'smCredito' => $this->request->getVar('Credito'),
'smDescrizione' => $this->request->getVar('Descrizione'),
'smStato' => $this->request->getVar('Stato'),
];
$model = new Sims_Model();
if ($model->save($newData)) {
session()->setFlashdata('success', 'Successfuly Updated');
return redirect()->to('/dashboard/sims');
} else {
session()->setFlashdata('danger', 'Errore durante l\'update del record nel DB.');
}
}// analisi validazione
}// Gestione POST
// Show form
echo view('pages/form/sims_form_add_edit', $data);
}//function edit
//--------------------------------------------------------------------
public function delete($IDsim = null){
helper(['tools']);
$data = [];
$model = new Sims_Model();
// Verifico sessione e livello:
if (!CheckLevel(3)) {
session()->setFlashdata('warning', 'Non si hanno i permessi per cancellare una SIM aziendale.');
return redirect()->to('/dashboard/sims');
}
// Verifico dato introdotto:
if ($IDsim==null) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/SIMs/delete -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Elimino il record:
if ($model->delete($IDsim)) {
session()->setFlashdata('success', 'Recors cancellato correttamente.');
} else {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', 'Errore durante la cancellazione del record.');
}
// Show profile
return redirect()->to('/dashboard/sims');
} // function delete($id)
//--------------------------------------------------------------------
public function export_csv(){
helper(['tools','form']);
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/SIMs/export_csv -> Error code 001'); }
return redirect()->to('/Lavoratori/login');
}
// Ricavo le ore dell'utente:
// SIMs = ['smIDsim', 'smNumero', 'smPIN', 'smPUK', 'smDescrizione', 'smCredito', 'smCreatedAt', 'smUpdatedAt', 'smStato', 'smDeletedAt'];
$model = new Sims_Model();
// Costruisco la query per selezionare le ore da esportare:
// - applico eventuale filtro per lo stato:
// imposto l'ordinamento richiesto:
CheckSort('sims',true);
$data['sortCol'] = session()->get('sort')['col'];
$data['sortDir'] = session()->get('sort')['dir'];
$model->orderBy($data['sortCol'], $data['sortDir']);
// eseguo la query:
$data['dataset'] = $model->asArray()
->findAll();
// Imposto il nome del file da downloadare:
$filepath = $_SERVER['MRK_FILE_PATH'];
$filename = 'CSiCoDB_SIMs_il_' . date('Y-m-d_H-i-s') . '.csv';
// file creation
$file = fopen($filepath . $filename,"w");
// Esport header
fputcsv($file,['ID SIM', 'Numero', 'PIN', 'PUK', 'Descrizione', 'Credito', 'CreatedAt', 'UpdatedAt', 'Stato']);
foreach ($data['dataset'] as $line){
fputcsv($file,$line);
}
// Chiudo il file
fclose($file);
// download
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=".$filename);
header("Content-Type: application/csv; ");
readfile($filepath . $filename);
// deleting file
unlink($filepath . $filename);
exit();
} // function export_csv
//--------------------------------------------------------------------
}//class Sims
+428
View File
@@ -0,0 +1,428 @@
<?php namespace App\Controllers;
use App\Libraries\Crud;
use App\Models\Lavoratori_Model;
use App\Models\Commesse_Model;
use App\Models\TipoOre_Model;
use App\Models\Orari_Model;
use App\Models\Spese_Model;
class Spese extends CRUDController {
// Tab: Spese = ['spIDspesa', 'spIDcommessa', 'spIDlavoratore', 'spImporto', 'spDaRimborsare', 'spDescrizione', 'spData'];
protected $crud;
function __construct() {
$params = [
'table' => 'Spese',
'dev' => false,
'fields' => $this->field_options(),
'form_title_add' => 'Add Spesa',
'form_title_update' => 'Edit Spesa',
'form_submit' => 'Add',
'table_title' => 'Pagina per la tabella Spese',
'form_submit_update' => 'Update',
'base' => '',
'UpdatedAt' => '',
'DeletedAt' => '',
];
$this->crud = new Crud($params, service('request'));
}// __construct
protected function field_options() {
$fields = [];
$fields['spIDspesa'] = ['label' => 'ID', 'helper' => 'Identificativo univoco del record nel database'];
$fields['spIDcommessa'] = [
'label' => 'Commessa',
'required' => true,
'type' => 'dropdown',
'helper' => 'Commessa a cui si riferisce la spesa',
'relation' => [
'table'=> 'Commesse',
'primary_key' => 'coIDcommessa',
'display' => ['coNome'],
'order_by' => 'coUpdatedAt',
'order' => 'DESC'
]
];
$fields['spIDlavoratore'] = [
'label' => 'Lavoratore',
'required' => true,
'type' => 'dropdown',
'helper' => 'Lavoratore a cui si riferisce la spesa',
'relation' => [
'table'=> 'Lavoratori',
'primary_key' => 'lvIDlavoratore',
'display' => ['lvNickname', 'lvNome', 'lvCognome'], //'display' => ['lvNickname'],
'order_by' => 'lvNickname',
'order' => 'ASC'
]
];
$fields['spImporto'] = ['label' => 'Importo', 'helper' => 'Importo della spesa. Se non in € specificare nella descrizione il cambio attuale relativo', 'required' => true];
$fields['spDaRimborsare'] = ['label' => 'Rimborsare', 'helper' => 'Indiva se la spesa è da rimborsare al lavoratore', 'required' => true];
$fields['spDescrizione'] = ['label' => 'Descrizione', 'helper' => 'Descrizione esaustiva della spesa effettuata.','required' => true];
$fields['spData'] = ['label' => 'Data', 'helper' => 'Data in cui si è avvenuta la spesa','required' => true];
return $fields;
}// field_options
public function index() { return $this->CRUD_view(['spIDspesa', 'spIDcommessa', 'spIDlavoratore', 'spImporto', 'spDaRimborsare', 'spDescrizione', 'spData']); }
//--------------------------------------------------------------------
// Auto CRUD terminato
//--------------------------------------------------------------------
public function add(){
helper(['form','tools']);
$data['Data'] = date('Y-m-d');
$model = new Spese_Model();
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Spese/add -> Error code 001'); }
return redirect()->to('/Lavoratori/login');
}
// Ricavo livello del lavoratore (solo amministratori o superiori, possono editare tutti i campi)
$enable = CheckLevel(3, false);
// Gestione POST
if ($this->request->getMethod() == 'post') {
// Regole per validare i campi introdotti nel form:
// Tab: Spese = ['spIDspesa', 'spIDcommessa', 'spIDlavoratore', 'spImporto', 'spDaRimborsare', 'spDescrizione', 'spData'];
$rules = [
'IDcommessa' => 'trim|required',
'Data' => 'trim|required',
'Importo' => 'trim|required',
'DaRimborsare' => 'trim|required',
'Descrizione' => 'trim|required|min_length[8]',
];
if ($enable){
//$rules['Level'] = 'trim|required|min_length[8]|max_length[255]';
$rules['IDlavoratore'] = 'trim|required';
}
// analisi della validazione
if (! $this->validate($rules)) {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', $data['validation']->listErrors());
}else{
// validazione passata
// Preparo i dati per l'inserimento
$newData = [
'spIDcommessa' => $this->request->getVar('IDcommessa'),
'spData' => $this->request->getVar('Data'),
'spImporto' => $this->request->getVar('Importo'),
'spDaRimborsare' => $this->request->getVar('DaRimborsare'),
'spDescrizione' => $this->request->getVar('Descrizione'),
];
if ($enable){
$newData['spIDlavoratore'] = $this->request->getVar('IDlavoratore');
} else {
$newData['spIDlavoratore'] = session()->get('lavoratore')->lvIDlavoratore;
}
if ($model->save($newData)) {
session()->setFlashdata('success', 'Record inserito con successo sul DB');
UpdateCommessa($newData['spIDcommessa']);
if(isset($_POST['crea_continua'])) {
// è stato premuto il secondo pulsante, quindi inserisco un secondo valore:
//return redirect()->to('/dashboard/spese');
} else {
return redirect()->to('/dashboard/spese');
}
} else {
session()->setFlashdata('danger', 'Errore durante l\'inserimento del record nel DB.');
}
}// analisi validazione
}// Gestione POST
// Rileggo i dati dal DB
$data['enable'] = $enable;
// Ricavo i dati per il select delle commesse:
$modelCommesse = new Commesse_Model();
$data['select_commesse'] = $modelCommesse->get_select();
// Ricavo i dati per il select dei lavoratori:
$modelLavoratori = new Lavoratori_Model();
$data['select_lavoratori'] = $modelLavoratori->get_select();
// Show profile
echo view('pages/spese/spese_form_add', $data);
} // function add($id)
//--------------------------------------------------------------------
public function edit($IDspesa = null){
helper(['form','tools']);
$data = [];
$model = new Spese_Model();
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Spese/edit -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Ricavo livello del lavoratore (solo amministratori o superiori, possono editare tutti i campi)
$enable = CheckLevel(3, false);
// Verifico dato introdotto:
if ($IDspesa==null) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Spese/edit -> Error code 002'); }
return redirect()->to('/dashboard');
}
// Ricavo il profilo della spesa da editare
$spesa = $model->where('spIDspesa', $IDspesa)
->first();
// Verifico che esista il record della spesa:
if (null==$spesa) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Spese/edit -> Error code 003'); }
return redirect()->to('/dashboard');
}
// Verifico se posso editare il campo:
// - utente amministratore o superiore, può editare tutti i campi
// - utente normale può editare solo i propi spese
$lav = session()->get('lavoratore');
if ((!$enable) && ($lav->IDlavoratore<>$spesa->IDlavoratore)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Spese/edit -> Error code 004'); }
return redirect()->to('/dashboard');
}
// Gestione POST
if ($this->request->getMethod() == 'post') {
// Regole per validare i campi introdotti nel form:
//
$rules = [
'IDspesa' => 'trim|required',
'IDcommessa' => 'trim|required',
'Data' => 'trim|required',
'Importo' => 'trim|required',
'DaRimborsare' => 'trim|required',
'Descrizione' => 'trim|required',
];
if ($enable){
//$rules['Level'] = 'trim|required|min_length[8]|max_length[255]';
$rules['IDlavoratore'] = 'trim|required';
}
// analisi della validazione
if (! $this->validate($rules)) {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', $data['validation']->listErrors());
}else{
// validazione passata
// Preparo i dati per l'aggiornamento
$newData = [
'spIDspesa' => $spesa->spIDspesa,
'spIDcommessa' => $this->request->getVar('IDcommessa'),
'spData' => $this->request->getVar('Data'),
'spImporto' => $this->request->getVar('Importo'),
'spDaRimborsare' => $this->request->getVar('DaRimborsare'),
'spDescrizione' => $this->request->getVar('Descrizione'),
];
if ($enable){
$newData['spIDlavoratore'] = $this->request->getVar('IDlavoratore');
} else {
$newData['spIDlavoratore'] = session()->get('lavoratore')->lvIDlavoratore;
}
if ($model->save($newData)) {
session()->setFlashdata('success', 'successfuly Updated');
UpdateCommessa($newData['spIDcommessa']);
return redirect()->to('/dashboard/spese');
} else {
session()->setFlashdata('danger', 'Errore durante l\'update del record nel DB.');
}
}// analisi validazione
}// Gestione POST
// Rileggo i dati dal DB
$data['spesa'] = $spesa;
$data['enable'] = $enable;
// Ricavo i dati per il select delle commesse:
$modelCommesse = new Commesse_Model();
$data['select_commesse'] = $modelCommesse->get_select();
// Ricavo i dati per il select dei lavoratori:
$modelLavoratori = new Lavoratori_Model();
$data['select_lavoratori'] = $modelLavoratori->get_select();
// Show profile
echo view('pages/spese/spese_form_edit', $data);
} // function edit($id)
//--------------------------------------------------------------------
public function delete($IDSpesa = null){
helper(['tools']);
$data = [];
$model = new Spese_Model();
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Spese/delete -> Error code 001'); }
return redirect()->to('/dashboard');
}
// Ricavo livello del lavoratore (solo amministratori o superiori, possono editare tutti i campi)
$enable = CheckLevel(3, false);
// Verifico dato introdotto:
if ($IDSpesa==null) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Spese/delete -> Error code 002'); }
return redirect()->to('/dashboard');
}
// Ricavo il record della spesa da editare
$Spesa = $model->where('spIDSpesa', $IDSpesa)
->first();
// Verifico che esista il record della spesa:
//if (null==$Spesa) { return redirect()->to('/dashboard'); }
if (!isset($Spesa)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Spese/delete -> Error code 003'); }
return redirect()->to('/dashboard');
}
// Verifico se posso editare il record:
// - utente amministratore o superiore, cancellare qualunque Spesa
// - utente normale può cancellare solo i propi spese
$lav = session()->get('lavoratore');
if ((!$enable) && ($lav->IDlavoratore<>$Spesa->IDlavoratore)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Spese/delete -> Error code 004'); }
return redirect()->to('/dashboard');
}
// Elimino il record:
if ($model->delete($IDSpesa)) {
session()->setFlashdata('success', 'Recors cancellato correttamente.');
} else {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', 'Errore durante la cancellazione del record.');
}
// Show profile
return redirect()->to('/dashboard/spese');
} // function delete($id)
//--------------------------------------------------------------------
public function export_csv(){
helper(['tools']);
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Spese/export_csv -> Error code 001'); }
return redirect()->to('/Lavoratori/login');
}
// Ricavo le ore dell'utente:
// Tab: Spese = ['spIDspesa', 'spIDcommessa', 'spIDlavoratore', 'spImporto', 'spDaRimborsare', 'spDescrizione', 'spData'];
// Tab: Lavoratori = ['lvIDlavoratore', 'lvNome', 'lvCognome', 'lvMail', 'lvLevel', 'lvRimborsoKm', 'lvNickname', 'lvPassword', 'lvCreatedAt', 'lvUpdatedAt', 'lvDeletedAt'];
// Tab: Commesse = ['coIDcommessa', 'coNome', 'coIDcliente', 'coDescrizione', 'coIDstatoCommessa', 'coModificatoIl', 'coCreatedAt', 'coUpdatedAt', 'coDeletedAt'];
$model = new Spese_Model();
$model->join('Lavoratori', 'Lavoratori.lvIDlavoratore = Spese.spIDlavoratore');
$model->join('Commesse', 'Commesse.coIDcommessa = Spese.spIDcommessa');
// Costruisco la query per selezionare le ore, in base al filtro attivo:
// - applico il filtro sull'intervallo temporale:
$model->where('spData >', session()->get('filter_dal'))
->where('spData <', session()->get('filter_al') . " 23:59:59");
// - applico eventuale filtro per lavoratore
if (session()->filter_lavoratore!='-1') { $model->where('spIDlavoratore', session()->get('filter_lavoratore')); }
// - applico eventuale filtro per commessa
if (session()->filter_commessa!='-1') { $model->where('spIDcommessa', session()->get('filter_commessa')); }
// - applico eventuale filtro per tipologia di ora:
if (session()->filter_rimborso!='-1') { $model->where('spDaRimborsare', session()->get('filter_rimborso')); }
// imposto l'ordinamento richiesto:
CheckSort('spese',true);
$data['sortCol'] = session()->get('sort')['col'];
$data['sortDir'] = session()->get('sort')['dir'];
$model->orderBy($data['sortCol'], $data['sortDir']);
// eseguo la query:
$data['dataset'] = $model->asArray()
->findAll();
// Imposto il nome del file da downloadare:
$filepath = $_SERVER['MRK_FILE_PATH'];
$filename = 'CSiCoDB_Spese_il_' . date('Y-m-d_H-i-s') . '.csv';
// file creation
$file = fopen($filepath . $filename,"w");
// Esport header
fputcsv($file,['ID-Spesa','ID-Commessa','Commessa','ID-Lavoratore','Lavoratore','Importo','Data','Rimborso','Descrizione']);
foreach ($data['dataset'] as $line){
//fputcsv($file,$line);
$record = [];
$record['spIDspesa'] = $line['spIDspesa'];
$record['spIDcommessa'] = $line['spIDcommessa'];
$record['coNome'] = $line['coNome'];
$record['spIDlavoratore'] = $line['spIDlavoratore'];
$record['lvNickname'] = $line['lvNickname'];
$record['spImporto'] = number_format( $line['spImporto'], 4);
$record['spData'] = $line['spData'];
$record['spDaRimborsare'] = ($line['spDaRimborsare'] ? 'Da Rimborsare' : 'No Rimborso');
$record['spDescrizione'] = $line['spDescrizione'];
fputcsv($file,$record);
}
// Chiudo il file
fclose($file);
// download
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=".$filename);
header("Content-Type: application/csv; ");
readfile($filepath . $filename);
// deleting file
unlink($filepath . $filename);
exit();
} // function export_csv
//--------------------------------------------------------------------
}
+55
View File
@@ -0,0 +1,55 @@
<?php namespace App\Controllers;
use App\Libraries\Crud;
class StatiCommessa extends CRUDController {
// Tab: StatiCommessa = ['stIDstatoCommessa', 'stDescrizione'];
protected $crud;
function __construct() {
$params = [
'table' => 'StatiCommessa',
'dev' => false,
'fields' => $this->field_options(),
'form_title_add' => 'Nuovo Stato Commessa',
'form_title_update' => 'Edit Stato Commessa',
'form_submit' => 'Add',
'table_title' => 'Pagina per la tabella StatiCommessa',
'form_submit_update' => 'Update',
'base' => '',
'UpdatedAt' => '',
'DeletedAt' => '',
];
$this->crud = new Crud($params, service('request'));
}// __construct
protected function field_options() {
$fields = [];
$fields['stIDstatoCommessa'] = ['label' => 'ID Stato', 'helper' => 'Identificativo univoco dello stato commessa (max 16 carateri)', 'required' => true, 'unique' => [true, 'stIDstatoCommessa']];
$fields['stDescrizione'] = ['label' => 'Descrizione', 'helper' => 'Descrizione esaustiva dello stato', 'required' => true];
return $fields;
}// field_options
public function index() { return $this->CRUD_view(['stIDstatoCommessa', 'stDescrizione']); }
//--------------------------------------------------------------------
// Auto CRUD terminato
//--------------------------------------------------------------------
}
+320
View File
@@ -0,0 +1,320 @@
<?php namespace App\Controllers;
use App\Libraries\Crud;
use App\Models\Stime_Model;
use App\Models\TipiWork_Model;
use App\Models\Commesse_Model;
class Stime extends CRUDController {
// Tab: Stime = ['stIDcommessa', 'stIDTipoWork', 'stStima', 'stNota'];
protected $crud;
function __construct() {
$params = [
'table' => 'Stime',
'dev' => false,
'fields' => $this->field_options(),
'form_title_add' => 'Nuova stima',
'form_title_update' => 'Edit stima',
'form_submit' => 'Add',
'table_title' => 'Pagina per la tabella Stime',
'form_submit_update' => 'Update',
'base' => '',
'UpdatedAt' => '',
'DeletedAt' => '',
];
$this->crud = new Crud($params, service('request'));
}// __construct
protected function field_options() {
$fields = [];
$fields['stIDcommessa'] = ['label' => 'ID Commessa', 'helper' => 'Identificativo univoco della commessa a cui si riferisce la stima', 'required' => true];
$fields['stIDTipoWork'] = ['label' => 'ID Tipo Work', 'helper' => 'Identificativo univoco della tipologia di lavoro a cui si riferisce la stima', 'required' => true];
$fields['stStima'] = ['label' => 'Stima', 'helper' => 'Stima oraria', 'required' => true];
$fields['stNota'] = ['label' => 'Nota', 'helper' => 'Eventuale nota associata alla stima', 'required' => true];
return $fields;
}// field_options
// public function index() {
// return $this->CRUD_view(['stIDcommessa', 'stIDTipoWork', 'stStima', 'stNota']);
// }
//--------------------------------------------------------------------
// Auto CRUD terminato
//--------------------------------------------------------------------
//--------------------------------------------------------------------
public function index() {
helper(['tools','form']);
$data['tab'] = 'admin';
// Verifico sessione e livello:
if (!CheckLevel(1)) { return redirect()->to('/dashboard'); }
// Ricavo le stime in base al filtro:
// Tab: Stime = ['stIDcommessa', 'stIDTipoWork', 'stStima', 'stNota'];
// Tab: TipiWork = ['twIDTipoWork', 'twDescrizione', 'twOrdinamento'];
// Tab: Commesse = ['coIDcommessa', 'coNome', 'coIDcliente', 'coDescrizione', 'coIDstatoCommessa', 'coCreatedAt', 'coUpdatedAt', 'coDeletedAt'];
$model = new Stime_Model();
$model->join('TipiWork', 'stIDTipoWork = twIDTipoWork');
$model->join('Commesse', 'stIDcommessa = coIDcommessa');
// Costruisco la query per selezionare le ore da mostrare:
if (session()->filter_commessa!='-1') { $model->where('stIDcommessa', session()->get('filter_commessa')); }
// imposto l'ordinamento richiesto:
$model->orderBy('twOrdinamento', 'ASC');
// eseguo la query con paginazione:
$data['dataset'] = $model->paginate(session()->get('pager_num'));
$data['pager'] = $model->pager;
// Ricavo i dati per il select delle commesse:
$modelCommesse = new Commesse_Model();
$data['select_commesse'] = $modelCommesse->get_select();
//return view('test', $data);
return view('pages/stime', $data);
}//function index
//--------------------------------------------------------------------
public function add(){
helper(['tools','form']);
$data['tab'] = 'admin';
$data['add'] = true;
$data['title'] = 'Dettagli nuova stima';
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Stime/add -> Error code 001'); }
return redirect()->to('/Lavoratori/login');
}
// Gestione POST
// Tab: Stime = ['stIDcommessa', 'stIDTipoWork', 'stStima', 'stNota'];
if ($this->request->getMethod() == 'post') {
// Regole per validare i campi introdotti nel form:
//
$rules = [
'IDcommessa' => 'trim|required',
'IDTipoWork' => 'trim|required',
'Stima' => 'trim|required',
'Nota' => 'trim|required',
];
// analisi della validazione
if (! $this->validate($rules)) {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', $data['validation']->listErrors());
}else{
// validazione passata
// Preparo i dati per l'inserimento
$newData = [
'stIDcommessa' => $this->request->getVar('IDcommessa'),
'stIDTipoWork' => $this->request->getVar('IDTipoWork'),
'stStima' => $this->request->getVar('Stima'),
'stNota' => $this->request->getVar('Nota'),
];
$model = new Stime_Model();
if ($model->save($newData)) {
session()->setFlashdata('success', 'Record inserito con successo sul DB');
if(isset($_POST['crea_continua'])) {
// è stato premuto il secondo pulsante, quindi inserisco un secondo valore:
//return redirect()->to('/dashboard/orari');
} else {
return redirect()->to('/Stime');
}
} else {
session()->setFlashdata('danger', 'Errore durante l\'inserimento del record nel DB.');
}
}// analisi validazione
}// Gestione POST
// Ricavo i dati per il select delle commesse:
$modelCommesse = new Commesse_Model();
$data['select_commesse'] = $modelCommesse->get_select();
// Ricavo i dati per il select delle tipologie:
$modelTipi = new TipiWork_Model();
$data['select_tipologie'] = $modelTipi->get_select();
// Show profile
echo view('pages/form/stime_form_add_edit', $data);
} // function add()
//--------------------------------------------------------------------
public function edit($IDcm, $IDtw){
helper(['tools','form']);
$data['tab'] = 'admin';
$data['add'] = false;
$data['title'] = 'Dettagli stima';
// Verifico sessione e livello:
if (!CheckLevel(1)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Stime/add -> Error code 001'); }
return redirect()->to('/Lavoratori/login');
}
// Ricavo il profilo della stima da editare
// Tab: Stime = ['stIDcommessa', 'stIDTipoWork', 'stStima', 'stNota'];
$model = new Stime_Model();
$data['stima'] = $model->where('stIDcommessa', $IDcm)->where('stIDTipoWork', $IDtw)->first();
// Gestione POST
// Tab: Stime = ['stIDcommessa', 'stIDTipoWork', 'stStima', 'stNota'];
if ($this->request->getMethod() == 'post') {
// Regole per validare i campi introdotti nel form:
//
$rules = [
'IDcommessa' => 'trim|required',
'IDTipoWork' => 'trim|required',
'Stima' => 'trim|required',
'Nota' => 'trim|required',
];
// analisi della validazione
if (! $this->validate($rules)) {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', $data['validation']->listErrors());
}else{
// validazione passata
// Preparo i dati per l'inserimento
$newData = [
'stIDcommessa' => $this->request->getVar('IDcommessa'),
'stIDTipoWork' => $this->request->getVar('IDTipoWork'),
'stStima' => $this->request->getVar('Stima'),
'stNota' => $this->request->getVar('Nota'),
];
// Cancello i record che devo andare a sostituire o aggiornare:
$model->where('stIDcommessa',$IDcm)->where('stIDTipoWork',$IDtw)->delete(); // Record di partenza
$model->where('stIDcommessa',$newData['stIDcommessa'])->where('stIDTipoWork',$newData['stIDTipoWork'])->delete(); // Nuovo record
if ($model->save($newData)) {
session()->setFlashdata('success', 'Record editato con successo sul DB');
if(isset($_POST['crea_continua'])) {
// è stato premuto il secondo pulsante, quindi inserisco un secondo valore:
//return redirect()->to('/dashboard/orari');
} else {
return redirect()->to('/Stime');
}
} else {
session()->setFlashdata('danger', 'Errore durante l\'inserimento del record nel DB.');
}
}// analisi validazione
}// Gestione POST
// Ricavo i dati per il select delle commesse:
$modelCommesse = new Commesse_Model();
$data['select_commesse'] = $modelCommesse->get_select();
// Ricavo i dati per il select delle tipologie:
$modelTipi = new TipiWork_Model();
$data['select_tipologie'] = $modelTipi->get_select();
// Show profile
echo view('pages/form/stime_form_add_edit', $data);
} // function edit($id)
//--------------------------------------------------------------------
public function Delete($IDcm = null, $IDtw = null){
helper(['tools','form']);
$data = [];
// Tab: Stime = ['stIDcommessa', 'stIDTipoWork', 'stStima', 'stNota'];
$model = new Stime_Model();
// Verifico sessione e livello:
if (!CheckLevel(3)) {
session()->setFlashdata('warning', 'Non si hanno i permessi per cancellare una stima.');
return redirect()->to('/Stime');
}
// Verifico dato introdotto:
if (($IDcm==null) OR ($IDtw==null)) {
if (ENVIRONMENT === 'development') { session()->setFlashdata('warning', '/Stime/delete -> Error code 001'); }
return redirect()->to('/Stime');
}
// Elimino il record:
if ($model->where('stIDcommessa',$IDcm)->where('stIDTipoWork',$IDtw)->delete()) {
session()->setFlashdata('success', 'Records cancellato correttamente.');
} else {
$data['validation'] = $this->validator;
session()->setFlashdata('warning', 'Errore durante la cancellazione del record.');
}
// Show profile
return redirect()->to('/Stime');
} // function edit($id)
//--------------------------------------------------------------------
}
+85
View File
@@ -0,0 +1,85 @@
<?php namespace App\Controllers;
class Test extends BaseController {
//--------------------------------------------------------------------
// Test CRUD automatico:
public function layout($lay='main') {
$data = [];
helper(['tools','form']);
$data = [];
if($lay=='main'){
$data['title'] = 'Test main';
echo view('pages/test_main', $data);
} else {
$data['title'] = 'Test form';
echo view('pages/test_form', $data);
}
//echo view('test', $data);
}//function t1()
//--------------------------------------------------------------------
public function index() {
$data = [];
helper(['tools']);
return view('test', $data);
}//function index()
//--------------------------------------------------------------------
public function timestamp() {
$data = [];
helper(['tools','form']);
$data['dt1'] = date("Y-m-d H:i:s");
$data['tz1'] = date_default_timezone_get();
date_default_timezone_set('Europe/Rome');
$data['dt2'] = date("Y-m-d H:i:s");
$data['tz2'] = date_default_timezone_get();
return view('Test', $data);
}//function timestamp()
//--------------------------------------------------------------------
public function env() {
$data = [];
helper(['tools']);
$data['pippo'] = $_SERVER['CI_ENVIRONMENT'];
$data['test'] = $_SERVER['MRK_FILE_PATH'];
$data['test2'] = $_SERVER['MRK_FILE_PATH2'];
return view('test', $data);
}//function index()
//--------------------------------------------------------------------
}//class Test
+58
View File
@@ -0,0 +1,58 @@
<?php namespace App\Controllers;
use App\Libraries\Crud;
class TipiWork extends CRUDController {
// Tab: TipiWork = ['twIDTipoWork', 'twDescrizione', 'twOrdinamento'];
protected $crud;
function __construct() {
$params = [
'table' => 'TipiWork',
'dev' => false,
'fields' => $this->field_options(),
'form_title_add' => 'Nuova tipologia lavoro',
'form_title_update' => 'Edit tipologia',
'form_submit' => 'Add',
'table_title' => 'Pagina per la tabella TipiWork',
'form_submit_update' => 'Update',
'base' => '',
'UpdatedAt' => '',
'DeletedAt' => '',
];
$this->crud = new Crud($params, service('request'));
}// __construct
protected function field_options() {
$fields = [];
$fields['twIDTipoWork'] = ['label' => 'ID Tipologia', 'helper' => 'Identificativo univoco della tipologia di lavoro (5 caratteri)', 'required' => true, 'unique' => [true, 'twIDTipoWork']];
$fields['twDescrizione'] = ['label' => 'Descrizione', 'helper' => 'Descrizione della tipologia di lavoro', 'required' => true];
$fields['twOrdinamento'] = ['label' => 'Ordinamento', 'helper' => 'Ordinamento per la visualizzazione (numero intero)', 'required' => true];
return $fields;
}// field_options
public function index() {
return $this->CRUD_view(['twIDTipoWork', 'twDescrizione', 'twOrdinamento']);
}
//--------------------------------------------------------------------
// Auto CRUD terminato
//--------------------------------------------------------------------
}
+56
View File
@@ -0,0 +1,56 @@
<?php namespace App\Controllers;
use App\Libraries\Crud;
class TipoOre extends CRUDController {
// Tab: TipoOre = ['toIDTipoOre', 'toDescrizione', 'toOrdinamento'];
protected $crud;
function __construct() {
$params = [
'table' => 'TipoOre',
'dev' => false,
'fields' => $this->field_options(),
'form_title_add' => 'Nuova tipologia orario',
'form_title_update' => 'Edit tipologia',
'form_submit' => 'Add',
'table_title' => 'Pagina per la tabella TipoOre',
'form_submit_update' => 'Update',
'base' => '',
'UpdatedAt' => '',
'DeletedAt' => '',
];
$this->crud = new Crud($params, service('request'));
}// __construct
protected function field_options() {
$fields = [];
$fields['toIDTipoOre'] = ['label' => 'ID Tipologia', 'helper' => 'Identificativo univoco della tipologia di orario (2 caratteri)', 'required' => true, 'unique' => [true, 'toIDTipoOre']];
$fields['toDescrizione'] = ['label' => 'Descrizione', 'helper' => 'Descriziona tipologia di orario', 'required' => true];
$fields['toOrdinamento'] = ['label' => 'Ordinamento', 'helper' => 'Ordinamento per la visualizzazione (numero intero)', 'required' => true];
return $fields;
}// field_options
public function index() { return $this->CRUD_view(['toIDTipoOre', 'toDescrizione', 'toOrdinamento']); }
//--------------------------------------------------------------------
// Auto CRUD terminato
//--------------------------------------------------------------------
}
View File
Whitespace-only changes.
View File
Whitespace-only changes.
+9
View File
@@ -0,0 +1,9 @@
<?php namespace App\Entities;
use CodeIgniter\Entity;
class CSiCoCar extends Entity {
//
}
+9
View File
@@ -0,0 +1,9 @@
<?php namespace App\Entities;
use CodeIgniter\Entity;
class CSiCoCarEvnt extends Entity {
//
}
+9
View File
@@ -0,0 +1,9 @@
<?php namespace App\Entities;
use CodeIgniter\Entity;
class Commessa extends Entity {
//
}
+9
View File
@@ -0,0 +1,9 @@
<?php namespace App\Entities;
use CodeIgniter\Entity;
class CreditCard extends Entity {
//
}
+9
View File
@@ -0,0 +1,9 @@
<?php namespace App\Entities;
use CodeIgniter\Entity;
class CreditCardEvnt extends Entity {
//
}
+9
View File
@@ -0,0 +1,9 @@
<?php namespace App\Entities;
use CodeIgniter\Entity;
class Issue extends Entity {
//
}
+9
View File
@@ -0,0 +1,9 @@
<?php namespace App\Entities;
use CodeIgniter\Entity;
class Lavoratore extends Entity {
//
}
+9
View File
@@ -0,0 +1,9 @@
<?php namespace App\Entities;
use CodeIgniter\Entity;
class Orario extends Entity {
//
}
+9
View File
@@ -0,0 +1,9 @@
<?php namespace App\Entities;
use CodeIgniter\Entity;
class SIM extends Entity {
//
}
+9
View File
@@ -0,0 +1,9 @@
<?php namespace App\Entities;
use CodeIgniter\Entity;
class SIMEvnt extends Entity {
//
}
+9
View File
@@ -0,0 +1,9 @@
<?php namespace App\Entities;
use CodeIgniter\Entity;
class Spesa extends Entity {
//
}
+9
View File
@@ -0,0 +1,9 @@
<?php namespace App\Entities;
use CodeIgniter\Entity;
class Stima extends Entity {
//
}
+9
View File
@@ -0,0 +1,9 @@
<?php namespace App\Entities;
use CodeIgniter\Entity;
class TipoOra extends Entity {
//
}
+9
View File
@@ -0,0 +1,9 @@
<?php namespace App\Entities;
use CodeIgniter\Entity;
class TipoWork extends Entity {
//
}
View File
Whitespace-only changes.
View File
Whitespace-only changes.
+269
View File
@@ -0,0 +1,269 @@
<?php
/*
File con utili funzioni generali
*/
use App\Models\Commesse_Model;
//--------------------------------------------------------------------
// Funzione che imposta i dati della sessione in base al alvoratore che si è loggato
function SetUserSession($lavoratore){
try {
$data = [
'lavoratore' => $lavoratore,
'isLoggedIn' => true,
'pager_num' => 20,
'filter_dal' => date("Y-m-d", strtotime("first day of this month")),
'filter_al' => date("Y-m-d", strtotime("last day of this month")),
'filter_tipo_ore' => '-1',
'filter_commessa' => '-1',
'filter_rimborso' => '-1',
'filter_ccStato' => '-1',
'filter_caStato' => '-1',
'filter_smStato' => '-1',
'filter_cc' => '-1',
'filter_car' => '-1',
'filter_sim' => '-1',
'sort' => [
'tab' => 'Lavoratori',
'col'=> 'lvIDLavoratore',
'dir'=> 'ASC',
],
];
if ($lavoratore->Level>=4) {
// root di default non filtra gli utenti
$data['filter_lavoratore'] = '-1';
} else {
if ($lavoratore->Level>=3) {
// Gli amministratori filtrano gli utenti ma possono editare il filtro
$data['filter_lavoratore'] = $lavoratore->lvIDlavoratore;
} else {
// Gli utenti normali filtrano per se stessi
$data['filter_lavoratore'] = $lavoratore->lvIDlavoratore;
}
}
session()->set($data);
return true;
} catch (Exception $e) {
return false;
}
}//function setUserSession
//--------------------------------------------------------------------
// Funzione che verifica se l'utente loggato ha il livello richiesto: 0=Guest; 1=Oper; 2=Inven; 3=Admin; 4=Root
function CheckLevel($level=0, $verbose = true){
// Verifico sessione e livello:
if ( (session()->get('lavoratore') != null) && (session()->get('lavoratore')->lvLevel>=$level) ) {
return true;
}
if ($verbose) {
session()->setFlashdata('warning', 'AMMINISTRAZIONE:<br />&nbsp;&nbsp;L\'utente utilizzato non ha i diritti necessari per la sezione richiesta.');
}
return false;
} // function CheckLevel
//--------------------------------------------------------------------
/**
* Verifico se l'ordinamento atuale riguarda la tabella in uso, se init true, forzo i valori di default
*/
function CheckSort($tab, $init=false){
try {
$data = [];
helper(['tools']);
$sort = session()->get('sort');
if ($sort['tab']==$tab){
return true;
}
if ($init){
$sort['tab'] = $tab;
switch ($tab) {
case 'articoli':
case 'Articoli':
$sort['col'] = 'arIDarticolo';
$sort['dir'] = 'ASC';
break;
case 'articoloevents':
case 'ArticoloEvents':
$sort['col'] = 'earData';
$sort['dir'] = 'DESC';
break;
case 'categorie':
case 'Categorie':
$sort['col'] = 'caNome';
$sort['dir'] = 'ASC';
break;
case 'clienti':
case 'Clienti':
$sort['col'] = 'clNome';
$sort['dir'] = 'ASC';
break;
case 'commesse':
case 'Commesse':
$sort['col'] = 'coNome';
$sort['dir'] = 'ASC';
break;
case 'evncredit':
case 'creditcardevents':
case 'CreditCardEvents':
$sort['col'] = 'eccData';
$sort['dir'] = 'DESC';
break;
case 'credit':
case 'creditcards':
case 'CreditCards':
$sort['col'] = 'ccNumero';
$sort['dir'] = 'ASC';
break;
case 'evncar':
case 'csicocarevents':
case 'CSiCoCarEvents':
$sort['col'] = 'ecaData';
$sort['dir'] = 'DESC';
break;
case 'cars':
case 'csicocars':
case 'CSiCoCars':
$sort['col'] = 'caTarga';
$sort['dir'] = 'ASC';
break;
case 'issues':
case 'Issues':
$sort['col'] = 'isIDissue';
$sort['dir'] = 'DESC';
break;
case 'anagrafica':
case 'lavoratori':
case 'Lavoratori':
$sort['col'] = 'lvNickname';
$sort['dir'] = 'ASC';
break;
case 'orari':
case 'Orari':
$sort['col'] = 'orData';
$sort['dir'] = 'DESC';
break;
case 'posizioni':
case 'Posizioni':
$sort['col'] = 'psCode';
$sort['dir'] = 'ASC';
break;
case 'evnsim':
case 'simevents':
case 'SIMEvents':
$sort['col'] = 'esmData';
$sort['dir'] = 'DESC';
break;
case 'sims':
case 'SIMs':
$sort['col'] = 'smNumero';
$sort['dir'] = 'ASC';
break;
case 'spese':
case 'Spese':
$sort['col'] = 'spData';
$sort['dir'] = 'DESC';
break;
case 'staticommessa':
case 'StatiCommessa':
$sort['col'] = 'stIDstatoCommessa';
$sort['dir'] = 'ASC';
break;
case 'stime':
case 'Stime':
$sort['col'] = 'stIDcommessa';
$sort['dir'] = 'ASC';
break;
case 'tipoore':
case 'TipoOre':
$sort['col'] = 'toOrdinamento';
$sort['dir'] = 'ASC';
break;
case 'tipiwork':
case 'TipiWork':
$sort['col'] = 'twOrdinamento';
$sort['dir'] = 'ASC';
break;
default:
throw new Exception("Not find the sort reference!");
}
session()->set('sort', $sort);
return true;
}
return false;
} catch (Exception $e) {
return false;
}
}//function CheckSort
//--------------------------------------------------------------------
/**
* Imposta l'ìordinamento voluto per la tabella visualizzata:
*/
function SetSort($tab, $col, $dir){
try {
$data = [];
helper(['tools']);
$sort = session()->get('sort');
$sort['tab'] = $tab;
$sort['col'] = $col;
$sort['dir'] = $dir;
session()->set('sort', $sort);
return true;
} catch (Exception $e) {
return false;
}
}//function CheckSort
//--------------------------------------------------------------------
function UpdateCommessa($IDcommessa){
$model = new Commesse_Model();
$newData = [
'coIDcommessa' => $IDcommessa,
];
$model->save($newData);
}
//--------------------------------------------------------------------
function Field_Text(){
}
//--------------------------------------------------------------------
View File
Whitespace-only changes.
+4
View File
@@ -0,0 +1,4 @@
<?php
// override core en language system validation or define your own en language validation message
return [];
View File
Whitespace-only changes.
+68
View File
@@ -0,0 +1,68 @@
<?php
namespace App\Libraries;
use App\Libraries\Crud_core;
use CodeIgniter\HTTP\RequestInterface;
class Crud extends Crud_core
{
function __construct($params, RequestInterface $request)
{
parent::__construct($params, $request);
}
function form()
{
return $this->parent_form();
}
public function callback_days_left($item){
$days = $this->days($item->p_end_date);
if($days < 0){
$out = '<span class="text-success">Completed</span>';
}else{
$out = '<span>' . $days . ' days left</span>';
}
return $out;
}
private function days($date)
{
$now = time(); // or your date as well
$your_date = strtotime($date);
$datediff = $your_date - $now;
return round($datediff / (60 * 60 * 24));
}
public function callback_featured_image($item){
$src = $item->p_image ? '/uploads/images/'.$item->p_image : '/admin/assets/img/profile.png';
return '<img src="'.$src.'" style="width:54px;" class="img-circle">';
}
public function callback_OreStimate($item){
//$out = $this->OreLavorateByCommessa($item->coIDcommessa);
$out = $this->model->GetStimaByCommessa($item->coIDcommessa);
//if ($out>0) { return $out;}
if ($out>0) { return number_format($out,2);}
return number_format(0,2);
}
public function callback_OreLavorate($item){
//$out = $this->OreLavorateByCommessa($item->coIDcommessa);
$out = $this->model->GetOreByCommessa($item->coIDcommessa);
//if ($out>0) { return $out;}
if ($out>0) { return number_format($out,2);}
return number_format(0,2);
}
//private function OreLavorateByCommessa($idCommessa){
// return '<span>' . $idCommessa . '</span>';
//}
}
File diff suppressed because it is too large. Load diff
View File
Whitespace-only changes.
+307
View File
@@ -0,0 +1,307 @@
<?php
namespace App\Models;
use CodeIgniter\Database\ConnectionInterface;
class AutoCRUD_Model {
protected $db;
public function __construct(ConnectionInterface &$db) { $this->db = &$db; }
public function schema($table) {
$query = "SHOW COLUMNS FROM $table";
$result = $this->db->query($query)->getResult();
return $result;
}//function schema
/**
* Ricava il nome del campo che fa da chiave primaria della tabella
* @param string $table nome della tabella nel DB
* @return string nome del campo che fa da chiave primaria della tabella
*/
function get_primary_key_field_name($table) {
$query = "SHOW KEYS FROM $table WHERE Key_name = 'PRIMARY'";
return $this->db->query($query)->getRow()->Column_name;
}//function get_primary_key_field_name
/**
* Calcola il numero di record in base al filtro
*/
public function countTotalRows($table, $where = null, $request, $schema, $fields) {
$count_query = "SELECT COUNT(*) as total FROM " . $table;
//get primary_key field name
$pk = $this->get_primary_key_field_name($table);
// Se ho dei filtri where, li decodifico e li inserisco nella query:
if ($where) {
$count_query .= " WHERE (";
$i = 0;
foreach ($where as $key => $value) {
if ($i > 0)
$count_query .= " AND ";
//Check if operator is different from = (equal sign)
$operator_arr = explode(" ", $key);
if (isset($operator_arr[1]))
$operator = $operator_arr[1];
else
$operator = "=";
$count_query .= " `$operator_arr[0]`$operator" . $this->db->escape($value) . " ";
$i++;
}
$count_query .= ")";
}
// Se ho indicato delle stringhe di ricerca nella tabella, le inserisco nella query come LIKE
if ($table_search = $request->getPost('table_search')) {
$allEmpty = true;
$tempQuery = '';
if ($where)
$tempQuery .= " AND ";
else
$tempQuery .= " WHERE ";
$tempQuery .= " ( ";
$i = 0;
// ciclo su tutti i campi della tabella per verificare se hanno delle stringhe di ricerca
foreach ($schema as $column) {
if (trim($request->getPost($column->Field)) == '')
continue;
if ($column->Extra == 'other_table')
continue;
$allEmpty = false;
if ($i > 0)
$tempQuery .= " OR ";
$tempQuery .= " " . $table_search
. "." . $column->Field
. " LIKE '%"
. trim($this->db->escapeLikeString($request->getPost($column->Field)))
. "%' ESCAPE '!'";
$i++;
}
$tempQuery .= ")";
if (!$allEmpty)
$count_query .= $tempQuery;
}
// MRK debug: echo $count_query;
return $this->db->query($count_query)->getRow()->total;
}//function countTotalRows
/**
* Select dei record in base alla query (clausole where principali e quelle di ricerca)
*/
public function getItems($table, $where = null, $request, $schema, $fields, $order, $offset, $per_page) {
$result_query = "SELECT * FROM " . $table;
//get primary_key field name
$pk = $this->get_primary_key_field_name($table);
// Ciclo fra le opzioni passate, per unire le tabelle che sono relazionate con questa tramite JOIN:
foreach ($fields as $key => $rel_field) {
if (isset($rel_field['relation']) && !isset($rel_field['relation']['save_table'])) {
$rfield = $rel_field['relation'];
$result_query .= " LEFT JOIN " . $rfield['table'] . " ON " . $table . '.' . $key . "=" . $rfield['table'] . "." . $rfield['primary_key'] . " ";
//$this->db->join($rfield['table'], $table.'.'.$key.'='.$rfield['table'].'.'.$rfield['primary_key'], 'left');
}
}
// Se ho dei filtri where, li decodifico e li inserisco nella query:
if ($where) {
$result_query .= " WHERE (";
$i = 0;
foreach ($where as $key => $value) {
if ($i > 0)
$result_query .= " AND ";
//Check if operator is different from = (equal sign)
$operator_arr = explode(" ", $key);
if (isset($operator_arr[1]))
$operator = $operator_arr[1];
else
$operator = "=";
$count_query .= " `$operator_arr[0]`$operator" . $this->db->escape($value) . " ";
$i++;
}
$result_query .= ")";
}
// Se ho indicato delle stringhe di ricerca nella tabella, le inserisco nella query come LIKE
if ($request->getPost('table_search')) {
$allEmpty = true;
$tempQuery = '';
$i = 0;
if ($where)
$tempQuery .= " AND ";
else
$tempQuery .= " WHERE ";
$tempQuery .= " ( ";
// ciclo su tutti i campi della tabella per verificare se hanno delle stringhe di ricerca
foreach ($schema as $column) {
if ($request->getPost($column->Field) == '')
continue;
$allEmpty = false;
$col_search = [];
$col_search[] = $column->Field;
if (isset($fields[$column->Field]['relation']) && isset($fields[$column->Field]['relation']['save_table'])) {
//Search relational table to get the ids of related ids
$relField = $fields[$column->Field]['relation'];
$parent_table = $relField['table'];
$relation_table = $relField['save_table'];
$joinString = $relation_table . '.' . $relField['child_field'] . '=' . $parent_table . '.' . $relField['primary_key'];
$likeColumns = $relField['display'];
$likeTerm = $request->getPost($column->Field);
//$relselect is optional. when used it will add DISTINCT to prevent dublicates
$relSelect = $relation_table . '.' . $relField['parent_field'];
$relatedItems = $this->searchRelatedItems($parent_table, $relation_table, $joinString, $likeColumns, $likeTerm, $relSelect);
$relatedItemsIdArr = [];
if (!$relatedItems)
$relatedItemsIdArr = '-1';
else {
//Create an array of ids for whereIn statement
foreach ($relatedItems as $relatedItem) {
$relatedItemsIdArr[] = $relatedItem->{$relField['parent_field']};
}
}
if ($i > 0)
$tempQuery .= " AND ";
if (is_array($relatedItemsIdArr))
$relTempQuery = '' . $table . '.' . $pk . ' IN (' . implode(',', $relatedItemsIdArr) . ')';
else
$relTempQuery = $table . '.' . $pk . ' = ' . $relatedItemsIdArr;
// echo $tempQuery.'<br>';
$tempQuery .= $relTempQuery;
// echo $tempQuery;
$i++;
//$allEmpty = false;
continue;
} else if (isset($fields[$column->Field]['relation'])) {
$col_search = $fields[$column->Field]['relation']['display'];
//check if display is an array of columns
if (!is_array($col_search))
$col_search[] = $col_search;
$table_search = $fields[$column->Field]['relation']['table'];
} else {
$table_search = $table;
//$col_search[] = $column->Field;
}
if ($i > 0)
$tempQuery .= " AND ";
//For loop is required when search must be performed in multiple relational columns from another table
$searchLikeTempQuery = '';
$searchLikeTempQueryArr = [];
foreach ($col_search as $colToSearch) {
$searchLikeTempQueryArr[] = $this->generateLikeClause($table_search, $colToSearch, $request->getPost($column->Field));
}
if (count($col_search) > 1) {
$searchLikeTempQuery = implode(' OR ', $searchLikeTempQueryArr);
$searchLikeTempQuery = "($searchLikeTempQuery)";
} else
$searchLikeTempQuery = $searchLikeTempQueryArr[0];
$tempQuery .= $searchLikeTempQuery;
//$this->db->like($table_search.'.'.$col_search, $request->getPost($column->Field), 'both');
$i++;
}
$tempQuery .= isset($searchLikeTempQuery) ? " " : "";
if (!$allEmpty)
$result_query .= $tempQuery;
}
if ($order) {
$result_query .= " ORDER BY ";
$i = 0;
foreach ($order as $ord) {
if ($i > 0)
$result_query .= ", ";
$result_query .= $ord[0] . " " . $ord[1];
//$this->db->order_by($ord[0], $ord[1]);
$i++;
}
} else {
$result_query .= " ORDER BY " . $pk . " DESC";
//$this->db->order_by($pk, 'DESC');
}
$result_query = rtrim($result_query, ',');
$result_query .= " LIMIT $offset, $per_page ";
//$this->db->limit($per_page, $offset);
$page_items = $this->db->query($result_query)->getResult();
return $page_items;
}
/**
* Estrae il singolo record in base all'id
*/
public function getItem($table, $field, $id) {
return $this->db->table($table)
->where([$field => $id])
->get()
->getRow();
}
public function generateLikeClause($table_search, $colToSearch, $searchTerm) {
return $table_search . "." . $colToSearch
. " LIKE '%"
. trim($this->db->escapeLikeString($searchTerm))
. "%' ESCAPE '!'";
}//function generateLikeClause
}//class AutoCRUD_Model
+82
View File
@@ -0,0 +1,82 @@
<?php namespace App\Models;
/*
CREATE TABLE IF NOT EXISTS `CSiCoCarEvents` (
`ecaIDcarEvent` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Identificativo univoco dell''evento',
`ecaIDcar` int(11) NOT NULL COMMENT 'Identificativo univoco del veicolo',
`ecaIDlavoratore` int(11) NOT NULL COMMENT 'Identificativo univoco del lavoratore che utilizza il veicolo',
`ecaDescrizione` text NOT NULL COMMENT 'Descrizione esplicativa del motivo per cui si utilizza il veicolo',
`ecaData` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Data in cui si è utilizzato il veicolo',
`ecaKm` float NOT NULL DEFAULT '0' COMMENT 'Kilometraggio totale alla data dell''evento',
`ecaTipologia` enum('Presa','Restituita','Dismessa') NOT NULL DEFAULT 'Presa' COMMENT 'Tipologia dell''evento',
`ecaStato` varchar(255) NOT NULL DEFAULT 'Tutto OK' COMMENT 'Annotazioni sullo stato del veicolo',
PRIMARY KEY (`ecaIDcarEvent`),
UNIQUE KEY `ecaIDcarEvent` (ecaIDcarEvent),
KEY `FK_CarEvents-CSiCoCars` (`ecaIDcar`),
KEY `FK_CarEvents-Lavoratori` (`ecaIDlavoratore`)
) ENGINE=InnoDB AUTO_INCREMENT=93 DEFAULT CHARSET=utf8 COMMENT='Tabella con tutti gli eventi riferiti alle macchina.';
Fields:
Tab: CSiCoCarEvents = ['ecaIDcarEvent', 'ecaIDcar', 'ecaIDlavoratore', 'ecaDescrizione', 'ecaData', 'ecaKm', 'ecaTipologia', 'ecaStato'];
*/
use CodeIgniter\Model;
class CSiCoCarEvents_Model extends Model {
//--------------------------------------------------------------------
// Property
protected $table = 'CSiCoCarEvents';
protected $primaryKey = 'ecaIDcarEvent';
protected $returnType = 'App\Entities\CSiCoCarEvnt';
//protected $returnType = 'array';
protected $allowedFields = ['ecaIDcar', 'ecaIDlavoratore', 'ecaDescrizione', 'ecaData', 'ecaKm', 'ecaTipologia', 'ecaStato'];
protected $useSoftDeletes = false;
protected $useTimestamps = false;
//protected $createdField = 'spCreatedAt';
//protected $updatedField = 'spUpdatedAt';
//protected $deletedField = 'spDeletedAt';
//--------------------------------------------------------------------
// Events
//protected $beforeInsert = ['beforeInsert'];
//protected $afterInsert = ['afterInsert'];
//protected $beforeUpdate = ['beforeUpdate'];
//protected $afterUpdate = ['afterUpdate'];
//protected $beforeDelete = ['beforeDelete'];
//protected $afterDelete = ['afterDelete'];
//protected $afterFind = ['afterFind'];
//--------------------------------------------------------------------
// Methods
//--------------------------------------------------------------------
}//class CSiCoCarEvents_Model
+81
View File
@@ -0,0 +1,81 @@
<?php namespace App\Models;
/*
CREATE TABLE IF NOT EXISTS `CSiCoCars` (
`caIDcar` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Identificativo univoco del veicolo',
`caTarga` varchar(10) NOT NULL COMMENT 'Targa del veicolo',
`caDescrizione` text NOT NULL COMMENT 'Descrizione del veicolo',
`caDataAssicurazione` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Prossima data di scadenza dell''assicurazione del veicolo',
`caTipoGomme` enum('Invernali','Estive','4Stagioni') NOT NULL DEFAULT '4Stagioni' COMMENT 'Tipologia di pneumatici in dotazione al veicolo',
`caCreatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Timestamp di inserimento del record nel database',
`caUpdatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Timestamp in cui il record è stato aggiornato',
`caStato` enum('Disponibile','Occupata','Dismessa') NOT NULL DEFAULT 'Disponibile' COMMENT 'Stato della macchina, riassume gli eventi',
`caDeletedAt` timestamp NULL DEFAULT NULL COMMENT 'Timestamp in cui il record è stato virtualmente cancellato (senza delete reale)',
PRIMARY KEY (`caIDcar`),
UNIQUE KEY `caIDcar` (`caIDcar`),
UNIQUE KEY `caTarga` (`caTarga`, `smDeletedAt`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT='Tabella con tutte le macchine della CSiCo.';
Fields:
Tab: CSiCoCars = ['caIDcar', 'caTarga', 'caDescrizione', 'caDataAssicurazione', 'caTipoGomme', 'caCreatedAt', 'caUpdatedAt', 'caStato', 'caDeletedAt'];
*/
use CodeIgniter\Model;
class CSiCoCars_Model extends Model {
//--------------------------------------------------------------------
// Property
protected $table = 'CSiCoCars';
protected $primaryKey = 'caIDcar';
protected $returnType = 'App\Entities\CSiCoCar';
//protected $returnType = 'array';
protected $allowedFields = ['caTarga', 'caDescrizione', 'caDataAssicurazione', 'caTipoGomme', 'caStato'];
protected $useSoftDeletes = true;
protected $useTimestamps = true;
protected $createdField = 'caCreatedAt';
protected $updatedField = 'caUpdatedAt';
protected $deletedField = 'caDeletedAt';
//--------------------------------------------------------------------
// Events
//protected $beforeInsert = ['beforeInsert'];
//protected $afterInsert = ['afterInsert'];
//protected $beforeUpdate = ['beforeUpdate'];
//protected $afterUpdate = ['afterUpdate'];
//protected $beforeDelete = ['beforeDelete'];
//protected $afterDelete = ['afterDelete'];
//protected $afterFind = ['afterFind'];
//--------------------------------------------------------------------
// Methods
//--------------------------------------------------------------------
}//class CSiCoCars_Model
+79
View File
@@ -0,0 +1,79 @@
<?php namespace App\Models;
/*
CREATE TABLE IF NOT EXISTS `Clienti` (
`clIDcliente` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Identificativo univoco del cliente',
`clNome` varchar(32) NOT NULL COMMENT 'Nome, per riferimento interno, del cliente',
`clInfo` text NOT NULL COMMENT 'Informazioni sul cliente che vogliamo storicizzare',
`clCreatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Timestamp di inserimento del record nel database',
`clUpdatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Timestamp in cui il record è stato aggiornato',
`clDeletedAt` timestamp NULL DEFAULT NULL COMMENT 'Timestamp in cui il record è stato virtualmente cancellato (senza delete reale)',
PRIMARY KEY (`clIDcliente`),
UNIQUE KEY `clIDcliente` (`clIDcliente`),
UNIQUE KEY `clNome` (`clNome`)
) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=utf8 COMMENT='Elenco dei Clienti della CSiCo';
Fields:
Tab: Clienti = ['clIDcliente', 'clNome', 'clInfo', 'clCreatedAt', 'clUpdatedAt', 'clDeletedAt'];
*/
use CodeIgniter\Model;
class Clienti_Model extends Model{
//--------------------------------------------------------------------
// Property
protected $table = 'Clienti';
protected $primaryKey = 'clIDcliente';
//protected $returnType = 'App\Entities\Cliente';
protected $returnType = 'array';
protected $allowedFields = ['clNome', 'clInfo'];
protected $useSoftDeletes = true;
protected $useTimestamps = true;
protected $createdField = 'clCreatedAt';
protected $updatedField = 'clUpdatedAt';
protected $deletedField = 'clDeletedAt';
//--------------------------------------------------------------------
// Events
//protected $beforeInsert = ['beforeInsert'];
//protected $afterInsert = ['afterInsert'];
//protected $beforeUpdate = ['beforeUpdate'];
//protected $afterUpdate = ['afterUpdate'];
//protected $beforeDelete = ['beforeDelete'];
//protected $afterDelete = ['afterDelete'];
//protected $afterFind = ['afterFind'];
//--------------------------------------------------------------------
// Methods
//--------------------------------------------------------------------
}//class Clienti_Model
+197
View File
@@ -0,0 +1,197 @@
<?php namespace App\Models;
/*
CREATE TABLE IF NOT EXISTS `Commesse` (
`coIDcommessa` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Identificativo univoco della commessa',
`coNome` varchar(32) NOT NULL COMMENT 'Nome univoco della commessa o codice identificativo della commessa',
`coIDcliente` int(11) NOT NULL COMMENT 'Codice identificativo del cliente a cui la commessa è associata',
`coDescrizione` text NOT NULL COMMENT 'Descrizione della commessa, cioè del lavoro che essa richiede',
`coIDstatoCommessa` varchar(16) NOT NULL COMMENT 'Stato a cui la commessa è associata, ne permette la filtrazione in modo conveniente',
`coCreatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Timestamp di inserimento del record nel database',
`coUpdatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Timestamp in cui il record è stato aggiornato',
`coDeletedAt` timestamp NULL DEFAULT NULL COMMENT 'Timestamp in cui il record è stato virtualmente cancellato (senza delete reale)',
PRIMARY KEY (`coIDcommessa`),
UNIQUE KEY `coIDcommessa` (`coIDcommessa`),
UNIQUE KEY `coNome` (`coNome`),
KEY `idx_Clienti_Used` (`coIDstatoCommessa`,`coModificatoIl`,`coNome`),
KEY `FK_Commesse-Clienti` (`coIDcliente`),
KEY `FK_Commesse-StatiCommessa` (`coIDstatoCommessa`)
) ENGINE=InnoDB AUTO_INCREMENT=197 DEFAULT CHARSET=utf8 COMMENT='Elenco delle Commesse';
Fields:
Tab: Commesse = ['coIDcommessa', 'coNome', 'coIDcliente', 'coDescrizione', 'coIDstatoCommessa', 'coCreatedAt', 'coUpdatedAt', 'coDeletedAt'];
*/
use CodeIgniter\Model;
class Commesse_Model extends Model{
//--------------------------------------------------------------------
// Property
protected $table = 'Commesse';
protected $primaryKey = 'coIDcommessa';
protected $returnType = 'App\Entities\Commessa';
//protected $returnType = 'array';
protected $allowedFields = ['coNome', 'coIDcliente', 'coDescrizione', 'coIDstatoCommessa'];
protected $useSoftDeletes = true;
protected $useTimestamps = true;
protected $createdField = 'coCreatedAt';
protected $updatedField = 'coUpdatedAt';
protected $deletedField = 'coDeletedAt';
//--------------------------------------------------------------------
// Events
//protected $beforeInsert = ['beforeInsert'];
//protected $afterInsert = ['afterInsert'];
//protected $beforeUpdate = ['beforeUpdate'];
//protected $afterUpdate = ['afterUpdate'];
//protected $beforeDelete = ['beforeDelete'];
//protected $afterDelete = ['afterDelete'];
//protected $afterFind = ['afterFind'];
//--------------------------------------------------------------------
// Methods
// Ritorna le coppie val,txt per compilare il select delle commesse in base al filtro attivo sugli orari
public function get_select_on_orari(){
// Tab: Commesse = ['coIDcommessa', 'coNome', 'coIDcliente', 'coDescrizione', 'coIDstatoCommessa', 'coModificatoIl', 'coCreatedAt', 'coUpdatedAt', 'coDeletedAt'];
// Creo la string SQL:
// - join fra le tabelle
$sql = 'SELECT Commesse.coIDcommessa AS val, Commesse.coNome AS txt FROM Commesse, Orari WHERE Commesse.coIDcommessa=Orari.orIDcommessa';
// - elimino le commesse chiuse:
$sql .= ' AND coIDstatoCommessa<>\'Chiusa\'';
// - Applico il filtro temporale:
$sql .= ' AND Orari.orData>=\'' . session()->get('filter_dal') . '\' AND Orari.orData<=\'' . session()->get('filter_al') . " 23:59:59" . '\'';
// - applico eventuale filtro per lavoratore
if ((null !== session()->get('filter_lavoratore')) && (session()->get('filter_lavoratore')!='-1')) {
$sql .= ' AND Orari.orIDlavoratore=\'' . session()->get('filter_lavoratore') . '\'';
}
// - Applico il filtro sulla tipologia di orario
if ((null !== session()->get('filter_tipo_ore')) && (session()->get('filter_tipo_ore')!='-1')) {
$sql .= ' AND Orari.orIDTipoOre=\'' . session()->get('filter_tipo_ore') . '\'';
}
// - Non applico il filtro sulla commessa:
if ((null !== session()->get('filter_commessa')) && (session()->get('filter_commessa')!='-1')) {
$sql .= ' AND Orari.orIDcommessa=\'' . session()->get('filter_commessa') . '\'';
}
// - Raggruppo i risultati:
$sql .= ' GROUP BY(txt)';
// - Ordino in modo decrescente sul numero di presenze e in modo alfabetico.
$sql .= ' ORDER BY COUNT(val) DESC, txt';
// Creo la query:
$query = $this->query($sql);
// Eseguo la query sul DB:
return $query->getResult();
} // function select_on_orari
//--------------------------------------------------------------------
// Ritorna le coppie val,txt per compilare il select delle commesse in base al filtro attivo sulle spese
public function get_select_on_spese(){
// Creo la string SQL:
// - join fra le tabelle\
$sql = 'SELECT Commesse.coIDcommessa AS val, CONCAT(Commesse.coNome, \' : \', Commesse.coDescrizione) AS txt FROM Commesse, Spese WHERE Commesse.coIDcommessa=Spese.spIDcommessa';
// - elimino le commesse chiuse:
$sql .= ' AND coIDstatoCommessa<>\'Chiusa\'';
// - Applico il filtro temporale:
$sql .= ' AND Spese.spData>=\'' . session()->get('filter_dal') . '\' AND Spese.spData<=\'' . session()->get('filter_al') . " 23:59:59" . '\'';
// - applico eventuale filtro per lavoratore
if ((null !== session()->get('filter_lavoratore')) && (session()->get('filter_lavoratore')!='-1')) {
$sql .= ' AND Spese.spIDlavoratore=\'' . session()->get('filter_lavoratore') . '\'';
}
// - Applico il filtro sulla tipologia di spesa
if ((null !== session()->get('filter_rimborso')) && (session()->get('filter_rimborso')!='-1')) {
$sql .= ' AND Spese.spDaRimborsare=\'' . session()->get('filter_rimborso') . '\'';
}
// - Non applico il filtro sulla commessa:
if ((null !== session()->get('filter_commessa')) && (session()->get('filter_commessa')!='-1')) {
$sql .= ' AND Spese.spIDcommessa=\'' . session()->get('filter_commessa') . '\'';
}
// - Raggruppo i risultati:
$sql .= ' GROUP BY(txt)';
// - Ordino in modo decrescente sul numero di presenze e in modo alfabetico.
$sql .= ' ORDER BY COUNT(val) DESC, txt';
// Creo la query:
$query = $this->query($sql);
// Eseguo la query sul DB:
return $query->getResult();
} // function select_on_orari
//--------------------------------------------------------------------
// Ritorna le coppie val,txt per compilare il select delle commesse
public function get_select(){
$query = $this->query('SELECT coIDcommessa AS val, CONCAT(coNome, \' : \', coDescrizione) AS txt FROM Commesse WHERE coIDstatoCommessa<>\'Chiusa\' ORDER BY coUpdatedAt DESC');
return $query->getResult();
}
//--------------------------------------------------------------------
// Ritorna i dati per il report della commessa indicata
public function get_ReportByCommessa($ID){
$query = $this->query("
SELECT
coIDcommessa AS ID,
coNome AS Nome,
(SELECT clNome FROM `Clienti` WHERE clIDcliente=coIDcliente) AS Cliente,
coDescrizione AS Descrizione,
(SELECT sum(stStima) FROM `Stime` WHERE stIDcommessa=coIDcommessa) AS Stima,
(SELECT sum(orOre) FROM `Orari` WHERE orIDcommessa=coIDcommessa) AS Usate,
coIDstatoCommessa AS Stato,
coCreatedAt AS CreatedAt,
coUpdatedAt AS UpdatedAt,
coDeletedAt AS DeletedAt
FROM `Commesse`
WHERE coIDcommessa='$ID'
");
return $query->getResult();
}
//--------------------------------------------------------------------
}//class Commesse_Model
+79
View File
@@ -0,0 +1,79 @@
<?php namespace App\Models;
/*
CREATE TABLE IF NOT EXISTS `CreditCardEvents` (
`eccIDcreditEvent` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Identificativo univoco dell''evento',
`eccIDcard` int(11) NOT NULL COMMENT 'Identificativo univoco della carta di credito aziendale',
`eccIDlavoratore` int(11) NOT NULL COMMENT 'Identificativo univoco del lavoratore che utilizza la carta',
`eccDescrizione` text NOT NULL COMMENT 'Descrizione esplicativa del motivo per cui si utilizza la carta',
`eccData` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Data in cui si è utilizzato la carta',
`eccCredito` float NOT NULL DEFAULT '0' COMMENT 'Stima del credito rimasto alla data dell''evento',
`eccTipologia` enum('Presa','Restituita') NOT NULL DEFAULT 'Presa' COMMENT 'Tipologia dell''evento',
PRIMARY KEY (`eccIDcreditEvent`),
KEY `FK_CreditEvents-CreditCards` (`eccIDcard`),
KEY `FK_CreditEvents-Lavoratori` (`eccIDlavoratore`)
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8 COMMENT='Tabella con tutti gli eventi riferiti alle carte di credito.';
Fields:
Tab: CreditCardEvents = ['eccIDcreditEvent', 'eccIDcard', 'eccIDlavoratore', 'eccDescrizione', 'eccData', 'eccCredito', 'eccTipologia'];
*/
use CodeIgniter\Model;
class CreditCardEvents_Model extends Model {
//--------------------------------------------------------------------
// Property
protected $table = 'CreditCardEvents';
protected $primaryKey = 'eccIDcreditEvent';
protected $returnType = 'App\Entities\CreditCardEvnt';
//protected $returnType = 'array';
protected $allowedFields = ['eccIDcard', 'eccIDlavoratore', 'eccDescrizione', 'eccData', 'eccCredito', 'eccTipologia'];
protected $useSoftDeletes = false;
protected $useTimestamps = false;
//protected $createdField = 'spCreatedAt';
//protected $updatedField = 'spUpdatedAt';
//protected $deletedField = 'spDeletedAt';
//--------------------------------------------------------------------
// Events
//protected $beforeInsert = ['beforeInsert'];
//protected $afterInsert = ['afterInsert'];
//protected $beforeUpdate = ['beforeUpdate'];
//protected $afterUpdate = ['afterUpdate'];
//protected $beforeDelete = ['beforeDelete'];
//protected $afterDelete = ['afterDelete'];
//protected $afterFind = ['afterFind'];
//--------------------------------------------------------------------
// Methods
//--------------------------------------------------------------------
}//class CreditCardEvents_Model
+79
View File
@@ -0,0 +1,79 @@
<?php namespace App\Models;
/*
CREATE TABLE IF NOT EXISTS `CreditCards` (
`ccIDcard` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Identificativo univoco della carta di credito aziendale',
`ccNumero` varchar(20) NOT NULL COMMENT 'Numero nella carta',
`ccDescrizione` text NOT NULL COMMENT 'Descrizione della carta per riferimento interno CSiCo',
`ccScadeIl` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Data di scadenza della carta',
`ccPIN` varchar(6) NOT NULL COMMENT 'PIN della carta',
`ccCreatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Timestamp di inserimento del record nel database',
`ccUpdatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Timestamp in cui il record è stato aggiornato',
`ccStato` enum('Disponibile','Occupata','Scaduta') NOT NULL DEFAULT 'Disponibile' COMMENT 'Stato della carta di credito, riassume gli eventi',
`ccDeletedAt` timestamp NULL DEFAULT NULL COMMENT 'Timestamp in cui il record è stato virtualmente cancellato (senza delete reale)',
PRIMARY KEY (`ccIDcard`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COMMENT='Tabella con tutte le carte di credito della CSiCo.';
Fields:
Tab: CreditCards = ['ccIDcard', 'ccNumero', 'ccDescrizione', 'ccScadeIl', 'ccPIN', 'ccCreatedAt', 'ccUpdatedAt', 'ccStato', 'ccDeletedAt'];
*/
use CodeIgniter\Model;
class CreditCards_Model extends Model {
//--------------------------------------------------------------------
// Property
protected $table = 'CreditCards';
protected $primaryKey = 'ccIDcard';
protected $returnType = 'App\Entities\CreditCard';
//protected $returnType = 'array';
protected $allowedFields = ['ccNumero', 'ccDescrizione', 'ccScadeIl', 'ccPIN', 'ccStato'];
protected $useSoftDeletes = true;
protected $useTimestamps = true;
protected $createdField = 'ccCreatedAt';
protected $updatedField = 'ccUpdatedAt';
protected $deletedField = 'ccDeletedAt';
//--------------------------------------------------------------------
// Events
//protected $beforeInsert = ['beforeInsert'];
//protected $afterInsert = ['afterInsert'];
//protected $beforeUpdate = ['beforeUpdate'];
//protected $afterUpdate = ['afterUpdate'];
//protected $beforeDelete = ['beforeDelete'];
//protected $afterDelete = ['afterDelete'];
//protected $afterFind = ['afterFind'];
//--------------------------------------------------------------------
// Methods
//--------------------------------------------------------------------
}//class CreditCards_Model
+379
View File
@@ -0,0 +1,379 @@
<?php
namespace App\Models;
use CodeIgniter\Database\ConnectionInterface;
class CrudModel
{
protected $db;
public function __construct(ConnectionInterface &$db)
{
$this->db = &$db;
}
public function schema($table)
{
$query = "SHOW COLUMNS FROM $table";
$result = $this->db->query($query)->getResult();
return $result;
}
public function insertItem($table, $data)
{
$this->db->table($table)->insert($data);
return $this->db->insertID();
}
public function getAnyItems($table, $where = false)
{
$builder = $this->db->table($table);
if ($where)
$builder->where($where);
return $builder->get()->getResult();
}
public function updateItem($table, $where, $data)
{
$this->db->table($table)->where($where)->update($data);
return $this->db->affectedRows();
}
function get_primary_key_field_name($table)
{
$query = "SHOW KEYS FROM $table WHERE Key_name = 'PRIMARY'";
return $this->db->query($query)->getRow()->Column_name;
}
//Get one item
public function getItem($table, $where)
{
return $this->db->table($table)
->where($where)
->get()
->getRow();
}
//Get total rows per request
public function countTotalRows($table, $where = null, $request, $schema, $fields)
{
$count_query = "SELECT COUNT(*) as total FROM " . $table;
//get primary_key field name
$pk = $this->get_primary_key_field_name($table);
if ($where) {
$count_query .= " WHERE (";
$i = 0;
foreach ($where as $key => $value) {
if ($i > 0)
$count_query .= " AND ";
//Check if operator is different from = (equal sign)
$operator_arr = explode(" ", $key);
if (isset($operator_arr[1]))
$operator = $operator_arr[1];
else
$operator = "=";
$count_query .= " `$operator_arr[0]`$operator" . $this->db->escape($value) . " ";
$i++;
}
$count_query .= ")";
}
if ($table_search = $request->getPost('table_search')) {
$allEmpty = true;
$tempQuery = '';
if ($where)
$tempQuery .= " AND ";
else
$tempQuery .= " WHERE ";
$tempQuery .= " ( ";
$i = 0;
// echo '<pre>';
// print_r($schema);
// echo '<pre>';
foreach ($schema as $column) {
if (trim($request->getPost($column->Field)) == '')
continue;
if ($column->Extra == 'other_table')
continue;
$allEmpty = false;
if ($i > 0)
$tempQuery .= " OR ";
$tempQuery .= " " . $table_search
. "." . $column->Field
. " LIKE '%"
. trim($this->db->escapeLikeString($request->getPost($column->Field)))
. "%' ESCAPE '!'";
$i++;
}
$tempQuery .= ")";
if (!$allEmpty)
$count_query .= $tempQuery;
}
return $this->db->query($count_query)->getRow()->total;
}
public function getItems($table, $where = null, $request, $schema, $fields, $order, $offset, $per_page)
{
$result_query = "SELECT * FROM " . $table;
//get primary_key field name
$pk = $this->get_primary_key_field_name($table);
//Check for relation fields
foreach ($fields as $key => $rel_field) {
if (isset($rel_field['relation']) && !isset($rel_field['relation']['save_table'])) {
$rfield = $rel_field['relation'];
$result_query .= " LEFT JOIN " . $rfield['table'] . " ON " . $table . '.' . $key . "=" . $rfield['table'] . "." . $rfield['primary_key'] . " ";
//$this->db->join($rfield['table'], $table.'.'.$key.'='.$rfield['table'].'.'.$rfield['primary_key'], 'left');
}
}
if ($where) {
$result_query .= " WHERE (";
$i = 0;
foreach ($where as $key => $value) {
if ($i > 0)
$result_query .= " AND ";
//Check if operator is different from = (equal sign)
$operator_arr = explode(" ", $key);
if (isset($operator_arr[1]))
$operator = $operator_arr[1];
else
$operator = "=";
$result_query .= " `$operator_arr[0]`$operator'$value' ";
//$this->db->where($key, $value);
$i++;
}
$result_query .= ")";
}
if ($request->getPost('table_search')) {
$allEmpty = true;
$tempQuery = '';
$i = 0;
if ($where)
$tempQuery .= " AND ";
else
$tempQuery .= " WHERE ";
//$tempQuery .= " ( ";
foreach ($schema as $column) {
if ($request->getPost($column->Field) == '')
continue;
$allEmpty = false;
$col_search = [];
$col_search[] = $column->Field;
if (isset($fields[$column->Field]['relation']) && isset($fields[$column->Field]['relation']['save_table'])) {
//Search relational table to get the ids of related ids
$relField = $fields[$column->Field]['relation'];
$parent_table = $relField['table'];
$relation_table = $relField['save_table'];
$joinString = $relation_table . '.' . $relField['child_field'] . '=' . $parent_table . '.' . $relField['primary_key'];
$likeColumns = $relField['display'];
$likeTerm = $request->getPost($column->Field);
//$relselect is optional. when used it will add DISTINCT to prevent dublicates
$relSelect = $relation_table . '.' . $relField['parent_field'];
$relatedItems = $this->searchRelatedItems($parent_table, $relation_table, $joinString, $likeColumns, $likeTerm, $relSelect);
$relatedItemsIdArr = [];
if (!$relatedItems)
$relatedItemsIdArr = '-1';
else {
//Create an array of ids for whereIn statement
foreach ($relatedItems as $relatedItem) {
$relatedItemsIdArr[] = $relatedItem->{$relField['parent_field']};
}
}
if ($i > 0)
$tempQuery .= " AND ";
if (is_array($relatedItemsIdArr))
$relTempQuery = '' . $table . '.' . $pk . ' IN (' . implode(',', $relatedItemsIdArr) . ')';
else
$relTempQuery = $table . '.' . $pk . ' = ' . $relatedItemsIdArr;
// echo $tempQuery.'<br>';
$tempQuery .= $relTempQuery;
// echo $tempQuery;
$i++;
//$allEmpty = false;
continue;
} else if (isset($fields[$column->Field]['relation'])) {
$col_search = $fields[$column->Field]['relation']['display'];
//check if display is an array of columns
if (!is_array($col_search))
$col_search[] = $col_search;
$table_search = $fields[$column->Field]['relation']['table'];
} else {
$table_search = $table;
//$col_search[] = $column->Field;
}
if ($i > 0)
$tempQuery .= " AND ";
//For loop is required when search must be performed in multiple relational columns from another table
$searchLikeTempQuery = '';
$searchLikeTempQueryArr = [];
foreach ($col_search as $colToSearch) {
$searchLikeTempQueryArr[] = $this->generateLikeClause($table_search, $colToSearch, $request->getPost($column->Field));
}
if (count($col_search) > 1) {
$searchLikeTempQuery = implode(' OR ', $searchLikeTempQueryArr);
$searchLikeTempQuery = "($searchLikeTempQuery)";
} else
$searchLikeTempQuery = $searchLikeTempQueryArr[0];
$tempQuery .= $searchLikeTempQuery;
//$this->db->like($table_search.'.'.$col_search, $request->getPost($column->Field), 'both');
$i++;
}
$tempQuery .= isset($searchLikeTempQuery) ? " " : "";
if (!$allEmpty)
$result_query .= $tempQuery;
}
if ($order) {
$result_query .= " ORDER BY ";
$i = 0;
foreach ($order as $ord) {
if ($i > 0)
$result_query .= ", ";
$result_query .= $ord[0] . " " . $ord[1];
//$this->db->order_by($ord[0], $ord[1]);
$i++;
}
} else {
$result_query .= " ORDER BY " . $pk . " DESC";
//$this->db->order_by($pk, 'DESC');
}
$result_query = rtrim($result_query, ',');
$result_query .= " LIMIT $offset, $per_page ";
//$this->db->limit($per_page, $offset);
$page_items = $this->db->query($result_query)->getResult();
return $page_items;
}
public function getRelationItems($table, $where = null, $orderField = null, $orderDirection = null)
{
$builder = $this->db->table($table);
if ($where)
$builder->where($where);
if ($orderField)
$builder->orderBy($orderField, $orderDirection);
$items = $builder->get()
->getResult();
return $items;
}
public function deleteItems($table, $where = null, $whereInField = null, $whereInValue = null)
{
$builder = $this->db->table($table);
if ($where)
$builder->where($where);
if ($whereInField && $whereInValue)
$builder->whereIn($whereInField, $whereInValue);
return $builder->delete();
}
public function batchInsert($table, $data)
{
$builder = $this->db->table($table);
return $builder->insertBatch($data);
}
public function getRelationItemsJoin($table, $where, $joinTable, $joinString)
{
$builder = $this->db->table($table);
$builder->where($where);
$builder->join($joinTable, $joinString);
return $builder->get()->getResult();
}
public function searchRelatedItems($parent_table, $relation_table, $joinString, $likeColumns, $likeTerm, $select = '*')
{
$builder = $this->db->table($relation_table);
$builder->select($select);
$builder->join($parent_table, $joinString);
for ($i = 0; $i < count($likeColumns); $i++) {
if ($i < 1) {
$builder->like($parent_table . '.' . $likeColumns[$i], $likeTerm);
} else {
$builder->orLike($parent_table . '.' . $likeColumns[$i], $likeTerm);
}
}
return $builder->distinct()->get()->getResult();
}
public function generateLikeClause($table_search, $colToSearch, $searchTerm)
{
return $table_search . "." . $colToSearch
. " LIKE '%"
. trim($this->db->escapeLikeString($searchTerm))
. "%' ESCAPE '!'";
}
//Get total rows per request
public function GetOreByCommessa($IDcommessa)
{
$cont_query = "SELECT SUM(orOre) as OreLavorate FROM Orari WHERE orIDcommessa='" . $IDcommessa . "'";
//return $query;
return $this->db->query($cont_query)->getRow()->OreLavorate;
}
public function GetStimaByCommessa($IDcommessa)
{
$cont_query = "SELECT SUM(stStima) AS Stima FROM `Stime` WHERE stIDcommessa='" . $IDcommessa . "'";
//return $query;
return $this->db->query($cont_query)->getRow()->Stima;
}
}
+81
View File
@@ -0,0 +1,81 @@
<?php namespace App\Models;
/*
CREATE TABLE IF NOT EXISTS `Issues` (
`isIDissue` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Identificativo univoco dell''issue',
`isTipologia` enum('BUG','IDEA','INFO','RICHIESTA') DEFAULT 'INFO' COMMENT 'Indica la tipologia dell''issue: -BUG indica un malfuzionamento della webapp o una mancanza; - IDEA indica una funzionalità da inserire o descrive un possibile miglioramento; INFO indica delle informazioni utili per tutti e che è utile tenere in evidenza.',
`isStato` enum('Da_Leggere','Da_Fare','In_Working','Sospesa','Abortita','Done') DEFAULT 'Da_Leggere' COMMENT 'Stato associabile all''issue.',
`isIDlavoratore` int(11) NOT NULL COMMENT 'Identificativo del lavoratore che ha inserito l''issue',
`isTesto` text NOT NULL COMMENT 'Testo o descrizione dell''issue.',
`isCreatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Timestamp di inserimento del record nel database',
`isUpdatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Timestamp in cui il record è stato aggiornato',
`isDeletedAt` timestamp NULL DEFAULT NULL COMMENT 'Timestamp in cui il record è stato virtualmente cancellato (senza delete reale)',
PRIMARY KEY (`isIDissue`),
KEY `FK_Issues-Lavoratori` (`isIDlavoratore`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Tabella con le issue relative alla webapplication. Utile per segnalare all''amministratore eventuali bug, migliorie o per evidenziare a tutti delle informazioni.';
Fields:
Tab: Issues = ['isIDissue', 'isTipologia', 'isStato', 'isIDlavoratore', 'isTesto', 'isCreatedAt', 'isUpdatedAt', 'isDeletedAt'];
*/
use CodeIgniter\Model;
class Issues_Model extends Model{
//--------------------------------------------------------------------
// Property
protected $table = 'Issues';
protected $primaryKey = 'isIDissue';
protected $returnType = 'App\Entities\Issue';
//protected $returnType = 'array';
protected $allowedFields = ['isIDissue', 'isTipologia', 'isStato', 'isIDlavoratore', 'isTesto'];
protected $useSoftDeletes = true;
protected $useTimestamps = true;
protected $createdField = 'isCreatedAt';
protected $updatedField = 'isUpdatedAt';
protected $deletedField = 'isDeletedAt';
//--------------------------------------------------------------------
// Events
//protected $beforeInsert = ['beforeInsert'];
//protected $afterInsert = ['afterInsert'];
//protected $beforeUpdate = ['beforeUpdate'];
//protected $afterUpdate = ['afterUpdate'];
//protected $beforeDelete = ['beforeDelete'];
//protected $afterDelete = ['afterDelete'];
//protected $afterFind = ['afterFind'];
//--------------------------------------------------------------------
// Methods
//--------------------------------------------------------------------
}//class Issues_Model
+200
View File
@@ -0,0 +1,200 @@
<?php namespace App\Models;
/*
CREATE TABLE IF NOT EXISTS `Lavoratori` (
`lvIDlavoratore` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Identificativo univoco del lavoratore',
`lvNome` varchar(64) NOT NULL COMMENT 'Nome anagrafico del lavoratore',
`lvCognome` varchar(64) NOT NULL COMMENT 'Cognome anagrfico del lavoratore',
`lvMail` varchar(128) NOT NULL COMMENT 'Indirizzo mail assegnato al al lavoratore',
`lvLevel` int(1) NOT NULL DEFAULT '1' COMMENT 'Livello di accesso alla webapp. 0=Guest; 1=Oper; 2=Inven; 3=Admin; 4=Root.',
`lvRimborsoKm` float NOT NULL DEFAULT '0' COMMENT 'Valore del rimborso kilometrico corrisposto al lavoratore',
`lvNickname` varchar(8) NOT NULL COMMENT 'Nickname distindivo del lavoratore',
`lvPassword` varchar(255) NOT NULL COMMENT 'Codice Hash della password editata dal lavoratore',
`lvCreatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Timestamp di inserimento del record nel database',
`lvUpdatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Timestamp in cui il record è stato aggiornato',
`lvDeletedAt` timestamp NULL DEFAULT NULL COMMENT 'Timestamp in cui il record è stato virtualmente cancellato (senza delete reale)',
PRIMARY KEY (`lvIDlavoratore`),
UNIQUE KEY `lvIDlavoratore` (`lvIDlavoratore`),
UNIQUE KEY `lvNikname` (`lvNickname`,`lvDeletedAt`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8 COMMENT='Elenco dei Lavoratori della CSiCo (CSiCoBoys)';
Fields:
Tab: Lavoratori = ['lvIDlavoratore', 'lvNome', 'lvCognome', 'lvMail', 'lvLevel', 'lvRimborsoKm', 'lvNickname', 'lvPassword', 'lvCreatedAt', 'lvUpdatedAt', 'lvDeletedAt'];
*/
use CodeIgniter\Model;
class Lavoratori_Model extends Model{
//--------------------------------------------------------------------
// Property
protected $table = 'Lavoratori';
protected $primaryKey = 'lvIDlavoratore';
protected $returnType = 'App\Entities\Lavoratore';
//protected $returnType = 'array';
protected $allowedFields = ['lvNome', 'lvCognome', 'lvMail', 'lvLevel', 'lvRimborsoKm', 'lvNickname', 'lvPassword', 'ccStato'];
protected $useSoftDeletes = true;
protected $useTimestamps = true;
protected $createdField = 'lvCreatedAt';
protected $updatedField = 'lvUpdatedAt';
protected $deletedField = 'lvDeletedAt';
//--------------------------------------------------------------------
// Events
protected $beforeInsert = ['beforeInsert'];
//protected $afterInsert = ['afterInsert'];
protected $beforeUpdate = ['beforeUpdate'];
//protected $afterUpdate = ['afterUpdate'];
//protected $beforeDelete = ['beforeDelete'];
//protected $afterDelete = ['afterDelete'];
//protected $afterFind = ['afterFind'];
//--------------------------------------------------------------------
// Methods
protected function beforeInsert(array $data){
$data = $this->passwordHash($data);
return $data;
}
protected function beforeUpdate(array $data){
$data = $this->passwordHash($data);
return $data;
}
protected function passwordHash(array $data){
if(isset($data['data']['lvPassword']))
$data['data']['lvPassword'] = password_hash($data['data']['lvPassword'], PASSWORD_DEFAULT);
return $data;
}
//--------------------------------------------------------------------
/**
* Ritorna le coppie val,txt per compilare il select dei lavoratori, in base al filtro attivo
*/
public function get_select_on_orari(){
// Creo la string SQL:
// - join fra le tabelle
$sql = 'SELECT Lavoratori.lvIDlavoratore AS val, Lavoratori.lvNickname AS txt FROM Lavoratori, Orari WHERE Lavoratori.lvIDlavoratore=Orari.orIDlavoratore';
// - Filtro fra i lavoratori Guest o i cancellati:
$sql .= " AND lvDeletedAt IS null AND lvLevel>0";
// - Applico il filtro temporale:
$sql .= ' AND Orari.orData>=\'' . session()->get('filter_dal') . '\' AND Orari.orData<=\'' . session()->get('filter_al') . " 23:59:59" . '\'';
// - applico eventuale filtro per lavoratore
if ((null !== session()->get('filter_lavoratore')) && (session()->get('filter_lavoratore')!='-1')) {
$sql .= ' AND Lavoratori.lvIDlavoratore=\'' . session()->get('filter_lavoratore') . '\'';
}
// - applico eventuale filtro per commessa
if ((null !== session()->get('filter_commessa')) && (session()->get('filter_commessa')!='-1')) {
$sql .= ' AND Orari.orIDcommessa=\'' . session()->get('filter_commessa') . '\'';
}
// - applico eventuale filtro per tipologia di ora:
if ((null !== session()->get('filter_tipo_ore')) && (session()->get('filter_tipo_ore')!='-1')) {
$sql .= ' AND Orari.orIDTipoOre=\'' . session()->get('filter_tipo_ore') . '\'';
}
// - Raggruppo i risultati:
$sql .= ' GROUP BY(txt)';
// - Ordino in modo decrescente sul numero di presenze e in modo alfabetico.
$sql .= ' ORDER BY COUNT(val) DESC, txt';
// Creo la query:
$query = $this->query($sql);
// Eseguo la query sul DB:
return $query->getResult();
} // function select_on_orari
//--------------------------------------------------------------------
// Ritorna le coppie val,txt per compilare il select dei lavoratori, in base al filtro attivo
public function get_select_on_spese(){
// Creo la string SQL:
// - join fra le tabelle
$sql = 'SELECT Lavoratori.lvIDlavoratore AS val, Lavoratori.lvNickname AS txt FROM Lavoratori, Spese WHERE Lavoratori.lvIDlavoratore=Spese.spIDlavoratore';
// - Filtro fra i lavoratori Guest o i cancellati:
$sql .= " AND lvDeletedAt IS null AND lvLevel>0";
// - Applico il filtro temporale:
$sql .= ' AND Spese.spData>=\'' . session()->get('filter_dal') . '\' AND Spese.spData<=\'' . session()->get('filter_al') . " 23:59:59" . '\'';
// - applico eventuale filtro per lavoratore
if ((null !== session()->get('filter_lavoratore')) && (session()->get('filter_lavoratore')!='-1')) {
$sql .= ' AND Lavoratori.lvIDlavoratore=\'' . session()->get('filter_lavoratore') . '\'';
}
// - applico eventuale filtro per commessa
if ((null !== session()->get('filter_commessa')) && (session()->get('filter_commessa')!='-1')) {
$sql .= ' AND Spese.spIDcommessa=\'' . session()->get('filter_commessa') . '\'';
}
// - applico eventuale filtro per tipologia di rimborso:
if ((null !== session()->get('filter_rimborso')) && (session()->get('filter_rimborso')!='-1')) {
$sql .= ' AND Spese.spDaRimborsare=\'' . session()->get('filter_rimborso') . '\'';
}
// - Raggruppo i risultati:
$sql .= ' GROUP BY(txt)';
// - Ordino in modo decrescente sul numero di presenze e in modo alfabetico.
$sql .= ' ORDER BY COUNT(val) DESC, txt';
// Creo la query:
$query = $this->query($sql);
// Eseguo la query sul DB:
return $query->getResult();
} // function select_on_spese
//--------------------------------------------------------------------
/**
* Ritorna le coppie val,txt per compilare il select dei lavoratori
*/
public function get_select() {
// Filtro fra i lavoratori cancellati e quelli solo guest:
$query = $this->query('SELECT lvIDlavoratore AS val, lvNickname AS txt FROM Lavoratori WHERE lvDeletedAt IS null AND lvLevel>0 ORDER BY lvNickname');
return $query->getResult();
}//function get_select
//--------------------------------------------------------------------
}//class Lavoratori_Model
+105
View File
@@ -0,0 +1,105 @@
<?php namespace App\Models;
/*
CREATE TABLE IF NOT EXISTS `Orari` (
`orIDorario` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Identificativo univoco dell''orario',
`orIDcommessa` int(11) NOT NULL COMMENT 'Identificativo univoco della commessa a cui si riferisce l''orario',
`orIDlavoratore` int(11) NOT NULL COMMENT 'Identificativo univoco del lavoratore a cui si riferisce l''orario',
`orData` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Data in cui si è avuto l''orario',
`orOre` float NOT NULL DEFAULT '0' COMMENT 'Durata espressa in ore con i decimali (0,5=30 minuti)',
`orIDTipoOre` varchar(2) NOT NULL COMMENT 'Tipologia dell''orario in base a quanto indicato sulle buste paga',
`orIDTipoWork` varchar(5) NOT NULL COMMENT 'Tipologia del lavoro svolto',
`orDescrizione` text NOT NULL COMMENT 'Descrizione esplicativa di quanto fatto nell''orario',
PRIMARY KEY (`orIDorario`),
KEY `FK_Orari-Commesse` (`orIDcommessa`),
KEY `FK_Orari-Lavoratori` (`orIDlavoratore`),
KEY `FK_Orari-TipoOre` (`orIDTipoOre`)
) ENGINE=InnoDB AUTO_INCREMENT=15429 DEFAULT CHARSET=utf8 COMMENT='Tabella con tutti i log delle ore lavorate.';
Fields:
Tab: Orari = ['orIDorario', 'orIDcommessa', 'orIDlavoratore', 'orData', 'orOre', 'orIDTipoOre', 'orIDTipoWork', 'orDescrizione'];
*/
use CodeIgniter\Model;
class Orari_Model extends Model{
//--------------------------------------------------------------------
// Property
protected $table = 'Orari';
protected $primaryKey = 'orIDorario';
protected $returnType = 'App\Entities\Orario';
//protected $returnType = 'array';
protected $allowedFields = ['orIDcommessa', 'orIDlavoratore', 'orData', 'orOre', 'orIDTipoOre', 'orIDTipoWork', 'orDescrizione'];
protected $useSoftDeletes = false;
protected $useTimestamps = false;
//protected $createdField = 'spCreatedAt';
//protected $updatedField = 'spUpdatedAt';
//protected $deletedField = 'spDeletedAt';
//--------------------------------------------------------------------
// Events
//protected $beforeInsert = ['beforeInsert'];
//protected $afterInsert = ['afterInsert'];
//protected $beforeUpdate = ['beforeUpdate'];
//protected $afterUpdate = ['afterUpdate'];
//protected $beforeDelete = ['beforeDelete'];
//protected $afterDelete = ['afterDelete'];
//protected $afterFind = ['afterFind'];
//--------------------------------------------------------------------
// Methods
//--------------------------------------------------------------------
// Ritorna i dati per il report della commessa indicata
public function get_ReportByCommessa($ID){
$query = $this->query("
SELECT
(SELECT coNome FROM `Commesse` WHERE coIDcommessa=orIDCommessa) AS Commessa,
(SELECT lvNickname FROM `Lavoratori` WHERE lvIDlavoratore=orIDlavoratore) AS Lavoratore,
orIDlavoratore AS IDlavoratore,
orIDTipoOre AS IDTipoOre,
orIDTipoWork AS IDTipoWork,
sum(orOre) AS TotOre
FROM `Orari`
WHERE orIDcommessa='$ID'
GROUP BY orIDlavoratore, orIDTipoOre, orIDTipoWork
WITH ROLLUP
");
return $query->getResult();
}
//--------------------------------------------------------------------
}//class Orari_Model
+79
View File
@@ -0,0 +1,79 @@
<?php namespace App\Models;
/*
CREATE TABLE IF NOT EXISTS `SIMEvents` (
`esmIDsimEvent` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Identificativo univoco dell''evento',
`esmIDsim` int(11) NOT NULL COMMENT 'Identificativo univoco della SIM telefonica',
`esmIDlavoratore` int(11) NOT NULL COMMENT 'Identificativo univoco del lavoratore',
`esmDescrizione` text NOT NULL COMMENT 'Descrizione esplicativa del''evento',
`esmData` timestamp NOT NULL DEFAULT current_timestamp() COMMENT 'Data dell''evento',
`esmTipologia` enum('Presa','Restituita','Dismessa') NOT NULL DEFAULT 'Restituita' COMMENT 'Tipologia dell''evento',
PRIMARY KEY (`esmIDsimEvent`),
UNIQUE KEY `esmIDsimEvent` (`esmIDsimEvent`),
KEY `FK_SIMEvents-SIMs` (`esmIDsim`),
KEY `FK_SIMEvents-Lavoratori` (`esmIDlavoratore`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='Tabella con tutti gli eventi riferiti alle SIM aziendali.';
Fields:
Tab: SIMEvents = ['esmIDsimEvent', 'esmIDsim', 'esmIDlavoratore', 'esmDescrizione', 'esmData', 'esmTipologia'];
*/
use CodeIgniter\Model;
class SIMEvents_Model extends Model {
//--------------------------------------------------------------------
// Property
protected $table = 'SIMEvents';
protected $primaryKey = 'esmIDsimEvent';
protected $returnType = 'App\Entities\SIMEvnt';
//protected $returnType = 'array';
protected $allowedFields = ['esmIDsim', 'esmIDlavoratore', 'esmDescrizione', 'esmData', 'esmTipologia'];
protected $useSoftDeletes = false;
protected $useTimestamps = false;
//protected $createdField = 'spCreatedAt';
//protected $updatedField = 'spUpdatedAt';
//protected $deletedField = 'spDeletedAt';
//--------------------------------------------------------------------
// Events
//protected $beforeInsert = ['beforeInsert'];
//protected $afterInsert = ['afterInsert'];
//protected $beforeUpdate = ['beforeUpdate'];
//protected $afterUpdate = ['afterUpdate'];
//protected $beforeDelete = ['beforeDelete'];
//protected $afterDelete = ['afterDelete'];
//protected $afterFind = ['afterFind'];
//--------------------------------------------------------------------
// Methods
//--------------------------------------------------------------------
}//class SIMEvents_Model
+82
View File
@@ -0,0 +1,82 @@
<?php namespace App\Models;
/*
CREATE TABLE IF NOT EXISTS `SIMs` (
`smIDsim` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Identificativo univoco della SIM telefonica',
`smNumero` varchar(16) NOT NULL COMMENT 'Numero telefonico della SIM',
`smPIN` varchar(16) NOT NULL COMMENT 'Pin della SIM',
`smPUK` varchar(16) NOT NULL COMMENT 'Puk della SIM',
`smDescrizione` text NOT NULL COMMENT 'Descrizione dell''articolo',
`smCredito` float NOT NULL DEFAULT 0 COMMENT 'Valore stimato del credito nella SIM',
`smCreatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Timestamp di inserimento del record nel database',
`smUpdatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Timestamp in cui il record è stato aggiornato',
`smStato` enum('Disponibile','In uso','Scaduta') NOT NULL DEFAULT 'Disponibile' COMMENT 'Stato della SIM, riassume gli eventi',
`smDeletedAt` timestamp NULL DEFAULT NULL COMMENT 'Timestamp in cui il record è stato virtualmente cancellato (senza delete reale)',
PRIMARY KEY (`smIDsim`),
UNIQUE KEY `smIDsim` (`smIDsim`),
UNIQUE KEY `smNumero` (`smNumero`, `smDeletedAt`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Tabella con tutte le SIM aziendali.';
Fields:
Tab: SIMs = ['smIDsim', 'smNumero', 'smPIN', 'smPUK', 'smDescrizione', 'smCredito', 'smCreatedAt', 'smUpdatedAt', 'smStato', 'smDeletedAt'];
*/
use CodeIgniter\Model;
class SIMs_Model extends Model {
//--------------------------------------------------------------------
// Property
protected $table = 'SIMs';
protected $primaryKey = 'smIDsim';
protected $returnType = 'App\Entities\SIM';
//protected $returnType = 'array';
protected $allowedFields = ['smNumero', 'smPIN', 'smPUK', 'smDescrizione', 'smCredito', 'smStato'];
protected $useSoftDeletes = true;
protected $useTimestamps = true;
protected $createdField = 'smCreatedAt';
protected $updatedField = 'smUpdatedAt';
protected $deletedField = 'smDeletedAt';
//--------------------------------------------------------------------
// Events
//protected $beforeInsert = ['beforeInsert'];
//protected $afterInsert = ['afterInsert'];
//protected $beforeUpdate = ['beforeUpdate'];
//protected $afterUpdate = ['afterUpdate'];
//protected $beforeDelete = ['beforeDelete'];
//protected $afterDelete = ['afterDelete'];
//protected $afterFind = ['afterFind'];
//--------------------------------------------------------------------
// Methods
//--------------------------------------------------------------------
}//class SIMs_Model
Loaded 100 of 371 files, more files were not shown because too many files have changed in this diff. Show more