MERGE_TEST_FIRST_LIVE_RELEASE

This commit is contained in:
Venba 2025-02-28 05:13:13 +00:00
commit 63a077e3e5
2706 changed files with 764637 additions and 41 deletions

5
.cpanel.yml Executable file
View File

@ -0,0 +1,5 @@
---
deployment:
tasks:
- export DEPLOYPATH=home/venbaehn/public_html/nhance/devauto
- /bin/cp /home/venbaehn/repositories/nhance_dev/* $DEPLOYPATH -r

67
.gitignore vendored Normal file → Executable file
View File

@ -1,50 +1,35 @@
# These are some examples of commonly ignored file patterns.
# You should customize this list as applicable to your project.
# Learn more about .gitignore:
# https://www.atlassian.com/git/tutorials/saving-changes/gitignore
#-------------------------
# Temporary Files
#-------------------------
writable/cache/*
!writable/cache/.gitkeep
# Node artifact files
node_modules/
dist/
writable/logs/*
!writable/logs/.gitkeep
# Compiled Java class files
*.class
writable/session/*
!writable/session/.gitkeep
# Compiled Python bytecode
*.py[cod]
writable/uploads/*
!writable/uploads/.gitkeep
# Log files
*.log
public/uploads/*
!public/uploads/.gitkeep
# Package files
*.jar
writable/debugbar/*
!writable/debugbar/.gitkeep
# Maven
target/
dist/
writable/**/*.db
writable/**/*.sqlite
# JetBrains IDE
.idea/
writable/e_card_template/*
!writable/e_card_template/.gitkeep
# Unit test reports
TEST*.xml
# Generated by MacOS
.DS_Store
# Generated by Windows
Thumbs.db
# Applications
*.app
*.exe
*.war
# Large media files
*.mp4
*.tiff
*.avi
*.flv
*.mov
*.wmv
writable/tmp/*
!writable/tmp/.gitkeep
vendor/
build/
composer.lock
.env
.phpunit*

67
.htaccess Executable file
View File

@ -0,0 +1,67 @@
# Disable directory browsing
Options -Indexes
# ----------------------------------------------------------------------
# Rewrite engine
# ----------------------------------------------------------------------
# Turning on the rewrite engine is necessary for the following rules and features.
# FollowSymLinks must be enabled for this to work.
<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On
# If you installed CodeIgniter in a subfolder, you will need to
# change the following line to match the subfolder you need.
# http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritebase
# RewriteBase /
# Redirect Trailing Slashes...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Rewrite "www.example.com -> example.com"
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
# Checks to see if the user is attempting to access a valid file,
# such as an image or css document, if this isn't true it sends the
# request to the front controller, index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\s\S]*)$ public/$1 [L,NC,QSA]
# Ensure Authorization header is passed along
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/js "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType application/javascript "access 1 month"
ExpiresByType application/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 2 days"
</IfModule>
<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
ErrorDocument 404 index.php
</IfModule>
# Disable server signature start
ServerSignature Off
# Disable server signature end

2
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,2 @@
{
}

22
LICENSE Executable file
View File

@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2014-2019 British Columbia Institute of Technology
Copyright (c) 2019-2023 CodeIgniter Foundation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

0
README.md Normal file → Executable file
View File

6
app/.htaccess Executable file
View File

@ -0,0 +1,6 @@
<IfModule authz_core_module>
Require all denied
</IfModule>
<IfModule !authz_core_module>
Deny from all
</IfModule>

15
app/Common.php Executable file
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 framework's
* 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
*
* @see: https://codeigniter.com/user_guide/extending/common.html
*/

180
app/Config/App.php Executable file
View File

@ -0,0 +1,180 @@
<?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/
*/
public string $baseURL = 'http://localhost/nhance/';
/**
* Allowed Hostnames in the Site URL other than the hostname in the baseURL.
* If you want to accept multiple Hostnames, set this.
*
* E.g. When your site URL ($baseURL) is 'http://example.com/', and your site
* also accepts 'http://media.example.com/' and
* 'http://accounts.example.com/':
* ['media.example.com', 'accounts.example.com']
*
* @var list<string>
*/
public array $allowedHostnames = [];
/**
* --------------------------------------------------------------------------
* 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 string $indexPage = 'index.php';
public $compressOutput = true;
/**
* --------------------------------------------------------------------------
* URI PROTOCOL
* --------------------------------------------------------------------------
*
* This item determines which server 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 string $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 string $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 bool $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.
*
* IncomingRequest::setLocale() also uses this list.
*
* @var string[]
*/
public array $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()
*
* @see https://www.php.net/manual/en/timezones.php for list of timezones supported by PHP.
*/
public string $appTimezone = 'UTC';
/**
* --------------------------------------------------------------------------
* 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 string $charset = 'UTF-8';
/**
* --------------------------------------------------------------------------
* Force Global Secure Requests
* --------------------------------------------------------------------------
*
* 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 bool $forceGlobalSecureRequests = 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
* X-Forwarded-For or Client-IP in order to properly identify
* the visitor's IP address.
*
* You need to set a proxy IP address or IP address with subnets and
* the HTTP header for the client IP address.
*
* Here are some examples:
* [
* '10.0.1.200' => 'X-Forwarded-For',
* '192.168.5.0/24' => 'X-Real-IP',
* ]
*
* @var array<string, string>
*/
public array $proxyIPs = [];
/**
* --------------------------------------------------------------------------
* 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:
*
* @see http://www.html5rocks.com/en/tutorials/security/content-security-policy/
* @see http://www.w3.org/TR/CSP/
*/
public bool $CSPEnabled = false;
}

103
app/Config/Autoload.php Executable file
View File

@ -0,0 +1,103 @@
<?php
namespace Config;
use CodeIgniter\Config\AutoloadConfig;
/**
* -------------------------------------------------------------------
* AUTOLOADER CONFIGURATION
* -------------------------------------------------------------------
*
* 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.
*
* NOTE: This class is required prior to Autoloader instantiation,
* and does not extend BaseConfig.
*
* @immutable
*/
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<string, array<int, string>|string>
* @phpstan-var array<string, string|list<string>>
*/
public $psr4 = [
APP_NAMESPACE => APPPATH, // For custom app namespace
'Config' => APPPATH . 'Config',
'Helpers' => APPPATH . 'Helpers'
];
/**
* -------------------------------------------------------------------
* 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<string, string>
*/
public $classmap = [];
/**
* -------------------------------------------------------------------
* Files
* -------------------------------------------------------------------
* The files array provides a list of paths to __non-class__ files
* that will be autoloaded. This can be useful for bootstrap operations
* or for loading functions.
*
* Prototype:
* $files = [
* '/path/to/my/file.php',
* ];
*
* @var string[]
* @phpstan-var list<string>
*/
public $files = [];
/**
* -------------------------------------------------------------------
* Helpers
* -------------------------------------------------------------------
* Prototype:
* $helpers = [
* 'form',
* ];
*
* @var string[]
* @phpstan-var list<string>
*/
public $helpers = ['uuid','session','utility', 'form', 'url', 'oauth', 'fileupload', 'excel_import_export', 'file', 'drive','ExcelSanitizeHelper'];
}

34
app/Config/Boot/development.php Executable file
View File

@ -0,0 +1,34 @@
<?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.
|
| If you set 'display_errors' to '1', CI4's detailed error report will show.
*/
error_reporting(E_ALL);
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);

23
app/Config/Boot/production.php Executable file
View File

@ -0,0 +1,23 @@
<?php
/*
|--------------------------------------------------------------------------
| ERROR DISPLAY
|--------------------------------------------------------------------------
| Don't show ANY in production environments. Instead, let the system catch
| it and display a generic error message.
|
| If you set 'display_errors' to '1', CI4's detailed error report will show.
*/
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);

38
app/Config/Boot/test.php Executable file
View File

@ -0,0 +1,38 @@
<?php
/*
* The environment testing is reserved for PHPUnit testing. It has special
* conditions built into the framework at various places to assist with that.
* You cant use it for your development.
*/
/*
|--------------------------------------------------------------------------
| 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(E_ALL);
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);

38
app/Config/Boot/testing.php Executable file
View File

@ -0,0 +1,38 @@
<?php
/*
* The environment testing is reserved for PHPUnit testing. It has special
* conditions built into the framework at various places to assist with that.
* You cant use it for your development.
*/
/*
|--------------------------------------------------------------------------
| 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(E_ALL);
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);

38
app/Config/Boot/uat.php Executable file
View File

@ -0,0 +1,38 @@
<?php
/*
* The environment testing is reserved for PHPUnit testing. It has special
* conditions built into the framework at various places to assist with that.
* You cant use it for your development.
*/
/*
|--------------------------------------------------------------------------
| 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(E_ALL);
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);

20
app/Config/CURLRequest.php Executable file
View File

@ -0,0 +1,20 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class CURLRequest extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* CURLRequest Share Options
* --------------------------------------------------------------------------
*
* Whether share options between requests or not.
*
* If true, all the options won't be reset between requests.
* It may cause an error request with unnecessary headers.
*/
public bool $shareOptions = false;
}

171
app/Config/Cache.php Executable file
View File

@ -0,0 +1,171 @@
<?php
namespace Config;
use CodeIgniter\Cache\CacheInterface;
use CodeIgniter\Cache\Handlers\DummyHandler;
use CodeIgniter\Cache\Handlers\FileHandler;
use CodeIgniter\Cache\Handlers\MemcachedHandler;
use CodeIgniter\Cache\Handlers\PredisHandler;
use CodeIgniter\Cache\Handlers\RedisHandler;
use CodeIgniter\Cache\Handlers\WincacheHandler;
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 string $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 string $backupHandler = 'dummy';
/**
* --------------------------------------------------------------------------
* Cache Directory Path
* --------------------------------------------------------------------------
*
* The path to where cache files should be stored, if using a file-based
* system.
*
* @deprecated Use the driver-specific variant under $file
*/
public string $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.
* ['q'] = Enabled, but only take into account the specified list
* of query parameters.
*
* @var bool|string[]
*/
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 string $prefix = '';
/**
* --------------------------------------------------------------------------
* Default TTL
* --------------------------------------------------------------------------
*
* The default number of seconds to save items when none is specified.
*
* WARNING: This is not used by framework handlers where 60 seconds is
* hard-coded, but may be useful to projects and modules. This will replace
* the hard-coded value in a future release.
*/
public int $ttl = 60;
/**
* --------------------------------------------------------------------------
* Reserved Characters
* --------------------------------------------------------------------------
*
* A string of reserved characters that will not be allowed in keys or tags.
* Strings that violate this restriction will cause handlers to throw.
* Default: {}()/\@:
*
* NOTE: The default set is required for PSR-6 compliance.
*/
public string $reservedCharacters = '{}()/\@:';
/**
* --------------------------------------------------------------------------
* File settings
* --------------------------------------------------------------------------
* Your file storage preferences can be specified below, if you are using
* the File driver.
*
* @var array<string, int|string|null>
*/
public array $file = [
'storePath' => WRITEPATH . 'cache/',
'mode' => 0640,
];
/**
* -------------------------------------------------------------------------
* 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
*
* @var array<string, bool|int|string>
*/
public array $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.
*
* @var array<string, int|string|null>
*/
public array $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.
*
* @var array<string, class-string<CacheInterface>>
*/
public array $validHandlers = [
'dummy' => DummyHandler::class,
'file' => FileHandler::class,
'memcached' => MemcachedHandler::class,
'predis' => PredisHandler::class,
'redis' => RedisHandler::class,
'wincache' => WincacheHandler::class,
];
}

117
app/Config/Constants.php Executable file
View File

@ -0,0 +1,117 @@
<?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', 2_592_000);
defined('YEAR') || define('YEAR', 31_536_000);
defined('DECADE') || define('DECADE', 315_360_000);
/*
| --------------------------------------------------------------------------
| 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
/**
* @deprecated Use \CodeIgniter\Events\Events::PRIORITY_LOW instead.
*/
define('EVENT_PRIORITY_LOW', 200);
/**
* @deprecated Use \CodeIgniter\Events\Events::PRIORITY_NORMAL instead.
*/
define('EVENT_PRIORITY_NORMAL', 100);
/**
* @deprecated Use \CodeIgniter\Events\Events::PRIORITY_HIGH instead.
*/
define('EVENT_PRIORITY_HIGH', 10);
/**
* @User Role Constant
*/
define('ENROLLMENT_TEAM_ID', '1');
define('CLAIMS_TEAM_ID', '2');
define('BUSINESS_TEAM_ID', '3');
define('FINANCE_TEAM_ID', '4');
define('SALES_TEAM_ID', '5');
define('MANAGEMENT_TEAM_ID', '6');
/**
* @User Teams Constant
*/
define('ADMIN_ROLE_ID', 1);
define('MANAGER_ROLE_ID', 2);
define('ACCOUNT_MANAGER_ROLE_ID', 3);
define('STAFF_ROLE_ID', 4);
define('HEAD_ROLE_ID', 5);

View File

@ -0,0 +1,176 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* 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:
*
* @see https://www.html5rocks.com/en/tutorials/security/content-security-policy/
*/
class ContentSecurityPolicy extends BaseConfig
{
// -------------------------------------------------------------------------
// Broadbrush CSP management
// -------------------------------------------------------------------------
/**
* Default CSP report context
*/
public bool $reportOnly = false;
/**
* Specifies a URL where a browser will send reports
* when a content security policy is violated.
*/
public ?string $reportURI = null;
/**
* Instructs user agents to rewrite URL schemes, changing
* HTTP to HTTPS. This directive is for websites with
* large numbers of old URLs that need to be rewritten.
*/
public bool $upgradeInsecureRequests = false;
// -------------------------------------------------------------------------
// Sources allowed
// NOTE: once you set a policy to 'none', it cannot be further restricted
// -------------------------------------------------------------------------
/**
* Will default to self if not overridden
*
* @var string|string[]|null
*/
public $defaultSrc;
/**
* Lists allowed scripts' URLs.
*
* @var string|string[]
*/
public $scriptSrc = 'self';
/**
* Lists allowed stylesheets' URLs.
*
* @var string|string[]
*/
public $styleSrc = 'self';
/**
* Defines the origins from which images can be loaded.
*
* @var string|string[]
*/
public $imageSrc = 'self';
/**
* Restricts the URLs that can appear in a page's `<base>` element.
*
* Will default to self if not overridden
*
* @var string|string[]|null
*/
public $baseURI;
/**
* Lists the URLs for workers and embedded frame contents
*
* @var string|string[]
*/
public $childSrc = 'self';
/**
* Limits the origins that you can connect to (via XHR,
* WebSockets, and EventSource).
*
* @var string|string[]
*/
public $connectSrc = 'self';
/**
* Specifies the origins that can serve web fonts.
*
* @var string|string[]
*/
public $fontSrc;
/**
* Lists valid endpoints for submission from `<form>` tags.
*
* @var string|string[]
*/
public $formAction = 'self';
/**
* Specifies the sources that can embed the current page.
* This directive applies to `<frame>`, `<iframe>`, `<embed>`,
* and `<applet>` tags. This directive can't be used in
* `<meta>` tags and applies only to non-HTML resources.
*
* @var string|string[]|null
*/
public $frameAncestors;
/**
* The frame-src directive restricts the URLs which may
* be loaded into nested browsing contexts.
*
* @var array|string|null
*/
public $frameSrc;
/**
* Restricts the origins allowed to deliver video and audio.
*
* @var string|string[]|null
*/
public $mediaSrc;
/**
* Allows control over Flash and other plugins.
*
* @var string|string[]
*/
public $objectSrc = 'self';
/**
* @var string|string[]|null
*/
public $manifestSrc;
/**
* Limits the kinds of plugins a page may invoke.
*
* @var string|string[]|null
*/
public $pluginTypes;
/**
* List of actions allowed.
*
* @var string|string[]|null
*/
public $sandbox;
/**
* Nonce tag for style
*/
public string $styleNonceTag = '{csp-style-nonce}';
/**
* Nonce tag for script
*/
public string $scriptNonceTag = '{csp-script-nonce}';
/**
* Replace nonce tag automatically
*/
public bool $autoNonce = true;
}

107
app/Config/Cookie.php Executable file
View File

@ -0,0 +1,107 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use DateTimeInterface;
class Cookie extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Cookie Prefix
* --------------------------------------------------------------------------
*
* Set a cookie name prefix if you need to avoid collisions.
*/
public string $prefix = '';
/**
* --------------------------------------------------------------------------
* Cookie Expires Timestamp
* --------------------------------------------------------------------------
*
* Default expires timestamp for cookies. Setting this to `0` will mean the
* cookie will not have the `Expires` attribute and will behave as a session
* cookie.
*
* @var DateTimeInterface|int|string
*/
public $expires = 0;
/**
* --------------------------------------------------------------------------
* Cookie Path
* --------------------------------------------------------------------------
*
* Typically will be a forward slash.
*/
public string $path = '/';
/**
* --------------------------------------------------------------------------
* Cookie Domain
* --------------------------------------------------------------------------
*
* Set to `.your-domain.com` for site-wide cookies.
*/
public string $domain = '';
/**
* --------------------------------------------------------------------------
* Cookie Secure
* --------------------------------------------------------------------------
*
* Cookie will only be set if a secure HTTPS connection exists.
*/
public bool $secure = false;
/**
* --------------------------------------------------------------------------
* Cookie HTTPOnly
* --------------------------------------------------------------------------
*
* Cookie will only be accessible via HTTP(S) (no JavaScript).
*/
public bool $httponly = true;
/**
* --------------------------------------------------------------------------
* Cookie SameSite
* --------------------------------------------------------------------------
*
* Configure cookie SameSite setting. Allowed values are:
* - None
* - Lax
* - Strict
* - ''
*
* Alternatively, you can use the constant names:
* - `Cookie::SAMESITE_NONE`
* - `Cookie::SAMESITE_LAX`
* - `Cookie::SAMESITE_STRICT`
*
* Defaults to `Lax` for compatibility with modern browsers. Setting `''`
* (empty string) means default SameSite attribute set by browsers (`Lax`)
* will be set on cookies. If set to `None`, `$secure` must also be set.
*
* @phpstan-var 'None'|'Lax'|'Strict'|''
*/
public string $samesite = 'Lax';
/**
* --------------------------------------------------------------------------
* Cookie Raw
* --------------------------------------------------------------------------
*
* This flag allows setting a "raw" cookie, i.e., its name and value are
* not URL encoded using `rawurlencode()`.
*
* If this is set to `true`, cookie names should be compliant of RFC 2616's
* list of allowed characters.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#attributes
* @see https://tools.ietf.org/html/rfc2616#section-2.2
*/
public bool $raw = false;
}

85
app/Config/Database.php Executable file
View File

@ -0,0 +1,85 @@
<?php
namespace Config;
use CodeIgniter\Database\Config;
/**
* Database Configuration
*/
class Database extends Config
{
/**
* The directory that holds the Migrations
* and Seeds directories.
*/
public string $filesPath = APPPATH . 'Database' . DIRECTORY_SEPARATOR;
/**
* Lets you choose which connection group to
* use if no other is specified.
*/
public string $defaultGroup = 'default';
/**
* The default database connection.
*/
public array $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => '',
'password' => '',
'database' => '',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => true,
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
'numberNative' => false,
];
/**
* This database connection is used when
* running PHPUnit database tests.
*/
public array $tests = [
'DSN' => '',
'hostname' => '119.18.54.85',
'username' => 'venbaehn_nhance_user1',
'password' => 'iM~X7(cR+}A-',
'database' => 'venbaehn_nhance',
'DBDriver' => 'SQLite3',
'DBPrefix' => 'db_', // Needed to ensure we're working correctly with prefixes live. DO NOT REMOVE FOR CI DEVS
'pConnect' => false,
'DBDebug' => true,
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
'foreignKeys' => true,
'busyTimeout' => 1000,
];
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';
}
}
}

46
app/Config/DocTypes.php Executable file
View File

@ -0,0 +1,46 @@
<?php
namespace Config;
/**
* @immutable
*/
class DocTypes
{
/**
* List of valid document types.
*
* @var array<string, string>
*/
public array $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">',
];
/**
* Whether to remove the solidus (`/`) character for void HTML elements (e.g. `<input>`)
* for HTML5 compatibility.
*
* Set to:
* `true` - to be HTML5 compatible
* `false` - to be XHTML compatible
*/
public bool $html5 = true;
}

131
app/Config/Email.php Executable file
View File

@ -0,0 +1,131 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Email extends BaseConfig
{
public string $fromEmail = '';
public string $fromName = '';
public string $recipients = '';
/**
* The "user agent"
*/
public string $userAgent = 'CodeIgniter';
/**
* The mail sending protocol: mail, sendmail, smtp
*/
public string $protocol = 'smtp';
/**
* The server path to Sendmail.
*/
public string $mailPath = '/usr/sbin/sendmail';
/**
* SMTP Server Hostname
*/
public string $SMTPHost = 'smtp.gmail.com';
/**
* SMTP Username
*/
public string $SMTPUser = 'venbatechnologies@gmail.com';
/**
* SMTP Password
*/
public string $SMTPPass = 'dsfllmxdzxxkcxgz';
/**
* SMTP Port
*/
public int $SMTPPort = 465;
/**
* SMTP Timeout (in seconds)
*/
public int $SMTPTimeout = 1000;
/**
* Enable persistent SMTP connections
*/
public bool $SMTPKeepAlive = false;
/**
* SMTP Encryption.
*
* @var string '', 'tls' or 'ssl'. 'tls' will issue a STARTTLS command
* to the server. 'ssl' means implicit SSL. Connection on port
* 465 should set this to ''.
*/
public string $SMTPCrypto = 'ssl';
/**
* Enable word-wrap
*/
public bool $wordWrap = true;
/**
* Character count to wrap at
*/
public int $wrapChars = 76;
/**
* Type of mail, either 'text' or 'html'
*/
public string $mailType = 'html';
/**
* Character set (utf-8, iso-8859-1, etc.)
*/
public string $charset = 'UTF-8';
/**
* Whether to validate the email address
*/
public bool $validate = false;
/**
* Email Priority. 1 = highest. 5 = lowest. 3 = normal
*/
public int $priority = 3;
/**
* Newline character. (Use “\r\n” to comply with RFC 822)
*/
public string $CRLF = "\r\n";
/**
* Newline character. (Use “\r\n” to comply with RFC 822)
*/
public string $newline = "\r\n";
/**
* Enable BCC Batch Mode.
*/
public bool $BCCBatchMode = false;
/**
* Number of emails in each BCC batch
*/
public int $BCCBatchSize = 200;
/**
* Enable notify message from server
*/
public bool $DSN = false;
/**
* SMTP Debugging level. Set to 0 to disable debugging.
* Set to 1 to output server connection status only.
* Set to 2 for more detailed debugging output.
* Set to 3 for maximum debugging output.
*/
public int $SMTPDebug = 2;
}

92
app/Config/Encryption.php Executable file
View File

@ -0,0 +1,92 @@
<?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 string $key = '';
/**
* --------------------------------------------------------------------------
* Encryption Driver to Use
* --------------------------------------------------------------------------
*
* One of the supported encryption drivers.
*
* Available drivers:
* - OpenSSL
* - Sodium
*/
public string $driver = 'OpenSSL';
/**
* --------------------------------------------------------------------------
* SodiumHandler's Padding Length in Bytes
* --------------------------------------------------------------------------
*
* This is the number of bytes that will be padded to the plaintext message
* before it is encrypted. This value should be greater than zero.
*
* See the user guide for more information on padding.
*/
public int $blockSize = 16;
/**
* --------------------------------------------------------------------------
* Encryption digest
* --------------------------------------------------------------------------
*
* HMAC digest to use, e.g. 'SHA512' or 'SHA256'. Default value is 'SHA512'.
*/
public string $digest = 'SHA512';
/**
* Whether the cipher-text should be raw. If set to false, then it will be base64 encoded.
* This setting is only used by OpenSSLHandler.
*
* Set to false for CI3 Encryption compatibility.
*/
public bool $rawData = true;
/**
* Encryption key info.
* This setting is only used by OpenSSLHandler.
*
* Set to 'encryption' for CI3 Encryption compatibility.
*/
public string $encryptKeyInfo = '';
/**
* Authentication key info.
* This setting is only used by OpenSSLHandler.
*
* Set to 'authentication' for CI3 Encryption compatibility.
*/
public string $authKeyInfo = '';
/**
* Cipher to use.
* This setting is only used by OpenSSLHandler.
*
* Set to 'AES-128-CBC' to decrypt encrypted data that encrypted
* by CI3 Encryption default configuration.
*/
public string $cipher = 'AES-256-CTR';
}

55
app/Config/Events.php Executable file
View File

@ -0,0 +1,55 @@
<?php
namespace Config;
use CodeIgniter\Events\Events;
use CodeIgniter\Exceptions\FrameworkException;
use CodeIgniter\HotReloader\HotReloader;
/*
* --------------------------------------------------------------------
* 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', static function () {
if (ENVIRONMENT !== 'testing') {
if (ini_get('zlib.output_compression')) {
throw FrameworkException::forEnabledZlibOutputCompression();
}
while (ob_get_level() > 0) {
ob_end_flush();
}
ob_start(static fn ($buffer) => $buffer);
}
/*
* --------------------------------------------------------------------
* Debug Toolbar Listeners.
* --------------------------------------------------------------------
* If you delete, they will no longer be collected.
*/
if (CI_DEBUG && ! is_cli()) {
Events::on('DBQuery', 'CodeIgniter\Debug\Toolbar\Collectors\Database::collect');
Services::toolbar()->respond();
// Hot Reload route - for framework use on the hot reloader.
if (ENVIRONMENT === 'development') {
Services::routes()->get('__hot-reload', static function () {
(new HotReloader())->run();
});
}
}
});

104
app/Config/Exceptions.php Executable file
View File

@ -0,0 +1,104 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Debug\ExceptionHandler;
use CodeIgniter\Debug\ExceptionHandlerInterface;
use Psr\Log\LogLevel;
use Throwable;
/**
* Setup how the exception handler works.
*/
class Exceptions extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* LOG EXCEPTIONS?
* --------------------------------------------------------------------------
* If true, then exceptions will be logged
* through Services::Log.
*
* Default: true
*/
public bool $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 array $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 string $errorViewPath = APPPATH . 'Views/errors';
/**
* --------------------------------------------------------------------------
* HIDE FROM DEBUG TRACE
* --------------------------------------------------------------------------
* Any data that you would like to hide from the debug trace.
* In order to specify 2 levels, use "/" to separate.
* ex. ['server', 'setup/password', 'secret_token']
*/
public array $sensitiveDataInTrace = [];
/**
* --------------------------------------------------------------------------
* LOG DEPRECATIONS INSTEAD OF THROWING?
* --------------------------------------------------------------------------
* By default, CodeIgniter converts deprecations into exceptions. Also,
* starting in PHP 8.1 will cause a lot of deprecated usage warnings.
* Use this option to temporarily cease the warnings and instead log those.
* This option also works for user deprecations.
*/
public bool $logDeprecations = true;
/**
* --------------------------------------------------------------------------
* LOG LEVEL THRESHOLD FOR DEPRECATIONS
* --------------------------------------------------------------------------
* If `$logDeprecations` is set to `true`, this sets the log level
* to which the deprecation will be logged. This should be one of the log
* levels recognized by PSR-3.
*
* The related `Config\Logger::$threshold` should be adjusted, if needed,
* to capture logging the deprecations.
*/
public string $deprecationLogLevel = LogLevel::WARNING;
/*
* DEFINE THE HANDLERS USED
* --------------------------------------------------------------------------
* Given the HTTP status code, returns exception handler that
* should be used to deal with this error. By default, it will run CodeIgniter's
* default handler and display the error information in the expected format
* for CLI, HTTP, or AJAX requests, as determined by is_cli() and the expected
* response format.
*
* Custom handlers can be returned if you want to handle one or more specific
* error codes yourself like:
*
* if (in_array($statusCode, [400, 404, 500])) {
* return new \App\Libraries\MyExceptionHandler();
* }
* if ($exception instanceOf PageNotFoundException) {
* return new \App\Libraries\MyExceptionHandler();
* }
*/
public function handler(int $statusCode, Throwable $exception): ExceptionHandlerInterface
{
return new ExceptionHandler($this);
}
}

30
app/Config/Feature.php Executable file
View File

@ -0,0 +1,30 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Enable/disable backward compatibility breaking features.
*/
class Feature extends BaseConfig
{
/**
* Enable multiple filters for a route or not.
*
* If you enable this:
* - CodeIgniter\CodeIgniter::handleRequest() uses:
* - CodeIgniter\Filters\Filters::enableFilters(), instead of enableFilter()
* - CodeIgniter\CodeIgniter::tryToRouteIt() uses:
* - CodeIgniter\Router\Router::getFilters(), instead of getFilter()
* - CodeIgniter\Router\Router::handle() uses:
* - property $filtersInfo, instead of $filterInfo
* - CodeIgniter\Router\RouteCollection::getFiltersForRoute(), instead of getFilterForRoute()
*/
public bool $multipleFilters = false;
/**
* Use improved new auto routing instead of the default legacy version.
*/
public bool $autoRoutesImproved = false;
}

80
app/Config/Filters.php Executable file
View File

@ -0,0 +1,80 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Filters\CSRF;
use CodeIgniter\Filters\DebugToolbar;
use CodeIgniter\Filters\Honeypot;
use CodeIgniter\Filters\InvalidChars;
use CodeIgniter\Filters\SecureHeaders;
use App\Filters\AuthMVC;
use App\Filters\HttpRequestLog;
use App\Filters\CloseDbConnection;
use App\Filters\AuthJWT;
class Filters extends BaseConfig
{
/**
* Configures aliases for Filter classes to
* make reading things nicer and simpler.
*
* @var array<string, array<int, string>|string> [filter_name => classname]
* or [filter_name => [classname1, classname2, ...]]
* @phpstan-var array<string, class-string|list<class-string>>
*/
public array $aliases = [
'csrf' => CSRF::class,
'toolbar' => DebugToolbar::class,
'honeypot' => Honeypot::class,
'invalidchars' => InvalidChars::class,
'secureheaders' => SecureHeaders::class,
'authMVC' => AuthMVC::class,
'HttpRequestLog' => HttpRequestLog::class,
'authJWT' => AuthJWT::class,
'CloseDbConnection' => CloseDbConnection::class
];
/**
* List of filter aliases that are always
* applied before and after every request.
*
* @var array<string, array<string, array<string, string>>>|array<string, array<string>>
* @phpstan-var array<string, list<string>>|array<string, array<string, array<string, string>>>
*/
public array $globals = [
'before' => [
'HttpRequestLog' => ['except' => 'cli/*'],
// 'csrf',
// 'invalidchars',
],
'after' => [
'CloseDbConnection'
// 'secureheaders',
],
];
/**
* List of filter aliases that works on a
* particular HTTP method (GET, POST, etc.).
*
* Example:
* 'post' => ['foo', 'bar']
*
* If you use this, you should disable auto-routing because auto-routing
* permits any HTTP method to access a controller. Accessing the controller
* with a method you don't expect could bypass the filter.
*/
public array $methods = [];
/**
* List of filter aliases that should run on any
* before or after URI patterns.
*
* Example:
* 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']]
*/
public array $filters = [];
}

View File

@ -0,0 +1,12 @@
<?php
namespace Config;
use CodeIgniter\Config\ForeignCharacters as BaseForeignCharacters;
/**
* @immutable
*/
class ForeignCharacters extends BaseForeignCharacters
{
}

77
app/Config/Format.php Executable file
View File

@ -0,0 +1,77 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Format\FormatterInterface;
use CodeIgniter\Format\JSONFormatter;
use CodeIgniter\Format\XMLFormatter;
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.
*
* @var string[]
*/
public array $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.
*
* @var array<string, string>
*/
public array $formatters = [
'application/json' => JSONFormatter::class,
'application/xml' => XMLFormatter::class,
'text/xml' => XMLFormatter::class,
];
/**
* --------------------------------------------------------------------------
* Formatters Options
* --------------------------------------------------------------------------
*
* Additional Options to adjust default formatters behaviour.
* For each mime type, list the additional options that should be used.
*
* @var array<string, int>
*/
public array $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.
*
* @return FormatterInterface
*
* @deprecated This is an alias of `\CodeIgniter\Format\Format::getFormatter`. Use that instead.
*/
public function getFormatter(string $mime)
{
return Services::format()->getFormatter($mime);
}
}

42
app/Config/Generators.php Executable file
View File

@ -0,0 +1,42 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Generators extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Generator Commands' Views
* --------------------------------------------------------------------------
*
* This array defines the mapping of generator commands to the view files
* they are using. If you need to customize them for your own, copy these
* view files in your own folder and indicate the location here.
*
* You will notice that the views have special placeholders enclosed in
* curly braces `{...}`. These placeholders are used internally by the
* generator commands in processing replacements, thus you are warned
* not to delete them or modify the names. If you will do so, you may
* end up disrupting the scaffolding process and throw errors.
*
* YOU HAVE BEEN WARNED!
*
* @var array<string, string>
*/
public array $views = [
'make:cell' => 'CodeIgniter\Commands\Generators\Views\cell.tpl.php',
'make:cell_view' => 'CodeIgniter\Commands\Generators\Views\cell_view.tpl.php',
'make:command' => 'CodeIgniter\Commands\Generators\Views\command.tpl.php',
'make:config' => 'CodeIgniter\Commands\Generators\Views\config.tpl.php',
'make:controller' => 'CodeIgniter\Commands\Generators\Views\controller.tpl.php',
'make:entity' => 'CodeIgniter\Commands\Generators\Views\entity.tpl.php',
'make:filter' => 'CodeIgniter\Commands\Generators\Views\filter.tpl.php',
'make:migration' => 'CodeIgniter\Commands\Generators\Views\migration.tpl.php',
'make:model' => 'CodeIgniter\Commands\Generators\Views\model.tpl.php',
'make:seeder' => 'CodeIgniter\Commands\Generators\Views\seeder.tpl.php',
'make:validation' => 'CodeIgniter\Commands\Generators\Views\validation.tpl.php',
'session:migration' => 'CodeIgniter\Commands\Generators\Views\migration.tpl.php',
];
}

