Browse Source

initial commit

master
kris@sentientgeeks.com 4 years ago
commit
501a8e18e0
19 changed files with 2615 additions and 0 deletions
  1. +103
    -0
      app/BaseModel.php
  2. +212
    -0
      app/Company.php
  3. +10
    -0
      app/CompanySetting.php
  4. +33
    -0
      app/Events/CompanyRegistered.php
  5. +72
    -0
      app/Exceptions/Handler.php
  6. +184
    -0
      app/Helper/Files.php
  7. +57
    -0
      app/Http/Controllers/Controller.php
  8. +59
    -0
      app/Http/Controllers/NotificationController.php
  9. +82
    -0
      app/Http/Controllers/SuperAdmin/SuperAdminBaseController.php
  10. +402
    -0
      app/Http/Controllers/SuperAdmin/SuperAdminCompanyController.php
  11. +36
    -0
      app/Http/Middleware/SuperAdmin.php
  12. +21
    -0
      app/Http/Requests/SuperAdmin/Companies/DeleteRequest.php
  13. +75
    -0
      app/Http/Requests/SuperAdmin/Companies/StoreRequest.php
  14. +37
    -0
      app/Http/Requests/SuperAdmin/Companies/UpdateRequest.php
  15. +18
    -0
      app/Http/Requests/SuperAdmin/SuperAdminBaseRequest.php
  16. +37
    -0
      app/Listeners/CompanyRegisteredListener.php
  17. +96
    -0
      app/Notifications/NewCompanyRegister.php
  18. +1046
    -0
      app/Observers/CompanyObserver.php
  19. +35
    -0
      app/Scopes/CompanyScope.php

+ 103
- 0
app/BaseModel.php View File

@ -0,0 +1,103 @@
<?php
namespace App;
use Froiden\RestAPI\ApiModel;
use Illuminate\Support\Facades\Schema;
class BaseModel extends ApiModel
{
protected $mimeType = [
'txt' => 'fa-file-text',
'htm' => 'fa-file-code-o',
'html' => 'fa-file-code-o',
// 'php' => 'fa-file-code-o',
'css' => 'fa-file-code-o',
'js' => 'fa-file-code-o',
'json' => 'fa-file-code-o',
'xml' => 'fa-file-code-o',
'swf' => 'fa-file-o',
'CR2' => 'fa-file-o',
'flv' => 'fa-file-video-o',
// images
'png' => 'fa-file-image-o',
'jpe' => 'fa-file-image-o',
'jpeg' => 'fa-file-image-o',
'jpg' => 'fa-file-image-o',
'gif' => 'fa-file-image-o',
'bmp' => 'fa-file-image-o',
'ico' => 'fa-file-image-o',
'tiff' => 'fa-file-image-o',
'tif' => 'fa-file-image-o',
'svg' => 'fa-file-image-o',
'svgz' => 'fa-file-image-o',
// archives
'zip' => 'fa-file-o',
'rar' => 'fa-file-o',
'exe' => 'fa-file-o',
'msi' => 'fa-file-o',
'cab' => 'fa-file-o',
// audio/video
'mp3' => 'fa-file-audio-o',
'qt' => 'fa-file-video-o',
'mov' => 'fa-file-video-o',
'mp4' => 'fa-file-video-o',
'mkv' => 'fa-file-video-o',
'avi' => 'fa-file-video-o',
'wmv' => 'fa-file-video-o',
'mpg' => 'fa-file-video-o',
'mp2' => 'fa-file-video-o',
'mpeg' => 'fa-file-video-o',
'mpe' => 'fa-file-video-o',
'mpv' => 'fa-file-video-o',
'3gp' => 'fa-file-video-o',
'm4v' => 'fa-file-video-o',
// adobe
'pdf' => 'fa-file-pdf-o',
'psd' => 'fa-file-image-o',
'ai' => 'fa-file-o',
'eps' => 'fa-file-o',
'ps' => 'fa-file-o',
// ms office
'doc' => 'fa-file-text',
'rtf' => 'fa-file-text',
'xls' => 'fa-file-excel-o',
'ppt' => 'fa-file-powerpoint-o',
'docx' => 'fa-file-text',
'xlsx' => 'fa-file-excel-o',
'pptx' => 'fa-file-powerpoint-o',
// open office
'odt' => 'fa-file-text',
'ods' => 'fa-file-text',
];
public function getIconAttribute($value) {
$isColExist = Schema::hasColumn($this->getTable(),'icon');
if($isColExist){
return $value;
}
if (is_null($this->external_link) && !$isColExist) {
$ext = pathinfo($this->filename, PATHINFO_EXTENSION);
if ($ext == 'png' || $ext == 'jpe' || $ext == 'jpeg' || $ext == 'jpg' || $ext == 'gif' || $ext == 'bmp' ||
$ext == 'ico' || $ext == 'tif' || $ext == 'svg' || $ext == 'svgz' || $ext == 'psd' || $ext == 'csv')
{
return 'images';
}
else{
return $this->mimeType[$ext];
}
}
}
}

+ 212
- 0
app/Company.php View File