42
app/Config/Honeypot.php Executable file
View File

@ -0,0 +1,42 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Honeypot extends BaseConfig
{
/**
* Makes Honeypot visible or not to human
*/
public bool $hidden = true;
/**
* Honeypot Label Content
*/
public string $label = 'Fill This Field';
/**
* Honeypot Field Name
*/
public string $name = 'honeypot';
/**
* Honeypot HTML Template
*/
public string $template = '<label>{label}</label><input type="text" name="{name}" value="">';
/**
* Honeypot container
*
* If you enabled CSP, you can remove `style="display:none"`.
*/
public string $container = '<div style="display:none">{template}</div>';
/**
* The id attribute for Honeypot container tag
*
* Used when CSP is enabled.
*/
public string $containerId = 'hpc';
}

31
app/Config/Images.php Executable file
View File

@ -0,0 +1,31 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Images\Handlers\GDHandler;
use CodeIgniter\Images\Handlers\ImageMagickHandler;
class Images extends BaseConfig
{
/**
* Default handler used if no other handler is specified.
*/
public string $defaultHandler = 'gd';
/**
* The path to the image library.
* Required for ImageMagick, GraphicsMagick, or NetPBM.
*/
public string $libraryPath = '/usr/local/bin/convert';
/**
* The available handler classes.
*
* @var array<string, string>
*/
public array $handlers = [
'gd' => GDHandler::class,
'imagick' => ImageMagickHandler::class,
];
}

66
app/Config/Kint.php Executable file
View File

@ -0,0 +1,66 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use Kint\Parser\ConstructablePluginInterface;
use Kint\Renderer\AbstractRenderer;
use Kint\Renderer\Rich\TabPluginInterface;
use Kint\Renderer\Rich\ValuePluginInterface;
/**
* --------------------------------------------------------------------------
* Kint
* --------------------------------------------------------------------------
*
* We use Kint's `RichRenderer` and `CLIRenderer`. This area contains options
* that you can set to customize how Kint works for you.
*
* @see https://kint-php.github.io/kint/ for details on these settings.
*/
class Kint extends BaseConfig
{
/*
|--------------------------------------------------------------------------
| Global Settings
|--------------------------------------------------------------------------
*/
/**
* @var list<class-string<ConstructablePluginInterface>|ConstructablePluginInterface>|null
*/
public $plugins;
public int $maxDepth = 6;
public bool $displayCalledFrom = true;
public bool $expanded = false;
/*
|--------------------------------------------------------------------------
| RichRenderer Settings
|--------------------------------------------------------------------------
*/
public string $richTheme = 'aante-light.css';
public bool $richFolder = false;
public int $richSort = AbstractRenderer::SORT_FULL;
/**
* @var array<string, class-string<ValuePluginInterface>>|null
*/
public $richObjectPlugins;
/**
* @var array<string, class-string<TabPluginInterface>>|null
*/
public $richTabPlugins;
/*
|--------------------------------------------------------------------------
| CLI Settings
|--------------------------------------------------------------------------
*/
public bool $cliColors = true;
public bool $cliForceUTF8 = false;
public bool $cliDetectWidth = true;
public int $cliMinWidth = 40;
}

148
app/Config/Logger.php Executable file
View File

@ -0,0 +1,148 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Log\Handlers\FileHandler;
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.
*
* @var array|int
*/
public $threshold = (ENVIRONMENT === 'production') ? 4 : 9;
/**
* --------------------------------------------------------------------------
* 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 string $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 array $handlers = [
/*
* --------------------------------------------------------------------
* File Handler
* --------------------------------------------------------------------
*/
FileHandler::class => [
// 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'],
// ],
/*
* The ErrorlogHandler writes the logs to PHP's native `error_log()` function.
* Uncomment this block to use it.
*/
// 'CodeIgniter\Log\Handlers\ErrorlogHandler' => [
// /* The log levels this handler can handle. */
// 'handles' => ['critical', 'alert', 'emergency', 'debug', 'error', 'info', 'notice', 'warning'],
//
// /*
// * The message type where the error should go. Can be 0 or 4, or use the
// * class constants: `ErrorlogHandler::TYPE_OS` (0) or `ErrorlogHandler::TYPE_SAPI` (4)
// */
// 'messageType' => 0,
// ],
];
}

50
app/Config/Migrations.php Executable file
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.
*
* You should enable migrations whenever you intend to do a schema migration
* and disable it back when you're done.
*/
public bool $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
* files have already been run.
*/
public string $table = 'migrations';
/**
* --------------------------------------------------------------------------
* Timestamp Format
* --------------------------------------------------------------------------
*
* This is the format that will be used when creating new migrations
* using the CLI command:
* > php spark make:migration
*
* NOTE: if you set an unsupported format, migration runner will not find
* your migration files.
*
* Supported formats:
* - YmdHis_
* - Y-m-d-His_
* - Y_m_d_His_
*/
public string $timestampFormat = 'Y-m-d-His_';
}

534
app/Config/Mimes.php Executable file
View File

@ -0,0 +1,534 @@
<?php
namespace Config;
/**
* Mimes
*
* 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.
*
* When working with mime types, please make sure you have the ´fileinfo´
* extension enabled to reliably detect the media types.
*
* @immutable
*/
class Mimes
{
/**
* Map of extensions to mime types.
*/
public static array $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/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/vnd.microsoft.portable-executable',
'application/x-dosexec',
'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',
],
'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',
],
'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/vnd.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',
],
'webp' => 'image/webp',
'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',
],
'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
'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',
'image/svg',
'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',
],
'stl' => [
'application/sla',
'application/vnd.ms-pki.stl',
'application/x-navistyle',
],
];
/**
* Attempts to determine the best mime type for the given file 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|null $proposedExtension - 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 $proposedExtension = null)
{
$type = trim(strtolower($type), '. ');
$proposedExtension = trim(strtolower($proposedExtension ?? ''));
if (
$proposedExtension !== ''
&& array_key_exists($proposedExtension, static::$mimes)
&& in_array($type, (array) static::$mimes[$proposedExtension], true)
) {
// The detected mime type matches with the proposed extension.
return $proposedExtension;
}
// Reverse check the mime type list if no extension was proposed.
// This search is order sensitive!
foreach (static::$mimes as $ext => $types) {
if (in_array($type, (array) $types, true)) {
return $ext;
}
}
return null;
}
}

84
app/Config/Modules.php Executable file
View File

@ -0,0 +1,84 @@
<?php
namespace Config;
use CodeIgniter\Modules\Modules as BaseModules;
/**
* Modules Configuration.
*
* NOTE: This class is required prior to Autoloader instantiation,
* and does not extend BaseConfig.
*
* @immutable
*/
class Modules extends BaseModules
{
/**
* --------------------------------------------------------------------------
* Enable Auto-Discovery?
* --------------------------------------------------------------------------
*
* If true, then auto-discovery will happen across all elements listed in
* $aliases below. If false, no auto-discovery will happen at all,
* giving a slight performance boost.
*
* @var bool
*/
public $enabled = true;
/**
* --------------------------------------------------------------------------
* Enable Auto-Discovery Within Composer Packages?
* --------------------------------------------------------------------------
*
* If true, then auto-discovery will happen across all namespaces loaded
* by Composer, as well as the namespaces configured locally.
*
* @var bool
*/
public $discoverInComposer = true;
/**
* The Composer package list for Auto-Discovery
* This setting is optional.
*
* E.g.:
* [
* 'only' => [
* // List up all packages to auto-discover
* 'codeigniter4/shield',
* ],
* ]
* or
* [
* 'exclude' => [
* // List up packages to exclude.
* 'pestphp/pest',
* ],
* ]
*
* @var array{only?: list<string>, exclude?: list<string>}
*/
public $composerPackages = [];
/**
* --------------------------------------------------------------------------
* Auto-Discovery 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.
*
* @var list<string>
*/
public $aliases = [
'events',
'filters',
'registrars',
'routes',
'services',
];
}

37
app/Config/Pager.php Executable file
View File

@ -0,0 +1,37 @@
<?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;
*
* @var array<string, string>
*/
public array $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 int $perPage = 20;
}

80
app/Config/Paths.php Executable file
View File

@ -0,0 +1,80 @@
<?php
namespace Config;
/**
* Paths
*
* Holds the paths that are used by the system to
* locate the main directories, app, system, etc.
*
* Modifying these allows you to restructure your application,
* share a system folder between multiple applications, and more.
*
* All paths are relative to the project's root folder.
*
* NOTE: This class is required prior to Autoloader instantiation,
* and does not extend BaseConfig.
*
* @immutable
*/
class Paths
{
/**
* ---------------------------------------------------------------
* SYSTEM FOLDER NAME
* ---------------------------------------------------------------
*
* This must contain the name of your "system" folder. Include
* the path if the folder is not in the same directory as this file.
*/
public string $systemDirectory = __DIR__ . '/../../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 server. If
* you do, use a full server path.
*
* @see http://codeigniter.com/user_guide/general/managing_apps.html
*/
public string $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 string $writableDirectory = __DIR__ . '/../../writable';
/**
* ---------------------------------------------------------------
* TESTS DIRECTORY NAME
* ---------------------------------------------------------------
*
* This variable must contain the name of your "tests" directory.
*/
public string $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 string $viewDirectory = __DIR__ . '/../Views';
}

28
app/Config/Publisher.php Executable file
View File

@ -0,0 +1,28 @@
<?php
namespace Config;
use CodeIgniter\Config\Publisher as BasePublisher;
/**
* Publisher Configuration
*
* Defines basic security restrictions for the Publisher class
* to prevent abuse by injecting malicious files into a project.
*/
class Publisher extends BasePublisher
{
/**
* A list of allowed destinations with a (pseudo-)regex
* of allowed files for each destination.
* Attempts to publish to directories not in this list will
* result in a PublisherException. Files that do no fit the
* pattern will cause copy/merge to fail.
*
* @var array<string, string>
*/
public $restrictions = [
ROOTPATH => '*',
FCPATH => '#\.(s?css|js|map|html?|xml|json|webmanifest|ttf|eot|woff2?|gif|jpe?g|tiff?|png|webp|bmp|ico|svg)$#i',
];
}

489
app/Config/Routes.php Executable file
View File

@ -0,0 +1,489 @@
<?php
use CodeIgniter\Router\RouteCollection;
/**
* @var RouteCollection $routes
*/
$routes->get('/swagger', 'SwaggerController::index', ['filter' => 'authMVC']);
// Reminder Mail Notification
$routes->get("reminder_mail", "NotificationController::reminder_mail");
$routes->get("getClientData", "ClientController::getClientData");
$routes->get("testing_for_review_mail/(:any)", "ClientController::testingForReviewMail/$1");
$routes->get("update-policy-terms-for-corrections", "ClientController::updatePolicyTermsForCorrections");
$routes->get("update_rack_rate_json", "ClientController::updateRackRateJson");
$routes->get("updatajson", "EmpDataServiceController::updatajson");
$routes->get("view", "EmployeeController::viewECard/$1");
// $routes->get("exportQCRandRFQ", "LeadsController::exportQCRandRFQ");
$routes->get("smapletest", "ClientController::smapletest");
$routes->get("testMailAttachments", "ClientController::testMailAttachments");
$routes->get("updatePolicyTermsKey", "ClientController::updatePolicyTermsKey");
$routes->get("updateRemainderDate", "ClientController::updateRemainderDate");
$routes->get("sendCroneRemainderMail", "DashboardController::sendCroneRemainderMail");
$routes->get("sendextraparam", "ClientController::sendextraparam");
// $routes->post("iAgreeForAddOn", "EmployeeRestController::iAgreeForAddOn");
// $routes->get("sendCroneRemainderMail", "DashboardController::sendCroneRemainderMail");
// $routes->post("employeeUpload", "EmployeeRestController::employeeUpload");
$routes->post("add_advertise_image", "AppContentManagementController::add_advertise_image");
$routes->get("add_image_index", "AppContentManagementController::add_image_index");
$routes->get("getAdvertiseImage/(:any)", "AppContentManagementController::getAdvertiseImage/$1");
$routes->get("frontend_content", "AppContentManagementController::frontend_content");
// $routes->get('/', 'LoginController::index');
$routes->get('/test', 'Home::index');
$routes->get('/login', 'LoginController::index'); ///auth/google
$routes->get('/logout', 'LoginController::logout');
$routes->get('/oauth2callback', 'LoginController::receiveGoogleOAuthResponse');
$routes->get('/auth/google', 'LoginController::initiateGoogleOAuth');
$routes->get('/update-emp-policy-status', 'ClientController::updateEmpAndPolicyStatus');
$routes->get('download-e-card/(:any)', 'EmployeeController::generateIDCardForEmployee/$1');
$routes->get('download-kyc-docs/(:segment)', 'ClientController::downloadKYCDocument/$1');
$routes->group("/user", ["filter" => "authMVC"], function ($routes) {
$routes->post("create", "UserController::create");
$routes->get("create", "UserController::create");
$routes->post("edit", "UserController::edit");
$routes->get("list", "UserController::list");
$routes->get("getuser/(:hash)", "UserController::getuser/$1");
$routes->get("deactive/(:hash)", "UserController::deactive/$1");
$routes->get("rolesandteams", "UserController::getRolesAndTeams");
});
$routes->group("/dashboard", ["filter" => "authMVC"], function ($routes) {
$routes->get("view", "DashboardController::dashboard");
$routes->get('get-notification', 'DashboardController::getDashboardNotifications');
$routes->get('acknowledge-notification/(:segment)', 'DashboardController::acknowledgeMessage/$1');
$routes->get('get-pending-action', 'PendingActionsController::getPendingActions');
});
$routes->group("/client", ["filter" => "authMVC"], function ($routes) {
$routes->get("list", "ClientController::index");
$routes->get("create", "ClientController::clientOnboarding");
$routes->get('deposit/(:num)', 'ClientController::deposit/$1');
$routes->get('remove/(:num)', 'ClientController::removeClient/$1');
$routes->get("list/(:any)", "ClientController::editClientOnboarding/$1");
// application/config/routes.php
// Add a route for the view_Deposit method
$routes->get('view_deposit/(:num)', 'ClientController::view_Deposit/$1');
$routes->get('createtransaction', 'ClientController::createtransaction');
$routes->post('save_deposit', 'ClientController::saveDeposit');
// $routes->get('view_Deposit/(:num)/(:num)','ClientController/view_Deposit/$1/$2');
$routes->group("notification", ["filter" => "authMVC"], function ($routes) {
$routes->post("create", "NotificationController::createNotification");
$routes->post("update_enable", "NotificationController::update_enable");
$routes->post("add_attachment", "NotificationController::insertAttachmentsForMailTemplates");
$routes->get("getMailTemplateData/(:any)/(:any)", "NotificationController::getMailTemplateData/$1/$2");
$routes->get("removeAttachment/(:any)", "NotificationController::removeAttachmentsForMailTemplates/$1");
});
$routes->group("general", ["filter" => "authMVC"], function ($routes) {
$routes->post("create", "ClientController::createClientGeneralInfo");
$routes->post("edit", "ClientController::editClientGeneralInfo");
});
$routes->group("branch", ["filter" => "authMVC"], function ($routes) {
$routes->post("create", "ClientController::createClientBranch");
$routes->post("edit", "ClientController::editClientBranch");
$routes->get("list/(:any)", "ClientController::getSingleBranchDataById/$1");
$routes->get("remove/(:any)", "ClientController::removeClientBranch/$1");
});
$routes->group("relation", ["filter" => "authMVC"], function ($routes) {
$routes->post("create", "ClientController::createClientRelation");
$routes->post("edit", "ClientController::editClientRelation");
});
$routes->group("policy", ["filter" => "authMVC"], function ($routes) {
$routes->post("create", "ClientController::createClientPolicy");
$routes->post("edit", "ClientController::editClientPolicy");
$routes->get("list/(:any)", "ClientController::getClientPolicyById/$1");
$routes->post("policyGMCTerms", "ClientController::policyGMCTerms");
$routes->get("getterms", "ClientController::getterms");
$routes->get("remove/(:any)", "ClientController::removePolicy/$1");
});
$routes->group("kyc", ["filter" => "authMVC"], function ($routes) {
$routes->post("create", "ClientController::createClientKYCInfo");
$routes->post("edit", "ClientController::editClientKYCInfo");
$routes->get("list/(:any)", "ClientController::getKycDocsById/$1");
$routes->get("delete/(:any)", "ClientController::deleteClientKycDocs/$1");
});
$routes->group("premimum", ["filter" => "authMVC"], function ($routes) {
$routes->post("create", "ClientController::createClientPolicyPremium");
$routes->post("edit", "ClientController::editClientPolicyPremium");
});
$routes->group("terms", ["filter" => "authMVC"], function ($routes) {
$routes->post("gpa_create", "ClientController::policyGPATerms");
$routes->post("edit", "ClientController::editClientPolicyPremium");
$routes->post("other_terms", "ClientController::otherPolicyTermsFormSubmit");
});
$routes->group("vehicle", ["filter" => "authMVC"], function ($routes) {
$routes->post("create", "ClientController::uploadVehicleFile");
$routes->post("edit", "ClientController::editUploadVehicleFile");
$routes->get("list/(:any)", "ClientController::listVehicleFiles/$1");
$routes->get("delete/(:any)", "ClientController::deleteVehicleFiles/$1");
});
$routes->group("others", ["filter" => "authMVC"], function ($routes) {
$routes->post("create", "ClientController::createOtherTabContent");
});
});
$routes->group("/employee", ["filter" => "authMVC"], function ($routes) {
$routes->get("list", "EmployeeController::list");
$routes->get("search", "EmployeeController::search");
$routes->get("upload", "EmployeeController::employeesUplodWithEvents");
$routes->post("upload", "EmployeeController::employeesUplodWithEvents");
$routes->get("excel_error/(:any)", "EmployeeController::getExcelFileErrors/$1");
$routes->get("endorsement-list", "EmployeeController::endorsementList");
$routes->match(['get','post'],'enrollment-list','EmployeeController::enrollmentClientList');
$routes->get("empby_client_clientbranch/(:any)/(:any)", "EmployeeController::empby_client_clientbranch/$1/$2");
$routes->get("truncate/(:any)", "EmployeeController::truncateFileData/$1");
$routes->get("test-rack-rate", "EmployeeController::testRackRate");
$routes->post("test-rack-rate", "EmployeeController::testRackRate");
$routes->get('test_members_list', 'EmployeeController::test_members_list');
});
$routes->group("/master", ["filter" => "authMVC"], function ($routes) {
$routes->group("insurer", ["filter" => "authMVC"], function ($routes) {
$routes->get("list", "MasterController::insurerList");
$routes->get("remove/(:any)", "MasterController::insurerRemove/$1");
$routes->get("create", "MasterController::insurerOnboarding");
$routes->post("createpost", "MasterController::createInsurerGeneralInfo");
$routes->post("edit", "MasterController::editInsurerGeneralInfo");
$routes->get("list/(:any)", "MasterController::editInsurerOnboarding/$1");
$routes->group("branch", ["filter" => "authMVC"], function ($routes) {
$routes->post("create", "MasterController::createInsurerBranch");
$routes->post("edit", "MasterController::editInsurerBranch");
$routes->get("editget/(:any)", "MasterController::editInsurerGet/$1");
$routes->get("list/(:any)", "MasterController::insurerBranchList/$1");
$routes->get("remove/(:any)", "MasterController::removeInsurerBranch/$1");
});
});
$routes->group("tpa", ["filter" => "authMVC"], function ($routes) {
$routes->get("list", "MasterController::tpaList");
$routes->get("create", "MasterController::tpaOnboarding");
$routes->post("createpost", "MasterController::createTPAGeneralInfo");
$routes->post("edit", "MasterController::editTPAGeneralInfo");
$routes->get("list/(:any)", "MasterController::editTPAOnboarding/$1");
$routes->get("remove/(:any)", "MasterController::tpaRemove/$1");
$routes->group("branch", ["filter" => "authMVC"], function ($routes) {
$routes->post("create", "MasterController::createTPABranch");
$routes->get("editget/(:any)", "MasterController::editTPAGet/$1");
$routes->post("edit", "MasterController::editTPABranch");
$routes->get("list/(:any)", "MasterController::tpaBranchList/$1");
$routes->get("remove/(:any)", "MasterController::removeTPABranch/$1");
});
});
$routes->group("kyc", ["filter" => "authMVC"], function ($routes) {
$routes->get("list", "MasterController::kycList");
$routes->get("create", "MasterController::kycOnboarding");
$routes->post("createpost", "MasterController::createKYCInfo");
$routes->post("edit", "MasterController::editKYCInfo");
$routes->get("list/(:any)", "MasterController::editKYCOnboarding/$1");
$routes->get("remove/(:any)", "MasterController::kycRemove/$1");
$routes->get("delete/(:any)", "MasterController::deleteClientKycDocs/$1");
$routes->group("kycdocs", ["filter" => "authMVC"], function ($routes) {
$routes->post("createpost", "MasterController::createKycDocs");
$routes->get("editget/(:any)", "MasterController::editKYCGet/$1");
$routes->post("edit", "MasterController::editKYCDocs");
// $routes->get("list", "MasterController::tpaBranchList");
$routes->get("list/(:any)", "MasterController::kycDocsList/$1");
$routes->get("remove/(:any)", "MasterController::removeKYCDocs/$1");
});
});
$routes->group("policy", ["filter" => "authMVC"], function ($routes) {
$routes->get("list", "MasterController::policyTypeList");
$routes->get("create", "MasterController::policyTypeOnboarding");
$routes->post("createpost", "MasterController::createPolicyType");
$routes->post("edit", "MasterController::editPolicyType");
$routes->get("list/(:any)", "MasterController::editPolicyTypeOnboarding/$1");
$routes->get("remove/(:any)", "MasterController::policyTypeRemove/$1");
$routes->group("policies", ["filter" => "authMVC"], function ($routes) {
$routes->post("createpost", "MasterController::createPolicies");
$routes->get("editget/(:any)", "MasterController::editPoliciesGet/$1");
$routes->post("edit", "MasterController::editPolicies");
$routes->get("list", "MasterController::tpaBranchList");
$routes->get("list/(:any)", "MasterController::policesList/$1");
$routes->get("remove/(:any)", "MasterController::removePolicyPolicies/$1");
});
});
$routes->group("cash_deposite", ["filter" => "authMVC"], function ($routes) {
$routes->get("list", "MasterController::CDMasterList");
$routes->post("create", "MasterController::createCDMasterData");
$routes->post("edit", "MasterController::editCDMasterData");
$routes->get("list/(:any)", "MasterController::getCDMasterDataByID/$1");
$routes->get("remove/(:any)", "MasterController::removeCDMaster/$1");
});
$routes->group("vehicle", ["filter" => "authMVC"], function ($routes) {
$routes->get("list", "MasterController::VehicleMasterList");
$routes->get("list/(:any)", "MasterController::getVehicleMasterDataByID/$1");
$routes->get("remove/(:any)", "MasterController::deactiveVehicleData/$1");
});
});
$routes->group("/util", ["filter" => "authMVC"], function ($routes) {
$routes->get("clients-with-policies", "EmployeeController::getClientWithPolicies");
$routes->get("police-by-insurer/(:any)", "ClientController::getPolicesByInsurerId/$1");
$routes->get("get-file-error/(:any)", "EmployeeController::getUploadedFileError/$1");
$routes->get("kyc-other-docs-delete/(:any)", "ClientController::deleteClientKycOtherDocs/$1");
$routes->get("policy-premium", "ClientController::getpolicyGridData/$1");
$routes->get("update-policy-status", "ClientController::updateClientPolicyStatus/$1");
$routes->get("download-excel/(:any)", "EmployeeController::downloadSampleExcelFile/$1");
$routes->get("get-emp-endorsement/(:any)", "EmployeeController::getEmpEndoresmentEntry/$1");
$routes->post("import-export", "EmployeeController::importExport");
$routes->get("featch-client-policy-list/(:any)", "ClientController::getClientPolicyList/$1");
$routes->get("download-file-list/(:any)", "EmployeeController::downloadFileList/$1");
$routes->get("featch-emp-list", "EmployeeController::featchEmpList/$1");
$routes->get("view-success-emp-list", "EmployeeController::viewUploadedEmployeeList/$1");
$routes->get("fetch-policy-for-policy-type", "ClientController::fetchPolicyDataForPolicyType/$1");
$routes->get("fetch-emp-count/(:any)", "EmployeeController::getEmpCount/$1");
$routes->get("init-Emp-onboard/(:any)", "EmployeeController::initiateManualEmployeesOnboardProcess/$1");
$routes->get("full-excel-error-file/(:any)", "EmployeeController::downloadFullExcelErrorFile/$1");
$routes->get("preview-card/(:any)", "EmployeeController::previewTemplate/$1");
$routes->get("export-import-error-list/(:any)", "EmployeeController::errorListExportImport/$1");
$routes->get("has_policy_config_completed/(:any)", "EmployeeController::hasPolicyConfigCompleted/$1");
$routes->get("get-client-branch/(:any)", "ClientController::getClientBranch/$1");
$routes->get("get-client-details/(:any)", "ClientController::getClientAllDetailsByUsingClientID/$1");
$routes->get("delete-additional-rack-rate/(:any)", "ClientController::deleteAdditionalRackRate/$1");
$routes->get("check_cd_ac_no/(:any)", "MasterController::checkUniqueCDAccountNumber/$1");
$routes->get("get_cd_ac/(:any)", "ClientController::get_cd_ac/$1");
$routes->get("check_policy_type/(:any)", "ClientController::checkPolicyType/$1");
$routes->get("getPolicyTerms/(:any)", "ClientController::getPolicyTerms/$1");
$routes->get("getPolicyTermsFormJson/(:any)", "ClientController::getPolicyTermsFormJson/$1");
$routes->get("checkHRNumber/(:any)", "ClientController::checkHRNumber/$1");
$routes->get("check_addition_premium_JSON/(:any)", "ClientController::checkAdditionPremiumJSON/$1");
$routes->get("get_policy_type_for_base_policy/(:any)", "ClientController::getPolicyTypeForBasePolicy/$1");
$routes->get("get_client_details/(:any)", "ClientController::getClientDetails/$1");
$routes->get("featch_dashboard_data/(:any)", "DashboardController::featch_dashboard_data/$1");
$routes->get("remove_rack_rate/(:any)", "ClientController::removeRackRate/$1");
$routes->get("rename_rack_rate_tab/(:any)", "ClientController::renameRackRateTab/$1");
$routes->post("create_excel_template", "MasterController::createExcelTemplate");
$routes->get("get_insurer_by_export_templete", "MasterController::getInsurerByExportTemplete");
$routes->get("copy_insurer_templete/(:any)", "MasterController::copyInsurerTemplete/$1");
$routes->get("get_single_excel_template/(:any)", "MasterController::getSingleExcelTemplate/$1");
$routes->get("dublicate_template/(:any)", "MasterController::duplicateTemplate/$1");
$routes->get("getBranchByClientID/(:any)", "ClientController::getBranchByClientID/$1");
$routes->get("getPolicyDetailsByPolicyId/(:any)", "ClientController::getPolicyDetailsByPolicyId/$1");
$routes->get("getClientAndBranchAndPolicy", "ClientController::getClientAndBranchAndPolicy");
$routes->get("getCDAccNoByClientAndInsurer/(:any)", "ClientController::getCDAccNoByClientAndInsurer/$1");
$routes->post("createClientWithMinimalData", "ClientController::createClientWithMinimalData");
$routes->post("createVehicleWithMinimalData", "ClientController::createVehicleWithMinimalData");
$routes->post("createClientBranchWithMinamalData", "ClientController::createClientBranchWithMinamalData");
$routes->post("createClientPolicyWithMinimalData", "ClientController::createClientPolicyWithMinimalData");
$routes->post("createCDAccountNumberUsingAjax", "MasterController::createCDAccountNumberUsingAjax");
$routes->post("drive_file_upload", "PolicyTransactionController::uploadFile");
$routes->post("updateInvoiceStatus", "PolicyTransactionController::updateInvoiceStatus");
$routes->get("remove_co_share_data/(:any)", "PolicyTransactionController::removeCoShareData/$1");
$routes->get("check_cost_center/(:any)", "ClientController::check_cost_center/$1");
$routes->get("getPTCOShareCount/(:any)", "PolicyTransactionController::getPTCOShareCount/$1");
$routes->get("test_mail", "MasterController::testGmailAPI");
$routes->post("test_mail", "MasterController::testGmailAPI");
$routes->get("check_policy_no/(:any)", "ClientController::check_policy_no/$1");
$routes->get("get_client_policy_data_using_policy_no/(:any)", "ClientController::get_client_policy_data_using_policy_no/$1");
$routes->get("get_client_policy_data_using_policy_no_and_endo_no/(:any)", "ClientController::get_client_policy_data_using_policy_no_and_endo_no/$1");
$routes->get("checkInvoiceStatus/(:any)", "PolicyTransactionController::checkInvoiceStatus/$1");
$routes->get("base_policy_for_policy_inception/(:any)", "PolicyTransactionController::getBasePolicy/$1");
$routes->get("sentTestMail/(:any)", "NotificationController::sentTestMail/$1");
$routes->get("send_manual_reminder/(:any)", "DashboardController::sendManualReminder/$1");
$routes->get("send_manual_ecard/(:any)", "DashboardController::sendManualEcard/$1");
$routes->get("get_client_policy_list_for_remainder/(:any)", "EmployeeController::get_client_policy_list_for_remainder/$1");
$routes->get("get_client_branch_data/(:any)", "ClientController::get_client_branch_data/$1");
$routes->get("getLevelContects", "LeadsController::getLevelContects");
$routes->get("get_emp_master_data_for_update/(:any)", "EmployeeController::get_emp_master_data_for_update/$1");
$routes->get("send_mail_for_individual_employee_ecard/(:any)", "EmployeeController::send_mail_for_individual_employee_ecard/$1");
$routes->post("update_emp_data", "EmployeeController::update_emp_data");
$routes->get("checkDeletionGetDataFunction", "EmployeeController::checkDeletionGetDataFunction");
$routes->get("download_import_excel/(:any)", "EmployeeController::downloadSampleImportExcelFile/$1");
$routes->get("getInsurerBranchContacts/(:any)", "LeadsController::getInsurerBranchContacts/$1");
$routes->get("download_import_file/(:any)", "EmployeeController::download_import_file/$1");
$routes->get('log_list', 'EmployeeController::listLogs');
$routes->get('view_log/(:any)', 'EmployeeController::viewLog/$1');
$routes->get('download_log/(:any)', 'EmployeeController::downloadLog/$1');
$routes->post('checkDuplicateTableFieldValue', 'ClientController::checkDuplicateTableFieldValue');
$routes->get('getCoShareStatementDetails/(:any)', 'PolicyTransactionController::getCoShareStatementDetails/$1');
$routes->get('getClientPolicyDataBasedOnClientAndInsuer', 'PolicyTransactionController::getClientPolicyDataBasedOnClientAndInsuer');
$routes->get('checkCDAmountForBasePremium', 'PolicyTransactionController::checkCDAmountForBasePremium');
$routes->post('map_employees', 'EmployeeController::mapEmployees');
$routes->post('get_data_for_mapping', 'EmployeeController::getDataForMapping');
$routes->post('unmap_employees/(:num)', 'EmployeeController::unmapEmployees/$1');
$routes->get('transformMailContent', 'LeadsController::transformMailContent');
$routes->get('getRackRateSIAmountAndAutoSiDataForAutoSI', 'ClientController::getRackRateSIAmountAndAutoSiDataForAutoSI');
$routes->post('createAutoSI', 'ClientController::createAutoSI');
$routes->get('getPolicySIRacketData','ClientController::getPolicySIRacketData');
$routes->get('fetchPolicySIDataForParentPolicy','ClientController::fetchPolicySIDataForParentPolicy');
$routes->post('saveSIMapping','ClientController::saveSIMapping');
$routes->post('checkSIMapping','ClientController::checkSIMapping');
$routes->post('deleteMapping','ClientController::deleteMapping');
});
$routes->group("policy_tranction", ["filter" => "authMVC"], function ($routes) {
$routes->group("inception", ["filter" => "authMVC"], function ($routes) {
$routes->get("list", "PolicyTransactionController::viewInception");
$routes->post("create", "PolicyTransactionController::createInceptionPolicy");
$routes->get("list/(:any)", "PolicyTransactionController::getInceptionDataForEdit/$1");
$routes->get("remove/(:any)", "PolicyTransactionController::removeCDMaster/$1");
$routes->get("removePolicyTransaction/(:any)", "PolicyTransactionController::removePolicyTransaction/$1");
});
$routes->group("endorsement", ["filter" => "authMVC"], function ($routes) {
$routes->get("list", "PolicyTransactionController::viewEndorsement");
$routes->post("create", "PolicyTransactionController::createEndorsementPolicy");
$routes->get("list/(:any)", "PolicyTransactionController::getEndorsementDataForEdit/$1");
$routes->get("remove/(:any)", "PolicyTransactionController::removeCDMaster/$1");
});
$routes->group("report", ["filter" => "authMVC"], function ($routes) {
$routes->get("list", "PolicyTransactionController::reportBDS");
$routes->get("report-varience-list", "PolicyTransactionController::reportVarience");
$routes->get("report-business-list", "PolicyTransactionController::reportBusinessList");
$routes->get("report-finance-list", "PolicyTransactionController::reportFinanceList");
$routes->get("report-outstanding-list", "PolicyTransactionController::reportOutstanding");
});
$routes->group("statement", ["filter" => "authMVC"], function ($routes) {
$routes->get("list", "PolicyTransactionController::statementList");
$routes->post("upload", "PolicyTransactionController::uploadInsurerStatement");
$routes->get("getPaymentDetails/(:any)", "PolicyTransactionController::getInvoicePaymentDetails/$1");
$routes->post("saveInvoicePaymentDetails", "PolicyTransactionController::saveInvoicePaymentDetails");
$routes->get("deletePaymentEntry/(:any)", "PolicyTransactionController::deletePaymentEntry/$1");
$routes->get("downloadSampleInsurerStatement", "PolicyTransactionController::downloadSampleInsurerStatement");
$routes->get("getFileErr/(:any)", "PolicyTransactionController::getFileErr/$1");
$routes->get("getInsurerStatementMonth", "PolicyTransactionController::getInsurerStatementMonth");
$routes->get("deleteStatement/(:any)", "PolicyTransactionController::deleteStatement/$1");
});
});
$routes->group("leads", ["filter" => "authMVC"], function ($routes) {
$routes->get("list", "LeadsController::viewLeadsList");
$routes->post("create", "LeadsController::createLead");
$routes->get("list/(:any)", "LeadsController::getLeadDataForEdit/$1");
$routes->get("sendMail", "LeadsController::sendMailWithAttachement");
$routes->post("sendMail", "LeadsController::sendMailWithAttachement");
$routes->get("exportQCRandRFQ/(:any)", "LeadsController::exportQCRandRFQ/$1");
$routes->get("featchLeadDataAndInsertClient/(:any)", "LeadsController::featchLeadDataAndInsertClient/$1");
$routes->get("featchClientPolicyFromLead/(:any)", "LeadsController::featchClientPolicyFromLead/$1");
});
$routes->group("rfq", ["filter" => "authMVC"], function ($routes) {
$routes->post("create", "LeadsController::createRFQ");
$routes->post("createQCR", "LeadsController::createQCR");
$routes->get("list/(:any)", "LeadsController::viewRFQ/$1");
});
$routes->get("driveListFiles", "GoogleDriveController::listFiles");
$routes->post('dmsSearch', 'PolicyTransactionController::dmsSearch', ['filter' => 'authMVC']);
$routes->get('dmsSearch', 'PolicyTransactionController::dmsSearch', ['filter' => 'authMVC']);
$routes->get('downloadGdriveFile', 'GoogleDriveController::downloadGdriveFile', ['filter' => 'authMVC']);
$routes->get('cli/sendZeptoMail', 'MasterController::testZeptoSMTP');
$routes->cli('cli/processjob', 'JobWorker::processJob');
$routes->cli('cli/processjobs', 'JobWorker::processJobs');
$routes->get("processjob", "JobWorker::processJob");
$routes->cli('cli/new_gmail_token', 'MasterController::generateNewGmailAPIToken');
$routes->cli('cli/send_mail_cli', 'MasterController::testGmailAPIViaCLI');
$routes->cli('cli/sendZeptoMail', 'MasterController::testZeptoSMTP');
$routes->cli('cli/check_bounce_mail_cli', 'MasterController::testCheckBounceMails');
$routes->cli('cli/app_check_list', 'MasterController::appCheckList');
$routes->cli('cli/new_gdrive_token', 'GoogleDriveController::generateNewGoogleDriveAccessToken');
//Employee login api's
$routes->post("/employeeRest/verifyEmployeeNumber", "RestAuthenticationController::verifyEmployeeWithMobileNumber");
$routes->post("/employeeRest/getVerifiedUserData", "RestAuthenticationController::getVerifiedUserData");
$routes->post("/employeeRest/verifyMpin", "RestAuthenticationController::verifyMpin");
$routes->post("/employeeRest/checkMpin", "RestAuthenticationController::checkMpin");
$routes->post("/employeeRest/verifyEmployeeEmailId", "RestAuthenticationController::verifyEmployeeWithEmailId");
//HR login api's
$routes->post("/employeeRest/verifyHrWithMobileNumber", "RestAuthenticationController::verifyHrWithMobileNumber");
$routes->post("/employeeRest/getVerifiedHrData", "RestAuthenticationController::getVerifiedHrData");
$routes->group("/api", ["filter" => "authJWT"], function ($routes) {
$routes->post("logined", "RestAuthenticationController::logined");
$routes->post("getId", "RestAuthenticationController::getUserIdFromToken");
});
$routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) {
$routes->post("getVerifiedUserData", "RestAuthenticationController::getVerifiedUserData");
$routes->post("storeFireBase", "EmployeeRestController::storeFireBase");
$routes->post("saveMpin", "RestAuthenticationController::saveMpin");
$routes->post("updateMpin", "RestAuthenticationController::updateMpin");
$routes->post("getChatResponse", "ChatBotController::getChatResponse");
$routes->get("getEmployeeProfile", "EmployeeRestController::getEmployeeProfile");
$routes->post("employeeUpload", "EmployeeRestController::employeeUpload");
$routes->get("relationshipList", "EmployeeRestController::relationshipList");
$routes->get("getEmployeeAndDependence", "EmployeeRestController::getEmployeeAndDependence");
$routes->post("editEmployeeAndDependence", "EmployeeRestController::editEmployeeAndDependence");
$routes->post("addEmployeeAndDependence", "EmployeeRestController::addEmployeeAndDependence");
$routes->get("getEmployeePolicy", "EmployeeRestController::getEmployeePolicy");
$routes->post("createOrUpdateEmployeePolicySiAmount", "EmployeeRestController::createOrUpdateEmployeePolicySiAmount");
$routes->get("deleteDependence", "EmployeeRestController::deleteDependence");
$routes->get("getEmployeeAndDependenceByClientId", "EmployeeRestController::getEmployeeAndDependenceByClientId");
$routes->get("getClientPolicy", "EmployeeRestController::getClientPolicy");
$routes->get("getClientDetails", "EmployeeRestController::getClientDetails");
$routes->get("getAddOnPolicy", "EmployeeRestController::getAddOnPolicy");
$routes->post("iAgreeForAddOn", "EmployeeRestController::iAgreeForAddOn");
$routes->get("exportDataByClientPolicyId", "EmployeeRestController::exportDataByClientPolicyId");
$routes->get("getCashDepositData", "EmployeeRestController::getCashDepositData");
$routes->get("exportCashDepositData", "EmployeeRestController::exportCashDepositData");
$routes->get("removeEmpAndEmpPolicyData", "EmployeeRestController::removeEmpAndEmpPolicyData");
$routes->post("calculatePremium", "EmployeeRestController::calculatePremium");
$routes->get("getEmployeeOldPolicy", "EmployeeRestController::getEmployeeOldPolicy");
$routes->get("getEmployeeActiveOrInactivePolicy", "EmployeeRestController::getEmployeeActiveOrInactivePolicy");
$routes->get("getFEContent", "EmployeeRestController::getFEContent");
$routes->get("getAdvertisementImage", "EmployeeRestController::getAdvertisementImage");
});
$routes->get("getEmployeeActiveOrInactivePolicy", "EmployeeRestController::getEmployeeActiveOrInactivePolicy");
$routes->get("sendPushNotification", "EmployeeRestController::sendPushNotification");
$routes->post("sendEmail", "EmployeeRestController::send_email");
$routes->get("getBackToEnrolledDetails", "EmployeeRestController::getBackToEnrolledDetails");
// Ticketing System
// Ticketing System End's

113
app/Config/Routing.php Executable file
View File

@ -0,0 +1,113 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Config;
use CodeIgniter\Config\Routing as BaseRouting;
/**
* Routing configuration
*/
class Routing extends BaseRouting
{
/**
* An array of files that contain route definitions.
* Route files are read in order, with the first match
* found taking precedence.
*
* Default: APPPATH . 'Config/Routes.php'
*/
public array $routeFiles = [
APPPATH . 'Config/Routes.php',
];
/**
* The default namespace to use for Controllers when no other
* namespace has been specified.
*
* Default: 'App\Controllers'
*/
public string $defaultNamespace = 'App\Controllers';
/**
* The default controller to use when no other controller has been
* specified.
*
* Default: 'Home'
*/
public string $defaultController = 'Home';
/**
* The default method to call on the controller when no other
* method has been set in the route.
*
* Default: 'index'
*/
public string $defaultMethod = 'index';
/**
* Whether to translate dashes in URIs to underscores.
* Primarily useful when using the auto-routing.
*
* Default: false
*/
public bool $translateURIDashes = false;
/**
* Sets the class/method that should be called if routing doesn't
* find a match. It can be either a closure or the controller/method
* name exactly like a route is defined: Users::index
*
* This setting is passed to the Router class and handled there.
*
* If you want to use a closure, you will have to set it in the
* class constructor or the routes file by calling:
*
* $routes->set404Override(function() {
* // Do something here
* });
*
* Example:
* public $override404 = 'App\Errors::show404';
*/
public ?string $override404 = null;
/**
* If TRUE, the system will attempt to match the URI against
* Controllers by matching each segment against folders/files
* in APPPATH/Controllers, when a match wasn't found against
* defined routes.
*
* If FALSE, will stop searching and do NO automatic routing.
*/
public bool $autoRoute = false;
/**
* If TRUE, will enable the use of the 'prioritize' option
* when defining routes.
*
* Default: false
*/
public bool $prioritize = false;
/**
* Map of URI segments and namespaces. For Auto Routing (Improved).
*
* The key is the first URI segment. The value is the controller namespace.
* E.g.,
* [
* 'blog' => 'Acme\Blog\Controllers',
* ]
*
* @var array [ uri_segment => namespace ]
*/
public array $moduleRoutes = [];
}

101
app/Config/Security.php Executable file
View File

@ -0,0 +1,101 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Security extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* CSRF Protection Method
* --------------------------------------------------------------------------
*
* Protection Method for Cross Site Request Forgery protection.
*
* @var string 'cookie' or 'session'
*/
public string $csrfProtection = 'cookie';
/**
* --------------------------------------------------------------------------
* CSRF Token Randomization
* --------------------------------------------------------------------------
*
* Randomize the CSRF Token for added security.
*/
public bool $tokenRandomize = true;
/**
* --------------------------------------------------------------------------
* CSRF Token Name
* --------------------------------------------------------------------------
*
* Token name for Cross Site Request Forgery protection.
*/
public string $tokenName = 'csrf_test_name';
/**
* --------------------------------------------------------------------------
* CSRF Header Name
* --------------------------------------------------------------------------
*
* Header name for Cross Site Request Forgery protection.
*/
public string $headerName = 'X-CSRF-TOKEN';
/**
* --------------------------------------------------------------------------
* CSRF Cookie Name
* --------------------------------------------------------------------------
*
* Cookie name for Cross Site Request Forgery protection.
*/
public string $cookieName = 'csrf_cookie_name';
/**
* --------------------------------------------------------------------------
* CSRF Expires
* --------------------------------------------------------------------------
*
* Expiration time for Cross Site Request Forgery protection cookie.
*
* Defaults to two hours (in seconds).
*/
public int $expires = 7200;
/**
* --------------------------------------------------------------------------
* CSRF Regenerate
* --------------------------------------------------------------------------
*
* Regenerate CSRF Token on every submission.
*/
public bool $regenerate = false;
/**
* --------------------------------------------------------------------------
* CSRF Redirect
* --------------------------------------------------------------------------
*
* Redirect to previous page with error on failure.
*/
public bool $redirect = true;
/**
* --------------------------------------------------------------------------
* CSRF SameSite
* --------------------------------------------------------------------------
*
* Setting for CSRF SameSite cookie token.
*
* Allowed values are: None - Lax - Strict - ''.
*
* Defaults to `Lax` as recommended in this link:
*
* @see https://portswigger.net/web-security/csrf/samesite-cookies
*
* @deprecated `Config\Cookie` $samesite property is used.
*/
public string $samesite = 'Lax';
}

84
app/Config/Services.php Executable file
View File

@ -0,0 +1,84 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseService;
use App\Libraries\Slug;
use App\Libraries\MyLogger;
use App\Libraries\GmailAPI;
use App\Libraries\MyGoogleDrive;
use App\Libraries\DataServiceSqlite;
use App\Controllers\Home;
/**
* 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 BaseService
{
public static function slug($getShared = true)
{
if ($getShared) {
return static::getSharedInstance('slug');
}
return new Slug();
}
public static function home($getShared = true)
{
if ($getShared) {
return static::getSharedInstance('home');
}
return new Home();
}
public static function mylogger($getShared = true)
{
if ($getShared) {
return static::getSharedInstance('mylogger');
}
return new MyLogger();
}
public static function dataServiceSqlite($getShared = true)
{
if ($getShared) {
return static::getSharedInstance('dataServiceSqlite');
}
return new DataServiceSqlite();
}
public static function gmailapi($getShared = true)
{
if ($getShared) {
return static::getSharedInstance('gmailapi');
}
return new GmailAPI();
}
public static function myGoogleDrive($getShared = true)
{
if ($getShared) {
return static::getSharedInstance('myGoogleDrive');
}
return new MyGoogleDrive();
}
}

102
app/Config/Session.php Executable file
View File

@ -0,0 +1,102 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Session\Handlers\BaseHandler;
use CodeIgniter\Session\Handlers\FileHandler;
class Session extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Session Driver
* --------------------------------------------------------------------------
*
* The session storage driver to use:
* - `CodeIgniter\Session\Handlers\FileHandler`
* - `CodeIgniter\Session\Handlers\DatabaseHandler`
* - `CodeIgniter\Session\Handlers\MemcachedHandler`
* - `CodeIgniter\Session\Handlers\RedisHandler`
*
* @var class-string<BaseHandler>
*/
public string $driver = FileHandler::class;
/**
* --------------------------------------------------------------------------
* Session Cookie Name
* --------------------------------------------------------------------------
*
* The session cookie name, must contain only [0-9a-z_-] characters
*/
public string $cookieName = 'ci_session';
/**
* --------------------------------------------------------------------------
* Session Expiration
* --------------------------------------------------------------------------
*
* The number of SECONDS you want the session to last.
* Setting to 0 (zero) means expire when the browser is closed.
*/
public int $expiration = 7200;
/**
* --------------------------------------------------------------------------
* Session Save Path
* --------------------------------------------------------------------------
*
* The location to save sessions to and is 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!
*/
public string $savePath = WRITEPATH . 'session';
/**
* --------------------------------------------------------------------------
* Session Match IP
* --------------------------------------------------------------------------
*
* 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.
*/
public bool $matchIP = false;
/**
* --------------------------------------------------------------------------
* Session Time to Update
* --------------------------------------------------------------------------
*
* How many seconds between CI regenerating the session ID.
*/
public int $timeToUpdate = 300;
/**
* --------------------------------------------------------------------------
* Session Regenerate Destroy
* --------------------------------------------------------------------------
*
* 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.
*/
public bool $regenerateDestroy = false;
/**
* --------------------------------------------------------------------------
* Session Database Group
* --------------------------------------------------------------------------
*
* DB Group for the database session.
*/
public ?string $DBGroup = null;
}

118
app/Config/Toolbar.php Executable file
View File

@ -0,0 +1,118 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Debug\Toolbar\Collectors\Database;
use CodeIgniter\Debug\Toolbar\Collectors\Events;
use CodeIgniter\Debug\Toolbar\Collectors\Files;
use CodeIgniter\Debug\Toolbar\Collectors\Logs;
use CodeIgniter\Debug\Toolbar\Collectors\Routes;
use CodeIgniter\Debug\Toolbar\Collectors\Timers;
use CodeIgniter\Debug\Toolbar\Collectors\Views;
/**
* --------------------------------------------------------------------------
* 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.
*/
class Toolbar extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Toolbar Collectors
* --------------------------------------------------------------------------
*
* List of toolbar collectors that will be called when Debug Toolbar
* fires up and collects data from.
*
* @var string[]
*/
public array $collectors = [
Timers::class,
Database::class,
Logs::class,
Views::class,
// \CodeIgniter\Debug\Toolbar\Collectors\Cache::class,
Files::class,
Routes::class,
Events::class,
];
/**
* --------------------------------------------------------------------------
* Collect Var Data
* --------------------------------------------------------------------------
*
* If set to false var data from the views will not be colleted. Useful to
* avoid high memory usage when there are lots of data passed to the view.
*/
public bool $collectVarData = true;
/**
* --------------------------------------------------------------------------
* Max History
* --------------------------------------------------------------------------
*
* `$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 int $maxHistory = 20;
/**
* --------------------------------------------------------------------------
* Toolbar Views Path
* --------------------------------------------------------------------------
*
* The full path to the the views that are used by the toolbar.
* This MUST have a trailing slash.
*/
public string $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 int $maxQueries = 100;
/**
* --------------------------------------------------------------------------
* Watched Directories
* --------------------------------------------------------------------------
*
* Contains an array of directories that will be watched for changes and
* used to determine if the hot-reload feature should reload the page or not.
* We restrict the values to keep performance as high as possible.
*
* NOTE: The ROOTPATH will be prepended to all values.
*/
public array $watchedDirectories = [
'app',
];
/**
* --------------------------------------------------------------------------
* Watched File Extensions
* --------------------------------------------------------------------------
*
* Contains an array of file extensions that will be watched for changes and
* used to determine if the hot-reload feature should reload the page or not.
*/
public array $watchedExtensions = [
'php', 'css', 'js', 'html', 'svg', 'json', 'env',
];
}

252
app/Config/UserAgents.php Executable file
View File

@ -0,0 +1,252 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* -------------------------------------------------------------------
* User Agents
* -------------------------------------------------------------------
*
* 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.
*/
class UserAgents extends BaseConfig
{
/**
* -------------------------------------------------------------------
* OS Platforms
* -------------------------------------------------------------------
*
* @var array<string, string>
*/
public array $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',
];
/**
* -------------------------------------------------------------------
* Browsers
* -------------------------------------------------------------------
*
* The order of this array should NOT be changed. Many browsers return
* multiple browser types so we want to identify the subtype first.
*
* @var array<string, string>
*/
public array $browsers = [
'OPR' => 'Opera',
'Flock' => 'Flock',
'Edge' => 'Spartan',
'Edg' => 'Edge',
'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',
];
/**
* -------------------------------------------------------------------
* Mobiles
* -------------------------------------------------------------------
*
* @var array<string, string>
*/
public array $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',
];
/**
* -------------------------------------------------------------------
* Robots
* -------------------------------------------------------------------
*
* There are hundred of bots but these are the most common.
*
* @var array<string, string>
*/
public array $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',
];
}

44
app/Config/Validation.php Executable file
View File

@ -0,0 +1,44 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Validation\StrictRules\CreditCardRules;
use CodeIgniter\Validation\StrictRules\FileRules;
use CodeIgniter\Validation\StrictRules\FormatRules;
use CodeIgniter\Validation\StrictRules\Rules;
class Validation extends BaseConfig
{
// --------------------------------------------------------------------
// Setup
// --------------------------------------------------------------------
/**
* Stores the classes that contain the
* rules that are available.
*
* @var string[]
*/
public array $ruleSets = [
Rules::class,
FormatRules::class,
FileRules::class,
CreditCardRules::class,
];
/**
* Specifies the views that are used to display the
* errors.
*
* @var array<string, string>
*/
public array $templates = [
'list' => 'CodeIgniter\Validation\Views\list',
'single' => 'CodeIgniter\Validation\Views\single',
];
// --------------------------------------------------------------------
// Rules
// --------------------------------------------------------------------
}

62
app/Config/View.php Executable file
View File

@ -0,0 +1,62 @@
<?php
namespace Config;
use CodeIgniter\Config\View as BaseView;
use CodeIgniter\View\ViewDecoratorInterface;
/**
* @phpstan-type ParserCallable (callable(mixed): mixed)
* @phpstan-type ParserCallableString (callable(mixed): mixed)&string
*/
class View extends BaseView
{
/**
* 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.
*
* @var bool
*/
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) }
*
* @var array<string, string>
* @phpstan-var array<string, ParserCallableString>
*/
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.
*
* @var array<string, array<string>|callable|string>
* @phpstan-var array<string, array<ParserCallableString>|ParserCallableString|ParserCallable>
*/
public $plugins = [];
/**
* View Decorators are class methods that will be run in sequence to
* have a chance to alter the generated output just prior to caching
* the results.
*
* All classes must implement CodeIgniter\View\ViewDecoratorInterface
*
* @var class-string<ViewDecoratorInterface>[]
*/
public array $decorators = [];
}

13
app/Config/google-services.json Executable file
View File

@ -0,0 +1,13 @@
{
"type": "service_account",
"project_id": "push-notification-enrollment",
"private_key_id": "979d0fcd0ce95d31367f3150d34ee0044ca51b0d",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC4Xsan6ESIzM12\nG15gRU361Yy6PVmoMzTToWtZHPEcDRd9weFNlCXjmX+WAqdgD/hQ42GcZQVCndse\nEQGJHbRu/ifMKGo53zxOpshNZnCSxojAGWIGrIHFE5kFumiKz9drW9vPWsFLtgx0\nEAW0T7su1MejjH33GftHG8k/q3uyWoU0+OFRD6emhYkFdVsucwR27hE7GsFwE+CF\nnRdSWQ5mu2e8J7q9Qbpgot5d7uk7iJgpiyNdChPvqUZ7XeknVrw1F4REZlbAkVjb\nFuwKg5qtG97LZ1NkyYqFmssA1rNkqSi4+T+2/ERegdwyA6W4/HLT9fPbSl4v1MvB\ntJlGYkMpAgMBAAECggEABhspdCUmo+s4gMleQkz5TK3m58IhZocvoDSv4/cn6xhp\n50HVDucxrAyI47R5y54ryK4HLRFRb8ffmmrQxLRFpgln0wShpAIHMsmmR531a38E\nx2vvya3L7HV+M2jdjn9csJMNwBvO3A2O8wcW0UZ0uhPU+s8r2tOy9UNv0lqBEcKM\nUxCtk7UxcLEM3btDP5I4oEHVo2f5jzPeb99KHbYQV/vc0BtA1wtuYTzGT2EhBpTG\nN1rbQhlj6iJ6vMwHETWrctNMohCQNQEv/QIC/NWYPNRqmtrJfNe29XGWN9IIhv0e\n/ZmhdzoO+uhJW4VaWpI93nB5ZAa6LHqJSg+OyrPoawKBgQDd45Aiq7d+4Z+kDZYu\n72bgW5CGhyck2hrqHpBdHA960AYIftw/wHgI9xb9Z8hi+Lh+W18xDywOLoaz7TJV\nElj2Gh3oj2ZLzDpeyqV9UOgz11dbm6yYUK8jl7zyajBt7RhGcdj+4x+YjUTT6O61\nuxm2ZbKsb/0er/W6DlKDVvpWSwKBgQDUtqowATEaGTrd+eutanRwtv+rdptVcadj\nD4H3XdY4PAsVSp1mT9knGgh7c5elI0lBH/VD/IbM5uPXOc7judnIK4RgKScrJT2P\nekyEJnXyFAZGS3WTFG7fzeXn/cNNx5MCZE2Yay7LqqON8Kg08IvvesiTushrDlMJ\nX8cunSyz2wKBgDIOwZigxq/QNNSs4AHMrpfU8GD5IqKUtde1d3oZ94AMaCAIhqW3\nRR04qS4X+MQjOnP/JxWJR7YXVvpGe8FndzxmHfM2Tqyw8UYrT3RbCVeQsDuRfjmK\nkkhkVhMWU8Co6X4S9xJhqOIglLN97ESBZkaY4Ns4FJGUvsnvqzvIJofLAoGBAKJO\ny2eb0TK/46ozJEELxNOo30efVgGJmpa844e0A1yffDl/2MCT1ve+JpDEcAbi+OeH\nkieRTe6Vk27LvnEHhAT4J6cUX73NSb7sK+x+SGsyGmOS+qEC62M8gdxWRqtXyHX/\nwTG3P1rK1sfcxQy4K57NSrVmxbzijjvN6HdKGS0XAoGATtsid5pypcZ0BsYUp/27\neS6z++ewo7QCVCBPa4Ag4nX56/0kdrECvy/ISMDjggNv+mR8hpyCjfm9ztJ88njB\nUBu1jzLBZ+u5gEjmtu43qvuDJNobyb+evDSReEJmify943vFZqnkIhFlwg1PcS6S\nCd+pr559KWURPIgfxb7S/JU=\n-----END PRIVATE KEY-----\n",
"client_email": "firebase-adminsdk-gzzkw@push-notification-enrollment.iam.gserviceaccount.com",
"client_id": "109128197176743587316",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-gzzkw%40push-notification-enrollment.iam.gserviceaccount.com",
"universe_domain": "googleapis.com"
}

View File

@ -0,0 +1,20 @@
<?php
namespace App\Controllers;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Controllers\PublicController;
//This is a controller act like base controller for business logics which are required
// authendication and authrizations also config the routes as per requirement in routes.php
class AdminController extends BaseController
{
public function __construct()
{
}
}

View File

@ -0,0 +1,96 @@
<?php
// declare(strict_types=1);
namespace App\Controllers;
use Psr\Log\LoggerInterface;
use CodeIgniter\API\ResponseTrait;
use App\Models\AddImgModel;
use App\Models\FEContentModel;
class AppContentManagementController extends AdminController
{
use ResponseTrait;
protected $myLogger;
protected $addImgModel;
protected $feContentModel;
public function __construct()
{
$this->myLogger = \Config\Services::mylogger();
$this->addImgModel = new AddImgModel();
$this->feContentModel = new FEContentModel();
}
public function add_image_index()
{
$this->myLogger->logme('error','Addvertisement Image list function called');
$headerData['page_name'] = 'Addvertisement Image List';
$data['addImageList'] = $this->addImgModel->findAll();
// dd($data);
echo view('layout/header', $headerData);
echo view('add_image_list', $data);
echo view('layout/footer');
// $this->loadLayout('client_onboarding', $data);
}
public function add_advertise_image(){
// print_r($this->request->getPost());die;
$uploadFilePath = ROOTPATH . 'public/uploads/advertiseImage/';
$file_name = file_Upload($this->request->getFile('advertise_image'), $uploadFilePath);
$data['id'] = $this->request->getPost('add_image_id');
// $data['created_by'] = get_session_userid();
$data['name'] = $file_name;
if($data['id'] == 0){
$insert = $this->addImgModel->insert($data);
if($insert){
return $this->respond(['status' => true,'code' => 200,'data' => "success"], 200);
}else{
return $this->respond(['status' => false,'code' => 404,'message' => 'no data found'], 200);
}
}else{
$id = $data['id'];
$update = $this->addImgModel->update($id,$data);
if($update){
return $this->respond(['status' => true,'code' => 200,'data' => "success"], 200);
}else{
return $this->respond(['status' => false,'code' => 404,'message' => 'no data found'], 200);
}
}
}
public function getAdvertiseImage($image_id){
$image_data = $this->addImgModel->select('name')->where(['id' => $image_id])->first();
if($image_data){
return $image_data['name'];
}else{
return ;
}
}
// Front End Content Area
public function frontend_content(){
$data['test'] = $this->feContentModel->findAll();
$headerData['page_name'] = 'Front-End Content';
echo view('layout/header', $headerData);
echo view('frontend_content_list', $data);
echo view('layout/footer');
}
}

View File

@ -0,0 +1,68 @@
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
/**
* 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.
*/
abstract class BaseController extends Controller
{
/**
* Instance of the main Request object.
*
* @var CLIRequest|IncomingRequest
*/
protected $request;
/**
* An array of helpers to be loaded automatically upon
* class instantiation. These helpers will be available
* to all other controllers that extend BaseController.
*
* @var array
*/
protected $helpers = [];
/**
* Be sure to declare properties for any property fetch you initialized.
* The creation of dynamic property is deprecated in PHP 8.2.
*/
// protected $session;
/**
* @return void
*/
protected $session;
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
// Do Not Edit This Line
// echo 'initController';
parent::initController($request, $response, $logger);
// Preload any models, libraries, etc, here.
$this->session = \Config\Services::session();
}
public function loadLayout($view_name,$data = [])
{
echo view('layout/header',$data);
echo view($view_name, $data);
echo view('layout/footer',$data);
}
}

View File