@ -0,0 +1,212 @@
<?php
namespace App;
use App\Notifications\EmailVerification;
use App\Notifications\NewUser;
use App\Observers\CompanyObserver;
use App\Scopes\CompanyScope;
use GuzzleHttp\Client;
use Illuminate\Notifications\Notifiable;
use Laravel\Cashier\Billable;
use Laravel\Cashier\Invoice;
use Stripe\Invoice as StripeInvoice;
class Company extends BaseModel
{
protected $table = 'companies';
protected $dates = ['trial_ends_at', 'licence_expire_on', 'created_at', 'updated_at', 'last_login'];
protected $fillable = ['last_login', 'company_name', 'company_email', 'company_phone', 'website', 'address', 'currency_id', 'timezone', 'locale', 'date_format', 'time_format', 'week_start', 'longitude', 'latitude', 'status'];
protected $appends = ['logo_url', 'login_background_url','moment_date_format'];
use Notifiable, Billable;
// public function findInvoice($id)
// {
// try {
// $stripeInvoice = StripeInvoice::retrieve(
// $id,
// $this->getStripeKey()
// );
// $stripeInvoice->lines = StripeInvoice::retrieve($id, $this->getStripeKey())
// ->lines
// ->all(['limit' => 1000]);
// $stripeInvoice->date = $stripeInvoice->created;
// return new Invoice($this, $stripeInvoice);
// } catch (\Exception $e) {
// //
// }
// }
public static function boot()
{
parent::boot();
static::observe(CompanyObserver::class);
}
public function currency()
{
return $this->belongsTo(Currency::class, 'currency_id')->withoutGlobalScopes(['enable']);
}
public function package()
{
return $this->belongsTo(Package::class, 'package_id');
}
public function employees()
{
return $this->hasMany(User::class)
->join('employee_details', 'employee_details.user_id', 'users.id');
}
public function file_storage()
{
return $this->hasMany(FileStorage::class, 'company_id');
}
public function getLogoUrlAttribute()
{
if (is_null($this->logo)) {
$global = global_settings();
return $global->logo_url;
}
return asset_url('app-logo/' . $this->logo);
}
public function getLoginBackgroundUrlAttribute()
{
if (is_null($this->login_background) || $this->login_background == 'login-background.jpg') {
return asset('img/login-bg.jpg');
}
return asset_url('login-background/' . $this->login_background);
}
public function validateGoogleRecaptcha($googleRecaptchaResponse)
{
$global = global_settings();
$client = new Client();
$response = $client->post(
'https://www.google.com/recaptcha/api/siteverify',
['form_params' =>
[
'secret' => $global->google_recaptcha_secret,
'response' => $googleRecaptchaResponse,
'remoteip' => $_SERVER['REMOTE_ADDR']
]]
);
$body = json_decode((string) $response->getBody());
return $body->success;
}
public function getMomentDateFormatAttribute()
{
$momentDateFormats = [
'd-m-Y' => 'DD-MM-YYYY',
'm-d-Y' => 'MM-DD-YYYY',
'Y-m-d' => 'YYYY-MM-DD',
'd.m.Y' => 'DD.MM.YYYY',
'm.d.Y' => 'MM.DD.YYYY',
'Y.m.d' => 'YYYY.MM.DD',
'd/m/Y' => 'DD/MM/YYYY',
'm/d/Y' => 'MM/DD/YYYY',
'Y/m/d' => 'YYYY/MM/DD',
'd/M/Y' => 'DD/MMM/YYYY',
'd.M.Y' => 'DD.MMM.YYYY',
'd-M-Y' => 'DD-MMM-YYYY',
'd M Y' => 'DD MMM YYYY',
'd F, Y' => 'DD MMMM, YYYY',
'D/M/Y' => 'ddd/MMM/YYYY',
'D.M.Y' => 'ddd.MMM.YYYY',
'D-M-Y' => 'ddd-MMM-YYYY',
'D M Y' => 'ddd MMM YYYY',
'd D M Y' => 'DD ddd MMM YYYY',
'D d M Y' => 'ddd DD MMM YYYY',
'dS M Y' => 'Do MMM YYYY',
];
return $momentDateFormats[$this->date_format];
}
public function addUser($company, $request)
{
// Save Admin
$user = User::withoutGlobalScopes([CompanyScope::class, 'active'])->where('email', $request->email)->first();
if (is_null($user)) {
$user = new User();
}
$user->company_id = $company->id;
$user->name = 'admin';
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->status = 'active';
$user->email_verification_code = str_random(40);
$user->save();
return $user;
}
public function addEmployeeDetails($user)
{
$employee = new EmployeeDetails();
$employee->user_id = $user->id;
$employee->employee_id = 'emp-' . $user->id;
$employee->company_id = $user->company_id;
$employee->address = 'address';
$employee->hourly_rate = '50';
$employee->save();
$global = global_settings();
if ($global->email_verification == 1) {
// Send verification mail
$user->notify(new EmailVerification($user));
$user->status = 'deactive';
$user->save();
$message = __('messages.signUpThankYouVerify');
} else {
$user->notify(new NewUser(request()->password));
$message = __('messages.signUpThankYou') . ' <a href="' . route('login') . '">Login Now</a>.';
}
return $message;
}
public function recaptchaValidate($request)
{
$global = global_settings();
if ($global->google_recaptcha_status) {
$gRecaptchaResponseInput = 'g-recaptcha-response';
$gRecaptchaResponse = $request->{$gRecaptchaResponseInput};
$validateRecaptcha = $this->validateGoogleRecaptcha($gRecaptchaResponse);
if (!$validateRecaptcha) {
return false;
}
}
return true;
}
public function assignRoles($user)
{
// Assign roles even before verification
$adminRole = Role::where('name', 'admin')->where('company_id', $user->company_id)->first();
$user->roles()->attach($adminRole->id);
$employeeRole = Role::where('name', 'employee')->where('company_id', $user->company_id)->first();
$user->roles()->attach($employeeRole->id);
return $user;
}
public function setSubDomainAttribute($value)
{
// domain is added in the request Class
$this->attributes['sub_domain'] = strtolower($value);
}
}