@ -0,0 +1,452 @@
<?php
namespace App\Controllers;
use App\Helpers\MailHelper;
use App\Helpers\sendMailNotification;
use App\Models\EmployeeModel;
use App\Models\EmployeePolicyModel;
use App\Models\ClientModel;
use App\Models\ClientRMModel;
use App\Models\PolicesModel;
use App\Models\RelationshipModel;
use App\Models\FileModel;
use App\Models\ClientPolicyModel;
use App\Models\PolicyPremium1Model;
use App\Models\PolicyPremium2Model;
use App\Models\PolicyTypeModel;
use App\Models\NotificationModel;
use App\Models\UserModel;
use App\Models\FEContentModel;
use App\Models\AddImgModel;
use App\Models\ChatBotModel;
use CodeIgniter\API\ResponseTrait;
class ChatBotController extends AdminController
{
use ResponseTrait;
protected $myLogger;
protected $employeeModel;
protected $employeePolicyModel;
protected $clientModel;
protected $clientRMModel;
protected $fileModel;
protected $policesModel;
protected $relationshipModel;
protected $clientPolicyModel;
protected $policyPremium1Model;
protected $policyPremium2Model;
protected $policyTypeModel;
protected $notificationModel;
protected $userModel;
protected $feContentModel;
protected $addImgModel;
protected $ChatBotModel;
public function __construct()
{
set_session_context('Employee');
$this->myLogger = \Config\Services::mylogger();
$this->employeeModel = new EmployeeModel();
$this->employeePolicyModel = new EmployeePolicyModel();
$this->clientModel = new ClientModel();
$this->clientRMModel = new ClientRMModel();
$this->policesModel = new PolicesModel();
$this->relationshipModel = new RelationshipModel();
$this->fileModel= new FileModel();
$this->clientPolicyModel = new ClientPolicyModel();
$this->policyPremium1Model = new PolicyPremium1Model();
$this->policyPremium2Model = new PolicyPremium2Model();
$this->policyTypeModel = new PolicyTypeModel();
$this->notificationModel = new NotificationModel();
$this->userModel = new UserModel();
$this->feContentModel = new FEContentModel();
$this->addImgModel = new AddImgModel();
$this->ChatBotModel = new ChatBotModel();
}
public function getChatResponse()
{
try {
$emp_code = $this->request->getVar('emp_code');
$client_id = $this->request->getVar('client_id');
$client_branch_id = $this->request->getVar('client_branch_id');
$request_for = $this->request->getVar('request_for');
$option = $this->request->getVar('option');
$is_option = $this->request->getVar('is_option');
$responseData = $this->ChatBotModel->where('request', $request_for)
->where('is_active', 1 )
->first();
if ($responseData) {
if(isset($option) && $option != 0)
{
$decodedData = json_decode($responseData['options'],true);
if (isset($decodedData[$option]) && $decodedData[$option] !== null) {
$requestFor = $decodedData[$option];
$responseData = $this->ChatBotModel->where('request', $requestFor)
->where('is_active', 1 )
->first();
if($responseData['request'] == 'Call' || $responseData['request'] == 'Mail'){
$AccountManagerDetails = $this->clientRMModel->select('client_rm.* , user_profiles.*')
->join('user_profiles', 'client_rm.user_id = user_profiles.id', 'left')
->where('client_rm.client_id', $client_id )
->where('client_rm.level', 3 )
->findAll();
if(isset($AccountManagerDetails) && $responseData['request'] == 'Call'){
$responseData['options'] = $AccountManagerDetails[0]['mobile'];
}else if(isset($AccountManagerDetails) && $responseData['request'] == 'Mail'){
$responseData['options'] = $AccountManagerDetails[0]['email'];
}
}
}else{
if( $request_for == 'Initiate claim'){
$result = [
'request_for' => $request_for,
'options' => json_decode($responseData['options'], true),
'text' => "Enter Message",
'is_option' => "0",
'policy_id' => $option,
'mobile_no' => $this->request->getVar('mobile_no'),
'navigation' => $responseData['navigation'],
'navigation_type' => $responseData['navigation_type']
];
return $this->respond(['status' => 'success','code' => 200,'data' => $result ],200);
}else{
$result = $this->sendDefaultMessage();
return $this->respond(['status' => 'success','code' => 200,'data' => $result ],200);
}
}
}
if(isset($is_option) && $is_option == 0){
$text = $this->request->getVar('text');
$value = $this->request->getVar('value');
$Data = $this->ChatBotModel->where('options', $text)->where('is_active', 1 )->first();
if($Data){
if($Data['options'] == 'Please Enter Your Mobile Number To View Your Policies')
{
$result = $this->getAllPolicyByMobileNumber($value,'text');
return $this->respond(['status' => 'success','code' => 200,'data' => $result ],200);
}else if($Data['options'] == 'Please Enter Your Mobile Number To Raise Claim'){
$result = $this->getAllPolicyByMobileNumber($value,'options');
return $this->respond(['status' => 'success','code' => 200,'data' => $result ],200);
}else if( $Data['options'] == 'Enter Your Claim Number'){
$result = $this->getTicket($value,$emp_code,$client_id);
return $this->respond(['status' => 'success','code' => 200,'data' => $result ],200);
}
}else{
if( $request_for == 'Create claim' && $text == 'Enter Message'){
$ticket = $this->claimTicket();
$ticket = json_decode($ticket,true);
if (isset($ticket['success']) && $ticket['success'] == 1) {
$result = [
'request_for' => $request_for,
'options' => null,
'text' => $ticket['message'].', Your Claim id is '.$ticket['ticket_id'],
'is_option' => "0",
'navigation' => "0",
'navigation_type' => null
];
}else{
$result = [
'request_for' => $request_for,
'options' => null,
'text' => $ticket['message'],
'is_option' => "0",
'navigation' => "0",
'navigation_type' => null
];
}
return $this->respond(['status' => 'success','code' => 200,'data' => $result ],200);
}else{
$result = $this->sendDefaultMessage();
return $this->respond(['status' => 'success','code' => 200,'data' => $result ],200);
}
}
}
$result = [
'request_for' => $responseData['request'],
'options' => json_decode($responseData['options'], true),
'text' => $responseData['is_option'] != 1 ? $responseData['options'] : null,
'is_option' => $responseData['is_option'],
'navigation' => $responseData['navigation'],
'navigation_type' => $responseData['navigation_type']
];
return $this->respond(['status' => 'success','code' => 200,'data' => $result ],200);
} else {
return $this->respond(['status' => 'failed','code' => 404,'data' => 'No Data'],404);
}
} catch (\Throwable $th) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500);
}
}
public function sendDefaultMessage()
{
$responseData = $this->ChatBotModel->where('id', 1)->where('is_active', 1 )->first();
return [
'request_for' => $responseData['request'],
'options' => json_decode($responseData['options'], true),
'text' => $responseData['is_option'] != 1 ? $responseData['options'] : null,
'is_option' => $responseData['is_option'],
'navigation' => $responseData['navigation'],
'navigation_type' => $responseData['navigation_type']
];
}
public function getAllPolicyByMobileNumber($mobileNo,$action)
{
$employee = $this->employeeModel->where('mobile', $mobileNo)->where('is_active', 1 )->first();
if($employee){
$employeeData = $this->employeeModel->where('emp_code', $employee['emp_code'])
->where('client_id',$employee['client_id'])
->where('client_branch_id',$employee['client_branch_id'])
->where('is_active', 1 )->findAll();
$whereArrayForId = [];
foreach ( $employeeData as $key => $value) { array_push($whereArrayForId, $value['id']); }
$ClientPolicyData = $this->clientPolicyModel->select('client_policy.* , policy_type.long_name as policy_name , policy_type.policy_type as policy_type')
->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left')
->where('client_policy.client_id', $employee['client_id'] )
->where('client_policy.client_branch_id', $employee['client_branch_id'] )
->where('client_policy.is_active', 1 )
->where('client_policy.policy_status', 1)
->orderby('client_policy.id' , 'ASC')
->findAll();
$options = [];
$text = '';
if(count($ClientPolicyData) > 0 && count($employeeData) > 0)
{
foreach ($ClientPolicyData as $key => $ClientPolicyValue) {
$data['policy_name'] = $ClientPolicyValue['policy_name'];
$data['policy_type'] = $ClientPolicyValue['policy_type'];
$data['policy_no'] = $ClientPolicyValue['policy_no'];
$employee_policy = $this->employeePolicyModel->select('employees.*,employee_polices.employee_id , employee_polices.basic_cover_si , employee_polices.premium , employee_polices.gst , employee_polices.tpa_id , employee_polices.rand_string , employee_polices.uhid as uhid')
->join('employees', 'employee_polices.employee_id = employees.id', 'left')
->whereIn('employee_polices.employee_id',$whereArrayForId)
->where('employee_polices.client_policy_id',$ClientPolicyValue['id'])
->where('employee_polices.is_active', 1 )->findAll();
if(count($employee_policy) > 0)
{
$policy[$ClientPolicyValue['id']] = $ClientPolicyValue['policy_name']."(".$ClientPolicyValue['policy_type'].")";
array_push($options, $policy);
$text .= $ClientPolicyValue['policy_name']." % ";
}else{
$text .= "There is no any active policies ";
}
}
if($action == 'options'){
return [
'request_for' => $this->request->getVar('request_for'),
'options' => $options[count($options) - 1],
'text' => null,
'is_option' => "1",
'mobile_no' => $mobileNo,
];
}else{
return [
'request_for' => $this->request->getVar('request_for'),
'options' => null,
'text' => $text,
'is_option' => "0",
'mobile_no' => $mobileNo,
];
}
}else{
return [
'request_for' => $this->request->getVar('request_for'),
'options' => null,
'text' => "Dear ".$employee['name']." Policy not yet bound for you.",
'is_option' => "0"
];
}
}else{
return [
'request_for' => $this->request->getVar('request_for'),
'options' => null,
'text' => "Invalid Mobile Number",
'is_option' => "0"
];
}
}
public function claimTicket()
{
$employee = $this->employeeModel->where('mobile', $this->request->getVar('mobile_no'))->where('is_active', 1 )->first();
if($employee){
$url = 'https://venbait.in/nhance/helpdesk/dev/api/tickets/create';
$token = 'uncp8FvG310bEyYdV9MmStlo7KDRZ65fLWTeXCI2JzwPrNHjBqQhUiAgxsaO';
$headers = [
'Token: ' . $token,
];
// Form data
$data = [
'opener' => 'user',
'department_id' => 2,
'subject' => 'Claim Raised by Chat Bot',
'body' => $this->request->getVar('value'),
'policy_id' => $this->request->getVar('policy_id'),
'emp_code' => $employee['emp_code'],
'mobile_number' => $this->request->getVar('mobile_no'),
'email' => 'adhavanvalli@gmail.com',
'fullname' => $employee['name'],
];
// Initialize cURL session
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
return $response;
// Check for errors
// if (curl_errno($ch)) {
// $error = curl_error($ch);
// curl_close($ch);
// return ['status' => 'failed', 'response' => $error];
// } else {
// // Close cURL session
// curl_close($ch);
// return ['status' => 'success', 'response' => $response];
// }
}else{
return ['status' => 'failed', 'response' => 'Employee Not Found'];
}
}
public function getTicket($value, $emp_code, $client_id)
{
// Construct the URL with query parameters
$url = 'https://venbait.in/nhance/helpdesk/dev/api/tickets/show/' . $value;
$token = 'uncp8FvG310bEyYdV9MmStlo7KDRZ65fLWTeXCI2JzwPrNHjBqQhUiAgxsaO';
$headers = [
'Token: ' . $token,
];
// Initialize cURL session
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute cURL request
$response = curl_exec($ch);
// Check for errors
if (curl_errno($ch)) {
$error = curl_error($ch);
curl_close($ch);
return ['status' => 'failed', 'response' => $error];
} else {
// Close cURL session
curl_close($ch);
return ['status' => 'success', 'response' => $response];
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,703 @@
<?php
namespace App\Controllers;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Helpers\sendMailNotification;
use CodeIgniter\API\ResponseTrait;
use App\Models\MessageModel;
use App\Models\UserMessageModel;
use App\Models\ClientModel;
use App\Models\PolicyTransactionModel;
use App\Models\JobModel;
use App\Models\ClientPolicyModel;
use App\Models\NotificationModel;
use App\Models\EmployeePolicyModel;
use App\Controllers\PendingActionsContrller;
use App\Controllers\EmpDataServiceController;
class DashboardController extends AdminController
{
use ResponseTrait;
protected $messageModel;
protected $clientModel;
protected $userMessageModel;
protected $clientPolicyModel;
protected $notificationModel;
protected $employeePolicyModel;
protected $policyTransactionModel;
protected $policyStatus;
protected $colorShades;
protected $myLogger;
public function __construct()
{
set_session_context('Dashboard');
$this->messageModel = new MessageModel();
$this->userMessageModel = new UserMessageModel();
$this->clientPolicyModel = new ClientPolicyModel();
$this->notificationModel = new NotificationModel();
$this->employeePolicyModel = new EmployeePolicyModel();
$this->clientModel = new ClientModel();
$this->policyTransactionModel = new PolicyTransactionModel();
$this->myLogger = \Config\Services::mylogger();
$this->policyStatus = [
'under_process' => 'Under Process',
'client_pending' => 'Client Pending',
'insurer_pending' => 'Insurer Pending',
'co_insurer_pending' => 'Co-Insurer Pending',
'tpa_pending' => 'TPA Pending',
'validated' => 'Validated',
'cancelled' => 'Cancelled',
'instalment_pending' => 'Instalment Pending',
'completed' => 'Completed',
];
$this->colorShades = [
[
'linear-gradient(45deg, #66e9eb, #5cc7d2)', // Lighter shade 1
'linear-gradient(45deg, #4ce2e5, #45bcc9)', // Lighter shade 2
'linear-gradient(45deg, #33dbe0, #2baebd)', // Original shade (slightly lighter)
'linear-gradient(45deg, #00d6db, #00a8b5)', // Original
'linear-gradient(45deg, #00bfc4, #00929f)', // Darker shade 1
'linear-gradient(45deg, #009ea1, #00767a)' // Darker shade 2
],
// Shades for Grenadier
[
'linear-gradient(45deg, #ff9d37, #ff7a10)', // Grenadier shade 1
'linear-gradient(45deg, #ff8b30, #ff7310)', // Grenadier shade 2
'linear-gradient(45deg, #ff8020, #ff5a00)', // Grenadier shade 3
'linear-gradient(45deg, #f06d15, #e05505)', // Grenadier shade 4
'linear-gradient(45deg, #d85f10, #c04805)', // Grenadier shade 5
'linear-gradient(45deg, #b85606, #a04605)' // Grenadier shade 6
],
// Shades for SilverChalice
[
'linear-gradient(45deg, #a3a8a8, #8f9494)', // SilverChalice shade 1
'linear-gradient(45deg, #989d9d, #848989)', // SilverChalice shade 2
'linear-gradient(45deg, #7e8484, #686e6e)', // SilverChalice shade 3
'linear-gradient(45deg, #6c7676, #545e5e)', // SilverChalice shade 4
'linear-gradient(45deg, #5c6363, #434949)', // SilverChalice shade 5
'linear-gradient(45deg, #494f4f, #353d3d)' // SilverChalice shade 6
]
];
}
public function dashboard()
{
$data = [];
$results = $this->clientModel->select('clients.id as client_id, clients.client_name, clients.short_name,
client_branch.id as client_branch_id, client_branch.branch_name,
client_branch.branch_code, employees.id as employee_id,
employees.name as employee_name, employees.relationship,
employees.emp_code, employees.emp_status, auth_history.user_type, client_policy.policy_type_id, client_policy.id as client_policy_id')
->join('client_branch', 'clients.id = client_branch.client_id', 'left')
->join('client_policy', 'client_branch.id = client_policy.client_branch_id', 'left')
->join('employees', 'client_branch.id = employees.client_branch_id', 'left')
->join('auth_history', 'employees.id = auth_history.user_id AND "employee" = auth_history.user_type', 'left')
->findAll();
// $pendingActionsController = new PendingActionsController;
// $pendingActionsData = $pendingActionsController->getPendingActionsForDashBoard();
// $businessTeamData = $this->policyTransactionModel->getBusinessReportList();
// $financeTeamData = $this->policyTransactionModel->getFinanceReportList();
// $businessTeamStatusData = $this->data_construct_for_bds($businessTeamData);
// $financeTeamStatusData = $this->data_construct_for_bds($financeTeamData);
$groupedData = [];
foreach ($results as $row) {
$clientId = $row['client_id'];
$clientName = $row['client_name'];
$shortName = $row['short_name'];
$branchId = $row['client_branch_id'];
$branchName = $row['branch_name'];
$branchCode = $row['branch_code'];
$clientPolicyId = $row['client_policy_id'];
$policyTypeId = $row['policy_type_id'];
$employeeId = '';
if ($employeeId != $row['employee_id']) {
$employeeId = $row['employee_id'];
} else {
$employeeId = null;
}
$employeeName = $row['employee_name'];
$employeeRelationship = $row['relationship'];
$employeeEmpCode = $row['emp_code'];
$employeeEmpStatus = $row['emp_status'];
$employeeUserType = $row['user_type'];
// Initialize the client entry if it doesn't exist
if (!isset($groupedData[$clientId])) {
$groupedData[$clientId] = [
'client_id' => $clientId,
'client_name' => $clientName,
'short_name' => $shortName,
'branches' => []
];
}
// Initialize the branch entry if it doesn't exist
if (!isset($groupedData[$clientId]['branches'][$branchId])) {
$groupedData[$clientId]['branches'][$branchId] = [
'client_branch_id' => $branchId,
'branch_name' => $branchName,
'branch_code' => $branchCode,
'emp_login' => 0,
'emp_enroll' => 0,
'client_policies' => [],
'employees' => []
];
}
// Add the client policy to the branch's policies list if it exists, not already added, and policyTypeId is not equal to 1
if ($clientPolicyId !== null && $policyTypeId != 1 && !in_array(['client_policy_id' => $clientPolicyId, 'policy_type_id' => $policyTypeId], $groupedData[$clientId]['branches'][$branchId]['client_policies'])) {
$groupedData[$clientId]['branches'][$branchId]['client_policies'][] = [
'client_policy_id' => $clientPolicyId,
'policy_type_id' => $policyTypeId
];
}
// Append employee error to the branch's employees list if relationship is 'Self' and not already added
$employeeKey = $employeeId . '-' . $employeeName; // unique key to identify an employee
if ($employeeId !== null && $employeeRelationship == 'Self' && !isset($groupedData[$clientId]['branches'][$branchId]['employees'][$employeeKey])) {
$groupedData[$clientId]['branches'][$branchId]['employees'][$employeeKey] = [
'employee_id' => $employeeId,
'employee_name' => $employeeName,
'relationship' => $employeeRelationship,
'emp_code' => $employeeEmpCode,
'emp_status' => $employeeEmpStatus,
'user_type' => $employeeUserType
];
if (!empty($employeeUserType)) {
$groupedData[$clientId]['branches'][$branchId]['emp_login']++;
}
// Increment emp_enroll if emp_status is not 'draft'
if ($employeeEmpStatus !== 'draft') {
$groupedData[$clientId]['branches'][$branchId]['emp_enroll']++;
}
}
}
// Re-index the arrays to match the expected structure
foreach ($groupedData as &$client) {
foreach ($client['branches'] as &$branch) {
$branch['employees'] = array_values($branch['employees']);
}
$client['branches'] = array_values($client['branches']);
}
$data['client_branch_emp_list'] = $groupedData;
$session = \Config\Services::session();
$session->set('enrollment_data', json_encode($data));
// echo "<pre>";
// $data['pendingActionsData'] = $pendingActionsData;
// $data['businessTeamCount'] = count($businessTeamData) ?? 0;
// $data['financeTeamCount'] = count($financeTeamData) ?? 0;
// $data['businessTeamStatusData'] = $businessTeamStatusData;
// $data['financeTeamStatusData'] = $financeTeamStatusData;
// $data['policyStatus'] = $this->policyStatus;
// $data['colorShades'] = $this->colorShades;
// dd($data);die;
$data['page_name'] = 'Dashboard';
echo view('layout/header', $data);
echo view('DashBoard', $data);
echo view('layout/footer');
}
public function getDashboardNotifications()
{
// Pull notifications for the dashboard, especially for file upload cases.
$userId = get_session_userid();
$roleId = 5;
$teamId = 1;
if ($userId != null && $roleId != null && $teamId != null) {
$messages = $this->messageModel->getMessagesForUser($userId, $roleId, $teamId);
return $this->respond(['status' => true, 'code' => 200, 'message' => $messages], 200);
} else {
$this->myLogger->logme('error', 'The session is not set correctly. USER_ID : {user_id}, ROLE_ID : {role_id}, TEAM_ID : {team_id}', ['user_id' => $userId, 'role_id' => $roleId, 'team_id' => $teamId]);
return $this->respond(['status' => false, 'code' => 404, 'message' => 'No data found'], 200);
}
}
public function acknowledgeMessage($messageId)
{
$userId = get_session_userid();
$this->userMessageModel->markAsRead($userId, $messageId);
return $this->respond(['status' => 'success']);
}
public function updatePolicyEnrollmentStatus()
{
$clientPolicyModel = new ClientPolicyModel();
$myLogger = \Config\Services::mylogger();
$client_policy_data = $clientPolicyModel->getPolicyDetailsForEnrollment();
$myLogger->logme('error', 'Fetched client policy data for Enrollment Status update');
// dd($client_policy_data);
$currentDate = date('d-m-Y');
$openEnrollment = [];
$closeEnrollment = [];
// Update policy status based on start and end dates
foreach ($client_policy_data as $client_policy) {
$id = $client_policy['id'];
$openDate = date('d-m-Y', strtotime($client_policy['open_date']));
$closeDate = date('d-m-Y', strtotime($client_policy['close_date']));
if ($currentDate == $openDate) {
$clientPolicyModel->update($id, ['open_for_enrollment' => 1]);
$openEnrollment[] = $id;
$myLogger->logme('error', 'Updated policy ID ' . $id . ' to open for enrollment.');
}
if ($closeDate < $currentDate) {
$clientPolicyModel->update($id, ['open_for_enrollment' => 0]);
$closeEnrollment[] = $id;
$myLogger->logme('error', 'Updated policy ID ' . $id . ' to close for enrollment.');
}
}
$myLogger->logme('error', 'enrollment_status function completed');
return $this->respond([
'status' => true,
'message' => 'updated Policy Enrollment Status',
'open_policy_count' => count($openEnrollment),
'close_policy_count' => count($closeEnrollment),
'open_policy_ids' => $openEnrollment,
'close_policy_ids' => $closeEnrollment,
]);
}
public function sendCroneRemainderMail()
{
$clientPolicyModel = new ClientPolicyModel();
$myLogger = \Config\Services::mylogger();
$client_policy_data = $clientPolicyModel->getPolicyDetailsForRemainder();
$myLogger->logme('error', 'Fetched client policy data');
// dd($client_policy_data);
// Mail send function
$result = $this->sendRemainderMail($client_policy_data, 'crone');
$myLogger->logme('error', 'sendCroneRemainderMail function completed');
if($result){
return json_encode(['status' => true, 'message' => 'Mail send successfully']);
}else{
return json_encode(['status' => false, 'message' => 'There is no data to send']);
}
}
public function featch_dashboard_data($type)
{
$pendingActionsController = new PendingActionsController;
$pendingActionsData = $pendingActionsController->getPendingActionsForClientData();
$data = [];
if($type == 'insurer'){
$data = $pendingActionsData['uhid'];
}else if($type == 'TPA'){
$data = $pendingActionsData['tpa'];
}else if($type == 'I'){
$data = $pendingActionsData['inception'];
}else if($type == 'D'){
$data = $pendingActionsData['deletion'];
}else if($type == 'C'){
$data = $pendingActionsData['correction'];
}else if($type == 'SI'){
$data = $pendingActionsData['si_enhancement'];
}else if($type == 'policy'){
$data = $pendingActionsData['policy'];
}else if($type == 'ticket'){
$data = $pendingActionsData['uhid'];
}
return $this->respond(['status' => true, 'data' => $data], 200);
}
public function sendRemainderMail($client_policy_data, $send_mail_for_manual_or_crone = null)
{
// $this->myLogger->logme('error', 'sendRemainderMail function called');
// dd($client_policy_data, $send_mail_for_manual_or_crone);
$reminder_whole_mail = [];
foreach ($client_policy_data as $client_policy) {
// Fetch client data
$client_data = $this->clientModel->find($client_policy['client_id']);
// Fetch notification settings
$notification_data = $this->notificationModel
->where('client_id', $client_policy['client_id'])
->where('template_name', 'member_reminder_mail')
->first();
if ($notification_data && $notification_data['enabled'] == 1 && !empty($notification_data['mail_content'])) {
//manaual
if (empty($send_mail_for_manual_or_crone)) {
// Check if notification should be sent
$this->myLogger->logme('error', 'Notification should be sent for client policy ID: ' . $client_policy['id']);
$employees = [];
if (in_array($client_policy['policy_type_id'], [2, 4]) || ($client_policy['policy_type_id'] == 3 && $client_policy['is_addon'] == 1)) {
// Fetch all employees related to the client policy
$employees = $this->employeePolicyModel
->select('employees.*, employee_polices.id as emp_policy_id')
->join('employees', 'employee_polices.employee_id = employees.id', 'left')
->where('employee_polices.client_policy_id', $client_policy['id'])
->where('employees.is_active', 1)
->where('employee_polices.is_active', 1)
->where('employees.emp_status', 'draft')
->where('employee_polices.status', 'draft')
->where('employees.relationship', 'Self')
->where("employees.email_corporate IS NOT NULL AND employees.email_corporate != ''")
->findAll();
// dd($employees, 'first');
} else if (($client_policy['policy_type_id'] == 3 && $client_policy['is_addon'] == 3) || $client_policy['policy_type_id'] == 5) {
$empDependentData = $this->employeePolicyModel
->select('employees.*, employee_polices.id as emp_policy_id')
->join('employees', 'employee_polices.employee_id = employees.id', 'left')
->where('employee_polices.client_policy_id', $client_policy['id'])
->where('employees.is_active', 1)
->where('employee_polices.is_active', 1)
->where('employees.emp_status', 'draft')
->where('employee_polices.status', 'draft')
->where('employees.relationship !=', 'Self')
->findAll();
$empCodes = array_column($empDependentData, 'emp_code');
// dd($empDependentData, $empCodes,'second');
if (!empty($empCodes)) {
$empSelfData = $this->employeePolicyModel
->select('employees.*, employee_polices.id as emp_policy_id')
->join('employees', 'employee_polices.employee_id = employees.id', 'left')
->whereIn('employees.emp_code', $empCodes)
->where('employees.is_active', 1)
->where('employee_polices.is_active', 1)
->where('employees.relationship', 'Self')
->where("employees.email_corporate IS NOT NULL AND employees.email_corporate != ''")
->findAll();
$employees = array_merge($employees, $empSelfData);
}
}
// dd($employees);
// Process each employee
if (!empty($employees) && count($employees) > 0) {
foreach ($employees as $employee) {
$this->myLogger->logme('error', 'Employee status and relationship check passed for employee ID: ' . $employee['id']);
// Mail params
$params['emp_data'] = $employee;
$params['client_data'] = $client_data;
$params['notification_data'] = $notification_data;
$params['common'] = [
'client_id' => $client_policy['client_id'],
'client_branch_id' => $client_policy['client_branch_id'],
'client_policy_id' => $client_policy['id'],
'employee_policy_id' => $employee['emp_policy_id'],
'employee_id' => $employee['id'],
'mail_type' => 'member_reminder_mail',
];
// Send the mail notification
$mail_result = sendMailNotification::sendMailNotification('member_reminder_mail', $params);
// dd($mail_result);
// $this->myLogger->logme('error', 'Mail sent result: ' . json_encode($mail_result));
$reminder_whole_mail[] = $mail_result;
}
}
} else { // crone
if (!empty($client_policy['reminder_date'])) {
$currentDate = date('d');
$remainder_dates = explode(",", $client_policy['reminder_date']);
foreach ($remainder_dates as $date) {
if ($currentDate == $date) {
$this->myLogger->logme('error', 'Notification should be sent for client policy ID: ' . $client_policy['id']);
// Fetch all employees related to the client policy
$employees = [];
if (in_array($client_policy['policy_type_id'], [2, 4]) || ($client_policy['policy_type_id'] == 3 && $client_policy['is_addon'] == 1)) {
$employees = $this->employeePolicyModel
->select('employees.*, employee_polices.id as emp_policy_id')
->join('employees', 'employee_polices.employee_id = employees.id', 'left')
->where('employee_polices.client_policy_id', $client_policy['id'])
->where('employees.is_active', 1)
->where('employee_polices.is_active', 1)
->where('employees.emp_status', 'draft')
->where('employee_polices.status', 'draft')
->where('employees.relationship', 'Self')
->where("employees.email_corporate IS NOT NULL AND employees.email_corporate != ''")
->findAll();
// dd($employees, 'first');
} else if (($client_policy['policy_type_id'] == 3 && $client_policy['is_addon'] == 3) || $client_policy['policy_type_id'] == 5) {
$empDependentData = $this->employeePolicyModel
->select('employees.*, employee_polices.id as emp_policy_id')
->join('employees', 'employee_polices.employee_id = employees.id', 'left')
->where('employee_polices.client_policy_id', $client_policy['id'])
->where('employees.is_active', 1)
->where('employee_polices.is_active', 1)
->where('employees.emp_status', 'draft')
->where('employee_polices.status', 'draft')
->where('employees.relationship !=', 'Self')
->findAll();
$empCodes = array_column($empDependentData, 'emp_code');
// dd($empDependentData, $empCodes,'second');
if (!empty($empCodes)) {
$empSelfData = $this->employeePolicyModel
->select('employees.*, employee_polices.id as emp_policy_id')
->join('employees', 'employee_polices.employee_id = employees.id', 'left')
->whereIn('employees.emp_code', $empCodes)
->where('employees.is_active', 1)
->where('employee_polices.is_active', 1)
->where('employees.relationship', 'Self')
->where("employees.email_corporate IS NOT NULL AND employees.email_corporate != ''")
->findAll();
$employees = array_merge($employees, $empSelfData);
}
}
// dd($employees);
// Process each employee
foreach ($employees as $employee) {
$this->myLogger->logme('error', 'Employee status and relationship check passed for employee ID: ' . $employee['id']);
// Mail params
$params['emp_data'] = $employee;
$params['client_data'] = $client_data;
$params['notification_data'] = $notification_data;
$params['common'] = [
'client_id' => $client_policy['client_id'],
'client_branch_id' => $client_policy['client_branch_id'],
'client_policy_id' => $client_policy['id'],
'employee_policy_id' => $employee['emp_policy_id'],
'employee_id' => $employee['id'],
'mail_type' => 'member_reminder_mail',
];
// Send the mail notification
$mail_result = sendMailNotification::sendMailNotification('member_reminder_mail', $params);
// $this->myLogger->logme('error', 'Mail sent result: ' . json_encode($mail_result));
$reminder_whole_mail[] = $mail_result;
}
}
}
} else {
$this->myLogger->logme('error', "SEND REMAINDER CRONE --- Remainder date is empty()");
}
}
} else {
$this->myLogger->logme('error', 'Notification setup not found or not enabled');
$this->myLogger->logme('error', 'Notification was not sent for this Client ID: ' . $client_policy['client_id']);
}
}
// dd($reminder_whole_mail);
// print_rr($reminder_whole_mail); die;
// Process and queue bulk emails
if (!empty($reminder_whole_mail) && count($reminder_whole_mail) > 0) {
$reminder_whole_mail = array_chunk($reminder_whole_mail, 20);
foreach ($reminder_whole_mail as $key => $value) {
// $job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'bulk_mail', 'payload' => $value]);
}
}
if (count($reminder_whole_mail) > 0) {
return true;
} else {
return false;
}
}
public function sendManualReminder($client_id, $client_branch_id, $client_policy_id = null)
{
$this->myLogger->logme('error','Log Works');
$this->myLogger->logme('error', "sendManualRemainder called with client_id: {$client_id}, client_branch_id: {$client_branch_id}");
$client_policy_data = $this->clientPolicyModel->getPolicyDetailsForRemainder($client_id, $client_branch_id, $client_policy_id);
// print_r($client_policy_data); die;
// print_r($this->clientPolicyModel->getLastQuery()); die;
// $this->myLogger->logme('error', "Policy details fetched: " . json_encode($client_policy_data));
if ($client_policy_data) {
$result = $this->sendRemainderMail($client_policy_data);
log_message('error',json_encode($result));
$this->myLogger->logme('error',$result);
$this->myLogger->logme('error', "Manual Remainder Mail sending result: " . ($result ? 'success' : 'failure'));
if ($result) {
$this->myLogger->logme('error', 'Manual Remainder Mail sent successfully');
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Mail sent successfully'], 200);
} else {
$this->myLogger->logme('error', 'Failed to send manual remainder mail, no data to send');
return $this->respond(['status' => false, 'code' => 200, 'message' => 'There is no data to send','message2' => 'Failed' ], 200);
}
} else {
$this->myLogger->logme('error', 'No policy data found to send');
return $this->respond(['status' => false, 'code' => 200, 'message' => 'There is no data to send', 'message2' => 'No policy data found to send'], 200);
}
}
public function sendManualEcard($client_id, $client_branch_id, $policy_id)
{
$this->myLogger->logme('error', "sendManualEcard called with client_id: {$client_id}, client_branch_id: {$client_branch_id}, policy id : {$policy_id}");
$notification = $this->notificationModel->where('client_id', $client_id)->where('template_name', 'member_ecard_mail')->first();
// print_r(($notification)); die;
if($notification && $notification['enabled'] == 0 && $notification['mail_content'] == '')
{
return $this->respond(['status' => false, 'code' => 400, 'message' => 'No template found','message2' => 'Failed' ], 200);
}
$emp_data = $this->employeePolicyModel->getEmployeePolicyForEcard($policy_id);
if(count($emp_data) == 0)
{
return $this->respond(['status' => false, 'code' => 400, 'message' => 'No employees found','message2' => 'Failed' ], 200);
}
$ids = array_column($emp_data, 'id');
// print_r(($ids)); die;
// print_r($this->clientPolicyModel->getLastQuery()); die;
// $this->myLogger->logme('error', "Policy details fetched: " . json_encode($client_policy_data));
Jobs::addJob(['job_name' => 'sendMailForDownloadingECard', 'payload' => $ids]);
// $empEmpDataServiceController = new EmpDataServiceController();
// $empEmpDataServiceController->sendMailForDownloadingECard($ids);
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Mail Queued'], 200);
}
public function data_construct_for_bds($data)
{
$groupedData = [
'under_process' => [],
'client_pending' => [],
'insurer_pending' => [],
'co_insurer_pending' => [],
'tpa_pending' => [],
'validated' => [],
'cancelled' => [],
'instalment_pending' => [],
'completed' => [],
];
// Loop through results and group them by their status
foreach ($data as $row) {
switch ($row['status']) {
case 'completed':
$groupedData['completed'][] = $row;
break;
case 'cancelled':
$groupedData['cancelled'][] = $row;
break;
case 'client_pending':
$groupedData['client_pending'][] = $row;
break;
case 'insurer_pending':
$groupedData['insurer_pending'][] = $row;
break;
case 'co_insurer_pending':
$groupedData['co_insurer_pending'][] = $row;
break;
case 'tpa_pending':
$groupedData['tpa_pending'][] = $row;
break;
case 'validated':
$groupedData['validated'][] = $row;
break;
case 'instalment_pending':
$groupedData['instalment_pending'][] = $row;
break;
default:
$groupedData['under_process'][] = $row;
break;
}
}
return $groupedData;
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,355 @@
<?php
namespace App\Controllers;
use App\Models\ClientModel;
use App\Models\ClientPolicyModel;
use Google_Service_Drive_DriveFile;
use Kint;
class GoogleDriveController extends BaseController
{
protected $clientModel;
protected $clientPolicyModel;
protected $googleDrive;
protected $driveService;
protected $cache;
public function __construct()
{
$this->clientModel = new ClientModel();
$this->clientPolicyModel = new ClientPolicyModel();
$this->googleDrive = \Config\Services::myGoogleDrive();
$this->driveService = $this->googleDrive->getDriveService();
$this->cache = \Config\Services::cache(); // Load the cache service
}
public function listFiles()
{
// dd($this->getClientFolderIds(client_id : 18));
$file_path = WRITEPATH.'uploads/client_kyc_documents/nhance_bpf.pdf';
// dd($file_path);
// dd($this->uploadFiletoGdrive(client_id : 18,doc_type:'KYC',file_path:$file_path,file_name:"dummy.pdf"));
dd( $this->uploadFiletoGdrive(client_id: 12, doc_type: 'KYC', file_path: $file_path, file_name: "dummy.pdf"));
$session = \Config\Services::session();
$fileName = $request->getVar('filename');
$fileType = $request->getVar('filetype');
$userAccess = $session->get('userEmail');
$parentFolderID = '1M0GH3GbNUOYZLNeHXA5U7C_P2NSx7F7O';
$searchQuery = '';//"'your-folder-id' in parents"
try {
// $driveService = $this->googleDrive->getDriveService();
$searchQuery = "name contains 'test' and 'vitvelz@gmail.com' in readers";
// Query to list files
$response = $this->driveService->files->listFiles([
'q' => $searchQuery,
'supportsAllDrives' => true,
'includeItemsFromAllDrives' => true,
'fields' => 'nextPageToken, files(id, name, mimeType, size, createdTime, modifiedTime, owners, shared, permissions, webViewLink, thumbnailLink)',
'pageSize' => 20,
]);
$files = $response->getFiles();
if (empty($files)) {
echo "No files found.";
} else {
foreach ($files as $file) {
echo "File Name: " . $file->getName() . " | File ID: " . $file->getId() . "<br>";
}
}
} catch (\Exception $e) {
return $this->response->setStatusCode(500)->setBody($e->getMessage());
}
}
//by file id
public function downloadFile(string $fileId = '',string $fileName = '',string $mimeType = '',string $fileSize = '')
{
// dd($fileName);
try {
if($fileName == '' && $mimeType == '')
{
// Get file metadata
$file = $this->driveService->files->get($fileId, ['fields' => 'name, mimeType,size']);
$fileName = $file->getName();
$mimeType = $file->getMimeType();
$fileSize = $file->getSize();
}
// Download the file content from Google Drive
$response = $this->driveService->files->get($fileId, ['alt' => 'media']);
$fileContent = $response->getBody()->getContents();
// dd($fileContent);
$temp_file_name = WRITEPATH.'/tmp/'.date('YmdHis');
$this->cache->save('temp_gdrive_file', $temp_file_name, 300);
file_put_contents( $temp_file_name, $fileContent );
// Use CodeIgniter helper for downloading the file
return $this->response->download($temp_file_name, null)->setFileName($fileName);
} catch (\Exception $e) {
return $this->response->setStatusCode(500)->setBody($e->getMessage());
}
}
public function generateNewGoogleDriveAccessToken()
{
$this->driveService->generateNewToken();
}
public function getClientFolderIds(int $client_id = 0,int $client_policy_id = 0)
{
// Fetch client short name from the database
if($client_id)
{
//check folder ids in cahce,
$cacheKey = "client_gdrive_folderids_{$client_id}";
$folderIds = $this->cache->get($cacheKey);
// dd($folderIds);
if($folderIds !== NULL)//if available retrun from cache
{
return $folderIds;
}
//if not in cache then get it from grdrive
$client = $this->clientModel->find($client_id);
$clientShortName = $client['short_name']; // Assuming short_name is the column for client's short name
}
else if($client_policy_id)
{
$cacheKey = "client_policy_gdrive_folderids_{$client_policy_id}";
$folderIds = $this->cache->get($cacheKey);
// dd($folderIds);
if($folderIds !== NULL)//if available retrun from cache
{
return $folderIds;
}
$client = $this->clientPolicyModel->select('c.short_name,pt.policy_type,client_policy.policy_no')
->join('clients c','client_policy.client_id = c.id')
->join('policy_type pt','client_policy.policy_type_id = pt.id')
->where('client_policy.id',$client_policy_id)
->get()->getResultarray();
// dd($client);
$clientShortName = $client[0]['short_name'];
$policyFolderName = $client[0]['policy_type'].'-'.$client[0]['policy_no'];
}
else
{
return [];
}
// dd($policyFolderName);
// Define parent folder ID where client folders are stored
$parentFolderId = getenv('GDRIVE_ROOT_FOLDER_ID');; // Replace with your specific folder ID
// Check if the client folder exists in GDrive, if not create one
$clientFolderId = $this->checkOrCreateFolder($clientShortName, $parentFolderId);
// Check or create KYC_DOCS folder inside the client folder
$kycFolderId = $this->checkOrCreateFolder('KYC_DOCS', $clientFolderId);
// Check or create POLICY_DOCS folder inside the client folder
$policyFolderId = $this->checkOrCreateFolder('POLICY_DOCS', $clientFolderId);
if($client_policy_id && (isset($policyFolderName)))
{
$clientPolicyFolderId = $this->checkOrCreateFolder($policyFolderName, $policyFolderId);
$clientPolicyUploadFolderId = $this->checkOrCreateFolder('UPLOADS', $clientPolicyFolderId);
}
// Return folder IDs in the specified format
$folderIds = [
'client_folder_id' => $clientFolderId, // example HCL,TCS
'kyc_doc_folder_id' => $kycFolderId, // KYC_DOCS inside HCL,TCS
'policy_doc_folder_id' => $policyFolderId, //POLICY_DOCS inside HCL,TCS
'client_policy_doc_folder_id' => isset($clientPolicyFolderId) ? $clientPolicyFolderId : null, //GMC-POLICY_NO inside POLICY_DOCS folder
'client_policy_uoload_doc_folder_id' => isset($clientPolicyUploadFolderId) ? $clientPolicyUploadFolderId : null, //UPLOADS folder in side GMC-POLICY_NO folder
];
// Save the folder IDs in cache for future requests
$this->cache->save($cacheKey, $folderIds, 604800); // Cache for 7 Days (3600 seconds * 24 * 7 )
return $folderIds;
}
// Method to check if a folder exists or create one if it doesn't
public function checkOrCreateFolder($folderName, $parentFolderId)
{
// Step 1: Check if the folder exists
$folderId = $this->getFolderId($folderName, $parentFolderId);
if ($folderId === null) {
// Step 2: If folder does not exist, create it
$folderId = $this->createFolder($folderName, $parentFolderId);
}
// Step 3: Return the folder ID
return $folderId;
}
// Method to get the folder ID by searching in Google Drive
private function getFolderId($folderName, $parentFolderId)
{
$query = "name = '$folderName' and mimeType = 'application/vnd.google-apps.folder' and '$parentFolderId' in parents and trashed = false";
$response = $this->driveService->files->listFiles([
'q' => $query,
'spaces' => 'drive',
'fields' => 'files(id, name)',
'pageSize' => 1,
]);
if (count($response->files) > 0) {
return $response->files[0]->id; // Return folder ID if found
}
return null; // Return null if folder doesn't exist
}
// Method to create a folder in Google Drive
private function createFolder($folderName, $parentFolderId)
{
$fileMetadata = new \Google_Service_Drive_DriveFile([
'name' => $folderName,
'mimeType' => 'application/vnd.google-apps.folder',
'parents' => [$parentFolderId]
]);
$folder = $this->driveService->files->create($fileMetadata, [
'fields' => 'id',
]);
return $folder->id; // Return the newly created folder's ID
}
// public function uploadFiletoGdrive(int $client_id = 0,int $client_policy_id = 0,string $doc_type,string
// $file_path,string $file_name)
public function uploadFiletoGdrive(int $client_id = 0, int $client_policy_id = 0, string $doc_type = '', string $file_path = '', string $file_name = '')
{
$gdriveFolderIds = $this->getClientFolderIds(client_id: $client_id,client_policy_id: $client_policy_id);
// Kint::dump($gdriveFolderIds);//die();
$parentFolderId = '';
if($client_id && $doc_type == 'KYC')
{
$parentFolderId = $gdriveFolderIds['kyc_doc_folder_id'];
}
else if($client_policy_id && $doc_type == 'POLICY')
{
$parentFolderId = $gdriveFolderIds['client_policy_doc_folder_id'];
}
else if($client_policy_id && $doc_type == 'UPLOADS')
{
$parentFolderId = $gdriveFolderIds['client_policy_uoload_doc_folder_id'];
}
if($parentFolderId == '')
{
return null;
}
// dd($parentFolderId);
$file = new \Google_Service_Drive_DriveFile([
'name' => $file_name,
'parents' => [$parentFolderId] // Specify the folder ID here
]);
$file_blob_data = file_get_contents($file_path);
$createdFile = $this->driveService->files->create($file, [
'data' => $file_blob_data,
'mimeType' => 'application/octet-stream',
'uploadType' => 'multipart',
'fields' => 'id' // Specify fields to return
]);
if($createdFile->id && $doc_type !== 'UPLOADS')
{
unlink($file_path);
}
return $createdFile->id;
}
public function downloadGdriveFile()
{
$client_id = $this->request->getGet('client_id');
$client_policy_id = $this->request->getGet('client_policy_id');
$file_type = $this->request->getGet('file_type');
$file_name = $this->request->getGet('file_name');
if(!is_numeric($client_policy_id))
$client_policy_id = 0;
else
$client_id = 0;
$gdriveFolderIds = $this->getClientFolderIds(client_id: $client_id,client_policy_id: $client_policy_id);
// dd($gdriveFolderIds);
$parentFolderId = '';
if($file_type == 'kyc')
{
$parentFolderId = $gdriveFolderIds['kyc_doc_folder_id'];
}
else if($file_type == 'policy')
{
$parentFolderId = $gdriveFolderIds['client_policy_doc_folder_id'];
}
else if($file_type == 'uploads')
{
$parentFolderId = $gdriveFolderIds['client_policy_uoload_doc_folder_id'];
}
if($parentFolderId == '')
{
return $this->response->setStatusCode(500)
->setHeader('Content-Type', 'text/html')
->setBody('<script>alert("File not found");</script>');
}
return $this->searchGdriveFileByName(parentFolderID: $parentFolderId, fileName: $file_name);
}
//search files in gdrive by parent folder id and name of the file
public function searchGdriveFileByName(string $parentFolderID,string $fileName)
{
//check exisitng temp file from cache and delete it
if($this->cache->get('temp_gdrive_file') && is_file($this->cache->get('temp_gdrive_file')))
{
unlink($this->cache->get('temp_gdrive_file'));
}
try {
$searchQuery = "'$parentFolderID' in parents and (name contains '$fileName')";
// Query to list files
$response = $this->driveService->files->listFiles([
'q' => $searchQuery,
'supportsAllDrives' => true,
'includeItemsFromAllDrives' => true,
'fields' => 'nextPageToken, files(id, name, mimeType, size)',
'pageSize' => 1,
]);
$files = $response->getFiles();
if (empty($files)) {
return $this->response->setStatusCode(500)
->setHeader('Content-Type', 'text/html')
->setBody('<script>alert("File not found");window.close();</script>');
}
else
{
//echo "File Name: " . $files[0]->getName() . " | File ID: " . $file[0]->getId() . "<br>";
// echo($files[0]->getId());
// echo 'working';
return $this->downloadFile(fileId:$files[0]->getId(),fileName:$files[0]->getName(),mimeType:$files[0]->getMimeType(),fileSize:$files[0]->getSize());
}
} catch (\Exception $e) {
return $this->response->setStatusCode(500)->setBody($e->getMessage());
}
}
}

31
app/Controllers/Home.php Executable file
View File

@ -0,0 +1,31 @@
<?php
namespace App\Controllers;
class Home extends PublicController
{
public function index(): string
{
return view('mail_welcome');
}
public function test()
{
echo base_url();
//echo ($_SERVER['SERVER_PORT'] == 443 ? 'https' : 'http') . "://{$_SERVER['SERVER_NAME']}".str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
return view('welcome_message');
return view('test');
}
public function testService()
{
return 'from test service';
}
public function addTwoNumbers($payload)
{
//echo $payload['a'] + $payload['b'];
return $payload['a'] + $payload['b'];
}
}

353
app/Controllers/JobWorker.php Executable file
View File

@ -0,0 +1,353 @@
<?php
namespace App\Controllers;
use App\Models\JobModel;
use App\Models\FileModel;
class JobWorker extends AdminController
{
const STATUS_DONE = 'done';
const STATUS_QUEUED = 'queued';
const STATUS_RUNNING = 'running';
const STATUS_FAILED = 'failed';
/**
* Constructs the class
*/
private static $event_class_mapping = [
'add' => [
'type' => 'HC', // Handler Category (Possible values: HC, CC, HF)
'handler' => 'App\Helpers\HttpRequestHelper',
],
'sub' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\Jobs\SubJob',
],
'fancy_date_time_format' => [
'type' => 'HF', // Handler Category (Possible values: HC, CC, HF)
'handler' => 'fancy_date_time_format', // Likely a custom function
],
'addNumber' => [
'type' => 'HC', // Handler Category
'handler' => 'App\Model\HttpRequestHelper',
],
'excelFileFormatValidation' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmployeeServiceController',
],
'excelFileDataValidation' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmployeeServiceController',
],
'employeesOnboardPreprocess' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmployeeServiceController',
],
'employeeDisembark' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmployeeServiceController',
],
'employeesSIEnhanceProcess' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmployeeServiceController',
],
'employeesCorrectionProcess' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmployeeServiceController',
],
'send_email' => [
'type' => 'HC', // Handler Category
'handler' => 'App\Helpers\MailHelper',
],
'bulk_mail' => [
'type' => 'HC', // Handler Category
'handler' => 'App\Helpers\MailHelper',
],
'insertBatchList' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmpDataServiceController',
],
// Employee Data Service Events
'importInceptionFileValidation' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmpDataServiceController',
],
'importInceptionUpdateTPAandUHID' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmpDataServiceController',
],
'cashDepositCalculationForInception' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmpDataServiceController',
],
'sendMailForDownloadingECard' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmpDataServiceController',
],
'importCorrectionValidation' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmpDataServiceController',
],
'importCorrectionUpdateEndorsementID' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmpDataServiceController',
],
'cashDepositCalculationForSIEnhancement' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmpDataServiceController',
],
'importSIEnhancementValidation' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmpDataServiceController',
],
'importSIEnhancementUpdateEndorsementID' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmpDataServiceController',
],
'cashDepositCalculationForDeletion' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmpDataServiceController',
],
'importDeletionValidation' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmpDataServiceController',
],
'importDeletionUpdateEndorsementID' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmpDataServiceController',
],
'employeesEnrollmentInsert' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\EmployeeServiceController',
],
'calculateMembersDemography' => [
'type' => 'CC', // Handler Category
'handler' => 'App\Controllers\LeadsController',
]
];
public function __construct()
{
// echo 'HiC';//die();
// parent::__construct();
// $this->load->model('JobModel');
// $this->dbm = $this->users_model;
// if (php_sapi_name() !== 'cli')
// {
// die('Invalid context');
// }
}
public static function streamOutput($data)
{
ob_implicit_flush(true);
// try { ob_end_flush(); } catch(Exception $e) { echo $e->getMessage(); }
echo $data;
flush();
}
public static function processJobs(array $jobdata = [])
{
// echo 'listen';//die();
$query = "
SELECT id, name, payload, uuid
FROM jobs
WHERE status=?
ORDER BY created_dt ASC";
$where_condition = [self::STATUS_QUEUED];
$db = \Config\Database::connect();
$jobs = $db->query($query, $where_condition)->getResult();
if(count($jobs))
{
// echo count($jobs);
// print_r($jobs);die;
foreach($jobs as $key => $job)
{
// echo $job->id.' - '.$job->name;
//sleep(1);
SELF::processjob(['id' => $job->id,'uuid' => $job->uuid]);
// usleep( 500000 );
}
}
}
/**
* process jobs
*/
public static function processJob(array $jobdata = [])
{
// print_r($jobdata);
// echo 'listen';
// die();
$query = "
SELECT id, name, payload, uuid
FROM jobs
WHERE status=?
ORDER BY created_dt ASC
LIMIT 1 FOR UPDATE";
$where_condition = [self::STATUS_QUEUED];
if(isset($jobdata) && count($jobdata))
{
$query = "
SELECT id, name, payload, uuid
FROM jobs
WHERE status=? AND id=? AND uuid=?
ORDER BY created_dt ASC
LIMIT 1 FOR UPDATE";
$where_condition = [self::STATUS_QUEUED,$jobdata['id'],$jobdata['uuid']];
}
$db = \Config\Database::connect();
$job = $db->query($query, $where_condition)->getResult();
// print_r($job);die();
if ($job !== [])
{
$job = $job[0];
// echo "\nProcessing job id - " . $job->id . "\n";
SELF::streamOutput("\nProcessing job id - " . $job->id . "\n");
// sleep(5);
// echo "Job name - " . $job->name . "\n";
SELF::streamOutput("Job name - " . $job->name . "\n");
// sleep(5);
// print_r(SELF::$event_class_mapping);
// echo array_key_exists($job->name,SELF::$event_class_mapping) ? 'mapped' : 'notmapped';
// die();
try
{
$start = microtime(true);
$runtime = null;
$job_status = self::STATUS_RUNNING;
$db->query("UPDATE jobs SET status=? WHERE id=? AND uuid=?", [$job_status, $job->id,$job->uuid]);
if (!array_key_exists($job->name,SELF::$event_class_mapping))
{
throw new \RuntimeException('Job ' . $job->name . ' handler not registered');
}
$handler = SELF::$event_class_mapping[$job->name];
$handleInstance = null;
if($handler['type'] == 'CC' || $handler['type'] == 'HC')
{
// echo 'CLASS - ' . $handler['type'].' - ' . $handler['handler'];
$handlerClass = $handler['handler'];
if(class_exists($handlerClass))
{
$handleInstance = new $handlerClass();
}
else
{
throw new \RuntimeException('Job ' . $job->name . ' or handler class not found');
// echo $e->getMessage();
}
if (method_exists($handleInstance, $job->name))
{
$jobHandler = [$handleInstance, $job->name];
//throw new \RuntimeException('Job ' . $job->name . ' not found');
}
else if(method_exists($handleInstance, 'handle'))
{
$jobHandler = [$handleInstance, 'handle'];
}
else
{
throw new \RuntimeException('Job ' . $job->name . ' or handler not found');
}
}
else if($handler['type'] == 'HF')
{
// echo 'HF - ' . $handler['type'];
$jobHandler = $handleInstance = $handler['handler'];
// echo $jobHandler;
}
else{
throw new \RuntimeException('Job ' . $job->name . ' Invalid job type');
}
$payload = json_decode($job->payload, true);
if (!is_array($payload))
{
throw new \InvalidArgumentException('Invalid payload format here');
}
$payload = is_array($payload) ? $payload : [];
try
{
$response = $jobHandler($payload,$job->id);
$job_status = self::STATUS_DONE;
}
catch(\Exception $e)
{
$job_status = self::STATUS_FAILED;
$runtime = $runtime === null ? microtime(true) - $start : $runtime;
$response = ['file_name' => $e->getFile(),'error' => $e->getMessage(),'line_no' => $e->getLine(),'info' => $e->getTraceAsString(),'scope' => 'task failed'];
}
$runtime = microtime(true) - $start;
}
catch (\Exception $e)
{
//die();
$job_status = self::STATUS_FAILED;
$runtime = $runtime === null ? microtime(true) - $start : $runtime;
$response = ['file_name' => $e->getFile(),'error' => $e->getMessage(),'line_no' => $e->getLine(),'info' => $e->getTraceAsString(),'scope' => 'worker failed'];
}
$db->query("UPDATE jobs SET status=?, run_time=?, response=? WHERE id=? AND uuid=?", [
$job_status,
$runtime,
json_encode($response),
$job->id,$job->uuid
]);
//update file status if this job is directly linked with a file id
if($job_status == self::STATUS_FAILED)
{
//get file from job payload
if(array_key_exists('file_id', $payload) && $payload['file_id'] != NULL && $payload['file_id'] != "" && is_numeric($payload['file_id']) && count($payload) == 1)
{
$fileModel = new FileModel();
$fileModel->where('id', $payload['file_id'])
->set(['status' => 'failed','reason' => json_encode(['error_type' => 0,'error_summary' => [0],'error_data' => 'System Error, please contact Admin/Support team']) ])
->update();
}
}
// echo "Job $job->id $job_status. Response - $response \n";
// echo "Job $job->id $job_status \n";
SELF::streamOutput("Job $job->id $job_status \n");
return true;
}
else
{
echo 'no job found in queue';
}
}
}