+ 10
- 0
app/CompanySetting.php View File

@ -0,0 +1,10 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class CompanySetting extends BaseModel
{
protected $table = 'organisation_settings';
}

+ 33
- 0
app/Events/CompanyRegistered.php View File

@ -0,0 +1,33 @@
<?php
namespace App\Events;
use App\Company;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class CompanyRegistered
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $company;
public function __construct(Company $company)
{
$this->company = $company;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('company-registered');
}
}

+ 72
- 0
app/Exceptions/Handler.php View File

@ -0,0 +1,72 @@
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Session\TokenMismatchException;
use Throwable;
use Illuminate\Validation\ValidationException as ValidationException;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
\Illuminate\Auth\AuthenticationException::class,
\Illuminate\Auth\Access\AuthorizationException::class,
\Symfony\Component\HttpKernel\Exception\HttpException::class,
\Illuminate\Database\Eloquent\ModelNotFoundException::class,
\Illuminate\Session\TokenMismatchException::class,
\Illuminate\Validation\ValidationException::class,
];
public function report(Throwable $exception)
{
parent::report($exception);
}
public function render($request, Throwable $exception)
{
// if (api_user()) {
// if ($exception instanceof ValidationException) {
// return response()->json(
// [
// 'message' => __('validation.givenDataInvalid'),
// 'errors' => $exception->validator->getMessageBag()
// ],
// 422
// );
// }
// }
if ($exception instanceof TokenMismatchException) {
return redirect(route('login'))->with('message', 'You page session expired. Please try again');
}
return parent::render($request, $exception);
}
/**
* Convert an authentication exception into an unauthenticated response.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Auth\AuthenticationException $exception
* @return \Illuminate\Http\Response
*/
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->guest(route('login'));
}
}

+ 184
- 0
app/Helper/Files.php View File

@ -0,0 +1,184 @@
<?php
namespace App\Helper;
use App\FileStorage;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\ImageManagerStatic as Image;
/**
* Class Reply
* @package App\Classes
*/
class Files
{
/**
* @param $image
* @param $dir
* @param null $width
* @param int $height
* @param $crop
* @return string
* @throws \Exception
*/
public static function upload($image, $dir, $width = null, $height = 800, $crop = false)
{
config(['filesystems.default' => 'local']);
/** @var UploadedFile $uploadedFile */
$uploadedFile = $image;
$folder = $dir . '/';
if (!$uploadedFile->isValid()) {
throw new \Exception('File was not uploaded correctly');
}
$newName = self::generateNewFileName($uploadedFile->getClientOriginalName());
$tempPath = public_path('user-uploads/temp/' . $newName);
/** Check if folder exits or not. If not then create the folder */
if (!\File::exists(public_path('user-uploads/' . $folder))) {
\File::makeDirectory(public_path('user-uploads/' . $folder), 0775, true);
}
$newPath = $folder . '/' . $newName;
/** @var UploadedFile $uploadedFile */
$uploadedFile->storeAs('temp', $newName);
if (!empty($crop)) {
// Crop image
if (isset($crop[0])) {
// To store the multiple images for the copped ones
foreach ($crop as $cropped) {
$image = Image::make($tempPath);
if (isset($cropped['resize']['width']) && isset($cropped['resize']['height'])) {
$image->crop(floor($cropped['width']), floor($cropped['height']), floor($cropped['x']), floor($cropped['y']));
$fileName = str_replace('.', '_' . $cropped['resize']['width'] . 'x' . $cropped['resize']['height'] . '.', $newName);
$tempPathCropped = public_path('user-uploads/temp') . '/' . $fileName;
$newPathCropped = $folder . '/' . $fileName;
// Resize in Proper format
$image->resize($cropped['resize']['width'], $cropped['resize']['height'], function ($constraint) {
//$constraint->aspectRatio();
// $constraint->upsize();
});
$image->save($tempPathCropped);
\Storage::put($newPathCropped, \File::get($tempPathCropped), ['public']);
// Deleting cropped temp file
\File::delete($tempPathCropped);
}
}
} else {
$image = Image::make($tempPath);
$image->crop(floor($crop['width']), floor($crop['height']), floor($crop['x']), floor($crop['y']));
$image->save();
}
}
// Do not compress if the gif is uploaded
if (($width || $height) && \File::extension($uploadedFile->getClientOriginalName()) !=='gif') {
// Crop image
$image = Image::make($tempPath);
$image->resize($width, $height, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$image->save();
}
\Storage::put($newPath, \File::get($tempPath), ['public']);
// Deleting temp file
\File::delete($tempPath);
return $newName;
}
public static function generateNewFileName($currentFileName)
{
$ext = strtolower(\File::extension($currentFileName));
$newName = md5(microtime());
if ($ext === '') {
return $newName;
}
return $newName . '.' . $ext;
}
public static function uploadLocalOrS3($uploadedFile, $dir)
{
if (!$uploadedFile->isValid()) {
throw new \Exception('File was not uploaded correctly');
}
if(config('filesystems.default') === 'local'){
$fileName = self::upload($uploadedFile,$dir,false,false,false);
self::storeSize($uploadedFile,$dir,$fileName);
return $fileName;
}
$newName = self::generateNewFileName($uploadedFile->getClientOriginalName());
self::storeSize($uploadedFile,$dir,$newName);
// We have given 2 options of upload for now s3 and local
#Storage::disk('s3')->putFileAs($dir, $uploadedFile, $newName, 'public');
Storage::disk('s3')->putFileAs($dir, $uploadedFile, $newName);
return $newName;
}
private static function storeSize($uploadedFile,$dir,$fileName){
FileStorage::create(
[
'name' => $fileName,
'path' => $dir,
'type' => $uploadedFile->getMimeType(),
'size' => $uploadedFile->getSize(),
]
);
}
public static function deleteFile($image, $folder)
{
$dir = trim($folder, '/');
$path = $dir . '/' . $image;
if (!\File::exists(public_path($path))) {
\Storage::delete($path);
}
try {
session()->forget('company_setting');
session()->forget('company');
FileStorage::where('name', $image)->delete();
} catch (\Exception $e) {
//
}
return true;
}
public static function deleteDirectory($folder)
{
$dir = trim($folder);
\Storage::deleteDirectory($dir);
return true;
}
}

+ 57
- 0
app/Http/Controllers/Controller.php View File

@ -0,0 +1,57 @@
<?php
namespace App\Http\Controllers;
use Carbon\Carbon;
use Froiden\Envato\Traits\AppBoot;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Artisan;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests, AppBoot;
public function __construct()
{
$this->showInstall();
$this->checkMigrateStatus();
$this->middleware(function ($request, $next) {
$this->global = global_settings();
$this->superadmin = global_settings();
config(['app.name' => $this->global->company_name]);
config(['app.url' => url('/')]);
App::setLocale($this->superadmin->locale);
Carbon::setLocale($this->superadmin->locale);
setlocale(LC_TIME, 'en' . '_' . strtoupper('en'));
$user = auth()->user();
if ($user && $user->super_admin == 1) {
config(['froiden_envato.allow_users_id' => true]);
}
return $next($request);
});
}
public function checkMigrateStatus()
{
$status = Artisan::call('migrate:check');
if ($status && !request()->ajax()) {
Artisan::call('migrate', array('--force' => true)); //migrate database
Artisan::call('optimize:clear');
}
}
}

+ 59
- 0
app/Http/Controllers/NotificationController.php View File

@ -0,0 +1,59 @@
<?php
namespace App\Http\Controllers;
use App\Helper\Reply;
use App\Http\Controllers\Admin\AdminBaseController;
use Illuminate\Http\Request;
class NotificationController extends AdminBaseController
{
public function __construct()
{
parent::__construct();
}
public function markAllRead()
{
$this->user->unreadNotifications->markAsRead();
return Reply::success(__('messages.notificationRead'));
}
public function showAdminNotifications()
{
$view = view('notifications.admin_user_notifications', $this->data)->render();
return Reply::dataOnly(['status' => 'success', 'html' => $view]);
}
public function showUserNotifications()
{
$view = view('notifications.user_notifications', $this->data)->render();
return Reply::dataOnly(['status' => 'success', 'html' => $view]);
}
public function showClientNotifications()
{
$view = view('notifications.client_notifications', $this->data)->render();
return Reply::dataOnly(['status' => 'success', 'html' => $view]);
}
public function showAllMemberNotifications()
{
return view('notifications.member.all_notifications', $this->data);
}
public function showAllClientNotifications()
{
return view('notifications.client.all_notifications', $this->data);
}
public function showAllAdminNotifications()
{
return view('notifications.admin.all_notifications', $this->data);
}
public function showAllSuperAdminNotifications()
{
return view('notifications.superadmin.all_notifications', $this->data);
}
}

+ 82
- 0
app/Http/Controllers/SuperAdmin/SuperAdminBaseController.php View File

@ -0,0 +1,82 @@
<?php
namespace App\Http\Controllers\SuperAdmin;
use App\GlobalSetting;
use App\LanguageSetting;
use App\OfflinePlanChange;
use App\Traits\FileSystemSettingTrait;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\App;
use Carbon\Carbon;
use App\PushNotificationSetting;
class SuperAdminBaseController extends Controller
{
use FileSystemSettingTrait;
/**
* @var array
*/
public $data = [];
/**
* @param $name
* @param $value
*/
public function __set($name, $value)
{
$this->data[$name] = $value;
}
/**
* @param $name
* @return mixed
*/
public function __get($name)
{
return $this->data[$name];
}
/**
* @param $name
* @return bool
*/
public function __isset($name)
{
return isset($this->data[ $name ]);
}
/**
* UserBaseController constructor.
*/
public function __construct()
{
$this->global = global_settings();
$this->superadmin = $this->global;
App::setLocale($this->global->locale);
Carbon::setLocale($this->global->locale);
setlocale(LC_TIME, $this->global->locale . '_' . strtoupper($this->global->locale));
$this->adminTheme = superadmin_theme();
$this->languageSettings = LanguageSetting::where('status', 'enabled')->get();
$this->pushSetting = PushNotificationSetting::first();
// Done for the purpose of updating. When updating this code runs before migration
try{
$this->offlineRequestCount = OfflinePlanChange::where('status', 'pending')->count();
}catch (\Exception $e){
$this->offlineRequestCount = 0;
}
$this->worksuitePlugins = worksuite_plugins();
$this->middleware(function ($request, $next) {
$this->user = user();
$this->unreadNotificationCount = count($this->user->unreadNotifications);
return $next($request);
});
}
}