65
app/Controllers/Jobs.php Executable file
View File

@ -0,0 +1,65 @@
<?php
namespace App\Controllers;
use App\Models\JobModel;
class Jobs extends AdminController
{
const STATUS_DONE = 'done';
const STATUS_QUEUED = 'queued';
const STATUS_RUNNING = 'running';
const STATUS_FAILED = 'failed';
protected $job_payload = [];
protected $myLogger;
/**
* Constructs the class
*/
// public function __construct(array $payload = ['job_name' => 'check','payload' => ['a' => 10]])
public function __construct()
{
// $this->job_payload = $payload;
// $this->myLogger = \Config\Services::mylogger();
}
/**
* add jobs to queue
*/
public static function addJob(array $payload)
{
$jobModel = new JobModel();
$myLogger = \Config\Services::mylogger();
try
{
if(!is_array($payload))
{
throw new \InvalidArgumentException('Invalid payload format while add job');
}
if(!isset($payload['job_name']))
{
throw new \InvalidArgumentException('Job name not found while add job');
}
if(!isset($payload['payload']))
{
throw new \InvalidArgumentException('Job payload not found while add job');
}
$uuid = generate_uuid();
$jobid = $jobModel->insert(['name' => $payload['job_name'],'uuid' => $uuid,'payload' => json_encode($payload['payload']), 'status' => isset($payload['status']) ? $payload['status'] : 'queued']);
// echo $jobid;
$myLogger->logme('error','new job {jobid} added to queue',['jobid' => $jobid]);
return ['id' => $jobid,'uuid' => $uuid,'job_name' => $payload['job_name']];
}
catch(\Exception $e)
{
$message = $e->getMessage();
return $message;
$myLogger->logme('error','{messgae}',['messgae' => $message]);
}
}
}

15
app/Controllers/Jobs/AddJob.php Executable file
View File

@ -0,0 +1,15 @@
<?php
namespace App\Controllers\Jobs;
use App\Controllers\PublicController;
class AddJob extends PublicController
{
public function handle($payload)
{
//echo $payload['a'] + $payload['b'];
return $payload['a'] + $payload['b'];
}
}

23
app/Controllers/Jobs/SubJob.php Executable file
View File