+ 402
- 0
app/Http/Controllers/SuperAdmin/SuperAdminCompanyController.php View File

@ -0,0 +1,402 @@
<?php
namespace App\Http\Controllers\SuperAdmin;
use App\Company;
use App\Currency;
use App\EmployeeDetails;
use App\GlobalCurrency;
use App\Helper\Files;
use App\Helper\Reply;
use App\Http\Requests\SuperAdmin\Companies\DeleteRequest;
use App\Http\Requests\SuperAdmin\Companies\PackageUpdateRequest;
use App\Http\Requests\SuperAdmin\Companies\StoreRequest;
use App\Http\Requests\SuperAdmin\Companies\UpdateRequest;
use App\LanguageSetting;
use App\OfflineInvoice;
use App\OfflinePaymentMethod;
use App\Package;
use App\Role;
use App\Scopes\CompanyScope;
use App\StripeInvoice;
use App\Traits\CurrencyExchange;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\Facades\DataTables;
class SuperAdminCompanyController extends SuperAdminBaseController
{
use CurrencyExchange;
/**
* AdminProductController constructor.
*/
public function __construct()
{
parent::__construct();
$this->pageTitle = 'Companies';
$this->pageIcon = 'icon-layers';
$this->colClass = '6';
if (module_enabled('Subdomain')) {
$this->colClass = '4';
}
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$this->totalCompanies = Company::count();
$this->packages = Package::all();
return view('super-admin.companies.index', $this->data);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$this->timezones = \DateTimeZone::listIdentifiers(\DateTimeZone::ALL);
$this->currencies = GlobalCurrency::all();
return view('super-admin.companies.create', $this->data);
}
/**
* Store a newly created resource in storage.
* @param StoreRequest $request
* @return array
*/
public function store(StoreRequest $request)
{
DB::beginTransaction();
$company = new Company();
$companyDetail = $this->storeAndUpdate($company, $request);
$globalCurrency = GlobalCurrency::findOrFail($request->currency_id);
$currency = Currency::where('currency_code', $globalCurrency->currency_code)
->where('company_id', $companyDetail->id)->first();
if (is_null($currency)) {
$currency = new Currency();
$currency->currency_name = $globalCurrency->currency_name;
$currency->currency_symbol = $globalCurrency->currency_symbol;
$currency->currency_code = $globalCurrency->currency_code;
$currency->is_cryptocurrency = $globalCurrency->is_cryptocurrency;
$currency->usd_price = $globalCurrency->usd_price;
$currency->company_id = $companyDetail->id;
$currency->save();
}
$company->currency_id = $currency->id;
$company->save();
$user = $company->addUser($company, $request);
$company->addEmployeeDetails($user);
$adminRole = Role::where('name', 'admin')->where('company_id', $companyDetail->id)->withoutGlobalScope('active')->first();
$user->roles()->attach($adminRole->id);
$employeeRole = Role::where('name', 'employee')->where('company_id', $user->company_id)->first();
$user->roles()->attach($employeeRole->id);
DB::commit();
return Reply::redirect(route('super-admin.companies.index'), 'Company added successfully.');
}
/**
* Display the specified resource.
*
* @param int $id
*/
public function show($id)
{
//
}
/**
* @param $companyId
* @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
* @throws \Throwable
*/
public function editPackage($companyId)
{
$packages = Package::all();
$global = $this->global;
$company = Company::find($companyId);
$currentPackage = Package::find($company->package_id);
$lastInvoice = StripeInvoice::where('company_id', $companyId)->orderBy('created_at', 'desc')->first();
$packageInfo = [];
foreach ($packages as $package) {
$packageInfo[$package->id] = [
'monthly' => $package->monthly_price,
'annual' => $package->annual_price
];
}
$offlinePaymentMethod = OfflinePaymentMethod::whereNull('company_id')->get();
$modal = view('super-admin.companies.editPackage', compact('packages', 'company', 'currentPackage', 'lastInvoice', 'packageInfo', 'global', 'offlinePaymentMethod'))->render();
return response(['status' => 'success', 'data' => $modal], 200);
}
public function updatePackage(PackageUpdateRequest $request, $companyId)
{
$company = Company::find($companyId);
try {
$package = Package::find($request->package);
$company->package_id = $package->id;
$company->package_type = $request->packageType;
$company->status = 'active';
$payDate = $request->pay_date ? Carbon::parse($request->pay_date) : Carbon::now();
$company->licence_expire_on = ($company->package_type == 'monthly') ?
$payDate->copy()->addMonth()->format('Y-m-d') :
$payDate->copy()->addYear()->format('Y-m-d');
$nextPayDate = $request->next_pay_date ? Carbon::parse($request->next_pay_date) : $company->licence_expire_on;
if ($company->isDirty('package_id') || $company->isDirty('package_type')) {
$offlineInvoice = new OfflineInvoice();
} else {
$offlineInvoice = OfflineInvoice::where('company_id', $companyId)->orderBy('created_at', 'desc')->first();
if (!$offlineInvoice) {
$offlineInvoice = new OfflineInvoice();
}
}
$offlineInvoice->company_id = $company->id;
$offlineInvoice->package_id = $company->package_id;
$offlineInvoice->package_type = $request->packageType;
$offlineInvoice->amount = $request->amount ?: $package->{$request->packageType . '_price'};
$offlineInvoice->pay_date = $payDate;
$offlineInvoice->next_pay_date = $nextPayDate;
$offlineInvoice->status = 'paid';
$offlineInvoice->save();
$company->save();
return response(['status' => 'success', 'message' => 'Package Updated Successfully.'], 200);
} catch (\Exception $e) {
return $e;
}
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$this->company = Company::find($id);
$this->timezones = \DateTimeZone::listIdentifiers(\DateTimeZone::ALL);
$this->currencies = Currency::where('company_id', $id)->get();
$this->packages = Package::all();
$this->companyUser = User::where('company_id', $id)->withoutGlobalScope('active')->first();
return view('super-admin.companies.edit', $this->data);
}
public function defaultLanguage()
{
$this->languages = LanguageSetting::where('status', 'enabled')->get();
return view('super-admin.companies.default-language', $this->data);
}
/**
* @param Request $request
* @return array
*/
public function defaultLanguageUpdate(Request $request)
{
$this->global->new_company_locale = $request->default_language;
$this->global->save();
return Reply::success(__('messages.defaultCompanyLanguage'));
}
/**
* Update the specified resource in storage.
*
* @param UpdateRequest $request
* @param int $id
* @return array
*/
public function update(UpdateRequest $request, $id)
{
$company = Company::find($id);
$this->storeAndUpdate($company, $request);
$company->currency_id = $request->currency_id;
$company->save();
$user = User::where('company_id', $id)->withoutGlobalScope('active')->first();
$user->email = $request->email;
if (!is_null($request->password)) {
$user->password = bcrypt($request->password);
}
$user->save();
return Reply::redirect(route('super-admin.companies.index'), __('messages.updateSuccess'));
}
/**
* Remove the specified resource from storage.
*
* @param DeleteRequest $request
* @param int $id
* @return array
*/
public function destroy(DeleteRequest $request, $id)
{
Company::destroy($id);
return Reply::success(__('messages.deleteSuccess'));
}
/**
* @param Request $request
* @return mixed
* @throws \Exception
*/
public function data(Request $request)
{
$packages = Company::with('currency', 'package');
if ($request->package != 'all' && $request->package != '') {
$packages = $packages->where('package_id', $request->package);
}
if ($request->type != 'all' && $request->type != '') {
$packages = $packages->where('package_type', $request->type);
}
return Datatables::of($packages)
->addColumn('action', function ($row) {
$companyUser = User::withoutGlobalScope(CompanyScope::class)->withoutGlobalScope('active')->where('company_id', $row->id)->first();
$list = '<p><a href="' . route('super-admin.companies.edit', [$row->id]) . '" class="btn btn-info btn-circle"
data-toggle="tooltip" data-original-title="Edit"><i class="fa fa-pencil" aria-hidden="true"></i></a></p>';
if ($companyUser && $companyUser->email_verification_code != null) {
$list .= '<p><a href="javascript:;" class="btn btn-success btn-circle verify-user"
data-toggle="tooltip" data-user-id="' . $companyUser->id . '" data-original-title="' . __('modules.company.verifyNow') . '"><i class="fa fa-check" aria-hidden="true"></i></a></p>';
} else if (module_enabled('Subdomain')) {
$list .= '<p><a href="javascript:;" class="btn btn-success btn-circle domain-params"
data-toggle="tooltip" data-company-id="' . $row->id . '" data-company-url="' . request()->getScheme() . '://' . $row->sub_domain . '" data-original-title="Domain Notify to company admins"><i class="fa fa-bell" aria-hidden="true"></i></a></p>';
}
$list .= '<p><a href="javascript:;" class="btn btn-danger btn-circle sa-params"
data-toggle="tooltip" data-user-id="' . $row->id . '" data-original-title="Delete"><i class="fa fa-times" aria-hidden="true"></i></a></p>';
return $list;
})
->editColumn('company_name', function ($row) {
return ucfirst($row->company_name) . '<br />' . '<img src="' . $row->logo_url . '" class="img-responsive" style="max-height: 35px" />';
})
->editColumn('status', function ($row) {
$class = ($row->status == 'active') ? 'label-custom' : 'label-danger';
return '<span class="label ' . $class . '">' . ucfirst($row->status) . '</span>';
})
->editColumn('company_email', function ($row) {
return '<a href="mailto:' . $row->company_email . '" target="_blank">' . $row->company_email . '</a>';
})
->editColumn('sub_domain', function ($row) {
return '<a href="http://' . $row->sub_domain . '" target="_blank">' . $row->sub_domain . '</a>';
})
->editColumn('last_login', function ($row) {
if ($row->last_login != null) {
return $row->last_login->diffForHumans();
}
return '-';
})
->editColumn('package', function ($row) {
$package = '<div class="w-100 text-center">';
$package .= '<div class="m-b-5">' . ucwords($row->package->name) . ' (' . ucfirst($row->package_type) . ')' . '</div>';
$package .= '<a href="javascript:;" class="label label-custom package-update-button"
data-toggle="tooltip" data-company-id="' . $row->id . '" data-original-title="Change"><i class="fa fa-edit" aria-hidden="true"></i> Change </a>';
$package .= '</div>';
return $package;
})
->addColumn('details', function ($row) {
$companyUser = User::withoutGlobalScope(CompanyScope::class)->withoutGlobalScope('active')->where('company_id', $row->id)->first();
if ($companyUser && $companyUser->email_verification_code == null) {
$verified = '<i class="fa fa-check-circle" style="color: green;"></i>';
} else if ($companyUser && $companyUser->email_verification_code != null) {
$verified = '<i class="fa fa-times" style="color: red;"></i>';
} else {
$verified = '-';
}
$registerDate = $row->created_at->format('d-m-Y');
$totalUsers = User::withoutGlobalScope(CompanyScope::class)->withoutGlobalScope('active')->where('company_id', $row->id)->count();
$string = "<ul class='p-l-20'>";
$string .= "<li>" . __('modules.superadmin.verified') . ": " . $verified . "</li>";
$string .= "<li>" . __('modules.superadmin.registerDate') . ": " . $registerDate . "</li>";
$string .= "<li>" . __('modules.superadmin.totalUsers') . ": " . $totalUsers . "</li>";
$string .= "</ul>";
return $string;
})
->rawColumns(['action', 'details', 'company_email', 'company_name', 'status', 'package', 'sub_domain'])
->make(true);
}
public function storeAndUpdate($company, $request)
{
$company->company_name = $request->input('company_name');
$company->company_email = $request->input('company_email');
$company->company_phone = $request->input('company_phone');
$company->website = $request->input('website');
$company->address = $request->input('address');
$company->timezone = $request->input('timezone');
$company->locale = $request->input('locale');
$company->status = $request->status;
if ($request->hasFile('logo')) {
$company->logo = Files::upload($request->logo, 'app-logo');
}
$company->last_updated_by = $this->user->id;
if (module_enabled('Subdomain')) {
$company->sub_domain = $request->sub_domain;
}
$company->save();
try {
$this->updateExchangeRatesCompanyWise($company);
} catch (\Exception $e) {
}
return $company;
}
public function verifyUser()
{
$userId = request('user_id');
$user = User::withoutGlobalScope(CompanyScope::class)->withoutGlobalScope('active')->find($userId);
User::emailVerify($user->email_verification_code);
return Reply::success(__('messages.updateSuccess'));
}
}

+ 36
- 0
app/Http/Middleware/SuperAdmin.php View File

@ -0,0 +1,36 @@
<?php
namespace App\Http\Middleware;
use App\GlobalSetting;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Storage;
class SuperAdmin
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$user = auth()->user();
$exists = Storage::disk('storage')->exists('down');
$setting = GlobalSetting::first();
if($exists && is_null($setting->purchase_code) && (strpos(request()->getHost(), '.test') === false) ){
return Redirect::route('verify-purchase');
}
if (!Auth::check() || $user->super_admin == '0'){
return Redirect::route('login');
}
return $next($request);
}
}

+ 21
- 0
app/Http/Requests/SuperAdmin/Companies/DeleteRequest.php View File

@ -0,0 +1,21 @@
<?php
namespace App\Http\Requests\SuperAdmin\Companies;
use App\Http\Requests\SuperAdmin\SuperAdminBaseRequest;
class DeleteRequest extends SuperAdminBaseRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
//
];
}
}

+ 75
- 0
app/Http/Requests/SuperAdmin/Companies/StoreRequest.php View File

@ -0,0 +1,75 @@
<?php
namespace App\Http\Requests\SuperAdmin\Companies;
use App\Http\Requests\SuperAdmin\SuperAdminBaseRequest;
use App\Scopes\CompanyScope;
use App\User;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;
class StoreRequest extends SuperAdminBaseRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
\Illuminate\Support\Facades\Validator::extend('check_client', function($attribute, $value, $parameters, $validator) {
$user = User::withoutGlobalScopes(['active', CompanyScope::class])
->join('client_details', 'client_details.user_id', 'users.id')
->where('users.email', $value)
->first();
$userTable = User::withoutGlobalScopes(['active', CompanyScope::class])
->where('users.email', $value)->first();
if(!is_null($user) && (!is_null($userTable) && !$userTable->hasRole('admin'))){
return true;
}
elseif((!is_null($userTable) && is_null($user) && $userTable->hasRole('admin')) ){
return false;
}
elseif(is_null($userTable) && is_null($user)){
return true;
}
return false;
});
return [
"company_name" => "required",
"company_email" => "required|email|unique:companies",
'sub_domain' => module_enabled('Subdomain') ?'required|min:4|unique:companies,sub_domain|max:50|sub_domain':'',
"company_phone" => "required",
"address" => "required",
"status" => "required",
'email' => 'required|check_client',
'password' => 'required|min:6'
];
}
public function prepareForValidation()
{
if (empty($this->sub_domain)) {
return;
}
// Add servername domain suffix at the end
$subdomain = trim($this->sub_domain, '.') . '.' . get_domain();
$this->merge(['sub_domain' => $subdomain]);
request()->merge(['sub_domain' => $subdomain]);
}
public function messages()
{
return [
'email.check_client' => 'The email has already been taken.'
];
}
}