@ -0,0 +1,23 @@
<?php
namespace App\Controllers\Jobs;
use App\Controllers\PublicController;
class SubJob extends PublicController
{
protected $myLogger;
public function __construct()
{
$this->myLogger = \Config\Services::mylogger();
}
public function handle($payload)
{
$log = \Config\Services::mylogger();
$log->logme('error', 'insdie handle called');
$this->myLogger->logme('error', 'common handle called');
return $payload['a'] - $payload['b'];
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,129 @@
<?php
namespace App\Controllers;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Models\UserModel;
use App\Models\AuthHistoryModel;
class LoginController extends BaseController
{
public function index(){
// $session_data = ['isLoggedIn' => True ,'userid' => '25'];
// set_session_data($session_data);
// $isLoggedIn = check_session();
$isLoggedIn = check_session();
$hasCookie = check_cookie();
if ($isLoggedIn || $hasCookie) {
return redirect()->to(base_url('/dashboard/view'));
}
return view('login');
}
public function receiveGoogleOAuthResponse()
{
$UserModel = new UserModel();
//echo 'DONE';die();
if ($this->request->getGet('code')) {
$code = (string) $this->request->getGet('code');
log_message('error', 'Get OAuth Responce Code Sucessfully');
log_message('error', 'OAuthResponceCode : `'.$code.'`');
$value = googleOAuthLogin($this->request->getGet('code'));
if($value){
$user = $UserModel->getUserByEmail($value->email);
if($user){
if($user->is_active !== '0'){
$user_team = $UserModel->getUserTeamsByUserID($user->id);
// dd($user_team);
$session_data = [
'isLoggedIn' => True ,
'userid' => $user->id,
'userData' => $user,
'userProfile' => $value->picture,
'user_team' => $user_team,
];
$path = getenv('cookie.Path');
$domain = getenv('cookie.Domain');
$https = getenv('ccokie.secure');
setcookie('session_data', json_encode($session_data), time() + 12 * 60 * 60, $path, $domain, $https, true);
set_session_data($session_data);
log_message('error', 'Set The UserId : `'. $user->id .'` in Session');
log_message('error', 'User Login Sucessfully');
$this->getUserDeviceInfo($user->id, 'NhanceUser');
return redirect()->to(base_url('/dashboard/view'));
}else{
log_message('error', 'User Not Active');
session()->setFlashdata('error', 'User Not Active');
return redirect()->to(base_url('login'));
}
}else{
log_message('error', 'User Not Registered');
session()->setFlashdata('error', 'User Not Registered');
return redirect()->to(base_url('login'));
}
}
}else{
return redirect()->to(base_url('login'));
}
}
public function initiateGoogleOAuth()
{
return googleOAuthLogin(false);
}
public function logout()
{
$path = getenv('cookie.Path');
session()->destroy();
setcookie('session_data', '', time() - 3600, $path);
return redirect()->to(base_url('login'));
}
public function getUserDeviceInfo($userId, $type_of_user){
// Load the UserAgent library
$userAgent = $this->request->getUserAgent();
// Get the user's platform (e.g., Windows, Mac, Linux)
$platform = $userAgent->getPlatform();
// Get the user's browser (e.g., Chrome, Firefox, Safari)
$browser = $userAgent->getBrowser();
// Get the user's IP address
$ipAddress = $this->request->getIPAddress();
$datd = [
'user_id' => $userId,
'user_type' => $type_of_user,
'ip' => $ipAddress,
'platform' => $platform,
'broswer' => $browser,
];
// print_r($datd);
// die();
$AuthHistoryModel = new AuthHistoryModel;
$insertAuthHistory = $AuthHistoryModel->insert($datd);
return $datd;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,283 @@
<?php
// declare(strict_types=1);
namespace App\Controllers;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use CodeIgniter\API\ResponseTrait;
use App\Controllers\Jobs ;
use App\Models\NotificationModel;
use App\Models\ClientModel;
use App\Models\EmployeeModel;
use App\Models\UserModel;
use App\Models\MailAttachmentModel;
use App\Helpers\sendMailNotification;
use App\Helpers\MailHelper;
class NotificationController extends AdminController
{
use ResponseTrait;
protected $myLogger;
protected $notificationModel;
protected $clientModel;
protected $MailAttachmentModel;
public function __construct()
{
$this->myLogger = \Config\Services::mylogger();
$this->notificationModel = new NotificationModel();
$this->clientModel = new ClientModel();
$this->MailAttachmentModel = new MailAttachmentModel();
}
// This is for Template Name Camel Case to Snake Case for store in DB
public function camelCaseToSnakeCase($input)
{
$input = preg_replace('/(?<!^)([A-Z])/', '$1', $input);
$input = str_replace(' ', '_', $input);
return strtolower($input);
}
// Create Or Update the Notification
public function createNotification()
{
$form_data['template_name'] = $this->camelCaseToSnakeCase($this->request->getPost('template_name'));
$form_data['subject'] = $this->request->getPost('subject');
$form_data['mail_content'] = $this->request->getPost('mailContent');
$form_data['client_id'] = $this->request->getPost('client_id');
$form_data['mail_content_json'] = $this->request->getPost('mailJson');
$notificationModel = new NotificationModel();
$find_notification = $notificationModel->where('client_id',$form_data['client_id'])->where('template_name',$form_data['template_name'])->first();
if ($find_notification) {
$id = $find_notification['id'];
$form_data['updated_by'] = get_session_userid();
$notificationModel->update($id,$form_data);
$complete = "Update";
}else{
$form_data['created_by'] = get_session_userid();
$notificationModel->insert($form_data);
$complete = "Inserted";
}
return json_encode($complete);
}
// This is for the Enabls in Notification area and Update the Recipient and HR Mail Id in( Enables -> Notification table and Mail id's -> Client table)
public function update_enable()
{
$checkboxNames = [
'member_welcome_mail_btn',
'member_reminder_mail_btn',
// 'member_ecard_mail_btn',
'member_review_and_summary_mail_btn',
// 'account_maneger_summary_mail_btn',
// 'client_hr_summary_mail_btn'
];
$data = [];
foreach ($checkboxNames as $checkboxName)
{
$data[str_replace('_btn', '', $checkboxName)] = ($this->request->getPost($checkboxName) === "true") ? 1 : 0;
}
$notificationModel = new NotificationModel();
$clientModel = new ClientModel();
$id =$this->request->getPost('client_id');
$clientData['common_mails'] = $this->request->getPost('nhance_team_mail_ids');
$clientData['hr_mails'] = $this->request->getPost('hr_mail_id');
$clientData['reply_to'] = $this->request->getPost('reply_to');
$clientData['mail_domain'] = $this->request->getPost('mail_domain');
$clientModel->update($id,$clientData);
foreach ($data as $key => $value)
{
$find = $notificationModel->where('client_id',$this->request->getPost('client_id'))->where('template_name', $key)->first();
if ($find)
{
$id = $find['id'];
$changeData['enabled']= $value;
$update = $notificationModel->update($id, $changeData);
}
}
return json_encode("true");
}
// This for Load the Template Data for in View Page
public function getMailTemplateData($template_name,$client_id)
{
$notificationModel = new NotificationModel();
$value = $notificationModel->where('client_id',$client_id)->where('template_name',$template_name)->first();
if($value){
$value['data'] = $this->MailAttachmentModel->where('notification_id', $value['id'])->where('is_active', 1)->findAll();
}
// return $this->respond(['status' => true, 'code' => 200, '' => 'Attachment deleted successfully'], 200);
return json_encode($value);
}
// This will send the Reminder Mail
public function reminder_mail()
{
$clientModel = new ClientModel();
$employeeModel = new EmployeeModel();
$notificationModel = new NotificationModel();
$client_list = $clientModel->where('is_active',1)->findAll();
$wholeData = [];
foreach($client_list as $key=>$value){
$notification_data = $notificationModel->where('client_id',$value['id'])->where('template_name', 'member_reminder_mail')->first();
$client_data = $clientModel->where('id', $value['id'])->first();
if(isset($notification_data) && $notification_data['enabled'] == 1){
$emp_data = $employeeModel->where('client_id', $value['id'])->where('is_active',1)->where('emp_status','draft')->findAll();
if( count($emp_data) != 0)
{
$params['emp_data'] = $emp_data;
$params['client_data'] = $client_data;
$params['notification_data'] = $notification_data;
$wholeData[] =sendMailNotification::sendMailNotification('member_reminder_mail', $params);
}
}
}
$count = 0;
foreach ($wholeData as $index => $values) {
$whole_index = $index;
foreach ($values as $index => $value) {
$count++;
$temp_whole_data[] = $value;
if($count == 20 || $whole_index == count($wholeData)-1 && $index == count($values)-1){
if (count($temp_whole_data) > 0) {
$job_details = new Jobs();
$r = Jobs::addJob(['job_name' => 'bulk_mail','payload' => $temp_whole_data]);
$temp_whole_data = [];
$count = 0;
}
}
}
}
}
// This function for sent a mail for testing
public function sentTestMail($template_id, $test_mail)
{
$notification_data = $this->notificationModel->where('id', $template_id)->where('enabled', 1)->first();
$client_data = $this->clientModel->where('id', $notification_data['client_id'])->where('is_active', 1)->first();
if(!empty($notification_data)){
$params = [
'client_data' => $client_data,
'notification_data' => $notification_data,
'test_mail' => $test_mail
];
$testMailData = sendMailNotification::sendMailNotificationForTesting($notification_data['template_name'], $params);
// print_r($testMailData); die;
if (!empty($testMailData)) {
$mail_send_return1 = MailHelper::send_email($testMailData);
$this->myLogger->logme("info", $mail_send_return1);
$this->myLogger->logme("info", $mail_send_return1);
return $this->respond(['status' => true,'code' => 200, 'respond' => json_decode($mail_send_return1)]);
}else{
return $this->respond(['status' => false,'code' => 200, 'message' => 'Test Mail Data Does Not Exist']);
}
}else{
return $this->respond(['status' => false,'code' => 200, 'message' => 'Notification Template not enabled']);
}
}
public function insertAttachmentsForMailTemplates()
{
$form_data = $this->request->getPost();
// Check if client_id and template_name are provided
if (empty($form_data['client_id']) || empty($form_data['template_name'])) {
return $this->respond(['status' => false, 'code' => 400, 'message' => 'Client ID and template name are required.'], 400);
}
// Attempt to find the notification
$find_notification = $this->notificationModel->where('client_id', $form_data['client_id'])
->where('template_name', $form_data['template_name'])
->first();
if (!$find_notification) {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Notification data not found.'], 404);
}
// Define upload path and attempt file upload
$uploadFilePath = WRITEPATH . 'uploads/attachments';
$uploadedFile = $this->request->getFile('file');
$fileName = file_Upload($uploadedFile, $uploadFilePath); // Assume file_Upload handles file saving
if ($fileName) {
// Prepare data for insertion
$data = [
'notification_id' => $find_notification['id'],
'file_name' => $fileName,
'file_path' => 'uploads/attachments/' . $fileName,
];
// Insert file attachment record
if ($this->MailAttachmentModel->insert($data)) {
// Retrieve active attachments to return in response
$attachment_data = $this->MailAttachmentModel->where('is_active', 1)->findAll();
return $this->respond([
'status' => true,
'code' => 200,
'data' => $attachment_data,
'message' => 'File uploaded successfully'
], 200);
} else {
return $this->respond(['status' => false, 'code' => 500, 'message' => 'Failed to save file attachment data.'], 500);
}
} else {
return $this->respond(['status' => false, 'code' => 400, 'message' => 'File upload failed.'], 400);
}
}
public function removeAttachmentsForMailTemplates($id, $client_id, $template_name)
{
$attachment_data_for_unlink_file = $this->MailAttachmentModel->where('id', $id)->first();
$file_path = WRITEPATH . $attachment_data_for_unlink_file['file_path'];
if ($this->MailAttachmentModel->where('id', $id)->delete()) {
unlink($file_path);
$find_notification = $this->notificationModel->where('client_id', $client_id)->where('template_name', $template_name)->first();
$attachmentDatas = $this->MailAttachmentModel->where('notification_id', $find_notification['id'])->where('is_active', 1)->findAll();
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Attachment deleted successfully', 'data' => $attachmentDatas], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'The Client has active policy'], 200);
}
}
}

View File

@ -0,0 +1,714 @@
<?php
namespace App\Controllers;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Helpers\MailHelper;
use App\Helpers\sendMailNotification;
use App\Models\EmployeeModel;
use App\Models\EmployeePolicyModel;
use App\Models\ClientModel;
use App\Models\ClientPolicyModel;
use App\Models\BatchListModel;
use App\Models\BatchFileModel;
use App\Models\EmpEndorsementModel;
use App\Controllers\Jobs;
use App\Controllers\JobWorker;
use CodeIgniter\API\ResponseTrait;
class PendingActionsController extends AdminController
{
use ResponseTrait;
protected $myLogger;
protected $employeeModel;
protected $employeePolicyModel;
protected $clientModel;
protected $clientPolicyModel;
protected $batchListModel;
protected $batchFileModel;
protected $empEndorsementModel;
protected $db;
public function __construct()
{
//session
set_session_context('PendingActionsController Called');
//log services
$this->myLogger = \Config\Services::mylogger();
$this->db = \Config\Database::connect();
//models
$this->employeeModel = new EmployeeModel();
$this->employeePolicyModel = new EmployeePolicyModel();
$this->clientModel = new ClientModel();
$this->clientPolicyModel = new ClientPolicyModel();
$this->batchListModel = new BatchListModel();
$this->batchFileModel = new BatchFileModel();
$this->empEndorsementModel = new EmpEndorsementModel();
}
//for AJAX
public function getPendingActions()
{
//get pending actions like inception, corrections,deletions,SI enhanccnement to users
$inception = $this->getPendingActionForInception();
$correction = $this->getPendingActionForCorrection();
$si_enhancement = $this->getPendingActionForSIEnhancement();
$deletion = $this->getPendingActionForDeletion();
$tpa = $this->getPendingActionForTPAIDEmpty();
$uhid = $this->getPendingActionForUHIDEmpty();
$PolicyRenewalData = $this->getPolicyRenewalDataForAllClient();
// dd($inception, $si_enhancement, $correction, $deletion, $tpa, $uhid);
$data = ['inception' => $inception, 'correction' => $correction, 'si_enhancement' => $si_enhancement, 'deletion' => $deletion, 'tpa' => $tpa, 'uhid' => $uhid, 'policy' => $PolicyRenewalData];
return $this->respond($data);
}
//for NORMAL
public function getPendingActionsForClientData()
{
$inception = $this->getPendingActionForInception();
$correction = $this->getPendingActionForCorrection();
$si_enhancement = $this->getPendingActionForSIEnhancement();
$deletion = $this->getPendingActionForDeletion();
$tpa = $this->getPendingActionForTPAIDEmpty();
$uhid = $this->getPendingActionForUHIDEmpty();
$PolicyRenewalData = $this->getPolicyRenewalDataForAllClient();
// dd($inception, $si_enhancement, $correction, $deletion, $tpa, $uhid);
$data = ['inception' => $inception, 'correction' => $correction, 'si_enhancement' => $si_enhancement, 'deletion' => $deletion, 'tpa' => $tpa, 'uhid' => $uhid, 'policy' => $PolicyRenewalData];
return $data;
}
//for only COUNT
public function getPendingActionsForDashBoard()
{
$tpa = $this->getPendingActionForTPAIDEmpty();
$uhid = $this->getPendingActionForUHIDEmpty();
$deletion = $this->getPendingActionForDeletion();
$inception = $this->getPendingActionForInception();
$ticketData = $this->getTicketsDataForDashBoard();
$correction = $this->getPendingActionForCorrection();
$si_enhancement = $this->getPendingActionForSIEnhancement();
$PolicyRenewalData = $this->getPolicyRenewalDataForAllClient();
$uhid_export_count = [];
$uhid_not_export_count = [];
foreach ($uhid as $value) {
if($value['batch_export_count'] == 1){
$uhid_export_count[] = $value['batch_export_count'];
}else{
$uhid_not_export_count[] = $value['batch_export_count'];
}
}
$tpa_export_count = [];
$tpa_not_export_count = [];
foreach ($tpa as $value) {
if($value['batch_export_count'] == 1){
$tpa_export_count[] = $value['batch_export_count'];
}else{
$tpa_not_export_count[] = $value['batch_export_count'];
}
}
$deletion_export_count = [];
$deletion_not_export_count = [];
foreach ($deletion as $value) {
if($value['batch_export_count'] == 1){
$deletion_export_count[] = $value['batch_export_count'];
}else{
$deletion_not_export_count[] = $value['batch_export_count'];
}
}
$correction_export_count = [];
$correction_not_export_count = [];
foreach ($correction as $value) {
if($value['batch_export_count'] == 1){
$correction_export_count[] = $value['batch_export_count'];
}else{
$correction_not_export_count[] = $value['batch_export_count'];
}
}
$si_export_count = [];
$si_not_export_count = [];
foreach ($si_enhancement as $value) {
if($value['batch_export_count'] == 1){
$si_export_count[] = $value['batch_export_count'];
}else{
$si_not_export_count[] = $value['batch_export_count'];
}
}
// dd($uhid_export_count, $tpa_export_count ,$deletion_export_count, $correction_export_count, $si_export_count, $ticketData, $inception, $si_enhancement, $correction, $deletion, $tpa, $uhid, $PolicyRenewalData);
$inception = count($inception);
$correction = count($correction);
$si_enhancement = count($si_enhancement);
$deletion = count($deletion);
$tpa = count($tpa);
$uhid = count($uhid);
$PolicyRenewalData = count($PolicyRenewalData);
$ticketData = count($ticketData);
$uhid_export_count = count($uhid_export_count);
$tpa_export_count = count($tpa_export_count);
$deletion_export_count = count($deletion_export_count);
$correction_export_count = count($correction_export_count);
$si_export_count = count($si_export_count);
$uhid_not_export_count = count($uhid_not_export_count);
$tpa_not_export_count = count($tpa_not_export_count);
$deletion_not_export_count = count($deletion_not_export_count);
$correction_not_export_count = count($correction_not_export_count);
$si_not_export_count = count($si_not_export_count);
// dd($inception, $si_enhancement, $correction, $deletion, $tpa, $uhid, $PolicyRenewalData);
$data = [
'inception' => $inception,
'correction' => $correction,
'si_enhancement' => $si_enhancement,
'deletion' => $deletion,
'tpa' => $tpa,
'uhid' => $uhid,
'PolicyRenewalData' => $PolicyRenewalData,
'ticketData' => $ticketData,
'uhid_export_count' => $uhid_export_count,
'tpa_export_count' => $tpa_export_count,
'deletion_export_count' => $deletion_export_count,
'correction_export_count' => $correction_export_count,
'si_export_count' => $si_export_count,
'uhid_not_export_count' => $uhid_not_export_count,
'tpa_not_export_count' => $tpa_not_export_count,
'deletion_not_export_count' => $deletion_not_export_count,
'correction_not_export_count' => $correction_not_export_count,
'si_not_export_count' => $si_not_export_count,
];
return $data;
}
public function getPendingActionForInception()
{
// Build the query
$builder = $this->db->table('client_policy cp');
$builder->select('
clients.client_name,
policy_type.policy_type as policy_name,
cp.id as client_policy_id,
cp.client_id,
cp.policy_id,
cp.policy_type_id,
cp.is_addon,
cp.policy_status,
cp.open_for_enrollment,
cp.inception_type,
cb.id as branch_id,
cb.branch_name,
COUNT(ep.id) AS employee_policy_count
');
$builder->join('employee_polices ep', 'cp.id = ep.client_policy_id AND ep.is_active = 1', 'left');
$builder->join('clients', 'cp.client_id = clients.id');
$builder->join('client_branch cb', 'cb.id = cp.client_branch_id');
$builder->join('policy_type', 'cp.policy_type_id = policy_type.id');
$builder->where('cp.is_active', 1);
$builder->where('cp.open_for_enrollment', 1);
$builder->where('cp.is_addon', 1);
$builder->where('cp.policy_status', 1);
$builder->where('cp.inception_type', 1);
$builder->whereIn('cp.policy_type_id', [1, 2, 3]);
$builder->groupBy('cp.id, cp.client_id, cp.policy_id, cp.policy_type_id, cp.is_addon, cp.policy_status, cp.open_for_enrollment');
$builder->having('employee_policy_count = 0 OR employee_policy_count IS NULL');
// Execute the query
$query = $builder->get();
// Fetch the results
$results = $query->getResultArray();
return $results;
}
public function getPendingActionForCorrection()
{
// Subquery for batch_export_count
$subQueryExport = $this->db->table('batch_files bl')
->select('COUNT(*)')
->where('bl.client_id = clients.id')
->where('bl.actions', 'export')
->where('bl.event_type', 'correction')
->where('bl.insurer_or_tpa', 'tpa')
->getCompiledSelect();
// Subquery for batch_import_count
$subQueryImport = $this->db->table('batch_files bl')
->select('COUNT(*)')
->where('bl.client_id = clients.id')
->where('bl.actions', 'import')
->where('bl.event_type', 'correction')
->where('bl.insurer_or_tpa', 'tpa')
->where('bl.status', 'success')
->getCompiledSelect();
// Subquery builder
$subqueryBuilder = $this->db->table('emp_endorsement')
->select('
clients.client_name as client_name,
clients.id as client_id,
client_branch.id as branch_id,
client_branch.branch_name,
policy_type.policy_type as policy_name,
emp_endorsement.id,
emp_endorsement.pk,
emp_endorsement.endorsement_id,
emp_endorsement.group_key,
emp_endorsement.emp_code,
emp_endorsement.table_name,
emp_endorsement.actions,
emp_endorsement.name,
emp_endorsement.status,
employees.name as ename,
(
SELECT COUNT(*)
FROM batch_files bl
WHERE bl.client_id = clients.id
AND bl.actions = "export"
AND bl.event_type = "correction"
AND bl.insurer_or_tpa = "tpa"
) AS export_count
')
->join('employees', 'emp_endorsement.pk = employees.id AND employees.is_active = 1 AND employees.emp_status = \'active\'')
->join('clients', 'employees.client_id = clients.id AND clients.is_active = 1', 'left')
->join('client_policy', 'client_policy.client_id = clients.id AND clients.is_active = 1', 'left')
->join('policy_type', 'client_policy.policy_type_id = policy_type.id ')
->join('client_branch', 'client_branch.id = employees.client_branch_id', 'left')
->where([
'emp_endorsement.actions' => 'c',
'emp_endorsement.is_active' => 1,
'emp_endorsement.status' => 'pending',
'emp_endorsement.endorsement_id' => null
])
->groupBy('emp_endorsement.pk, emp_endorsement.emp_code, emp_endorsement.table_name, emp_endorsement.actions, emp_endorsement.name');
// Main query builder
$builder = $this->db->table('clients');
$builder->select("
subquery.client_name,
subquery.client_id,
subquery.branch_name,
subquery.branch_id,
COUNT(subquery.id) AS subquery_count,
($subQueryExport) AS batch_export_count,
($subQueryImport) AS batch_import_count
");
$builder->join('(' . $subqueryBuilder->getCompiledSelect() . ') AS subquery', 'clients.id = subquery.client_id', 'left');
$builder->groupBy('clients.id');
// Execute the query
$query = $builder->get();
// Fetch the results
$results = $query->getResultArray();
$filteredResults = [];
foreach ($results as $value) {
if ($value['subquery_count'] != 0) {
$filteredResults[] = $value;
}
}
return $filteredResults;
}
public function getPendingActionForSIEnhancement()
{
// Subquery for batch_export_count
$subQueryExport = $this->db->table('batch_files bl')
->select('COUNT(*)')
->where('bl.client_id = clients.id')
->where('bl.actions', 'export')
->where('bl.event_type', 'si_enhancement')
->where('bl.insurer_or_tpa', 'tpa')
->getCompiledSelect();
// Subquery for batch_import_count
$subQueryImport = $this->db->table('batch_files bl')
->select('COUNT(*)')
->where('bl.client_id = clients.id')
->where('bl.actions', 'import')
->where('bl.event_type', 'si_enhancement')
->where('bl.insurer_or_tpa', 'tpa')
->where('bl.status', 'success')
->getCompiledSelect();
// Build the subquery
$subqueryBuilder = $this->db->table('emp_endorsement')
->select('
clients.client_name as client_name,
clients.id as client_id,
client_branch.id as branch_id,
client_branch.branch_name,
client_policy.id as client_policy_id,
policy_type.policy_type as policy_name,
emp_endorsement.id,
emp_endorsement.pk,
emp_endorsement.endorsement_id,
emp_endorsement.group_key,
emp_endorsement.emp_code,
emp_endorsement.table_name,
emp_endorsement.actions,
emp_endorsement.name,
emp_endorsement.status
')
->join('employee_polices', 'emp_endorsement.pk = employee_polices.id AND employee_polices.is_active = 1 AND employee_polices.status = \'active\'')
->join('client_policy', 'employee_polices.client_policy_id = client_policy.id AND client_policy.is_active = 1 AND client_policy.policy_status = 1')
->join('clients', 'client_policy.client_id = clients.id AND clients.is_active = 1')
->join('client_branch', 'client_branch.id = client_policy.client_branch_id')
->join('policy_type', 'client_policy.policy_type_id = policy_type.id')
->where([
'emp_endorsement.actions' => 'si',
'emp_endorsement.is_active' => 1,
'emp_endorsement.status' => 'pending',
'emp_endorsement.endorsement_id' => null
])
->groupBy('emp_endorsement.pk, emp_endorsement.emp_code, emp_endorsement.table_name, emp_endorsement.actions, emp_endorsement.name');
// Build the main query
$builder = $this->db->table('clients');
$builder->select("
clients.id,
subquery.client_name,
subquery.client_id,
subquery.client_policy_id,
subquery.policy_name,
subquery.branch_name,
subquery.branch_id,
COUNT(subquery.id) AS subquery_count,
($subQueryExport) AS batch_export_count,
($subQueryImport) AS batch_import_count
");
$builder->join('(' . $subqueryBuilder->getCompiledSelect() . ') AS subquery', 'clients.id = subquery.client_id', 'left');
$builder->groupBy('clients.id');
// Execute the query
$query = $builder->get();
// Fetch the results
$results = $query->getResultArray();
$filteredResults = [];
foreach ($results as $value) {
if ($value['subquery_count'] != 0) {
$filteredResults[] = $value;
}
}
return $filteredResults;
}
public function getPendingActionForDeletion()
{
// Subquery for batch_export_count
$subQueryExport = $this->db->table('batch_files bl')
->select('COUNT(*)')
->where('bl.client_id = clients.id')
->where('bl.actions', 'export')
->where('bl.event_type', 'deletion')
->where('bl.insurer_or_tpa', 'insurer')
->getCompiledSelect();
// Subquery for batch_import_count
$subQueryImport = $this->db->table('batch_files bl')
->select('COUNT(*)')
->where('bl.client_id = clients.id')
->where('bl.actions', 'import')
->where('bl.event_type', 'deletion')
->where('bl.insurer_or_tpa', 'insurer')
->where('bl.status', 'success')
->getCompiledSelect();
// Build the subquery
$subqueryBuilder = $this->db->table('emp_endorsement')
->select('
clients.id as client_id,
clients.client_name as client_name,
client_branch.id as branch_id,
client_branch.branch_name,
client_policy.id as client_policy_id,
policy_type.policy_type as policy_name,
emp_endorsement.pk,
emp_endorsement.id,
emp_endorsement.group_key,
emp_endorsement.emp_code,
emp_endorsement.table_name,
emp_endorsement.actions,
emp_endorsement.name,
emp_endorsement.status
')
->join('employee_polices', 'emp_endorsement.pk = employee_polices.id AND employee_polices.is_active = 1 AND employee_polices.status = \'active\' AND emp_endorsement.table_name = \'employee_polices\'', 'left')
->join('client_policy', 'employee_polices.client_policy_id = client_policy.id AND client_policy.is_active = 1 AND client_policy.policy_status = 1', 'left')
->join('clients', 'client_policy.client_id = clients.id AND clients.is_active = 1', 'left')
->join('client_branch', 'client_branch.id = client_policy.client_branch_id', 'left')
->join('policy_type', 'client_policy.policy_type_id = policy_type.id', 'left')
->where([
'emp_endorsement.actions' => 'd',
'emp_endorsement.is_active' => 1,
'emp_endorsement.status' => 'pending',
'emp_endorsement.endorsement_id' => null,
'emp_endorsement.table_name' => 'employee_polices'
])
->groupBy('emp_endorsement.pk, emp_endorsement.emp_code, emp_endorsement.actions, emp_endorsement.name');
// Build the main query
$builder = $this->db->table('clients');
$builder->select("
clients.id,
subquery.client_name,
subquery.client_id,
subquery.client_policy_id,
subquery.policy_name,
subquery.branch_name,
subquery.branch_id,
COUNT(subquery.id) AS subquery_count,
($subQueryExport) AS batch_export_count,
($subQueryImport) AS batch_import_count
");
$builder->join('(' . $subqueryBuilder->getCompiledSelect() . ') AS subquery', 'clients.id = subquery.client_id', 'left');
$builder->groupBy('clients.id');
// Execute the query
$query = $builder->get();
// Fetch the results
$results = $query->getResultArray();
$filteredResults = [];
foreach ($results as $value) {
if ($value['subquery_count'] != 0) {
$filteredResults[] = $value;
}
}
return $filteredResults;
}
public function getPendingActionForUHIDEmpty()
{
// Subquery for batch_export_count
$subQueryExport = $this->db->table('batch_files bl')
->select('COUNT(*)')
->where('bl.client_policy_id = cp.id')
->where('bl.actions', 'export')
->where('bl.event_type', 'inception')
->where('bl.insurer_or_tpa', 'insurer')
->getCompiledSelect();
// Subquery for batch_import_count
$subQueryImport = $this->db->table('batch_files bl')
->select('COUNT(*)')
->where('bl.client_policy_id = cp.id')
->where('bl.actions', 'import')
->where('bl.event_type', 'inception')
->where('bl.insurer_or_tpa', 'insurer')
->where('bl.status', 'success')
->getCompiledSelect();
// Main query
$query = $this->db->table('employee_polices ep')
->select('c.id as client_id')
->select('ep.client_policy_id')
->select('c.client_name')
->select('c.short_name')
->select('policy_type.policy_type as policy_name')
->select('ep.uhid')
->select('cb.branch_name, cb.id as branch_id')
->select("($subQueryExport) AS batch_export_count", false)
->select("($subQueryImport) AS batch_import_count", false)
->join('client_policy cp', 'ep.client_policy_id = cp.id AND cp.is_active = 1 AND cp.policy_status = 1')
->join('clients c', 'c.id = cp.client_id')
->join('client_branch cb', 'cb.id = cp.client_branch_id')
->join('policy_type', 'policy_type.id = cp.policy_type_id')
->where('ep.uhid IS NULL')
->where('ep.status', 'active')
->where('ep.is_active', 1)
->groupBy('ep.client_policy_id, ep.uhid, c.short_name, policy_type.policy_type')
->get();
// Fetch the results
$results = $query->getResultArray();
return $results;
}
public function getPendingActionForTPAIDEmpty()
{
// Subquery for batch_export_count
$subQueryExport = $this->db->table('batch_files bl')
->select('COUNT(*)')
->where('bl.client_policy_id = client_policy.id')
->where('bl.actions', 'export')
->where('bl.event_type', 'inception')
->where('bl.insurer_or_tpa', 'tpa')
->getCompiledSelect();
// Subquery for batch_import_count
$subQueryImport = $this->db->table('batch_files bl')
->select('COUNT(*)')
->where('bl.client_policy_id = client_policy.id')
->where('bl.actions', 'import')
->where('bl.event_type', 'inception')
->where('bl.insurer_or_tpa', 'tpa')
->where('bl.status', 'success')
->getCompiledSelect();
// Build the query
$builder = $this->db->table('employee_polices');
$builder->select('
employee_polices.client_policy_id,
employee_polices.uhid,
employee_polices.tpa_id,
clients.short_name,
clients.client_name,
policy_type.policy_type as policy_name,
clients.id as client_id,
client_branch.id as branch_id,
client_branch.branch_name
');
$builder->select("($subQueryExport) AS batch_export_count", false);
$builder->select("($subQueryImport) AS batch_import_count", false);
$builder->join('client_policy', 'employee_polices.client_policy_id = client_policy.id AND client_policy.is_active = 1 AND client_policy.policy_status = 1');
$builder->join('clients', 'clients.id = client_policy.client_id');
$builder->join('client_branch', 'client_branch.id = client_policy.client_branch_id');
$builder->join('policy_type', 'policy_type.id = client_policy.policy_type_id');
$builder->where('employee_polices.tpa_id', null);
$builder->where('employee_polices.uhid IS NOT NULL');
$builder->where('employee_polices.status', 'active');
$builder->where('employee_polices.is_active', 1);
$builder->groupBy('employee_polices.client_policy_id');
// Execute the query
$query = $builder->get();
// Fetch the results
$results = $query->getResultArray();
return $results;
}
public function getPolicyRenewalDataForAllClient()
{
$PolicyRenewalData = $this->clientPolicyModel
->select('
clients.client_name,
client_branch.branch_name,
policy_type.policy_type as policy_name,
client_policy.policy_end_date,
client_branch.id as branch_id
')
->join('clients', 'clients.id = client_policy.client_id')
->join('client_branch', 'client_branch.id = client_policy.client_branch_id')
->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
->where('client_policy.is_active', 1)
->where('client_policy.policy_status', 0)
->where('clients.is_active', 1)
->where('client_branch.is_active', 1)
->where('client_policy.policy_end_date < DATE_ADD(CURDATE(), INTERVAL 2 MONTH)', null, false)
->get()
->getResultArray();
return $PolicyRenewalData;
}
public function getTicketsDataForDashBoard()
{
$db = \Config\Database::connect();
$ticket_data = $db->table('hdz_tickets')
->select('hdz_tickets.*, hdz_status.status')
->join('hdz_status', 'hdz_status.id = hdz_tickets.status')
->where('hdz_status.active', 1)
->where('hdz_tickets.status !=', 5)
->get()
->getResultArray();
return $ticket_data;
}
//ticket status count
public function getTicketStatusCount()
{
$db = \Config\Database::connect();
// Count status = 1
$countStatus1 = $db->table('hdz_tickets')
->selectCount('status')
->where('status', 1)
->get()
->getRowArray()['status'];
// Count status = 4
$countStatus4 = $db->table('hdz_tickets')
->selectCount('status')
->where('status', 4)
->get()
->getRowArray()['status'];
// Count status = 2
$countStatus2 = $db->table('hdz_tickets')
->selectCount('status')
->where('status', 2)
->get()
->getRowArray()['status'];
// Count status = 3
$countStatus3 = $db->table('hdz_tickets')
->selectCount('status')
->where('status', 3)
->get()
->getRowArray()['status'];
}
public function getexportCount()
{
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,16 @@
<?php
namespace App\Controllers;
//This is a publilc controller act like base controller for business logics which are open to public
// not requried any authendication. also config the routes as per requirement in routes.php
class PublicController extends BaseController
{
public function __construct()
{
}
}

View File

@ -0,0 +1,471 @@
<?php
// declare(strict_types=1);
namespace App\Controllers;
use App\Helpers\MailHelper;
use App\Controllers\LoginController;
use App\Helpers\DepositHelper;
use App\Helpers\JWTToken;
use App\Helpers\HttpRequestHelper;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use CodeIgniter\API\ResponseTrait;
use App\Models\EmployeeModel;
use App\Models\AuthHistoryModel;
use App\Models\LevelContactModel;
use Firebase\JWT\JWT;
// require_once('../vendor/autoload.php');
class RestAuthenticationController extends AdminController
{
use ResponseTrait;
protected $myLogger;
protected $employeeModel;
protected $authHistoryModel;
protected $hrModel;
public function __construct()
{
// set_session_context('Client');
$this->myLogger = \Config\Services::mylogger();
$this->employeeModel = new EmployeeModel();
$this->authHistoryModel = new AuthHistoryModel();
$this->hrModel = new LevelContactModel();
}
public function index()
{
$this->myLogger->logme('error','Rest Authentication function called');
$data =["id"=>"2", "role"=>"staff"];
print_r(JWTToken::encode($data));
}
public function logined()
{
$this->myLogger->logme('error','Rest Authentication function called');
echo "Rest Authentication Logined Success........";
}
private function callThirdPartyAPI($postData , $endPoint)
{
$client = \Config\Services::curlrequest();
$url = env('POST_ENROLLMENT_BASEURL').$endPoint;
$response = $client->post( $url, ['json' => $postData, 'http_errors' => false ] );
// return json_decode($response->getBody(), true);
return $response->getBody();
}
public function verifyEmployeeWithMobileNumber()
{
try {
$mobile_number = $this->request->getJSON()->mobile_number;
$employeeData = $this->employeeModel->select('employees.relationship,EP.employee_id')
->join('employee_polices EP', 'EP.employee_id = employees.id', 'inner')
->where('employees.is_active', 1)
->where('employees.relationship', 'self')
->where('employees.emp_status !=', 'truncated')
->where('employees.mobile', $mobile_number)
->where('EP.is_active', 1)
->whereIn('EP.status', ['draft', 'enrolled'])
->first();
if (isset($employeeData['employee_id']))
{
$result = ['user_verification' => true ,'message' => "Verified Successfully" ];
return $this->respond(['status' => 'success','code' => 200,'data' => $result],200);
} else {
// Call the third-party API function
return $this->callThirdPartyAPI($this->request->getJSON(),'verifyEmployeeNumber');
}
} catch (\Throwable $th) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500);
}
}
public function verifyEmployeeWithEmailId()
{
try {
$email = $this->request->getJSON()->email;
$employeeData = $this->employeeModel->select('employees.relationship,EP.employee_id')
->join('employee_polices EP', 'EP.employee_id = employees.id', 'inner')
->where('employees.is_active', 1)
->where('employees.relationship', 'self')
->where('employees.emp_status !=', 'truncated')
->where('employees.email_corporate', $email)
->where('EP.is_active', 1)
->whereIn('EP.status', ['draft', 'enrolled'])
->first();
if (isset($employeeData['employee_id']))
{
$otp = random_int(100000, 999999);
$update = $this->employeeModel->where('email_corporate', $email)->where('relationship', 'self')
->where('is_active', 1)->set(array('otp' => $otp ))
->update();
if($update)
{
$common = [
'client_id' => $employeeData['client_id'],
'client_branch_id' => $employeeData['client_branch_id'],
'client_policy_id' => null,
'employee_policy_id' => null,
'employee_id' => $employeeData['id'],
'mail_type' => 'otp_mail',
];
$subject = 'Nhance user verification - OTP';
$mail_content = $otp.' is your verification code for Nhance.';
$res = MailHelper::send_email(['mail' => $employeeData['email_corporate'], 'subject' => $subject ,'common'=>$common ,'message' => $mail_content]);
$this->myLogger->logme("info", $res);
if(json_decode($res)->status == 'success')
{
$result = ['user_verification' => true ,'message' => "Verified Successfully"];
return $this->respond(['status' => 'success','code' => 200,'data' => $result],200);
}else{
$result = ['user_verification' => false , 'message' => "Mail sending failed , try again"];
return $this->respond(['status' => 'failed','code' => 404,'data' => $result],200);
}
}else{
$result = ['user_verification' => false , 'message' => "Verification failed , try again"];
return $this->respond(['status' => 'failed','code' => 404,'data' => $result],200);
}
} else {
// Call the third-party API function
return $this->callThirdPartyAPI($this->request->getJSON(),'verifyEmployeeEmailId');
}
} catch (\Throwable $th) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500);
}
}
public function getVerifiedUserData()
{
try {
$otp_verification = isset($this->request->getJSON()->otp_verification) ? $this->request->getJSON()->otp_verification : null;
$mobile_number = isset($this->request->getJSON()->mobile_number) ? $this->request->getJSON()->mobile_number : null;
$otp = isset($this->request->getJSON()->otp) ? $this->request->getJSON()->otp : null;
$email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null;
if (isset($this->request->getJSON()->login_by_hr))
{
$employeeData = $this->employeeModel->where('id', $this->request->getJSON()->employee_id)->where('relationship', 'self')->where('emp_status !=', 'truncated')->where('is_active', 1)->first();
}else{
if (isset($mobile_number))
{
$employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->where('emp_status !=', 'truncated')->where('is_active', 1)->first();
} else {
$employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('otp', $otp)->where('relationship', 'self')->where('emp_status !=', 'truncated')->where('is_active', 1)->first();
}
}
if ($employeeData && $otp_verification == true || $employeeData && isset($this->request->getJSON()->login_by_hr) || $employeeData && isset($this->request->getJSON()->otp) )
{
$auth = HttpRequestHelper::getRequestInfo();
if ($auth) {
$data = [
'user_id' => $employeeData['id'],
'user_type' => 'employee',
'ip' => $auth['ip'],
'platform' => $auth['platform'],
'broswer' => $auth['browser'],
];
$this->authHistoryModel->insert($data);
}
$result = JWTToken::encode($employeeData);
if(isset($this->request->getJSON()->otp)){
$this->employeeModel->where('email_corporate', $email_id)->where('otp', $otp)->where('relationship', 'self')->set(['otp'=>null])->update();
}
// Call the third-party API function
$apiResponse = $this->callThirdPartyAPI($this->request->getJSON(),'getVerifiedUserData');
return $this->respond(['status' => 'success','code' => 200,'data' => $result , 'post_enrollment'=> json_decode($apiResponse, true)],200);
} else {
// Call the third-party API function
$apiResponse = $this->callThirdPartyAPI($this->request->getJSON(),'getVerifiedUserData');
return $this->respond(['status' => 'failed','code' => 404,'data' => "Invalid OTP" , 'post_enrollment'=> json_decode($apiResponse, true)],200);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()],500);
}
}
public function verifyHrWithMobileNumber()
{
try {
$mobile_number = $this->request->getJSON()->mobile_number;
$HrData = $this->hrModel->where('mobile', $mobile_number)
->where('contact_type', 'client')
->where('is_active', 1)
->first();
if ($HrData) {
$result = ['user_verification' => true ,'message' => "Verified Successfully"];
return $this->respond(['status' => 'success','code' => 200,'data' => $result],200);
} else {
$result = ['user_verification' => false , 'message' => "User not found"];
return $this->respond(['status' => 'failed','code' => 404,'data' => $result],200);
}
} catch (\Throwable $th) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500);
}
}
public function getVerifiedHrData()
{
try {
$mobile_number = $this->request->getJSON()->mobile_number;
$otp_verification = $this->request->getJSON()->otp_verification;
$hrData = $this->hrModel->where('mobile', $mobile_number)->first();
if ($hrData && $otp_verification == true) {
$auth = HttpRequestHelper::getRequestInfo();
if ($auth) {
$data = [
'user_id' => $hrData['id'],
'user_type' => 'hr',
'ip' => $auth['ip'],
'platform' => $auth['platform'],
'broswer' => $auth['browser'],
];
$this->authHistoryModel->insert($data);
}
$hrData = $this->hrModel ->select('level_contacts.* , client_branch.client_id as client_id')
->join('client_branch', 'level_contacts.ref_id = client_branch.id', 'left')
->where('level_contacts.mobile', $mobile_number )
->find();
$result = JWTToken::encode($hrData['0']);
return $this->respond(['status' => 'success','code' => 200,'data' => $result],200);
} else {
return $this->respond(['status' => 'failed','code' => 404,'data' => "Invalid OTP"],200);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()],500);
}
}
public function getUserIdFromToken()
{
$id = JWTToken::getUserIdFromToken();
// echo $id['id'];
echo "Id----> ";
print_r($id);
$role = JWTToken::getUserRoleFromToken();
echo " Role----> ";
echo $role;
$tokenArray = JWTToken::decodeToken();
echo " TokenArray----> ";
print_r($tokenArray);
}
public function saveMpin()
{
try {
$mobile_number = isset($this->request->getJSON()->mobile_number) ? $this->request->getJSON()->mobile_number : null;
$email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null;
if (isset($mobile_number)) {
$employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->first();
} else {
$employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('relationship', 'self')->first();
}
$mpin = $this->request->getJSON()->mpin;
if ($employeeData) {
$id= $employeeData["id"];
$updateMpin = $this->employeeModel->where('id', $id)->set('mpin', $mpin)->update();
if($updateMpin){
$result = ['user_verification' => true , 'message' => "Mpin Updated"];
return $this->respond(['status' => 'success','code' => 200,'data' => $result],200);
}else{
$result = ['user_verification' => true , 'message' => "Mpin Not Updated"];
return $this->respond(['status' => 'failed','code' => 404,'data' => $result],200);
}
} else {
$result = ['user_verification' => false , 'message' => "User not found"];
return $this->respond(['status' => 'failed','code' => 404,'data' => $result],200);
}
} catch (\Throwable $th) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500);
}
}
public function updateMpin()
{
try {
$mobile_number = isset($this->request->getJSON()->mobile_number) ? $this->request->getJSON()->mobile_number : null;
$email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null;
$old_mpin = $this->request->getJSON()->old_mpin;
$mpin = $this->request->getJSON()->new_mpin;
if (isset($mobile_number))
{
$employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('mpin', $old_mpin)->where('relationship', 'self')->first();
}else{
$employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('mpin', $old_mpin)->where('relationship', 'self')->first();
}
if ($employeeData) {
$id= $employeeData["id"];
$updateMpin = $this->employeeModel->where('id', $id)->set('mpin', $mpin)->update();
if($updateMpin){
$result = ['mpin_verification' => true , 'message' => "Mpin Updated"];
return $this->respond(['status' => 'success','code' => 200,'data' => $result],200);
}else{
$result = ['mpin_verification' => true , 'message' => "Mpin Not Updated"];
return $this->respond(['status' => 'failed','code' => 404,'data' => $result],200);
}
} else {
$result = ['mpin_verification' => false , 'message' => "Wrong Mpin"];
return $this->respond(['status' => 'failed','code' => 404,'data' => $result],200);
}
} catch (\Throwable $th) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $th],500);
}
}
public function verifyMpin()
{
try {
$mobile_number = isset($this->request->getJSON()->mobile_number) ? $this->request->getJSON()->mobile_number : null;
$email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null;
$mpin = $this->request->getJSON()->mpin;
if (isset($mobile_number))
{
$employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->first();
}else{
$employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('relationship', 'self')->first();
}
if ($employeeData && $mpin == $employeeData["mpin"]) {
$auth = HttpRequestHelper::getRequestInfo();
if ($auth) {
$data = [
'user_id' => $employeeData['id'],
'user_type' => 'employee',
'ip' => $auth['ip'],
'platform' => $auth['platform'],
'broswer' => $auth['browser'],
];
$authdata= $this->authHistoryModel->insert($data);
}
$result = JWTToken::encode($employeeData);
// Call the third-party API function
$apiResponse = $this->callThirdPartyAPI($this->request->getJSON(),'verifyMpin');
return $this->respond(['status' => 'success','code' => 200,'data' => $result , 'post_enrollment'=> json_decode($apiResponse, true)],200);
} else {
// Call the third-party API function
$apiResponse = $this->callThirdPartyAPI($this->request->getJSON(),'getVerifiedUserData');
return $this->respond(['status' => 'failed','code' => 404,'data' => "Invalid OTP", 'post_enrollment'=> json_decode($apiResponse, true)],200);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()],500);
}
}
public function checkMpin()
{
try {
$mobile_number = isset($this->request->getJSON()->mobile_number) ? $this->request->getJSON()->mobile_number : null;
$email_id = isset($this->request->getJSON()->email_id) ? $this->request->getJSON()->email_id : null;
if (isset($mobile_number))
{
$employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('relationship', 'self')->first();
}else{
$employeeData = $this->employeeModel->where('email_corporate', $email_id)->where('relationship', 'self')->first();
}
if ($employeeData && $employeeData["mpin"] != null) {
return $this->respond(['status' => 'success','code' => 200,'data' => "Mpin - exist" , 'Mpin' =>$employeeData["mpin"]],200);
} else {
return $this->respond(['status' => 'failed','code' => 404,'data' => "Mpin - not found", 'Mpin' =>null],200);
}
} catch (\Exception $e) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $e->getMessage()],500);
}
}
}