+ 37
- 0
app/Http/Requests/SuperAdmin/Companies/UpdateRequest.php View File

@ -0,0 +1,37 @@
<?php
namespace App\Http\Requests\SuperAdmin\Companies;
use App\Http\Requests\SuperAdmin\SuperAdminBaseRequest;
class UpdateRequest extends SuperAdminBaseRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'company_name' => 'required',
'company_email' => 'required|email|unique:companies,company_email,'.$this->route('company'),
'sub_domain' => module_enabled('Subdomain')?'required|min:4|max:50|sub_domain|unique:companies,sub_domain,'.$this->route('company'):'',
'company_phone' => 'required',
'address' => 'required',
'status' => 'required'
];
}
public function prepareForValidation()
{
if (empty($this->sub_domain)) {
return;
}
// Add servername domain suffix at the end
$subdomain = trim($this->sub_domain, '.') . '.' . get_domain();
$this->merge(['sub_domain' => $subdomain]);
request()->merge(['sub_domain' => $subdomain]);
}
}

+ 18
- 0
app/Http/Requests/SuperAdmin/SuperAdminBaseRequest.php View File

@ -0,0 +1,18 @@
<?php
namespace App\Http\Requests\SuperAdmin;
use App\Http\Requests\CoreRequest;
class SuperAdminBaseRequest extends CoreRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return !empty(superAdmin());
}
}