View File

@ -0,0 +1,10 @@
<?php namespace App\Controllers;
use App\Controllers\BaseController;
class SwaggerController extends BaseController
{
public function index(){
return view('swagger/index');
}
}

View File

@ -0,0 +1,235 @@
<?php
namespace App\Controllers;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Models\UserModel;
use App\Models\RoleModel;
use App\Models\TeamModel;
use App\Models\UserTeamsModel;
class UserController extends AdminController
{
protected $myLogger;
protected $userModel;
protected $roleModel;
protected $teamModel;
protected $userTeamsModel;
public function __construct()
{
set_session_context('User');
$this->myLogger = \Config\Services::mylogger();
$this->userModel = new UserModel();
$this->roleModel = new RoleModel();
$this->teamModel = new TeamModel();
$this->userTeamsModel = new UserTeamsModel();
}
public function list()
{
$data['page_name'] = 'User';
$this->myLogger->logme('error','User list function called');
$data['UserList'] = $this->userModel->getUserList();
// echo '<pre>';
// print_r($data); die;
$data['roleData'] = $this->roleModel->select('id, role')->findAll();
$data['teamData'] = $this->teamModel->select('id, name')->findAll();
$this->loadLayout('UserList', $data);
}
public function create()
{
$this->myLogger->logme('error', 'User create function called');
$teams = $this->request->getPost('team');
//if this is get method return to user creation page
if (!$this->request->getPost()) {
return redirect()->to(base_url('/user/list'));
} else {
$userData = $this->request->getPost();
$userData['created_by'] = get_session_userid();
$temp_team = $userData['team'];
unset($userData['team']);
$insert = $this->userModel->insert($userData);
if ($insert) {
$teamData['user_id'] = $insert;
foreach ($teams as $value) {
$teamData['team_id'] = $value;
$teamData['created_by'] = get_session_userid();
$this->userTeamsModel->insert($teamData);
}
$db = \Config\Database::connect();
$tableName = 'hdz_staff';
// Set default values
$admin = 0;
$acm = 0;
$acm_id = null;
if ($userData['role'] == 3) {
$admin = 0;
$acm = 1;
$acm_id = $insert;
} else if (in_array($userData['role'], [1, 5])) {
$admin = 1;
$acm = 0;
$acm_id = null;
}
$password = '12345678'; // Default password
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$hdz_staff = [
'emp_code' => $userData['emp_code'],
'fullname' => $userData['first_name'],
'username' => strtolower($userData['first_name']),
'email' => $userData['email'],
'admin' => $admin,
'acm' => $acm,
'acm_id' => $acm_id,
'registration' => time(),
'password' => $hashedPassword,
'active' => 1,
'department' => 'a:7:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"5";i:3;s:1:"3";i:4;s:1:"9";i:5;s:1:"4";i:6;s:2:"10";}',
];
$db->table($tableName)->insert($hdz_staff);
}
}
$this->myLogger->logme('error', 'User create Successfully created by id {data}', ['data' => get_session_userid()]);
return redirect()->to(base_url('/user/list'));
}
public function getuser($id = null)
{
$userTeamData = $this->userTeamsModel->where('user_id', $id)->findAll();
$data = $this->userModel->getUserById($id);
if($data){
echo json_encode(array("status" => true , 'data' => $data, 'userTeamData' => $userTeamData));
}else{
echo json_encode(array("status" => false));
}
}
public function edit()
{
if (!$this->request->getPost()) {
return redirect()->to(base_url('/user/list'));
} else {
$id = $this->request->getPost('PrimaryKey');
$teams = $this->request->getPost('team');
$userData = $this->request->getPost();
unset($userData['csrf_test_name']);
unset($userData['PrimaryKey']);
// Update data in the 'users' table based on the $id
$userData['updated_by'] = get_session_userid();
$update = $this->userModel->where('id', $id)->set($userData)->update();
if ($update) {
if ($teams) {
$this->userTeamsModel->where('user_id', $id)->delete();
$teamData['user_id'] = $id;
foreach ($teams as $value) {
$teamData['team_id'] = $value;
$teamData['created_by'] = get_session_userid();
$this->userTeamsModel->insert($teamData);
}
}
$db = \Config\Database::connect();
$tableName = 'hdz_staff';
$hdz_staff = [
'emp_code' => $userData['emp_code'],
'fullname' => $userData['first_name'],
'username' => strtolower($userData['first_name']),
'email' => $userData['email'],
'registration' => time(),
'active' => 1,
'department' => 'a:7:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"5";i:3;s:1:"3";i:4;s:1:"9";i:5;s:1:"4";i:6;s:2:"10";}',
];
if ($userData['role'] == 3) {
$hdz_staff['admin'] = 0;
$hdz_staff['acm'] = 1;
$hdz_staff['acm_id'] = $id;
} elseif (in_array($userData['role'], [1, 5])) {
$hdz_staff['admin'] = 1;
$hdz_staff['acm'] = 0;
$hdz_staff['acm_id'] = null;
} else {
return redirect()->to(base_url('/user/list'));
}
// Check if staff data exists
$staffData = $db->table($tableName)
// ->where('emp_code', $userData['emp_code'])
->where('email', $userData['email'])
->get()->getResult();
if (!empty($staffData)) {
// Update existing record
$db->table($tableName)
// ->where('emp_code', $userData['emp_code'])
->where('email', $userData['email'])
->set($hdz_staff)->update();
} else {
$password = '12345678'; // Default password
$hdz_staff['password'] = password_hash($password, PASSWORD_DEFAULT);
// Insert new record
$db->table($tableName)->insert($hdz_staff);
}
}
return redirect()->to(base_url('/user/list'));
}
}
public function deactive($id = null)
{
$model = new UserModel();
$deactive = $model->where('id', $id)->set(['is_active' => 0])->update();
if($deactive)
{
// $db = \Config\Database::connect();
// $tableName = 'hdz_staff';
// $db->table($tableName)->insert($hdz_staff);
echo json_encode(array("status" => true));
}else{
echo json_encode(array("status" => false));
}
}
public function getRolesAndTeams()
{
$roleData = $this->roleModel->select('id, role')->findAll();
$teamData = $this->teamModel->select('id, name')->findAll();
echo json_encode(array("status" => true , 'roleData' => $roleData, 'teamData' => $teamData,));
}
}

View File

0
app/Database/Seeds/.gitkeep Executable file
View File

0
app/Filters/.gitkeep Executable file
View File

89
app/Filters/AuthJWT.php Executable file
View File

@ -0,0 +1,89 @@
<?php
namespace App\Filters;
use App\Helpers\JWTToken;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use ReflectionClass;
require_once('../vendor/autoload.php');
use App\Models\EmployeeModel;
use App\Models\LevelContactModel;
class AuthJWT implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
$jwt = $request->getHeader('Authorization');
if ($jwt) {
if (JWTToken::validateJWT($jwt)) {
$data = JWTToken::validateJWT($jwt);
$data = json_decode($data);
$id = $data->decoded->id;
if(isset($data->decoded->emp_code)){
$model = new EmployeeModel();
$user_data = $model->where('id', $id)->first();
if($user_data['token_time_out'] > time()){
$data =["token_time_out" => time() + getenv('TOKENTIMEOUT') ];
$model->update($id, $data);
return true;
}else{
// if($user_data['token_time_out'] != "" && $user_data['token_time_out'] != NULL)
$data =["token_time_out" => ''];
$model->update($id, $data);
header('Content-Type: application/json');
http_response_code(401);
// $error = json_encode(["status" => 401, "message" => $data->message]);
$error = json_encode(["status" => 401, "message" => "Token is Invalid"]);
echo $error;
exit;
}
}else{
$model = new LevelContactModel();
$hr_data = $model->where('id', $id)->first();
if($hr_data['token_time_out'] > time()){
$data =["token_time_out" => time() + getenv('TOKENTIMEOUT') ];
$model->update($id, $data);
return true;
}else{
$data =["token_time_out" => ''];
$model->update($id, $data);
header('Content-Type: application/json');
http_response_code(401);
// $error = json_encode(["status" => 401, "message" => $data->message]);
$error = json_encode(["status" => 401, "message" => "Token is Invalid"]);
echo $error;
exit;
}
}
}
} else {
header('Content-Type: application/json');
http_response_code(403);
$error = json_encode(["status" => 403, "message" => "Access Forbidden!"]);
echo $error;
exit();
}
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// Do something here after the response is sent
}
}

23
app/Filters/AuthMVC.php Executable file
View File

@ -0,0 +1,23 @@
<?php
namespace App\Filters;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
class AuthMVC implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
if (!check_session() && !check_cookie()) {
return redirect()->to(base_url('/login'));
}
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// Do something here
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace App\Filters;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\Database\Config;
class CloseDbConnection implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
// No action needed before the request
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// Get all database configurations
$db = \Config\Database::connect();
$log = \Config\Services::mylogger();
// $log->logme('error','CloseDbConnections....!');
$db->close();
}
}

28
app/Filters/HttpRequestLog.php Executable file
View File

@ -0,0 +1,28 @@
<?php
namespace App\Filters;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
class HttpRequestLog implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
// log_message('info', 'HttpRequestLog before');
$uuid = generate_uuid();
// echo $uuid;//die();
set_session_uuid($uuid);
$context = 'HTTP REQUEST';
$log = \Config\Services::mylogger();
$message = '{ip} - {platform} - {browser} - {method} - {endpoint} - {getparams} - {postparams} - REQ RECEIVED';
$log->logme('ERROR',$message,['context' => $context],1);
;
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
}
}

25
app/Filters/RoleCheck.php Executable file
View File

@ -0,0 +1,25 @@
<?php
namespace App\Filters;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
class RoleCheck implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
if (!session()->get('role')) {
return redirect()->to(site_url('login'));
}
$current_loggedin_user_role = session()->get('role');
//check this role has permisssion to access current resource
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// Do something here
}
}

0
app/Helpers/.gitkeep Executable file
View File

119
app/Helpers/DepositHelper.php Executable file
View File

@ -0,0 +1,119 @@
<?php
// File: App\Helpers\DepositHelper.php
namespace App\Helpers;
use App\Models\ClientDepositModel;
use App\Models\CDMasterModel;
class DepositHelper
{
/**
* Calculate the new balance based on the transaction type.
*
* @param float $lastBalance The last known balance.
* @param float $amount The transaction amount.
* @param string $transactionType The transaction type.
*
* @return float The new balance.
*/
public static function calculateBalance(float $lastBalance, float $amount, string $transactionType): float
{
return ($transactionType === 'Credit') ? $lastBalance + $amount : $lastBalance - $amount;
}
/**
* Save a deposit transaction.
*
* @param array $data The transaction data.
* @param float $newBalance The new balance.
*
* @return array The response array.
*/
public static function saveDeposit(array $data, int $loggedInUserID): array
{
// Retrieve the last known balance
$lastBalance = self::calculateLastBalance($data['client_id'], $data['insurer_id'], $data['cd_ac_no']);
// Calculate the new balance based on the transaction type
$newBalance = self::calculateBalance(
$lastBalance,
(float)$data['amount'],
$data['transaction_type'] ?: 'Credit'
);
// Insert data into cash_deposit table
$model = new ClientDepositModel();
// Insert data into the cash_deposit table
$insertData = [
'amount' => $data['amount'],
'sub_type' => $data['sub_type_id'],
'client_id' => $data['client_id'],
'client_policy_id' => $data['client_policy_id'] ?? 0,
'cd_ac_no' => $data['cd_ac_no'],
'endorsement_no' => $data['endorsement_no'],
'insurer_id' => $data['insurer_id'],
'unit' => $data['unit'] ?? null,
'description' => $data['description'] ?? null,
'event_name' => $data['event_name'] ?? null,
'transaction_type' => $data['transaction_type'],
'is_active' => 1,
'created_by' => $loggedInUserID,
'updated_by' => $data['updated_by'],
'balance' => $newBalance, // Include the new balance in the data array
'cd_ac_pk'=> isset($data['cd_ac_pk'])?$data['cd_ac_pk']:null,
];
// Insert data and get the insert ID
$insertId = $model->insert($insertData);
// Return the response
if ($insertId) {
return [
'success' => true,
'message' => 'Transaction saved successfully',
'insert_id' => $insertId,
];
} else {
return [
'success' => false,
'message' => 'Failed to save transaction',
];
}
}
/**
* Calculate the last balance based on client and insurer ID.
*
* @param int $clientId The client ID.
* @param int $insurerId The insurer ID.
*
* @return float The last known balance.
*/
public static function calculateLastBalance(int $clientId, int $insurerId, $cd_ac_no): float
{
$model = new ClientDepositModel();
// $getLastBalanceQuery = "SELECT balance FROM cash_deposit WHERE client_id = ? AND insurer_id = ? ORDER BY created_at DESC LIMIT 1";
// $getLastBalanceParams = [$clientId, $insurerId];
$getLastBalanceQuery = "SELECT balance FROM cash_deposit WHERE cd_ac_no = ? AND is_active = 1 ORDER BY created_at DESC LIMIT 1";
$getLastBalanceParams = [$cd_ac_no];
$lastBalance = $model->query($getLastBalanceQuery, $getLastBalanceParams)->getRow()->balance ?? 0;
// if(empty($lastBalance) && $lastBalance == null){
// $cd_model = new ClientDepositModel();
// $getLastBalanceQuery = "SELECT opening_bal FROM cd_master WHERE client_id = ? AND insurer_id = ? AND cd_ac_no = ? AND is_active = 1 ORDER BY created_at DESC LIMIT 1";
// $getLastBalanceParams = [$clientId, $insurerId, $cd_ac_no];
// $lastBalance = $cd_model->query($getLastBalanceQuery, $getLastBalanceParams)->getRow()->opening_bal ?? 0;
// }
return $lastBalance;
}
}
?>

150
app/Helpers/ExcelMergeHelper.php Executable file
View File

@ -0,0 +1,150 @@
<?php
namespace App\Helpers;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Exception;
class ExcelMergeHelper {
/**
* Main merge function with auto-retry
*
* @param array $filePaths Array of file paths with optional sheets to merge.
* @param string $outputPath Path to save the merged Excel file.
* @return string|null Returns output path on success, null on failure.
*/
public static function mergeExcelFiles(array $filePaths, string $outputPath): ?string
{
try {
log_message('debug', 'Attempting merge with original file order');
return self::processFiles($filePaths, $outputPath);
} catch (Exception $e) {
log_message('error', 'First attempt failed: ' . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine());
log_message('debug', 'Retrying with reversed file order');
// Reverse the file order and try again
$reversedFiles = array_reverse($filePaths);
try {
return self::processFiles($reversedFiles, $outputPath);
} catch (Exception $e2) {
log_message('error', 'Both attempts failed. Last error: ' . $e2->getMessage() . ' in ' . $e2->getFile() . ' on line ' . $e2->getLine());
return null;
}
}
}
/**
* Process files to merge spreadsheets
*
* @param array $filePaths
* @param string $outputPath
* @return string
* @throws Exception
*/
private static function processFiles(array $filePaths, string $outputPath): string
{
log_message('debug', 'Starting Excel merge process');
log_message('debug', 'Files to process: ' . json_encode($filePaths));
if (empty($filePaths)) {
throw new Exception("No files provided to merge");
}
// Initialize an empty merged spreadsheet
$mergedSpreadsheet = new Spreadsheet();
$mergedSpreadsheet->removeSheetByIndex(0); // Remove the default empty sheet
// Process the base file
$firstFile = array_shift($filePaths);
self::processSingleFile($firstFile, $mergedSpreadsheet);
// Process remaining files
foreach ($filePaths as $index => $fileInfo) {
self::processSingleFile($fileInfo, $mergedSpreadsheet, $index);
}
// Save the merged file
log_message('debug', "Saving merged file to: {$outputPath}");
$writer = IOFactory::createWriter($mergedSpreadsheet, 'Xlsx');
$writer->setPreCalculateFormulas(false);
$writer->save($outputPath);
// Clean up
$mergedSpreadsheet->disconnectWorksheets();
unset($mergedSpreadsheet);
gc_collect_cycles();
log_message('debug', 'Excel merge process completed successfully');
return $outputPath;
}
/**
* Process a single file to merge its sheets into the merged spreadsheet
*
* @param array $fileInfo
* @param Spreadsheet $mergedSpreadsheet
* @param int|null $index
* @throws Exception
*/
private static function processSingleFile(array $fileInfo, Spreadsheet $mergedSpreadsheet, int $index = null)
{
if (!isset($fileInfo['file_path']) || !file_exists($fileInfo['file_path'])) {
$path = $fileInfo['file_path'] ?? 'undefined';
log_message('error', "File " . ($index ?? 'base') . ": Invalid or missing file path: {$path}");
return;
}
log_message('debug', "Processing file " . ($index ?? 'base') . ": " . $fileInfo['file_path']);
try {
// Load the source spreadsheet
$sourceSpreadsheet = IOFactory::load($fileInfo['file_path']);
// Get all worksheets
$worksheets = $sourceSpreadsheet->getAllSheets();
$totalSheets = count($worksheets);
log_message('debug', "Total sheets in file: " . $totalSheets);
$sheetsToMerge = $fileInfo['sheets'] ?? [];
// Process each worksheet
foreach ($worksheets as $sheetIndex => $worksheet) {
if (empty($sheetsToMerge) || in_array($sheetIndex, $sheetsToMerge)) {
try {
$sheetName = $worksheet->getTitle();
log_message('debug', "Processing sheet: {$sheetName}");
// Generate unique sheet name before cloning
$newName = $sheetName;
$counter = 1;
while (in_array($newName, $mergedSpreadsheet->getSheetNames())) {
$newName = $sheetName . "_" . $counter++;
log_message('debug', "Sheet name already exists. Trying new name: {$newName}");
}
// Clone the worksheet and set the new name
$clonedSheet = clone $worksheet;
$clonedSheet->setTitle($newName);
// Add as external sheet
$mergedSpreadsheet->addExternalSheet($clonedSheet);
log_message('debug', "Successfully added sheet: {$newName}");
} catch (Exception $e) {
log_message('error', "Error processing sheet {$sheetName} as new name {$newName}: " . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine());
}
}
}
// Clean up source spreadsheet
$sourceSpreadsheet->disconnectWorksheets();
unset($sourceSpreadsheet);
gc_collect_cycles();
} catch (Exception $e) {
log_message('error', "Error processing file {$fileInfo['file_path']}: " . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine());
}
}
}

View File

@ -0,0 +1,51 @@
<?php
namespace App\Helpers;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
class ExcelSanitizeHelper
{
/**
* Array of non-printable characters to be removed from strings.
*
* You can modify this array to include any characters you want to remove.
*/
private static $nonPrintableChars = [
"\x00", "\x01", "\x02", "\x03", "\x04", "\x05", "\x06", "\x07", "\x08", "\x09",
"\x0A", "\x0B", "\x0C", "\x0D", "\x0E", "\x0F", "\x10", "\x11", "\x12", "\x13",
"\x14", "\x15", "\x16", "\x17", "\x18", "\x19", "\x1A", "\x1B", "\x1C", "\x1D",
"\x1E", "\x1F", "\x7F", "_x000D_", "_x000A_", "_x0009_", "_x0008_", "_x0007_",
"_x0006_", "_x0005_", "_x0004_", "_x0003_", "_x0002_", "_x0001_"
];
/**
* Sanitizes array data by removing non-printable characters and trimming whitespace from strings.
*
* @param array $data Input array containing data to sanitize
* @return array Sanitized array with non-printable characters removed and leading/trailing whitespace trimmed
*/
public static function sanitizeArrayData(array $data): array
{
try {
$cleanData = [];
foreach ($data as $key => $value) {
if (is_array($value)) {
$cleanData[$key] = self::sanitizeArrayData($value); // Recursive call for nested arrays
} elseif (is_string($value)) {
// Remove non-printable characters and trim whitespace from strings
$cleanData[$key] = trim(str_replace(self::$nonPrintableChars, '', $value));
} else {
$cleanData[$key] = $value; // Keep non-string/non-array data as is
}
}
return $cleanData;
} catch (\Exception $e) {
// Log the error and the problematic data for debugging
log_message('error', 'Error sanitizing array data: ' . $e->getMessage());
log_message('error', 'Problematic data: ' . json_encode($data));
return $data; // Return the original data in case of error
}
}
}

View File

@ -0,0 +1,125 @@
<?php
namespace App\Helpers;
use App\Models\EmployeePolicyModel;
use App\Models\GmailSentHistoryModel;
use Exception;
class GmailResponseHandler{
private $myLogger;
public function __construct()
{
$this->myLogger = \Config\Services::mylogger();
}
public function receive_and_distribute_param_to_functions($params)
{
try{
$this->store_gmail_response_data($params);
$this->gmail_response_logger($params);
$this->client_id_flag_setter($params);
}
catch(Exception $e)
{
$error = $e->getMessage();
echo "An Error Occured" . $error;
log_message('error',$error);
}
}
public function store_gmail_response_data($params){
// foreach ($params as $key => $value){
// $prepare_data = [
// $key => $value
// ];
// }
// $data = [
// 'email' => isset($params['params']['mail']) ? $params['params']['mail'] : null,
// 'bcc' => isset($params['params']['bcc']) ? json_encode($params['params']['bcc']) : null,
// 'cc' => isset($params['params']['cc']) ? json_encode($params['params']['cc']) : null,
// 'message' => isset($params['params']['message']) ? $params['params']['message'] : null,
// 'attachments' => isset($params['params']['attachments']) ? json_encode($params['params']['attachments']) : null,
// 'client_id' => isset($params['params']['common']['client_id']) ? $params['params']['common']['client_id'] : null,
// 'client_branch_id' => isset($params['params']['common']['client_branch_id']) ? $params['params']['common']['client_branch_id'] : null,
// 'client_policy_id' => isset($params['params']['common']['client_policy_id']) ? $params['params']['common']['client_policy_id'] : null,
// 'employee_policy_id' => isset($params['params']['common']['employee_policy_id']) ? $params['params']['common']['employee_policy_id'] : null,
// 'employee_id' => isset($params['params']['common']['employee_id']) ? $params['params']['common']['employee_id'] : null,
// 'mail_type' => isset($params['params']['common']['mail_type']) ? $params['params']['common']['mail_type'] : null,
// 'gmail_api_status' => isset($params['gmail_api']['status']) ? $params['gmail_api']['status'] : null,
// 'gmail_api_id' => isset($params['gmail_api']['data']['id']) ? $params['gmail_api']['data']['id'] : null
// ];
// Initialize data array
$data = [];
// print_r($params['params']['common']);die();
if (isset($params['params']['common'])) {
foreach ($params['params']['common'] as $key => $value) {
$data[$key] = isset($value) ? $value : null;
}
unset($params['params']['common']);
}
if (isset($params['params'])){
foreach($params['params'] as $key => $value){
$arr = ['bcc','cc','attachments'];
if(in_array($key,$arr)){
$data[$key] = isset($value)?json_encode($value):null;
}else{
$data[$key] = isset($value)?$value:null;
}
}
}
if(isset($params['zepto_api']['data']) && $params['zepto_api']['message'] == 'OK' ){
$data['gmail_api_status'] = isset($params['zepto_api']['data']) ? $params['zepto_api']['data'][0]['code'] : null;
$data['gmail_api_id'] = isset($params['zepto_api']['request_id']) ? $params['zepto_api']['request_id'] : null;
$data['received_message'] = isset($params['zepto_api']['data'][0]['message']) ? json_encode($params['zepto_api']['data'][0]['message']) : null;
}
elseif(isset($params['zepto_api']['error'])){
$data['gmail_api_status'] = isset($params['zepto_api']['error']['code'])?$params['zepto_api']['error']['code']:null;
$data['received_message'] = json_encode($params['zepto_api']);
$data['gmail_api_id'] = isset($params['zepto_api']['error']['request_id']) ? $params['zepto_api']['error']['request_id'] : null;
}
$gmailModel = new GmailSentHistoryModel();
$save_status = $gmailModel->insert($data);
}
public function gmail_response_logger($params)
{
if(isset($params['zepto_api']['error'])){
$this->myLogger->logme('error',json_encode($params));
}
}
public function client_id_flag_setter($params)
{
try{
if (isset($params['params']['common']['mail_type'])){
if($params['params']['common']['mail_type'] == 'member_ecard_mail'){
$employeePolicyModel = new EmployeePolicyModel();
$update_status = $employeePolicyModel->where('id',$params['params']['common']['employee_policy_id'])->set('ecard_sent_status',1)->update();
if($update_status){
$this->myLogger->logme('error',"ecard_sent_status updated for ".$params['params']['common']['employee_policy_id']);
}else{
$this->myLogger->logme('error','ecard_sent_status failed to update');
}
}
}
}
catch(Exception $e){
$error = $e->getMessage();
$this->myLogger->logme('error','An Error Occured - '.$error);
}
}
}

View File

@ -0,0 +1,27 @@
<?php
namespace App\Helpers;
class HttpRequestHelper
{
public static function getRequestInfo()
{
$request = service('request');
$data = [
'ip' => $request->getIPAddress(),
'platform' => $request->getUserAgent()->getPlatform(),
'browser' => ($request->getUserAgent()->getBrowser().' '.$request->getUserAgent()->getVersion()),
'method' => $request->getMethod(),
'endpoint' => $request->uri->getPath(),
'getparams' => $request->uri->getSegments(),
'postparams' => $request->getPost()
];
$data['method'] = (isset($data['method']) ? strtoupper($data['method']) : $data['method']);
$data['getparams'] = is_array($data['getparams']) ? json_encode($data['getparams']) : $data['getparams'];
$data['postparams'] = is_array($data['postparams']) ? json_encode($data['postparams']) : $data['postparams'];
return $data;
}
public static function add($payload)
{return $payload['a'] + $payload['b'];}
}

136
app/Helpers/JWTToken.php Executable file
View File

@ -0,0 +1,136 @@
<?php
namespace App\Helpers;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\BeforeValidException;
use Firebase\JWT\SignatureInvalidException;
// use Psr\Http\Message\RequestInterface;
use CodeIgniter\HTTP\RequestInterface;
use ReflectionClass;
use Exception;
use App\Models\EmployeeModel;
use App\Models\LevelContactModel;
class JWTToken
{
public static function encode($data =null)
{
$secret_Key ="secret";
$request_data = (array)$data;
try{
$token = JWT::encode($request_data ,$secret_Key,'HS512');
$id = $request_data['id'];
$data["token_time_out"] = time() + getenv('TOKENTIMEOUT');
if(isset($data['emp_code'])){
$model = new EmployeeModel();
$model->update($id, $data);
}else{
$models = new LevelContactModel();
$models->update($id, $data);
}
return $token;
}
catch (Exception $e) {
return ['status' => false,'message' => $e->getMessage()];
}
}
public static function validateJWT($jwt)
{
$jwtParts = explode(' ', $jwt);
// print_r($jwtParts);
if (count($jwtParts) != 2 || $jwtParts[0] == 'Bearer') {
return false;
}
$token = $jwtParts[1];
try {
$decoded = JWT::decode($token, new Key("secret", 'HS512'));
return json_encode(['status' => true, 'message' => 'Token is valid', 'decoded' => (array) $decoded]);
} catch (ExpiredException $e) {
return json_encode(['status' => false, 'message' => 'Token has expired']);
} catch (BeforeValidException $e) {
return json_encode(['status' => false, 'message' => 'Token is not yet valid']);
} catch (SignatureInvalidException $e) {
return json_encode(['status' => false, 'message' => 'Token signature is invalid']);
} catch (\Exception $e) {
return json_encode(['status' => false, 'message' => 'An error occurred while decoding the token']);
}
}
public static function getIdFromToken($jwt)
{
$jwtParts = explode(' ', $jwt);
$token = $jwtParts[0];
try {
$decoded = JWT::decode($token, new Key("secret", 'HS512'));
return json_encode(['status' => true, 'message' => 'Token is valid', 'data' =>$decoded->data->id ]);
} catch (ExpiredException $e) {
return json_encode(['status' => false, 'message' => 'Token has expired']);
} catch (BeforeValidException $e) {
return json_encode(['status' => false, 'message' => 'Token is not yet valid']);
} catch (SignatureInvalidException $e) {
return json_encode(['status' => false, 'message' => 'Token signature is invalid']);
} catch (\Exception $e) {
return json_encode(['status' => false, 'message' => 'An error occurred while decoding the token']);
}
}
public static function getUserIdFromToken()
{
$request = \Config\Services::request();
$jwt = $request->getHeader('Authorization');
$jwtParts = explode(' ', $jwt);
$token = $jwtParts[1];
$decoded = JWT::decode($token, new Key("secret", 'HS512'));
return $decoded->id;
}
public static function getUserRoleFromToken()
{
$request = \Config\Services::request();
$jwt = $request->getHeader('Authorization');
$jwtParts = explode(' ', $jwt);
$token = $jwtParts[1];
$decoded = JWT::decode($token, new Key("secret", 'HS512'));
return $decoded->role;
}
public static function decodeToken()
{
$request = \Config\Services::request();
$jwt = $request->getHeader('Authorization');
$jwtParts = explode(' ', $jwt);
$token = $jwtParts[1];
$decoded = JWT::decode($token, new Key("secret", 'HS512'));
return $decoded;
}
}

446
app/Helpers/MailHelper.php Executable file
View File

@ -0,0 +1,446 @@
<?php
// namespace App\Helpers;
// use Psr\Log\LoggerInterface;
// use App\Controllers\BaseController;
// use PHPMailer\PHPMailer\PHPMailer;
// use PHPMailer\PHPMailer\SMTP;
// use PHPMailer\PHPMailer\Exception;
// use App\Models\JobModel;
// class MailHelper
// {
// public static function send_email_smtp($params)
// {
// // print_r($params);die;
// $myLogger = \Config\Services::mylogger();
// $emaill = $params['mail'];
// $subject = $params['subject'];
// $message = $params['message'];
// if (isset($params['bcc'])) {
// $bcc = $params['bcc'];
// }else{
// $bcc= '';
// }
// try {
// $email = \Config\Services::email();
// $email->setMailType('html');
// $email->setFrom('bbone@venbait.in', 'Nhance');
// $email->setTo($emaill);
// if (!empty($bcc)) {
// // Convert the comma-separated string into an array
// $bccList = explode(',', $bcc);
// // Trim whitespace from each email ID
// $bccList = array_map('trim', $bccList);
// // Set BCC recipients
// $email->setBCC($bccList);
// }
// $email->setSubject($subject);
// $email->setMessage($message);
// if ($email->send()) {
// return json_encode(['status' => 'success','code' => 200, 'message'=>'Email Sent Successfully...','data' => $emaill,],200);
// } else {
// $myLogger->logme('error', "mail sent failed - $emaill");
// return json_encode(['status' => 'failed','code' => 404,'message'=>'Email Sent Failed...','data' => $emaill ],404);
// }
// } catch (Exception $e) {
// $msg = $e->getMessage();
// $myLogger->logme('error', "mail sent failed - $msg");
// return json_encode(['status' => 'failed','code' => 500,'data' => $emaill],500);
// }
// }
// public static function bulk_mail_smtp(array $mails = [])
// {
// // print_r();die;
// $model = new JobModel();
// $start = microtime(true);
// $runtime= 0;
// try {
// foreach ( $mails as $index=>$mail) {
// $runtime = microtime(true) - $start;
// $send_mail = self::send_email($mail);
// }
// return json_encode(['status' => 'success','code' => 200, 'message'=>'Email Sent Successfully...'],200);
// } catch (\Throwable $th) {
// return json_encode(['status' => 'failed','code' => 500],500);
// }
// }
// //using GmailAPI
// public static function send_email($params)
// {
// // print_r($params);die;
// $myLogger = \Config\Services::mylogger();
// $gmailapi = \Config\Services::gmailapi();
// $emaill = $params['mail'];
// $subject = $params['subject'];
// $message = $params['message'];
// $attachments = isset($params['attachments']) && count($params['attachments']) ? $params['attachments'] : [];
// $common = isset($params['common'])?$params['common']:'';
// //check BCC mail
// if (isset($params['bcc'])) {
// $bcc = $params['bcc'];
// if(!is_array($bcc)){
// $bcc = explode(',', $bcc);
// }
// }else{
// $bcc = [];
// }
// //check CC mail
// if (isset($params['cc'])) {
// $cc = $params['cc'];
// if(!is_array($cc)){
// $cc = explode(',', $cc);
// }
// }else{
// $cc = [];
// }
// //check REPLY TO mail
// $reply_to = "";
// if(isset($params['reply_to']) && !empty($params['reply_to'])){
// $reply_to = $params['reply_to'];
// }
// $MailDataHelper = new GmailResponseHandler();
// $res['params'] = $params;
// try {
// $res['gmail_api'] = $gmailapi->sendMessage($emaill, $subject, $message, 'no-reply@nhanceindia.in', $reply_to, $cc, $bcc,$attachments);
// if($res['gmail_api']['status'])
// {
// $response = $res;
// $MailDataHelper->receive_and_distribute_param_to_functions($response);
// return json_encode(['status' => 'success','code' => 200, 'message'=>('Email Sent Successfully...'.$emaill),'data' => $res,],200);
// }
// else
// {
// $myLogger->logme('error', "mail sent failed - $emaill");
// $response = $res;
// $MailDataHelper->receive_and_distribute_param_to_functions($response);
// return json_encode(['status' => 'failed','code' => 404,'message'=>( 'Email Sent Failed...' . $emaill ),'data' => $res ],404);
// }
// } catch (Exception $e) {
// $msg['error'] = $e->getMessage();
// $msg['params'] = $params;
// $myLogger->logme('error', "mail sent failed - $msg");
// $response = $msg;
// $MailDataHelper->receive_and_distribute_param_to_functions($response);
// return json_encode(['status' => 'failed','code' => 500,'data' => $msg],500);
// }
// }
// public static function bulk_mail(array $mails = [])
// {
// // print_r($mails);die;
// $model = new JobModel();
// $start = microtime(true);
// $runtime= 0;
// try {
// foreach ( $mails as $index=>$mail) {
// $runtime = microtime(true) - $start;
// $send_mail = self::send_email($mail);
// }
// return json_encode(['status' => 'success','code' => 200, 'message'=>'Email Sent Successfully...'],200);
// } catch (\Throwable $th) {
// $error = $th->getMessage();
// log_message('error',$error);
// return json_encode(['status' => 'failed','code' => 500,'error'=>$error],500);
// }
// }
// }
namespace App\Helpers;
use Psr\Log\LoggerInterface;
use App\Controllers\BaseController;
use App\Models\JobModel;
class MailHelper
{
public static function send_email_smtp($params)
{
$myLogger = \Config\Services::mylogger();
$emaill = $params['mail'];
$subject = $params['subject'];
$message = $params['message'];
if (isset($params['bcc'])) {
$bcc = $params['bcc'];
} else {
$bcc = '';
}
$from_address = getenv('email.fromEmail');
try {
$curl = curl_init();
$postData = [
'from' => [
'address' => $from_address
],
'to' => [
[
'email_address' => [
'address' => $emaill
]
]
],
'subject' => $subject,
'htmlbody' => $message
];
// Add BCC if present
if (!empty($bcc)) {
$bccList = explode(',', $bcc);
$bccList = array_map('trim', $bccList);
$postData['bcc'] = array_map(function($email) {
return [
'email_address' => [
'address' => $email
]
];
}, $bccList);
}
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.zeptomail.in/v1.1/email",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($postData),
CURLOPT_HTTPHEADER => [
"accept: application/json",
"authorization: Zoho-enczapikey " . getenv('ZEPTO_API_KEY'),
"cache-control: no-cache",
"content-type: application/json",
],
]);
$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
$myLogger->logme('error', "mail sent failed - $emaill");
return json_encode(['status' => 'failed', 'code' => 404, 'message' => 'Email Sent Failed...', 'data' => $emaill], 404);
}
$apiResponse = json_decode($response, true);
if ($httpCode === 200) {
return json_encode(['status' => 'success', 'code' => 200, 'message' => 'Email Sent Successfully...', 'data' => $emaill], 200);
} else {
$myLogger->logme('error', "mail sent failed - $emaill");
return json_encode(['status' => 'failed', 'code' => 404, 'message' => 'Email Sent Failed...', 'data' => $emaill], 404);
}
} catch (\Exception $e) {
$msg = $e->getMessage();
$myLogger->logme('error', "mail sent failed - $msg");
return json_encode(['status' => 'failed', 'code' => 500, 'data' => $emaill], 500);
}
}
public static function bulk_mail_smtp(array $mails = [])
{
$model = new JobModel();
$start = microtime(true);
$runtime = 0;
try {
foreach ($mails as $index => $mail) {
$runtime = microtime(true) - $start;
$send_mail = self::send_email($mail);
}
return json_encode(['status' => 'success', 'code' => 200, 'message' => 'Email Sent Successfully...'], 200);
} catch (\Throwable $th) {
return json_encode(['status' => 'failed', 'code' => 500], 500);
}
}
public static function send_email($params)
{
$myLogger = \Config\Services::mylogger();
$emaill = $params['mail'];
$subject = $params['subject'];
$message = $params['message'];
$attachments = isset($params['attachments']) ? $params['attachments'] : [];
$common = isset($params['common']) ? $params['common'] : '';
$bcc = isset($params['bcc']) ? $params['bcc'] : '';
$cc = isset($params['cc']) ? $params['cc'] : '';
$from_address = getenv('email.fromEmail');
try {
$curl = curl_init();
$postData = [
'from' => [
'address' => $from_address
],
'to' => [
[
'email_address' => [
'address' => $emaill
]
]
],
'subject' => $subject,
'htmlbody' => $message
];
// Add CC recipients if provided
if (!empty($cc)) {
$postData['cc'] = [];
// Handle both string and array inputs for CC
$ccEmails = is_array($cc) ? $cc : [$cc];
foreach ($ccEmails as $ccEmail) {
$postData['cc'][] = [
'email_address' => [
'address' => $ccEmail
]
];
}
}
// Add BCC recipients if provided
if (!empty($bcc)) {
$postData['bcc'] = [];
// Handle both string and array inputs for BCC
$bccEmails = is_array($bcc) ? $bcc : [$bcc];
foreach ($bccEmails as $bccEmail) {
$postData['bcc'][] = [
'email_address' => [
'address' => $bccEmail
]
];
}
}
// Handle attachments
if (!empty($attachments)) {
$postData['attachments'] = [];
foreach ($attachments as $attachment) {
if (isset($attachment['filePath']) && file_exists($attachment['filePath'])) {
// Determine MIME type dynamically
$fileMimeType = mime_content_type($attachment['filePath']);
$postData['attachments'][] = [
'content' => base64_encode(file_get_contents($attachment['filePath'])),
'name' => $attachment['fileName'],
'mime_type' => $fileMimeType,
];
}
}
}
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.zeptomail.in/v1.1/email",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($postData),
CURLOPT_HTTPHEADER => [
"accept: application/json",
"authorization: Zoho-enczapikey " . getenv('ZEPTO_API_KEY'),
"cache-control: no-cache",
"content-type: application/json",
],
]);
$mail_result = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$res['params'] = $params;
$MailDataHelper = new GmailResponseHandler();
$apiResponse = json_decode($mail_result, true);
$res['zepto_api'] = $apiResponse;
if (isset($apiResponse['error'])) {
$response = $res;
$MailDataHelper->receive_and_distribute_param_to_functions($response);
return json_encode([
'status' => 'failed',
'code' => 404,
'message' => 'Email Sent Failed...' . $emaill,
'data' => $res
], 404);
}
if (isset($apiResponse['data'])) {
$response = $res;
$MailDataHelper->receive_and_distribute_param_to_functions($response);
return json_encode([
'status' => 'success',
'code' => 200,
'message' => 'Email Sent Successfully...' . $emaill,
'data' => $res
], 200);
}
} catch (\Exception $e) {
$msg['error'] = $e->getMessage();
$msg['params'] = $params;
$response = $res;
$MailDataHelper->receive_and_distribute_param_to_functions($response);
return json_encode([
'status' => 'failed',
'code' => 500,
'data' => $msg
], 500);
}
}
public static function bulk_mail(array $mails = [])
{
$model = new JobModel();
$start = microtime(true);
$runtime = 0;
try {
foreach ($mails as $index => $mail) {
$runtime = microtime(true) - $start;
$send_mail = self::send_email($mail);
}
return json_encode(['status' => 'success', 'code' => 200, 'message' => 'Email Sent Successfully...'], 200);
} catch (\Throwable $th) {
$error = $th->getMessage();
log_message('error', $error);
return json_encode(['status' => 'failed', 'code' => 500, 'error' => $error], 500);
}
}
}
?>

150
app/Helpers/drive_helper.php Executable file
View File

@ -0,0 +1,150 @@
<?php
use Google\Client as GoogleClient;
use Google\Service\Drive;
if (!function_exists('uploadFilesToGoogleDrive')) {
function uploadFilesToGoogleDrive(array $files, $doc_name, $pt_id)
{
$appName = getenv('GOOGLE_OAUTH_APP_NAME');
$clientID = getenv('GOOGLE_OAUTH_CLIENT_ID');
$clientSecret = getenv('GOOGLE_OAUTH_CLIENT_SECRET');
$redirectUri = getenv('GOOGLE_OAUTH_REDIRECT_URI');
$scopes = explode(',', getenv('GOOGLE_OAUTH_SCOPES'));
$accessToken = session()->get('access_token');
log_message('error', '////////////// --- G-Drive Access Token {data}', ['data' => $accessToken]);
// Initialize Google Client
$client = new GoogleClient();
$client->setApplicationName($appName);
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectUri);
$client->addScope($scopes);
// $client->setApprovalPrompt('force');
$client->setPrompt('consent');
$client->setAccessType('offline');
if ($accessToken) {
$client->setAccessToken($accessToken);
log_message('error', '////////////// --- G-Drive Access Token expired : {data}', ['data' => $client->isAccessTokenExpired()]);
if ($client->isAccessTokenExpired()) {
$refreshToken = session()->get('refresh_token');
log_message('error', '////////////// --- G-Drive Refresh Token : {data}', ['data' => $refreshToken]);
if ($refreshToken) {
$client->fetchAccessTokenWithRefreshToken($refreshToken);
$token = $client->getAccessToken();
if (isset($token['access_token'])) {
session()->set('access_token', $token['access_token']);
// $client->setAccessToken($token);
log_message('error', '////////////// --- G-Drive Access Token refreshed and stored successfully.');
} else {
log_message('error', '////////////// --- G-Drive Access Token not available after refresh.');
}
if (isset($token['refresh_token'])) {
session()->set('refresh_token', $token['refresh_token']);
log_message('error', '////////////// --- G-Drive Refresh Token updated successfully.');
} else {
log_message('error', '////////////// --- G-Drive Refresh Token not available after refresh.');
}
} else {
log_message('error', '////////////// --- G-Drive Refresh Token Not Available');
redirect()->to(filter_var($client->createAuthUrl(), FILTER_SANITIZE_URL));
}
} else {
log_message('error', '////////////// --- G-Drive Access Token is still valid.');
}
try {
$driveService = new Drive($client);
$folderName = 'New Folder';
// Check if the folder already exists
$response = $driveService->files->listFiles([
'q' => "mimeType='application/vnd.google-apps.folder' and name='{$folderName}' and trashed=false",
'fields' => 'files(id, name)'
]);
$filesList = $response->getFiles();
$folderId = null;
if (count($filesList) > 0) {
// Folder already exists
$folderId = $filesList[0]->getId();
} else {
// Create a new folder
$folder = new Drive\DriveFile();
$folder->setName($folderName);
$folder->setMimeType('application/vnd.google-apps.folder');
$createdFolder = $driveService->files->create($folder, [
'fields' => 'id'
]);
$folderId = $createdFolder->id;
}
$uploadedFiles = [];
foreach ($files as $key => $file) {
if (!empty($file)) {
$dname = $doc_name[$key];
$driveFile = new Drive\DriveFile();
$driveFile->setName($file->getClientName());
$driveFile->setParents([$folderId]);
$result = $driveService->files->create(
$driveFile,
[
'data' => file_get_contents($file->getTempName()),
'mimeType' => $file->getClientMimeType(),
'uploadType' => 'multipart'
]
);
$uploadedFiles[] = [
'file_name' => $file->getClientName(),
'drive_id' => $result->id,
'doc_name' => $dname,
'pt_id' => $pt_id,
'created_by' => get_session_userid(),
'url' => "https://drive.google.com/file/d/{$result->id}/view",
];
}
}
return $uploadedFiles;
} catch (\Exception $e) {
$errorDetails = [
'status' => 'error',
'error_message' => 'Error uploading files: ' . $e->getMessage(),
'error_code' => $e->getCode(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'stack_trace' => $e->getTraceAsString()
];
return $errorDetails;
}
} else {
$url = $client->createAuthUrl();
return redirect()->to(filter_var($url, FILTER_SANITIZE_URL));
}
}
}

File diff suppressed because it is too large Load Diff

2283
app/Helpers/excel_util_helper.php Executable file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,40 @@
<?php
if (!function_exists('file_to_upload')) {
function file_to_upload($file, $allowedTypes = [], $uploadDirectory = '')
{
$uploadPath = ROOTPATH . 'public/uploads/' . $uploadDirectory;
// Check if the upload directory exists
if (!is_dir($uploadPath)) {
throw new \Exception('Upload directory does not exist.');
}
// Validate file type
if (!empty($allowedTypes) && !in_array($file->getClientMimeType(), $allowedTypes)) {
throw new \Exception('Invalid file type.');
}
// Generate a unique filename
$originalName = $file->getName();
$ext = pathinfo($originalName, PATHINFO_EXTENSION);
$baseName = pathinfo($originalName, PATHINFO_FILENAME);
$counter = 0;
$newName = $baseName . '.' . $ext;
while (file_exists($uploadPath . $newName)) {
$counter++;
$newName = $baseName . '_' . $counter . '.' . $ext;
}
// Move the file to the upload directory
try {
$file->move($uploadPath, $newName);
} catch (\Exception $e) {
throw new \Exception('Failed to upload file: ' . $e->getMessage());
}
return $uploadDirectory . $newName;
}
}

658
app/Helpers/header.php Executable file
View File

@ -0,0 +1,658 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title><?= isset($page_name) ? $page_name : 'NHance'; ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta content="" name="description" />
<meta content="NHANCE" name="NHANCE" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<!-- App favicon -->
<link rel="shortcut icon" href="<?= base_url() . "public"; ?>/assets/images/Nhance_Favi.svg">
<!-- plugin css -->
<link href="<?= base_url() . "public"; ?>/assets/libs/admin-resources/jquery.vectormap/jquery-jvectormap-1.2.2.css" rel="stylesheet" type="text/css" />
<!-- third party css -->
<link href="<?= base_url() . "public"; ?>/assets/libs/datatables.net-bs4/css/dataTables.bootstrap4.min.css" rel="stylesheet" type="text/css" />
<link href="<?= base_url() . "public"; ?>/assets/libs/datatables.net-responsive-bs4/css/responsive.bootstrap4.min.css" rel="stylesheet" type="text/css" />
<link href="<?= base_url() . "public"; ?>/assets/libs/datatables.net-buttons-bs4/css/buttons.bootstrap4.min.css" rel="stylesheet" type="text/css" />
<link href="<?= base_url() . "public"; ?>/assets/libs/datatables.net-select-bs4/css//select.bootstrap4.min.css" rel="stylesheet" type="text/css" />
<!-- third party css end -->
<!-- App css -->
<link href="<?= base_url() . "public"; ?>/assets/css/bootstrap-creative.min.css" rel="stylesheet" type="text/css" id="bs-default-stylesheet" />
<link href="<?= base_url() . "public"; ?>/assets/css/app-creative.min.css" rel="stylesheet" type="text/css" id="app-default-stylesheet" />
<link href="<?= base_url() . "public"; ?>/assets/css/bootstrap-creative-dark.min.css" rel="stylesheet" type="text/css" id="bs-dark-stylesheet" />
<link href="<?= base_url() . "public"; ?>/assets/css/app-creative-dark.min.css" rel="stylesheet" type="text/css" id="app-dark-stylesheet" />
<!-- icons -->
<link href="<?= base_url() . "public"; ?>/assets/css/icons.min.css" rel="stylesheet" type="text/css" />
<!-- <link href="<?= base_url() . "public"; ?>/assets/css/bootstrap-material.min.css" rel="stylesheet" type="text/css" id="bs-default-stylesheet" /> -->
<!-- <link href="<?= base_url() . "public"; ?>/assets/css/app-material.min.css" rel="stylesheet" type="text/css" id="app-default-stylesheet" /> -->
<!-- <link href="<?= base_url() . "public"; ?>/assets/css/bootstrap-editable.css" rel="stylesheet" type="text/css" /> -->
<link href="https://cdn.jsdelivr.net/npm/remixicon/fonts/remixicon.css" rel="stylesheet">
<!-- Jodit Css -->
<link href="<?= base_url() . "public"; ?>/assets/css/jodit.css" rel="stylesheet" type="text/css" />
<!-- JQuery CDN -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Sweet Alert CDN -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.10.4/dist/sweetalert2.all.min.js"></script>
<!-- select2 -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" type="text/css">
<link rel="manifest" href="../manifest.json">
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('../service-worker.js').then(function(registration) {
// console.log('Service Worker registration successful with scope:', registration.scope);
}, function(err) {
// console.log('Service Worker registration failed:', err);
});
});
}
</script>
<style>
body[data-sidebar-size=condensed]:not([data-layout=compact]):not(.auth-fluid-pages) {
min-height: 0;
}
.navbar-custom {
top: -10px !important;
height: 61px !important;
}
.logo-box {
top: -10px !important;
height: 61px !important;
}
.content-page {
padding: 80px 15px 65px 15px !important;
}
/* Media query for small screens */
@media screen and (min-width: 768px) {
/* Styles for screens with a minimum width of 768px (e.g., tablets and larger devices) */
.navbar-custom .button-menu-mobile {
display: none;
/* Hide the button on larger screens */
}
}
.loader-mask {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #00000069;
z-index: 99999;
}
.loader {
position: absolute;
left: 50%;
top: 50%;
width: 50px;
height: 50px;
font-size: 0;
color: #00c9d0;
display: inline-block;
margin: -25px 0 0 -25px;
text-indent: -9999em;
-webkit-transform: translateZ(0);
-ms-transform: translateZ(0);
transform: translateZ(0);
}
.lead {
font-size: 13px;
}
.loader div {
background-color: #6ad9cf;
display: inline-block;
float: none;
position: absolute;
top: 0;
left: 0;
width: 50px;
height: 50px;
opacity: .5;
border-radius: 50%;
-webkit-animation: ballPulseDouble 2s ease-in-out infinite;
animation: ballPulseDouble 2s ease-in-out infinite;
}
.loader div:last-child {
-webkit-animation-delay: -1s;
animation-delay: -1s;
}
@-webkit-keyframes ballPulseDouble {
0%,
100% {
-webkit-transform: scale(0);
transform: scale(0);
}
50% {
-webkit-transform: scale(1);
transform: scale(1);
}
}
@keyframes ballPulseDouble {
0%,
100% {
-webkit-transform: scale(0);
transform: scale(0);
}
50% {
-webkit-transform: scale(1);
transform: scale(1);
}
}
.toast-success {
background-color: #009688 !important;
color: #FFFFFF !important;
}
/* .dataTables_wrapper .text-right {
position: relative;
} */
.dataTables_wrapper .dt-buttons .buttons-csv,
.dataTables_wrapper .dt-buttons .buttons-html5 {
background-color: #02a8b5;
color: #fff;
border-color: #02a8b5;
}
.dataTables_wrapper .dt-buttons .buttons-csv:hover,
.dataTables_wrapper .dt-buttons .buttons-html5:hover {
background-color: #028291;
border-color: #028291;
}
.modal-full-width {
width: 80% !important;
/* width: 95% !important; */
/* max-width: none; */
}
.modal-body {
/* position: relative;
flex: 1 1 auto; */
padding: 2rem !important;
}
</style>
<style>
.text-danger-2 {
font-style: italic;
color: black !important;
/* color: #02a8b5 !important; */
font-size: 12px;
}
/* .form-group {
margin-bottom: -0.2rem !important;
}
.form-row{
width: 84%;
} */
</style>
<style>
.select2-container--default .select2-selection--single {
height: 37px !important;
}
.select2-container--default .select2-selection--single .select2-selection__rendered {
line-height: 35px !important;
}
.select2-container--default .select2-selection--single .select2-selection__arrow {
top: 7px !important;
}
</style>
<style>
.toast-body {
padding: .75rem;
background: aliceblue !important;
}
#messages-list li {
margin-top: 0;
margin-bottom: -25px;
/* Adjust this value to reduce the space */
}
.toast-footer {
text-align: right;
color: #000;
border-top: 1px solid aliceblue;
margin-top: 11px;
margin-bottom: -6px;
}
.right-bar {
width: 300px;
/* Adjust as needed */
overflow: hidden;
}
.fixed-header {
position: relative;
top: 0;
z-index: 1000;
background-color: #f8f9fa !important;
}
.scrollable-content {
max-height: 42vh;
overflow-y: auto;
padding-top: 0px;
}
/* Additional styles to enhance appearance */
.header-title {
position: relative;
bottom: 5px;
left: 60px;
}
#app_content_management:hover {
color: red;
}
</style>
<script>
$(window).on('load', function() {
setTimeout(function() {
$('.loader').fadeOut();
$('.loader-mask').fadeOut('slow');
}, 1000);
});
</script>
</head>
<body class="loading" data-layout-mode="" data-layout='{"mode": "light", "width": "fluid", "menuPosition": "fixed", "sidebar": { "color": "light", "size": "condensed", "showuser": false}, "topbar": {"color": "dark"}, "showRightSidebarOnPageLoad": false}'></body>
<!-- Preloader -->
<div class="loader-mask">
<div class="loader">
<img src="<?= base_url() . "public" ?>/assets/images/nhance-loader-fast.gif" height="40" width="40" alt="Loading...">
</div>
</div>
<!-- <img src="<?= base_url() . "public" ?>/assets/images/nhance-loader-fast.gif" height="40" width="40" alt="Loading..."> -->
<!-- Begin page -->
<div id="wrapper">
<!-- Topbar Start -->
<div class="navbar-custom">
<div class="container-fluid">
<ul class="list-unstyled topnav-menu float-right mb-0">
<li class="d-none d-lg-block">
<form class="app-search">
<div class="app-search-box dropdown">
<div class="input-group">
<input type="search" class="form-control" placeholder="Search..." id="top-search">
<div class="input-group-append">
<button class="btn" type="submit">
<i class="fe-search"></i>
</button>
</div>
</div>
<!-- <div class="dropdown-menu dropdown-lg" id="search-dropdown">
<div class="dropdown-header noti-title">
<h5 class="text-overflow mb-2">Found <span class="text-danger">09</span> results</h5>
</div>
<a href="javascript:void(0);" class="dropdown-item notify-item">
<i class="fe-home mr-1"></i>
<span>Analytics Report</span>
</a>
<a href="javascript:void(0);" class="dropdown-item notify-item">
<i class="fe-aperture mr-1"></i>
<span>How can I help you?</span>
</a>
<a href="javascript:void(0);" class="dropdown-item notify-item">
<i class="fe-settings mr-1"></i>
<span>User profile settings</span>
</a>
<div class="dropdown-header noti-title">
<h6 class="text-overflow mb-2 text-uppercase">Users</h6>
</div>
<div class="notification-list">
<a href="javascript:void(0);" class="dropdown-item notify-item">
<div class="media">
<img class="d-flex mr-2 rounded-circle" src="<?= base_url() . "public"; ?>/assets/images/users/avatar-2.jpg" alt="Generic placeholder image" height="32">
<div class="media-body">
<h5 class="m-0 font-14">Erwin E. Brown</h5>
<span class="font-12 mb-0">UI Designer</span>
</div>
</div>
</a>
<a href="javascript:void(0);" class="dropdown-item notify-item">
<div class="media">
<img class="d-flex mr-2 rounded-circle" src="<?= base_url() . "public"; ?>/assets/images/users/avatar-5.jpg" alt="Generic placeholder image" height="32">
<div class="media-body">
<h5 class="m-0 font-14">Jacob Deo</h5>
<span class="font-12 mb-0">Developer</span>
</div>
</div>
</a>
</div>
</div> -->
</div>
</form>
</li>
<li class="dropdown notification-list topbar-dropdown">
<a class="nav-link dropdown-toggle right-bar-toggle waves-effect waves-light">
<i class="fe-bell noti-icon"></i>
<span class="badge badge-danger rounded-circle noti-icon-badge" id="notification_count">0</span>
</a>
</li>
<li class="dropdown notification-list topbar-dropdown">
<a class="nav-link dropdown-toggle nav-user mr-0 waves-effect waves-light" data-toggle="dropdown" href="#" role="button" aria-haspopup="false" aria-expanded="false">
<img src="<?php echo (get_userProfile() != null && !empty(get_userProfile())) ? get_userProfile() : base_url() . 'public/assets/images/avatar_2x.png'; ?>" alt="user-image" class="rounded-circle">
<span class="pro-user-name ml-1" style="font-size: 16px;">
<?= (isset(get_session_userdata()->first_name) ? get_session_userdata()->first_name : 'NOT SET') ?>
<!-- <i class="mdi mdi-chevron-down"></i> -->
</span>
</a>
<!--<div class="dropdown-menu dropdown-menu-right profile-dropdown ">
<div class="dropdown-header noti-title">
<h6 class="text-overflow m-0">Welcome !</h6>
</div>
<a href="javascript:void(0);" class="dropdown-item notify-item">
<i class="ri-account-circle-line"></i>
<span>My Account</span>
</a>
<a href="javascript:void(0);" class="dropdown-item notify-item">
<i class="ri-settings-3-line"></i>
<span>Settings</span>
</a>
<a href="javascript:void(0);" class="dropdown-item notify-item">
<i class="ri-wallet-line"></i>
<span>My Wallet <span class="badge badge-success float-right">3</span> </span>
</a>
<a href="javascript:void(0);" class="dropdown-item notify-item">
<i class="ri-lock-line"></i>
<span>Lock Screen</span>
</a>
<a href="<?= base_url('/logout'); ?>" class="dropdown-item notify-item">
<i class="ri-logout-box-line"></i>
<span>Logout</span>
</a>
</div>-->
</li>
<!-- <li class="dropdown notification-list">
<a href="javascript:void(0);" class="nav-link right-bar-toggle waves-effect waves-light">
<i class="fe-settings noti-icon"></i>
</a>
</li> -->
<li class="dropdown notification-list">
<a href="<?= base_url('/logout'); ?>" class="nav-link waves-effect waves-light">
<i class="ri-logout-box-r-line" style="font-size: 25px;"></i>
</a>
</li>
</ul>
<!-- LOGO -->
<div class="logo-box">
<a href="https://localhost/nhance/dashboard/view" class="logo logo-dark text-center">
<span class="logo-sm">
<img src="<?= base_url() . "public"; ?>/assets/images/Nhance_Favi.svg" alt="" height="24">
<!-- <span class="logo-lg-text-light">NHANCE</span> -->
</span>
<span class="logo-lg">
<img src="<?= base_url() . "public"; ?>/assets/images/Nhance_Favi.svg" alt="" height="20">
<!-- <span class="logo-lg-text-light">M</span> -->
</span>
</a>
<a href="https://localhost/nhance/dashboard/view" class="logo logo-light text-center">
<span class="logo-sm">
<img src="<?= base_url() . "public"; ?>/assets/images/Nhance_Favi.svg" alt="" height="24">
</span>
<!-- <span class="logo-lg">
<img src="<?= base_url() . "public"; ?>/assets/images/logo-light.png" alt="" height="20">
</span> -->
</a>
</div>
<ul class="list-unstyled topnav-menu topnav-menu-left m-0">
<li>
<button class="button-menu-mobile waves-effect waves-light">
<i class="fe-menu"></i>
</button>
</li>
<li>
<!-- Mobile menu toggle (Horizontal Layout)-->
<a class="navbar-toggle nav-link" data-toggle="collapse" data-target="#topnav-menu-content">
<div class="lines">
<span></span>
<span></span>
<span></span>
</div>
</a>
<!-- End mobile menu toggle-->
</li>
</ul>
<div class="clearfix"></div>
</div>
</div>
<!-- end Topbar -->
<!-- ========== Left Sidebar Start ========== -->
<div class="left-side-menu">
<!-- LOGO -->
<div class="logo-box">
<a href="<?= base_url('/dashboard/view') ?>" class="logo logo-dark text-center">
<span class="logo-sm">
<img src="<?= base_url() . "public"; ?>/assets/images/logo-sm-dark.png" alt="" height="24">
<!-- <span class="logo-lg-text-light">nHance</span> -->
</span>
<span class="logo-lg">
<img src="<?= base_url() . "public"; ?>/assets/images/logo-dark.png" alt="" height="20">
<!-- <span class="logo-lg-text-light">N</span> -->
</span>
</a>
<a href="<?= base_url('/dashboard/view') ?>" class="logo logo-light text-center">
<span class="logo-sm">
<img src="<?= base_url() . "public"; ?>/assets/images/Nhance_Favi_white_2.png" alt="" width="30" height="30">
</span>
<!-- <span class="logo-lg">
<img src="<?= base_url() . "public"; ?>./assets/images/logo-light.png" alt="" height="20">
</span> -->
</a>
</div>
<div class="h-100" data-simplebar>
<!--- Sidemenu -->
<div id="sidebar-menu">
<ul id="side-menu">
<li>
<a href="<?= base_url('/dashboard/view') ?>">
<i class="ri-dashboard-line"></i>
<span> Dashboard </span>
</a>
</li>
<li>
<a href="<?= base_url('/client/list') ?>">
<i class="mdi mdi-domain"></i>
<span> Clients </span>
</a>
</li>
<li>
<a href="#sidebarDashboards" data-toggle="collapse" class="waves-effect">
<i class="fas fa-user-tie"></i>
<span class="badge badge-success badge-pill float-right">2</span>
<span> Members </span>
</a>
<div class="collapse" id="sidebarDashboards">
<ul class="nav-second-level">
<li>
<a href="<?= base_url('/employee/upload') ?>">Upload</a>
</li>
<li>
<a href="<?= base_url('/employee/list') ?>">List</a>
</li>
<li>
<a href="<?= base_url('/employee/endorsement-list') ?>">Endorsement List</a>
</li>
</ul>
</div>
</li>
<li>
<a href="#sidebarDashboards" data-toggle="collapse" class="waves-effect">
<i class="ri-database-2-line"></i>
<span class="badge badge-success badge-pill float-right">2</span>
<span> Masters </span>
</a>
<div class="collapse" id="sidebarDashboards">
<ul class="nav-second-level">
<li>
<a href="<?= base_url('/master/insurer/list') ?>">Insurer</a>
</li>
<li>
<a href="<?= base_url('/master/tpa/list') ?>">TPA</a>
</li>
<li>
<a href="<?= base_url('/master/kyc/list') ?>">KYC</a>
</li>
<li>
<a href="<?= base_url('/master/policy/list') ?>">Policy</a>
</li>
<li>
<a href="<?= base_url('/master/cash_deposite/list') ?>">CD Master</a>
</li>
</ul>
</div>
</li>
<li>
<?php
$sessionData = get_session_userdata();
$currentUrl = base_url();
$parsedUrl = parse_url($currentUrl);
$baseUrl = $parsedUrl['scheme'] . '://' . $parsedUrl['host'] . '/';
$hashedEmail = hash('sha256', $sessionData->email);
$redirectUrl = getenv('helpdeskURL') .'/staff/login?' . http_build_query(['token' => $hashedEmail]);
?>
<a href="<?php echo $redirectUrl; ?>" target="_blank">
<i class="mdi mdi-lifebuoy"></i>
<span> Tickets </span>
</a>
</li>
<li>
<a href="<?= base_url('/user/list') ?>">
<i class=" ri-user-3-line"></i>
<span> Users </span>
</a>
</li>
<li>
<a id="app_content_management" href="#sidebarDashboardsmenu" data-toggle="collapse" class="waves-effect" style="color: grey;">
<i class="fa fa-info-circle" aria-hidden="true"></i>
<span class="badge badge-success badge-pill float-right">2</span>
<span> App Content Management </span>
</a>
<div class="collapse" id="sidebarDashboardsmenu">
<ul class="nav-second-level">
<li>
<a href="<?= base_url('/add_image_index') ?>"> Advertisement Images </a>
</li>
<li>
<a href="<?= base_url('/frontend_content') ?>">Front-end Content</a>
</li>
<li>
</li>
<li>
</li>
</ul>
</div>
</li>
<li>
<!-- <li class="menu-title mt-2">Apps</li> -->
</ul>
</div>
<!-- End Sidebar -->
</div>
<!-- Sidebar -left -->
</div>
<!-- Left Sidebar End -->
<!-- ============================================================== -->
<!-- Start Page Content here -->
<!-- ============================================================== -->
<div class="content-page">
<div class="content">
<!-- Start Content-->
<div class="container-fluid">

64
app/Helpers/oauth_helper.php Executable file
View File

@ -0,0 +1,64 @@
<?php
// File: app/Helpers/oauth_helper.php
// require 'vendor/autoload.php';
use Google\Client as GoogleClient;
use Google\Service\Oauth2;
// Check if the function exists, to prevent redeclaration
if (!function_exists('googleOauthLogin')) {
function googleOAuthLogin($oauthToken)
{
// Retrieve configuration values from environment variables
$appName = getenv('GOOGLE_OAUTH_APP_NAME');
$clientID = getenv('GOOGLE_OAUTH_CLIENT_ID');
$clientSecret = getenv('GOOGLE_OAUTH_CLIENT_SECRET');
$redirectUri = getenv('GOOGLE_OAUTH_REDIRECT_URI');
$scopes = getenv('GOOGLE_OAUTH_SCOPES');
// Convert the scopes string into an array
$scopesArray = explode(',', $scopes);
// Initialize a new Google client
$client = new GoogleClient();
$client->setApplicationName($appName);
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectUri);
$client->addScope($scopesArray);
// $client->setApprovalPrompt('force');
$client->setPrompt('consent');
$client->setAccessType('offline');
// Check if an OAuth token is provided
if ($oauthToken) {
try {
// Attempt to fetch the access token with the provided OAuth token
$token = $client->fetchAccessTokenWithAuthCode($oauthToken);
session()->set('access_token', $token['access_token']);
if(isset($token['refresh_token'])){
session()->set('refresh_token', $token['refresh_token']);
}
$client->setAccessToken($token);
$oauth = new Oauth2($client);
// Get user information using the OAuth2 service
$user_info = $oauth->userinfo->get();
return $user_info;
} catch (\Exception $e) {
// Handle exceptions and return an error message
return 'Error fetching access token: ' . $e->getMessage();
}
} else {
// If no OAuth token is provided, generate the authentication URL
$url = $client->createAuthUrl();
// Redirect the user to the authentication URL
return redirect()->to(filter_var($url, FILTER_SANITIZE_URL));
}
}
}
?>

Some files were not shown because too many files have changed in this diff Show More