+ 37
- 0
app/Listeners/CompanyRegisteredListener.php View File

@ -0,0 +1,37 @@
<?php
namespace App\Listeners;
use App\Events\CompanyRegistered;
use App\Notifications\NewCompanyRegister;
use App\User;
use Illuminate\Support\Facades\Notification;
class CompanyRegisteredListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param CompanyRegistered $event
* @return void
*/
public function handle(CompanyRegistered $event)
{
if (!isRunningInConsoleOrSeeding()) {
$company = $event->company;
$generatedBy = User::whereNull('company_id')->get();
Notification::send($generatedBy, new NewCompanyRegister($company));
}
}
}

+ 96
- 0
app/Notifications/NewCompanyRegister.php View File

@ -0,0 +1,96 @@
<?php
namespace App\Notifications;
use App\Company;
use App\SlackSetting;
use App\Traits\SmtpSettings;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class NewCompanyRegister extends Notification implements ShouldQueue
{
use Queueable, SmtpSettings;
/**
* Create a new notification instance.
*
* @return void
*/
private $company;
public function __construct(Company $company)
{
$this->company = $company;
$this->setMailConfigs();
}
/**
* Get the notification's delivery channels.
*t('mail::layout')
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
$via = ['database'];
if ($notifiable->email_notifications) {
array_push($via, 'mail');
}
return $via;
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->subject(__('email.newCompany.subject').' '.config('app.name').'!')
->greeting(__('email.hello').' '.ucwords($notifiable->name).'!')
->line(__('email.newCompany.text'))
->line('With name:- '.$this->company->company_name)
->action(__('email.loginDashboard'), getDomainSpecificUrl(url('/login')))
->line(__('email.thankyouNote'));
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return array_merge($notifiable->toArray(), ['company_name' => $this->company->company_name]);
}
/**
* Get the Slack representation of the notification.
*
* @param mixed $notifiable
* @return SlackMessage
*/
public function toSlack($notifiable)
{
$slack = SlackSetting::first();
if(count($notifiable->employee) > 0 && !is_null($notifiable->employee[0]->slack_username)){
return (new SlackMessage())
->from(config('app.name'))
->image($slack->slack_logo_url)
->to('@' . $notifiable->employee[0]->slack_username)
->content('Welcome to ' . config('app.name') . '! New company has been registered.');
}
return (new SlackMessage())
->from(config('app.name'))
->image($slack->slack_logo_url)
->content('This is a redirected notification. Add slack username for *'.ucwords($notifiable->name).'*');
}
}

+ 1046
- 0
app/Observers/CompanyObserver.php
File diff suppressed because it is too large
View File


+ 35
- 0
app/Scopes/CompanyScope.php View File

@ -0,0 +1,35 @@
<?php
namespace App\Scopes;
use App\ClientDetails;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Support\Facades\Schema;
class CompanyScope implements Scope
{
public function apply(Builder $builder, Model $model)
{
// When user is logged in
// auth()->user() do not work in apply so we have use auth()->hasUser()
if ((session()->has('client_company') && $model->getTable() != "users") || !session()->has('client_company') ) {
if (auth()->hasUser() && Schema::hasColumn($model->getTable(), 'company_id')) {
$company = company();
if ($company) {
$builder->where($model->getTable() . '.company_id', '=', $company->id);
}
}
if (session()->has('company') && Schema::hasColumn($model->getTable(), 'company_id')) {
$company = company();
if ($company) {
$builder->where($model->getTable() . '.company_id', '=', $company->id);
}
}
}
}
}

Loading…
Cancel
Save