Файловый менеджер - Редактировать - /var/www/vhosts/aviointeriors.dev1.mndrn.cloud/app/update/Controllers.tar
Назад
CabinController.php 0000644 00000004164 15233463364 0010353 0 ustar 00 <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\ValidationException; use App\Models\CabinClass; use App\Models\AdminNotification; use App\Events\AdminNotificationEvent; use App\Models\Document; class CabinController extends Controller { public function __construct() { // $this->middleware('auth:api'); $api_user = auth()->guard('api')->user(); if (!$api_user) { return response()->json(['error' => 'Unauthorized.'], 401); } } public function delete($id, Request $request) { $user = auth()->guard('api')->user(); $company = $user->company; # $cabin = CabinClass::find($id); $cabin = CabinClass::where('id', $id)->with('products')->first(); if ($cabin->company_id != $company->id) { return response()->json(['error' => 'Unauthorized.'], 401); } if ($cabin) { if (isset($cabin->products)) { foreach ($cabin->products as $k => $v) { $document = Document::where('product_id', $v->id)->first(); if ($document) { $document->product_id = null; $document->save(); } } } $notification = AdminNotification::create(['cta_label' => 'View Company']); $notification->instigator_id = $user->id; $notification->message = $user->first_name.' '.$user->last_name.' deleted cabin class '.$cabin->name.' from '.$company->name.' and all '.$cabin->products->count().' product(s).'; $notification->href = 'companies/'.$user->company->id; $notification->save(); $notification->instigator = $user; event(new AdminNotificationEvent($notification)); $cabin->products()->delete(); $cabin->delete(); } return response()->json(['success' => 'Cabin deleted successfully']); } } NotificationsController.php 0000644 00000005616 15233463364 0012153 0 ustar 00 <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Carbon\Carbon; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\ValidationException; use App\Models\UserNotification; class NotificationsController extends Controller { public function __construct() { // $this->middleware('auth:api'); $api_user = auth()->guard('api')->user(); if (!$api_user) { return response()->json(['error' => 'Unauthorized.'], 401); } } public function index() { $api_user = auth()->guard('api')->user(); $company_id = $api_user->company_id; $notifications = UserNotification::where([['id', '>', 0],['company_id', $company_id]])->orderBy('created_at', 'DESC')->get(); return response()->json(['notifications' => $notifications], 200); } public function markAll(Request $request) { $api_user = auth()->guard('api')->user(); $type = $request->type; $company_id = $api_user->company_id; if ($type == true) { // Read all $notifications = UserNotification::where([['id', '>', 0],['company_id', $company_id]])->get(); foreach ($notifications as $key => $notification) { $notification->read_at = Carbon::now(); $notification->save(); } }else{ // Unread all $notifications = UserNotification::where([['id', '>', 0],['company_id', $company_id]])->get(); foreach ($notifications as $key => $notification) { $notification->read_at = null; $notification->save(); } } return response()->json(['status' => 'ok'], 200); } public function markRead($id, Request $request) { $notification = UserNotification::find($id); if (!$notification) { return response()->json(['error' => 'Notification not found'], 404); } $notification->read_at = Carbon::now(); $notification->save(); return response()->json(['success' => 'Notification marked as read'], 200); } public function markUnread($id, Request $request) { $notification = UserNotification::find($id); if (!$notification) { return response()->json(['error' => 'Notification not found'], 404); } $notification->read_at = null; $notification->save(); return response()->json(['success' => 'Notification marked as unread'], 200); } public function delete($id, Request $request) { $notification = UserNotification::find($id); if ($notification) { $notification->delete(); } return response()->json(['success' => 'Product deleted successfully']); } } FileController.php 0000644 00000021001 15233463364 0010203 0 ustar 00 <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\File; use App\Models\User; use App\Models\CabinClass; use App\Models\Company; use App\Models\Product; use App\Models\Folder; use App\Models\Document; class FileController extends Controller { public $local_store; public function __construct() { // $this->local_store = 'fake_s3'; $this->middleware('auth:api'); $api_user = auth()->guard('api')->user(); if (!$api_user) { return response()->json(['error' => 'Unauthorized.'], 401); } } public function index(Request $request) { $user = auth()->guard('api')->user(); $company = Company::where('id', $user->company_id)->first(); $companyFolder = Folder::where('id', $company->folder_id)->first(); $items = []; $dirs = Storage::disk($this->local_store)->directories($companyFolder->path); $files = Storage::disk($this->local_store)->files($companyFolder->path); foreach ($dirs as $index => $dir) { $folder = Folder::where('path', $this->pathFromUrl(Storage::disk($this->local_store)->url($dir)))->first(); if (!$folder) { $folder = Folder::create(['path' => $this->pathFromUrl(Storage::disk($this->local_store)->url($dir))]); } array_push($items, [ 'name' => basename($dir), 'path' => $this->pathFromUrl(Storage::disk($this->local_store)->url($dir)), 'folder_id' => $folder->id, 'type' => 'folder' ]); } foreach ($files as $index => $file) { array_push($items, [ 'name' => basename($file), 'path' => $this->pathFromUrl(Storage::disk($this->local_store)->url($file)), 'type' => 'file' ]); } $res = [ 'parent' => '/', 'items' => $items ]; return response()->json(['parent' => '/', 'items' => $items]); } public function showById($id, Request $request) { $user = auth()->guard('api')->user(); $items = []; $folder = Folder::find($id); if (!$folder) { return response()->json(['error' => 'Folder not found'], 404); } $path = $folder->path; $dirs = Storage::disk($this->local_store)->directories($folder->path); $files = Storage::disk($this->local_store)->files($folder->path); foreach ($dirs as $index => $dir) { $sub_files = Storage::disk($this->local_store)->files($dir); if ($sub_files) { foreach ($sub_files as $k => $v){ if ( count(explode("/", $v)) == 4 ) { $files[] = $v; } } } if (!$sub_files || count( explode("/", $dir) ) <= 2 ) { $folderPath = $this->pathFromUrl(Storage::disk($this->local_store)->url($dir)); $folder_expl = explode("/", $folderPath); // if (count($folder_expl) == 3) { // $folderPath = $folder_expl[0]."/".$folder_expl[1]; // } $subdir = Folder::where('path', $folderPath)->first(); # die(); if (!$subdir) { return response()->json(['error' => config('app.url')], 500); } $subdir->path = $dir; #var_dump($folderPath); #var_dump($subdir->path); #var_dump($this->pathFromUrl(Storage::disk($this->local_store)->url($dir))); array_push($items, [ 'name' => basename($dir), 'path' => $this->pathFromUrl(Storage::disk($this->local_store)->url($dir)), 'folder_id' => $subdir->id, 'type' => 'folder' ]); } } #die('ok'); #var_dump($items); #var_dump($files);die(); foreach ($files as $index => $file) { $document = Document::where('path', $this->pathFromUrl(Storage::disk($this->local_store)->url($file)))->first(); $serial = ''; if ($document) { $product = $document->product; $serial = $product ? $product->serial_number : ''; } # var_dump($this->pathFromUrl(Storage::disk($this->local_store)->url($file))); $path_expl = explode("/", $file); if (count($path_expl) == 4 ) { array_push($items, [ 'name' => $path_expl[2]."/".basename($file), 'sub_folder' => $path_expl[2], 'name' => ($document->name != null ? $document->name : $this->pathFromUrl(Storage::disk($this->local_store)->url($file)) ), 'path' => $this->pathFromUrl(Storage::disk($this->local_store)->url($file)), 'serial_number' => $serial, 'type' => 'file' ]); }else{ array_push($items, [ 'name' => basename($file), 'sub_folder' => '', 'name' => ($document->name != null ? $document->name : $this->pathFromUrl(Storage::disk($this->local_store)->url($file)) ), 'path' => $this->pathFromUrl(Storage::disk($this->local_store)->url($file)), 'serial_number' => $serial, 'type' => 'file' ]); } } return response()->json(['parent' => $path, 'parent_id' => $folder->parent_id, 'company_id' => $folder->company_id, 'items' => $items]); } public function showByIdDEPRECATED($id, Request $request) { $user = auth()->guard('api')->user(); $company = Company::where('id', $user->company_id)->first(); $companyFolder = Folder::where('id', $company->folder_id)->first(); $items = []; $folder = Folder::find($id); if (!$folder) { return response()->json(['error' => 'Folder not found'], 404); } else if ($folder->company_id != $company->id) { return response()->json(['error' => 'Permission denied'], 403); } $path = $folder->path; $path_arr = explode('/', $path); $cabin = CabinClass::where('name', end($path_arr)); $dirs = Storage::disk($this->local_store)->directories($folder->path); $files = Storage::disk($this->local_store)->files($folder->path); if (!$cabin) { return response()->json(['error' => 'Permission denied.'], 403); } foreach ($dirs as $index => $dir) { $folderPath = $this->pathFromUrl(Storage::disk($this->local_store)->url($dir)); $subdir = Folder::where('path', $folderPath)->first(); if (!$subdir) { return response()->json(['error' => 'Folder not found'], 500); } array_push($items, [ 'name' => basename($dir), 'path' => $this->pathFromUrl(Storage::disk($this->local_store)->url($dir)), 'folder_id' => $subdir->id, 'type' => 'folder' ]); } foreach ($files as $index => $file) { $document = Document::where('path', $this->pathFromUrl(Storage::disk($this->local_store)->url($file)))->first(); if ($document) { $product = $document->product; $serial = $product ? $product->serial_number : ''; } array_push($items, [ 'name' => basename($file), 'path' => $this->pathFromUrl(Storage::disk($this->local_store)->url($file)), 'serial_number' => $serial, 'type' => 'file' ]); } return response()->json(['parent' => $path, 'parent_id' => $folder->parent_id, 'items' => $items]); } public function download(Request $request) { $user = auth()->guard('api')->user(); $company = Company::where('id', $user->company_id)->first(); return Storage::disk($this->local_store)->download('\/'.$request->path); } protected function pathFromUrl($path) { $path = str_replace(config('app.url'), '', $path); $path = str_replace('storage/', '', $path); $path = trim($path, '/'); return $path; } } CompanyController.php 0000644 00000026147 15233463364 0010752 0 ustar 00 <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\ValidationException; use App\Models\User; use App\Models\CabinClass; use App\Models\Product; use App\Models\Folder; use App\Models\Document; use App\Models\Company; use App\Models\AdminNotification; use App\Events\AdminNotificationEvent; class CompanyController extends Controller { public function __construct() { // $this->middleware('auth:api'); $api_user = auth()->guard('api')->user(); if (!$api_user) { return response()->json(['error' => 'Unauthorized.'], 401); } } public function delete(Request $request) { $user = auth()->guard('api')->user(); $company = Company::find($user->company_id); if ($company) { $company->delete(); return response()->json(['success' => 'Company deleted successfully.'], 200); } else { return response()->json(['error' => 'Company not found.'], 404); } } public function show(Request $request) { $user = auth()->guard('api')->user(); $company = Company::where('id', $user->company_id)->with('cabinClasses')->with('users')->first(); foreach ($company->cabinClasses as $cabinClass) { $cabinClass->products = Product::where('cabin_class_id', $cabinClass->id)->get(); } if (!$company) { return response()->json(['error' => 'Company not found.'], 404); } return response()->json(['company' => $company], 200); } public function edit(Request $request) { $user = auth()->guard('api')->user(); $company = Company::where('id', $user->company_id)->with('cabinClasses')->with('users')->first(); $validator = Validator::make($request->all(), [ 'name' => 'required|unique:companies,name,'.$company->id ]); if ($validator->fails()) { throw new ValidationException($validator); } if (!$company) { return response()->json(['error' => 'Company not found.'], 404); } $company->name = $request->name; $company->save(); foreach ($request->cabin_classes as $cabinClass) { $cabin = CabinClass::where('id', $cabinClass)->with('products')->first(); if (!$cabin) { $cabin = CabinClass::create(['name' => $cabinClass['name']]); $cabin->company_id = $company->id; if (!Storage::disk('fake_s3')->exists($company->name.'/'.$cabin->name)) { Storage::disk('fake_s3')->makeDirectory($company->name.'/'.$cabin->name); $folder = Folder::create([ 'path' => $company->name.'/'.$cabin->name ]); $folder->parent_id = $company->folder_id; $folder->company_id = $company->id; $folder->save(); } } $cabin->save(); foreach ($cabinClass['products'] as $cabinProduct) { $product = isset($cabinProduct['id']) ? Product::find($cabinProduct['id']) : null; if (!$product && $cabinProduct['serial_number'] != '') { $check = Product::where([ ['serial_number', '=', $cabinProduct['serial_number']], ['cabin_class_id', '=', $cabin->id], ])->first(); // Check PN duplicato if (!$check || $check) { $p = new Product([ 'serial_number' => $cabinProduct['serial_number'], 'cabin_class_id' => $cabin->id, 'user_id' => $user->id, 'active' => 0, 'user_first_name' => $user->first_name, 'user_last_name' => $user->last_name, ]); # $p = Product::create(['serial_number' => $product['serial_number']]); # $p->cabin_class_id = $cabin->id; # $p->save(); $cabin->products()->save($p); # $product = Product::create(['serial_number' => $cabinProduct['serial_number']]); # $product->cabin_class_id = $cabin->id; # $product->save(); } } else { if ($cabinProduct['serial_number'] != '') { $product->serial_number = $cabinProduct['serial_number']; $product->save(); } } } } $notification = AdminNotification::create(['cta_label' => 'View Company']); $notification->instigator_id = $user->id; $notification->message = $user->first_name.' '.$user->last_name.' updated company '.$user->company->name.'.'; $notification->href = 'companies/'.$user->company->id; $notification->save(); $notification = $notification->toArray(); $notification['instigator'] = $user; event(new AdminNotificationEvent($notification)); return response()->json(['success' => 'Company updated successfully.']); } public function edit_deprecated(Request $request) { $user = auth()->guard('api')->user(); $company = Company::where('id', $user->company_id)->with('cabinClasses')->with('users')->first(); $validator = Validator::make($request->all(), [ 'name' => 'required|unique:companies,name,'.$company->id ]); if ($validator->fails()) { throw new ValidationException($validator); } if (!$company) { return response()->json(['error' => 'Company not found.'], 404); } $company->name = $request->name; $company->save(); foreach ($request->cabin_classes as $cabinClass) { $cabin = CabinClass::where('id', $cabinClass)->with('products')->first(); if (!$cabin && $company->cabinClasses->count() < 4) { $cabin = CabinClass::create(['name' => $cabinClass['name']]); $cabin->company_id = $company->id; if (!Storage::disk('fake_s3')->exists($company->name.'/'.$cabin->name)) { Storage::disk('fake_s3')->makeDirectory($company->name.'/'.$cabin->name); $folder = Folder::create([ 'path' => $company->name.'/'.$cabin->name ]); $folder->parent_id = $company->folder_id; $folder->save(); } $cabin->save(); } foreach ($cabinClass['products'] as $cabinProduct) { $product = isset($cabinProduct['id']) ? Product::find($cabinProduct['id']) : null; if (!$product && $cabinProduct['serial_number'] != '') { $product = Product::create(['serial_number' => $cabinProduct['serial_number'], 'user_id' => $user->id, 'user_first_name' => $user->first_name, 'user_last_name' => $user->last_name]); $product->cabin_class_id = $cabin->id; } $product->save(); } } $notification = AdminNotification::create(['cta_label' => 'View Company']); $notification->instigator_id = $user->id; $notification->message = $user->first_name.' '.$user->last_name.' updated company '.$user->company->name.'.'; $notification->href = 'companies/'.$user->company->id; $notification->save(); $notification = $notification->toArray(); $notification['instigator'] = $user; event(new AdminNotificationEvent($notification)); return response()->json(['success' => 'Company updated successfully.']); } public function create(Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required|unique:companies' ]); if ($validator->fails()) { throw new ValidationException($validator); } $company = Company::create([ 'name' => $request->name ]); Storage::disk('fake_s3')->makeDirectory($company->name); $path = $company->name; $companyFolder = Folder::create(['path' => $path]); $company->folder_id = $companyFolder->id; $company->save(); $cabinClasses = $request->cabin_classes; foreach ($cabinClasses as $cabinClass) { $cabin = CabinClass::create([ 'name' => $cabinClass['name'] ]); $cabin->company_id = $company->id; if (!Storage::disk('fake_s3')->makeDirectory($company->name.'/'.$cabin->name)) { return response()->json(['error' => 'Could not create folder'], 500); } $folder = Folder::create([ 'path' => $company->name.'/'.$cabin->name ]); $folder->parent_id = $companyFolder->id; $folder->save(); $cabin->save(); $products = $cabinClass['products']; foreach ($products as $product) { if ($product['serial_number'] != '') { $p = Product::create([ 'serial_number' => $product['serial_number'] ]); $p->cabin_class_id = $cabin->id; $p->save(); } } } $notification = AdminNotification::create(['cta_label' => 'View Folder']); $notification->instigator_id = $user->id; $notification->message = $user->first_name.' '.$user->last_name.' created company '.$company->name.' with '.$cabinClasses->count().' cabin classes.'; $notification->href = 'documents/folder/'.$user->company->folder_id; $notification->save(); $notification->instigator = $user; event(new AdminNotificationEvent($notification)); return response()->json(['success' => 'Company created successfully', 'company' => $company]); } public function linkUser(Request $request) { $company = Company::find($request->company_id); $user = User::find($request->user_id); if (!$company || !$user) { return response()->json(['error' => 'Resource not found.'], 404); } $user->company_id = $company->id; $user->save(); return response()->json(['success' => 'User linked successfully.'], 200); } public function unlinkUser(Request $request) { $user = User::find($request->user_id); if (!$user) { return response()->json(['error' => 'User not found'], 404); } $user->company_id = null; $user->save(); return response()->json(['success' => 'User unlinked successfully.'], 200); } } ProductController.php 0000644 00000012041 15233463364 0010750 0 ustar 00 <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\ValidationException; use App\Models\User; use App\Models\CabinClass; use App\Models\Company; use App\Models\Product; use App\Models\AdminNotification; use App\Events\AdminNotificationEvent; use App\Models\EmailQueue; use App\Models\Admin; class ProductController extends Controller { public function __construct() { // $this->middleware('auth:api'); $api_user = auth()->guard('api')->user(); if (!$api_user) { return response()->json(['error' => 'Unauthorized.'], 401); } } public function delete($id, Request $request) { $user = auth()->guard('api')->user(); $product = Product::find($id); if ($product) { $cabin = CabinClass::find($product->cabin_class_id); if ($cabin->company_id == $user->company->id) { $notification = AdminNotification::create(['cta_label' => 'View Folder']); $notification->instigator_id = $user->id; $notification->message = $user->first_name.' '.$user->last_name.' deleted product '.$product->serial_number.' from '.$cabin->name.'.'; $notification->href = 'documents/folder/'.$user->company->folder_id; $notification->save(); $notification->instigator = $user; event(new AdminNotificationEvent($notification)); $mail = EmailQueue::create([ 'label' => 'PN / MCC (s) deleted', 'type' => '4', 'user_id' => $user->id, 'info' => $user->first_name.' '.$user->last_name.' deleted: '.$product->serial_number.' '.$cabin->name.' '.$user->company->name.'.', 'to' => $user->email ]); $product->delete(); } } return response()->json(['success' => 'Product deleted successfully']); } public function update($id, Request $request) { $user = auth()->guard('api')->user(); $product = Product::find($id); if (!$product) { return response()->json(['error' => 'Product not found'], 404); } $cabin = CabinClass::find($product->cabin_class_id); if (!$cabin || $cabin->company_id != $user->company->id) { return response()->json(['error' => 'Unauthorized'], 403); } // Validate request $validator = Validator::make($request->all(), [ 'serial_number' => 'required|string|max:255', ]); if ($validator->fails()) { return response()->json(['error' => $validator->errors()], 422); } // Store old serial number for notification $old_serial_number = $product->serial_number; $new_serial_number = $request->serial_number; // If the serial number hasn't changed, return early if ($old_serial_number === $new_serial_number) { return response()->json(['info' => 'No changes were made to the product']); } // Update product and set as inactive $product->serial_number = $new_serial_number; $product->active = 0; // Set to inactive $product->save(); // Create notification for admin $notification = AdminNotification::create(['cta_label' => 'View Folder']); $notification->instigator_id = $user->id; $notification->message = $user->first_name.' '.$user->last_name.' modified product from '.$old_serial_number.' to '.$new_serial_number.' in '.$cabin->name.'.'; $notification->href = 'documents/folder/'.$user->company->folder_id; $notification->save(); $notification->instigator = $user; event(new AdminNotificationEvent($notification)); // Get admin emails for notification $admins = Admin::all(); $admin_emails = $admins->pluck('email')->toArray(); // Add to email queue for each admin foreach ($admin_emails as $admin_email) { $mail_info = [ 'user_name' => $user->first_name.' '.$user->last_name, 'company_name' => $user->company->name, 'cabin_name' => $cabin->name, 'old_pn' => $old_serial_number, 'new_pn' => $new_serial_number ]; EmailQueue::create([ 'label' => 'PN Modified', 'type' => '5', // New type for PN modification 'user_id' => $user->id, 'info' => json_encode($mail_info), 'to' => $admin_email ]); } return response()->json([ 'success' => 'Product updated successfully and set to inactive. It will be reviewed by an administrator.', 'product' => $product ]); } } Controller.php 0000644 00000000224 15233463364 0007407 0 ustar 00 <?php namespace App\Http\Controllers; use Laravel\Lumen\Routing\Controller as BaseController; class Controller extends BaseController { // } UserController.php 0000644 00000013550 15233463364 0010254 0 ustar 00 <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\ValidationException; use App\Models\User; use App\Models\EmailQueue; use App\Models\Company; use App\Models\CabinClass; use App\Models\Product; use App\Models\Folder; use App\Models\AdminNotification; use App\Events\AdminNotificationEvent; class UserController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { // $this->middleware('auth:api'); $api_user = auth()->guard('api')->user(); if (!$api_user) { return response()->json(['error' => 'Unauthorized.'], 401); } } public function create(Request $req) { $validator = Validator::make($req->all(), [ 'first_name' => 'required', 'last_name' => 'required', 'company_name' => 'required', 'email' => 'required|unique:users|email', 'password' => 'required|min:6|confirmed' ]); if ($validator->fails()) { throw new ValidationException($validator); } $company = Company::where('name', $req->company_name)->first(); $companyFolder = null; $cabinClasses = $req->cabin_classes; $user = User::create([ 'first_name' => $req->first_name, 'last_name' => $req->last_name, 'email' => $req->email, 'password' => Hash::make($req->password) ]); if ($company) { $user->company_id = $company->id; } else { $company = Company::create(['name' => $req->company_name]); $user->company_id = $company->id; Storage::disk('fake_s3')->makeDirectory($company->name); $path = $company->name; $companyFolder = Folder::create(['path' => $path]); $company->folder_id = $companyFolder->id; $companyFolder->company_id = $company->id; $company->save(); } foreach($cabinClasses as $cabinClass) { if ($company->cabinClasses->count() <= 4 && array_key_exists('name', $cabinClass)) { if($existing_company == 1){ $cabin = CabinClass::where([ ['name', $cabinClass['name'] ], ['company_id', $company->id] ] )->first(); }else{ $cabin = CabinClass::create(['name' => $cabinClass['name']]); } $cabin->company_id = $company->id; Storage::disk('fake_s3')->makeDirectory($company->name.'/'.$cabin->name); $folder = Folder::create([ 'path' => $company->name.'/'.$cabin->name ]); $folder->parent_id = $companyFolder->id; $folder->company_id = $company->id; $folder->save(); $cabin->save(); foreach($cabinClass['products'] as $product) { # $p = Product::create(['serial_number' => $product['serial_number']]); $p = Product::create(['serial_number' => $product['serial_number'], 'user_id' => $user->id, 'user_first_name' => $user->first_name, 'user_last_name' => $user->last_name]); $p->cabin_class_id = $cabin->id; $p->save(); } } } $notification = AdminNotification::create(['cta_label' => 'View Folder']); $notification->instigator_id = $user->id; $notification->message = $user->first_name.' '.$user->last_name.' was created with company '.$company->name.' and '.$cabinClasses->count().' cabin classes.'; $notification->href = 'documents/folder/'.$user->company->folder_id; $notification->save(); $notification->instigator = $user; event(new AdminNotificationEvent($notification)); $mail = EmailQueue::create([ 'label' => 'New Company', 'type' => '1', 'user_id' => $user->id, 'info' => $user->first_name.' '.$user->last_name.' created a company '.$company->name.' and '.$cabinClasses->count().' cabin classes.', 'to' => $user->email ]); //$user = User::create($req->only(['name', 'email'])); $user->save(); return response()->json($user); } public function edit(Request $request) { $user = auth()->guard('api')->user(); $validator = Validator::make($request->all(), [ 'first_name' => 'required', 'last_name' => 'required', 'email' => 'required|unique:users,email,'.$user->id.'|email', 'new_password' => 'min:6|confirmed' ]); if ($validator->fails()) { throw new ValidationException($validator); } if (!$user) { return response()->json(['error' => 'User not found'], 404); } $user->first_name = $request->first_name; $user->last_name = $request->last_name; if ($request->current_password && $request->new_password) { if (Hash::check($request->current_password, $user->password)) { $user->password = Hash::make($request->new_password); } else { return response()->json(['error' => 'Invalid password'], 400); } } $user->save(); return response()->json(['success' => 'User updated']); } public function delete($id, Request $request) { $user = User::find($id); $user->delete(); return response()->json(['success' => 'User deleted successfully.'], 200); } } Admin/CabinController.php 0000644 00000002475 15233463364 0011406 0 ustar 00 <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\ValidationException; use App\Models\CabinClass; use App\Models\Document; class CabinController extends Controller { public function __construct() { // $this->middleware('auth:admin'); $adminUser = auth()->guard('admin')->user(); if (!$adminUser) { return response()->json(['error' => 'Unauthorized.'], 401); } } public function delete($id, Request $request) { # $cabin = CabinClass::find($id); $cabin = CabinClass::where('id', $id)->with('products')->first(); if ($cabin) { if (isset($cabin->products)) { foreach ($cabin->products as $k => $v) { $document = Document::where('product_id', $v->id)->first(); if ($document) { $document->product_id = null; $document->save(); } } } $cabin->products()->delete(); $cabin->delete(); } return response()->json(['success' => 'Cabin deleted successfully']); } } Admin/NotificationsController.php 0000644 00000005635 15233463364 0013204 0 ustar 00 <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Carbon\Carbon; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\ValidationException; use App\Models\AdminNotification; class NotificationsController extends Controller { public function __construct() { // $this->middleware('auth:admin'); $adminUser = auth()->guard('admin')->user(); if (!$adminUser) { return response()->json(['error' => 'Unauthorized.'], 401); } } public function index() { $notifications = AdminNotification::with('instigator')->orderBy('created_at', 'DESC')->get(); return response()->json(['notifications' => $notifications], 200); } public function markAll(Request $request) { $type = $request->type; if ($type == true) { // Read all $notifications = AdminNotification::where('id', '>', 0)->get(); foreach ($notifications as $key => $notification) { $notification->read_at = Carbon::now(); $notification->save(); } }else{ // Unread all $notifications = AdminNotification::where('id', '>', 0)->get(); foreach ($notifications as $key => $notification) { $notification->read_at = null; $notification->save(); } } return response()->json(['status' => 'ok'], 200); } public function markRead($id, Request $request) { $notification = AdminNotification::find($id); if (!$notification) { return response()->json(['error' => 'Notification not found'], 404); } $notification->read_at = Carbon::now(); $notification->save(); return response()->json(['success' => 'Notification marked as read'], 200); } public function markUnread($id, Request $request) { $notification = AdminNotification::find($id); if (!$notification) { return response()->json(['error' => 'Notification not found'], 404); } $notification->read_at = null; $notification->save(); return response()->json(['success' => 'Notification marked as unread'], 200); } public function delete($id, Request $request) { $notification = AdminNotification::find($id); if ($notification) { $notification->delete(); } return response()->json(['success' => 'Product deleted successfully']); } public function lastNotification(Request $request) { $notification = AdminNotification::where([ ['id', '>', 0], ['read_at', null] ])->orderBy('id', 'DESC')->limit(1)->get(); return response()->json($notification, 200); } } Admin/FileController.php 0000644 00000122735 15233463364 0011253 0 ustar 00 <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\File; use App\Models\User; use App\Models\Company; use App\Models\CabinClass; use App\Models\Product; use App\Models\Folder; use App\Models\Document; use App\Models\UserNotification; use App\Events\UserNotificationEvent; use App\Events\NotificationEvent; use App\Models\AdminNotification; use App\Events\AdminNotificationEvent; use League\Flysystem\Filesystem; use Aws\S3\S3Client; use League\Flysystem\AwsS3v3\AwsS3V3Adapter; class FileController extends Controller { private $bucket_name; private $local_adapter; private $client; private $s3_adapter; private $s3; private $local; private $manager; private $local_store; public function __construct() { // $this->middleware('auth:admin'); $this->local_store = 'fake_s3'; $adminUser = auth()->guard('admin')->user(); if (!$adminUser) { return response()->json(['error' => 'Unauthorized.'], 401); } /** * LOCAL + STORE (S3 like) */ $this->bucket_name = env('AWS_BUCKET'); $this->local_adapter = new \League\Flysystem\Local\LocalFilesystemAdapter( // Determine root directory __DIR__.'/' ); $this->client = new \Aws\S3\S3Client([ 'endpoint' => env('AWS_URL'), 'credentials' => [ 'key' => env('AWS_ACCESS_KEY_ID'), 'secret' => env('AWS_SECRET_ACCESS_KEY'), ], 'region' => env('AWS_DEFAULT_REGION'), 'version' => 'latest', ]); // The internal adapter $this->s3_adapter = new \League\Flysystem\AwsS3V3\AwsS3V3Adapter( // S3Client $this->client, // Bucket name $this->bucket_name ); $this->s3 = new \League\Flysystem\Filesystem($this->s3_adapter); $this->local = new \League\Flysystem\Filesystem($this->local_adapter); // Add them in the constructor $manager = new \League\Flysystem\MountManager([ 'local' => $this->local, 's3' => $this->s3, ]); } public function index(Request $request) { $items = []; $dirs = Storage::disk($this->local_store)->directories('/'); $files = Storage::disk($this->local_store)->files('/'); foreach ($dirs as $index => $dir) { $folder = Folder::where('path', $this->pathFromUrl(Storage::disk($this->local_store)->url($dir)))->first(); if (!$folder) { $folder = Folder::create(['path' => $this->pathFromUrl(Storage::disk($this->local_store)->url($dir))]); } array_push($items, [ 'name' => basename($dir), 'path' => $this->pathFromUrl(Storage::disk($this->local_store)->url($dir)), 'folder_id' => $folder->id, 'type' => 'folder' ]); } foreach ($files as $index => $file) { array_push($items, [ 'name' => basename($file), 'path' => $this->pathFromUrl(Storage::disk($this->local_store)->url($file)), 'type' => 'file' ]); } $res = [ 'parent' => '/', 'items' => $items ]; return response()->json(['parent' => '/', 'items' => $items]); } public function show(Request $request) { $items = []; $path = $this->pathFromUrl($request->path); $dirs = Storage::disk($this->local_store)->directories($path); $files = Storage::disk($this->local_store)->files($path); foreach ($dirs as $index => $dir) { $folder = Folder::where('path', $this->pathFromUrl(Storage::disk($this->local_store)->url($dir)))->first(); array_push($items, [ 'name' => basename($dir), 'path' => $this->pathFromUrl(Storage::disk($this->local_store)->url($dir)), 'folder_id' => $folder->id, 'type' => 'folder' ]); } foreach ($files as $index => $file) { $document = Document::where('path', $this->pathFromUrl(Storage::disk($this->local_store)->url($file)))->first(); $serial = ''; if ($document) { $product = $document->product; $serial = $product ? $product->serial_number : ''; } array_push($items, [ 'name' => basename($file), 'path' => $this->pathFromUrl(Storage::disk($this->local_store)->url($file)), 'serial_number' => $serial, 'type' => 'file' ]); } return response()->json(['parent' => $path, 'items' => $items]); } public function editLabelAndPN(Request $request) { $item = $request->item; $pn = $request->selected_serial; $year = ''; if (isset( $request->selected_year_flag) && $request->selected_year_flag == true && isset( $request->selected_year )) { $year = $request->selected_year; } if ($item) { $document = Document::where('path', $this->pathFromUrl(Storage::disk($this->local_store)->url($item['path'])))->first(); $document->name = $item['name']; if ($pn != '' && isset( $request->selected_serial_flag) && $request->selected_serial_flag == true ) { $pn_exist = Product::where('serial_number', $pn)->first(); if ($pn_exist) { $document->product_id = $pn_exist->id; } } if (isset( $request->selected_year_flag) && $request->selected_year_flag == true && $year != $document->year &&$year != '') { $path_expl = explode("/", $document->path); $new_path = ''; $folder_path = ''; $file_to_upload = ''; // senza anno if (count($path_expl) == 3) { $new_path = $path_expl[0]."/".$path_expl[1]."/".$year."/".$path_expl[2]; $folder_path = $path_expl[0]."/".$path_expl[1]."/".$year."/"; $file_to_upload = $path_expl[2]; } // con anno if (count($path_expl) == 4) { $new_path = $path_expl[0]."/".$path_expl[1]."/".$year."/".$path_expl[3]; $folder_path = $path_expl[0]."/".$path_expl[1]."/".$year."/"; $file_to_upload = $path_expl[3]; } # var_dump($year); # var_dump($document->year); # var_dump($new_path);die(); # $document->year = $year; // CHANGE PATH // save new file if(!Storage::disk($this->local_store)->exists($folder_path)){ Storage::disk($this->local_store)->makeDirectory($folder_path, 0775, true); //creates directory } Storage::disk($this->local_store)->copy($document->path, $new_path); // copy file $destination_path = Storage::disk($this->local_store)->path($folder_path); $this->S3_upload($this->bucket_name, $destination_path.$file_to_upload, $this->pathFromUrl($folder_path), $file_to_upload); // DELETE OLD FILES // Local delete Storage::disk($this->local_store)->delete($document->path); if ( count( $path_expl ) == 4) { $old_dir_to_check = "/".$path_expl[0]."/".$path_expl[1]."/".$path_expl[2]; if( Storage::disk($this->local_store)->assertDirectoryEmpty($old_dir_to_check)){ Storage::disk($this->local_store)->delete($old_dir_to_check); // s3_delete_folder ??? } } // S3 Delete file $result = $this->S3_delete_file($this->bucket_name, $document->path); $document->path = $new_path; } # die(); $document->save(); } return response()->json(['status' => 'ok', 'info' => 'Name or/and PN updated'], 200); } public function showById($id, Request $request) { $items = []; $folder = Folder::find($id); if (!$folder) { return response()->json(['error' => 'Folder not found'], 404); } $path = $folder->path; $dirs = Storage::disk($this->local_store)->directories($folder->path); $files = Storage::disk($this->local_store)->files($folder->path); foreach ($dirs as $index => $dir) { $sub_files = Storage::disk($this->local_store)->files($dir); if ($sub_files) { foreach ($sub_files as $k => $v){ if ( count(explode("/", $v)) == 4 ) { $files[] = $v; } } } if (!$sub_files || count( explode("/", $dir) ) <= 2 ) { $folderPath = $this->pathFromUrl(Storage::disk($this->local_store)->url($dir)); $folder_expl = explode("/", $folderPath); // if (count($folder_expl) == 3) { // $folderPath = $folder_expl[0]."/".$folder_expl[1]; // } $subdir = Folder::where('path', $folderPath)->first(); # die(); # var_dump($path); if (!$subdir) { # return response()->json(['error' => config('app.url')], 500); }else{ $subdir->path = $dir; #var_dump($folderPath); #var_dump($subdir->path); #var_dump($this->pathFromUrl(Storage::disk($this->local_store)->url($dir))); array_push($items, [ 'name' => basename($dir), 'path' => $this->pathFromUrl(Storage::disk($this->local_store)->url($dir)), 'folder_id' => $subdir->id, 'type' => 'folder' ]); } } } #die('ok'); #var_dump($items); #var_dump($files);die(); foreach ($files as $index => $file) { $document = Document::where('path', $this->pathFromUrl(Storage::disk($this->local_store)->url($file)))->first(); $serial = ''; if ($document) { $product = $document->product; $serial = $product ? $product->serial_number : ''; } # var_dump($this->pathFromUrl(Storage::disk($this->local_store)->url($file))); $path_expl = explode("/", $file); if (count($path_expl) == 4 ) { array_push($items, [ 'name' => $path_expl[2]."/".basename($file), 'sub_folder' => $path_expl[2], 'name' => (( $document && $document->name != null) ? $document->name : $this->pathFromUrl(Storage::disk($this->local_store)->url($file)) ), 'path' => $this->pathFromUrl(Storage::disk($this->local_store)->url($file)), 'serial_number' => $serial, 'type' => 'file' ]); }else{ array_push($items, [ 'name' => basename($file), 'sub_folder' => '', 'name' => (( $document && $document->name != null) ? $document->name : $this->pathFromUrl(Storage::disk($this->local_store)->url($file)) ), 'path' => $this->pathFromUrl(Storage::disk($this->local_store)->url($file)), 'serial_number' => $serial, 'type' => 'file' ]); } } return response()->json(['parent' => $path, 'parent_id' => $folder->parent_id, 'company_id' => $folder->company_id, 'items' => $items]); } /** * Delete file on local + S3 */ public function delete(Request $request) { $path = $request->path; $document = Document::where('path', $path)->first(); if ($document) { $document->delete(); } // Local delete Storage::disk($this->local_store)->delete($path); // S3 Delete file $result = $this->S3_delete_file($this->bucket_name, $path); return response()->json($path, 200); } /** * Delete folder on local */ public function deleteFolder($id, Request $request) { $folder = Folder::find($id); if (!$folder) { return response()->json(['error' => 'Folder not found.'], 404); } if (Storage::disk($this->local_store)->exists($folder->path)) { $res = Storage::disk($this->local_store)->deleteDirectory($folder->path); $folder->delete(); return response()->json(['success' => 'Folder deleted']); } } /** * Delete file on S3 */ private function S3_delete_file($bucket_name='', $file_to_delete='') { $result = false; if ($bucket_name != '' && $file_to_delete != '') { try { $result = $this->client->deleteObject(array( 'Bucket' => $bucket_name, 'Key' => $file_to_delete )); } catch (S3Exception $e) { // Catch an S3 specific exception. echo $e->getMessage(); } } return $result; } /** * S3 file listing */ public function S3_list_files($bucket_name='', $prefix = '') { $all_files_and_folders = []; $files = []; if ($bucket_name != '') { $response = $this->client->listObjectsV2(array('Bucket' => $bucket_name, 'MaxKeys' => 10000, 'Prefix' => $prefix)); $files = $response->getPath('Contents'); $request_id = array(); if ($files != null) { foreach ($files as $file) { if (strpos($file['Key'], ".file_placeholder") <= 0 && substr($file['Key'], -1) != "/" ) { #$filename = $file['Key']; $all_files_and_folders[] = $file; #print "\n\nFilename:". $filename; } } } } return $all_files_and_folders; return $files; } /** * Get a list of files on S3 and local store */ public function S3_check_storage() { $S3_files_and_folders = $this->S3_list_files($this->bucket_name); $local_files_and_folders_raw = Storage::disk($this->local_store)->allFiles("/"); $local_files_and_folders = []; foreach ($local_files_and_folders_raw as $k => $v) { $local_files_and_folders[$v] = $v; } return ['s3' => $S3_files_and_folders, 'local' => $local_files_and_folders]; } public function S3_check_path(Request $request) { $type = $request->type; $path = $request->path; $storage_path = storage_path()."/app/public/"; $content = $this->S3_list_files($this->bucket_name, $request->path); $local_files_and_folders = []; if ($type != 'file') { $local_files_and_folders_raw = Storage::disk($this->local_store)->allFiles($path); if ($local_files_and_folders_raw != null) { foreach ($local_files_and_folders_raw as $k => $v) { $local_files_and_folders[$v] = $v; } } #var_dump($local_files_and_folders);die(); } $to_delete = []; $to_upload = []; $to_update = []; $same_file = []; if ($content) { // Il path o il file esiste if ($type == 'file') { // E' un file if (isset( $content[0] )) { $s3_md5 = str_replace('"', '', $content[0]['ETag']); $local_md5 = md5_file( $storage_path.$path ); if ($s3_md5 == $local_md5) { // Stesso file $same_file[ $content[0]['Key'] ] = $content[0]; if (array_key_exists($content[0]['Key'], $local_files_and_folders)) { unset( $local_files_and_folders[ $content[0]['Key'] ] ); } }else{ // Stesso file ma aggiornato $to_update[ $content[0]['Key'] ] = $content[0]; if (array_key_exists($content[0]['Key'], $local_files_and_folders)) { unset( $local_files_and_folders[ $content[0]['Key'] ] ); } } } }else{ // E' una cartella foreach ($content as $k => $v) { if (!is_dir( $storage_path.$v['Key'] ) && file_exists( $storage_path.$v['Key'] )) { $s3_md5 = str_replace('"', '', $v['ETag']); $local_md5 = md5_file( $storage_path.$v['Key'] ); # var_dump($s3_md5); # var_dump($local_md5);die(); if ($s3_md5 == $local_md5) { // Stesso file $same_file[ $v['Key'] ] = $v; if (array_key_exists($v['Key'], $local_files_and_folders)) { unset( $local_files_and_folders[ $v['Key'] ] ); } }else{ // Stesso file ma aggiornato $to_update[ $v['Key'] ] = $v; if (array_key_exists($v['Key'], $local_files_and_folders)) { unset( $local_files_and_folders[ $v['Key'] ] ); } } }else{ // Se non esiste in locale if (!file_exists( $storage_path.$v['Key'] )) { $to_upload[ $v['Key'] ] = $v; if (array_key_exists($v['Key'], $local_files_and_folders)) { unset( $local_files_and_folders[ $v['Key'] ] ); } } } } } }else{ // Path o file non trovato } #var_dump($path);die(); if ($local_files_and_folders != null) { foreach ($local_files_and_folders as $key => $value) { $to_delete[ $value ]['Key'] = $value; } } #var_dump($to_update);die(); return response()->json([ 'type' => $type, 'to_update' => $to_update, 'to_upload' => $to_upload, 'to_delete' => $to_delete, 'same_file' => $same_file, ]); } /** * From S3 to local upload (New files) */ public function S3_to_local_upload(Request $request) { $to_upload = $request->to_upload; $log_uploaded = []; $base_path = Storage::disk($this->local_store)->path("/"); foreach ($to_upload as $key => $value) { if (substr($value, -1) != "/") { // OK, non è una directory # echo "TO UPLOAD\n"; # echo $base_path.$value."\n"; // Upload del file dall'S3 al local $file_from_s3 = $this->client->GetObject([ 'Bucket' => $this->bucket_name, 'Key' => $value, 'SaveAs' => $base_path.$value ]); $file_saved_upload[ $base_path.$value ] = Storage::disk($this->local_store)->put($value, (string) $file_from_s3['Body']); // Creo l'entry nel database $document = Document::create([ 'path' => $value, 'created_at' => date("Y-m-d H:i:s"), 'updated_at' => date("Y-m-d H:i:s"), ]); $document->save(); $log_uploaded[ $base_path.$value ] = $file_saved_upload[ $base_path.$value ]; # var_dump($document);die(); } } return response()->json(["FILE UPLOADED:" => count($log_uploaded)], 200); } /** * From S3 to local update (file changed) */ public function S3_to_local_update(Request $request) { $to_update = $request->to_update; $log_updated = []; $base_path = Storage::disk($this->local_store)->path("/"); foreach ($to_update as $key => $value) { # echo "TO UPDATE\n"; # echo $base_path.$value."\n"; // Upload del file dall'S3 al local $file_from_s3 = $this->client->GetObject([ 'Bucket' => $this->bucket_name, 'Key' => $value, //'SaveAs' => $base_path.$value ]); $file_saved_update[$base_path.$value] = Storage::disk($this->local_store)->put($value, (string) $file_from_s3['Body']); $log_updated[ $base_path.$value ] = $file_saved_update[ $base_path.$value ]; } return response()->json(["FILE UPDATED:" => count($log_updated)]); } /** * Delete local file if there is no match on S3 */ public function S3_to_local_delete(Request $request) { $to_delete = $request->to_delete; $log_deleted = []; $base_path = Storage::disk($this->local_store)->path("/"); foreach ($to_delete as $key => $value) { // Non deve essere una cartella, elimino solo file if(File::exists($base_path.$value) && !File::isDirectory($base_path.$value) && substr($value, -1) != "/" ) { // Esiste // Cerco il file sul database $document = Document::where('path', $value)->first(); if ($document) { // SE esiste cancello la row nel database $document->delete(); } // ELimino il file in local $res = Storage::disk($this->local_store)->delete($value); // Log $log_deleted[ $value ] = $res; } } return response()->json(["FILE deleted:" => count($log_deleted)]); } public function S3_apply_force_sync_result(Request $request) { $base_path = Storage::disk($this->local_store)->path("/"); $to_delete = $request->to_delete; $to_upload = $request->to_upload; $to_update = $request->to_update; $same_file = $request->same_file; $text_log = ''; $dirs = Storage::allDirectories("/public"); $dirs_on_local = []; foreach ($dirs as $k_dir => $v_dir) { $dirs_on_local[$v_dir] = $v_dir; } $files = Storage::files("/public"); # var_dump($to_upload); # var_dump($dirs); # var_dump($files);die(); $text_log .= "\n\n----- Applying the differences from S3 to local + database -----\n\n"; foreach ($to_update as $key => $value) { $text_log .= "TO UPDATE\n"; $text_log .= $base_path.$value."\n"; // Upload del file dall'S3 al local $file_from_s3 = $this->client->GetObject([ 'Bucket' => $this->bucket_name, 'Key' => $value, 'SaveAs' => $base_path.$value ]); $file_saved_update[$base_path.$value] = Storage::disk($this->local_store)->put($value, (string) $file_from_s3['Body']); $log_updated[ $base_path.$value ] = $file_saved_update[ $base_path.$value ]; } foreach ($to_upload as $key => $value) { if (substr($value, -1) != "/") { // OK, non è una directory $text_log .= "TO UPLOAD\n"; $text_log .= $base_path.$value."\n"; $file_dir_obj_to_sync = explode('/',$value); array_pop($file_dir_obj_to_sync); $folder_path = implode("/", $file_dir_obj_to_sync); // Controllo che la directory esiste if(!Storage::exists('public/'.$folder_path)) { $folder_path_expl = explode("/", $folder_path); $company_name = $folder_path_expl[0]; $cabin_class = ucwords(strtolower($folder_path_expl[1])); if (isset($folder_path_expl[2])) { $year = $folder_path_expl[2]; }else{ $year = ''; } // Creao solo se cabin_class è uno dei 4 if ($cabin_class == 'Business' || $cabin_class == 'Economy' || $cabin_class == 'Premium Economy' || $cabin_class == 'First Class') { // Controllo se esiste la company $company = Company::where('name', $company_name)->first(); if (!$company) { $company = Company::create([ 'name' => $company_name ]); Storage::disk('fake_s3')->makeDirectory($company->name); $path = $company->name; $companyFolder = Folder::create(['path' => $path]); $company->folder_id = $companyFolder->id; $company->active = 1; $companyFolder->company_id = $company->id; $company->save(); $notification = AdminNotification::create([ 'cta_label' => 'New Company from CLOUD', ]); $notification->instigator_id = 0; $notification->message = 'SYSTEM created a company '.$company->name.' from CLOUD import.'; $notification->href = 'companies/'.$company->id; $notification->save(); $notification = $notification->toArray(); #$notification['instigator'] = $user; } if ($cabin_class != '') { $cabin = CabinClass::create([ 'name' => $cabin_class ]); $path = $company->name; $companyFolder = Folder::where('path', $path)->first(); $cabin->company_id = $company->id; Storage::disk('fake_s3')->makeDirectory($company->name.'/'.$cabin->name); $folder = Folder::create([ 'path' => $company->name.'/'.$cabin->name ]); if ($companyFolder) { $folder->parent_id = $companyFolder->id; } $folder->company_id = $company->id; $folder->save(); $cabin->save(); } } Storage::makeDirectory('public/'.$folder_path, 0775, true); //creates directory } // Upload del file dall'S3 al local $file_from_s3 = $this->client->GetObject([ 'Bucket' => $this->bucket_name, 'Key' => $value, //'SaveAs' => $base_path.$value ]); $file_saved_upload[ $base_path.$value ] = Storage::disk($this->local_store)->put($value, (string) $file_from_s3['Body']); // Creo l'entry nel database $document = Document::create([ 'path' => $value, 'created_at' => date("Y-m-d H:i:s"), 'updated_at' => date("Y-m-d H:i:s"), ]); $document->save(); $log_uploaded[ $base_path.$value ] = $file_saved_upload[ $base_path.$value ]; # var_dump($document);die(); } } /** * REMOVE */ # die("STOP"); $log_deleted = []; foreach ($to_delete as $key => $value) { $text_log .= "TO DELETE\n"; $text_log .= $base_path.$value."\n"; // Non deve essere una cartella, elimino solo file if(File::exists($base_path.$value) && !File::isDirectory($base_path.$value) && substr($value, -1) != "/" ) { // Esiste // Cerco il file sul database $document = Document::where('path', $value)->first(); if ($document) { // SE esistte cancello la row nel database $document->delete(); } // ELimino il file in local $res = Storage::disk($this->local_store)->delete($value); // Log $log_deleted[ $value ] = $res; } } $text_log .= "\n\n---- DONE ----\n"; return response()->json(['log' => $text_log]); } /** * Discover and Syncro ( die before real syncro) */ public function S3_force_sync(Request $request) { # error_reporting(E_ALL); $all_files = $this->S3_check_storage(); $storage_path = storage_path()."/app/public/"; $to_delete = []; $to_upload = []; $to_update = []; $same_file = []; #echo "\n---- S3 TO LACAL SYNC ----\n\n"; #echo "---- Scanning S3 bucket ----\n"; foreach ($all_files['s3'] as $k => $v_s3) { if( array_key_exists($v_s3['Key'], $all_files['local']) ) { // File exists $local_file = $all_files['local'][ $v_s3['Key'] ]; $s3_md5 = str_replace('"', '', $v_s3['ETag']); $local_md5 = md5_file( $storage_path.$local_file ); // If ETag != md5_file => file changed, transfer to local storage from s3 if ( $s3_md5 != $local_md5 ) { # echo "FILE CHANGED: ".$v_s3['Key']."\n"; $to_update[ $all_files['local'][ str_replace('"', '', $v_s3['Key'] ) ] ] = $all_files['local'][ str_replace('"', '', $v_s3['Key'] ) ]; unset( $all_files['local'][ str_replace('"', '', $v_s3['Key'] ) ] ); }else{ // Same file, notthing to do # echo "SAME FILE: ".$v_s3['Key']."\n"; $same_file[ $all_files['local'][ str_replace('"', '', $v_s3['Key'] ) ] ] = $all_files['local'][ str_replace('"', '', $v_s3['Key'] ) ]; unset( $all_files['local'][ str_replace('"', '', $v_s3['Key'] ) ] ); } }else{ // File to add // echo "FILE TO ADD (FROM S3): ".$v_s3['Key']."\n"; if (strpos($v_s3['Key'], "/www/vhosts/aviointeriors.dev1.mndrn.cloud/") > 0 ) { $remove_key = str_replace('"', '', $v_s3['Key'] ); unset( $all_files['local'][ $remove_key ] ); }else{ $remove_key = str_replace('"', '', $v_s3['Key'] ); $to_upload[ $remove_key ] = $remove_key; unset( $all_files['local'][ $remove_key ] ); } } } $base_path = Storage::disk($this->local_store)->path("/"); // File to remove, not matched on S3 foreach ($all_files['local'] as $key => $value) { # echo "FILE TO REMOVE: ".$key."\n"; $to_delete[ $key ] = $key; } // GESTIONE CREAZIONE FILE E CARTELLE E MODIFICA DB (documents) # var_dump($to_update); # var_dump($to_upload); # var_dump($to_delete); return response()->json( [ "to_update" => $to_update, "to_upload" => $to_upload, "to_delete" => $to_delete, "same_file" => $same_file, ] ); die('STOP'); echo "\n\n----- Applying the differences from S3 to local + database -----\n\n"; foreach ($to_update as $key => $value) { echo "TO UPDATE\n"; echo $base_path.$value."\n"; // Upload del file dall'S3 al local $file_from_s3 = $this->client->GetObject([ 'Bucket' => $this->bucket_name, 'Key' => $value, //'SaveAs' => $base_path.$value ]); $file_saved_update[$base_path.$value] = Storage::disk($this->local_store)->put($value, (string) $file_from_s3['Body']); $log_updated[ $base_path.$value ] = $file_saved_update[ $base_path.$value ]; } foreach ($to_upload as $key => $value) { if (substr($value, -1) != "/") { // OK, non è una directory echo "TO UPLOAD\n"; echo $base_path.$value."\n"; // Upload del file dall'S3 al local $file_from_s3 = $this->client->GetObject([ 'Bucket' => $this->bucket_name, 'Key' => $value, 'SaveAs' => $base_path.$value ]); $file_saved_upload[ $base_path.$value ] = Storage::disk($this->local_store)->put($value, (string) $file_from_s3['Body']); // Creo l'entry nel database $document = Document::create([ 'path' => $value, 'created_at' => date("Y-m-d H:i:s"), 'updated_at' => date("Y-m-d H:i:s"), ]); $document->save(); $log_uploaded[ $base_path.$value ] = $file_saved_upload[ $base_path.$value ]; # var_dump($document);die(); } } /** * REMOVE */ # die("STOP"); $log_deleted = []; foreach ($to_delete as $key => $value) { // Non deve essere una cartella, elimino solo file if(File::exists($base_path.$value) && !File::isDirectory($base_path.$value) && substr($value, -1) != "/" ) { // Esiste // Cerco il file sul database $document = Document::where('path', $value)->first(); if ($document) { // SE esistte cancello la row nel database $document->delete(); } // ELimino il file in local $res = Storage::disk($this->local_store)->delete($value); // Log $log_deleted[ $value ] = $res; } } # return response()->json( $all_files ); } /** * S3: Delete folder */ private function S3_delete_folder($bucket_name='', $folder_to_delete='') { $result = false; if ($bucket_name != '' && $folder_to_delete != '') { try { $result = $this->client->deleteMatchingObjects( $bucket_name, '/'.$folder_to_delete, '/^'.$folder_to_delete.'//' ); } catch (S3Exception $e) { // Catch an S3 specific exception. echo $e->getMessage(); } } return $result; } /** * S3: Make folder */ private function S3_create_folder($bucket_name='', $folder_to_create='', $acl = 'public-read') { if ($bucket_name != '' && $folder_to_create != '') { $result = false; try { // CREATE FOLDER $result = $this->client->putObject(array( 'Bucket' => $bucket_name, 'Key' => $folder_to_create."/", 'Body' => "", 'ACL' => $acl )); } catch (S3Exception $e) { // Catch an S3 specific exception. echo $e->getMessage(); } return $result; }else{ return false; } } /** * S3: Upload a file, make folder if not exists */ public function S3_upload($bucket_name='', $source_local_file='', $destination_path='', $file_to_upload='', $acl = 'public-read') { if ($bucket_name != '' && $destination_path != '' && $source_local_file != '') { $info = $this->client->doesObjectExist($bucket_name, $destination_path); if (!$info) { // Cartella da creare $result = $this->S3_create_folder($bucket_name, $destination_path); } try { $this->client->putObject(array( 'Bucket'=> $bucket_name, 'Key' => $destination_path."/".$file_to_upload, 'SourceFile' => $source_local_file, //'StorageClass' => 'REDUCED_REDUNDANCY' )); } catch (S3Exception $e) { // Catch an S3 specific exception. echo $e->getMessage(); } }else{ return false; } } /** * LOCAL + S3 Upload */ public function upload(Request $request) { $path = $this->pathFromUrl($request->path); if ($request->hasFile('document')) { $original_filename = $request->file('document')->getClientOriginalName(); $original_filename_arr = explode('.', $original_filename); $file_ext = end($original_filename_arr); $destination_path = Storage::disk($this->local_store)->path($path); $document = Document::where('path', $path.'/'.$original_filename)->first(); if (!$document) { $document = Document::create([ 'path'=> $path.'/'.$original_filename, ]); } if ($request->serialNumber) { $product = Product::where('serial_number', $request->serialNumber)->first(); if (!$product) { $product = Product::create([ 'serial_number' => $request->serialNumber ]); } $document->product_id = $product->id; $document->save(); } if ($request->file('document')->storeAs($path, $original_filename, $this->local_store)) { $companyName = explode('/', $request->path)[0]; $subdirName = explode('/', $request->path)[1]; $folder = Folder::where('path', $path)->first(); $company = Company::where('name', $companyName)->first(); if ($company && $request->isLastFile) { $notification = UserNotification::create(['cta_label' => 'View Folder']); $notification->company_id = $company->id; $notification->message = 'An administrator uploaded '.$request->totalFiles.' file(s) to '.$subdirName.'.'; if ($folder) { $notification->href = 'documents/folder/'.$folder->id; } else { $notification->href = 'documents/folder/'.$company->folder_id; } $notification->save(); event(new UserNotificationEvent($company, $notification)); } // AWS S3 Like $file_to_upload = $destination_path."/".$original_filename; if (file_exists( $file_to_upload )) { $this->S3_upload($this->bucket_name, $file_to_upload, $path, $original_filename); } // ---- return $this->responseRequestSuccess($original_filename); } else { return $this->responseRequestError('Cannot upload file'); } } else { return $this->responseRequestError('File not found'); } } public function download(Request $request) { return Storage::disk($this->local_store)->download('\/'.$request->path); } protected function responseRequestSuccess($ret) { return response()->json(['status' => 'success', 'data' => $ret], 200) ->header('Access-Control-Allow-Origin', '*') ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); } protected function responseRequestError($message = 'Bad request', $statusCode = 200) { return response()->json(['status' => 'error', 'error' => $message], $statusCode) ->header('Access-Control-Allow-Origin', '*') ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); } protected function pathFromUrl($path) { $path = str_replace(config('app.url'), '', $path); $path = str_replace('storage/', '', $path); $path = trim($path, '/'); return $path; } } Admin/CompanyController.php 0000644 00000065220 15233463364 0011775 0 ustar 00 <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\ValidationException; use App\Models\User; use App\Models\CabinClass; use App\Models\Product; use App\Models\Folder; use App\Models\Document; use App\Models\Company; use App\Models\UserNotification; use App\Events\UserNotificationEvent; use App\Models\EmailQueue; use League\Flysystem\Filesystem; class CompanyController extends Controller { private $local_store; public function __construct() { $this->local_store = 'fake_s3'; $this->middleware('auth:admin', [ 'except' => ['exportInactivePN', 'exportCustomersAndFiles']]); $adminUser = auth()->guard('admin')->user(); if (!$adminUser) { return response()->json(['error' => 'Unauthorized.'], 401); } } public function index(Request $req) { if (isset( $req->inactive ) && $req->inactive == 1) { $companies = Company::where('active', '!=', 1)->with('cabinClasses')->withCount('users')->get(); }else{ $companies = Company::with('cabinClasses')->withCount('users')->get(); } return response()->json($companies); } public function delete(Request $request) { $company = Company::where('id', $request->id)->with('cabinClasses')->first(); if ($company) { if ($company->cabinClasses) { foreach ($company->cabinClasses as $k_cc => $v_cc) { $products_to_delete = Product::where('cabin_class_id', $v_cc->id)->get(); if ($products_to_delete) { foreach ($products_to_delete as $k_p => $v_p) { $document = Document::where('product_id', $v_p->product_id)->first(); // Unlink documento // if ($document) { // $document->product_id = null; // $document->save(); // } if ($document) { $document->delete(); } // Elimino il prodotto $v_p->company_id = null; $v_p->delete(); } } // Elimino le cabin Clasess $v_cc->delete(); } $company->cabinClasses()->delete(); } $company->folder()->delete(); // Elimino la company # $company->folder_id = null; # $company->save(); # $company = Company::where('id', $request->id)->first(); $users = User::where('company_id', $request->id)->get(); if ($users) { foreach ($users as $key => $v_user) { $v_user->company_id = 0; $v_user->save(); } } $company->delete(); return response()->json(['success' => 'Company deleted successfully.'], 200); }else{ return response()->json(['error' => 'Company not found.'], 404); } // ----- Deprecato da qui in poi --- die('ok'); # $company = Company::find($request->id)->with('cabinClasses'); if ($company) { $company->folder()->delete(); $company->delete(); return response()->json(['success' => 'Company deleted successfully.'], 200); } else { return response()->json(['error' => 'Company not found.'], 404); } } public function show($id, Request $request) { $company = Company::where('id', $id)->with('cabinClasses')->with('folder')->with('users')->first(); if ($company) { # var_dump( $company->cabinClasses ); # var_dump( $company->folder );die; if (count($company->cabinClasses) != count($company->folder) && count($company->folder) <= 4 && count($company->cabinClasses) <= 4) { $company->missing_folders = 1; }else{ $company->missing_folders = 0; } foreach ($company->cabinClasses as $cabinClass) { $cabinClass->removable = true; $cabinClass->products = Product::where('cabin_class_id', $cabinClass->id)->get(); foreach ($cabinClass->products as $k => $v) { $cabinClass->products[$k]->active = ($cabinClass->products[$k]->active == 1 ? true : false); } } } if (!$company) { return response()->json(['error' => 'Company not found.'], 404); } return response()->json(['company' => $company], 200); } public function getCompanyByName(Request $request) { $company = Company::where('name', $request->company_name)->with('cabinClasses')->with('cabinClasses.products')->first(); if (!$company) { return response()->json(['error' => 'Company not found.'], 404); } return response()->json(['company' => $company]); } public function edit($id, Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required|unique:companies,name,'.$id ]); if ($validator->fails()) { throw new ValidationException($validator); } $company = Company::where('id', $id)->with('cabinClasses')->first(); if (!$company) { return response()->json(['error' => 'Company not found.'], 404); } $company->name = $request->name; $company->save(); foreach ($request->cabin_classes as $cabinClass) { $cabin = CabinClass::where('id', $cabinClass)->with('products')->first(); if (!$cabin) { $cabin = CabinClass::create(['name' => $cabinClass['name']]); $cabin->company_id = $company->id; if (!Storage::disk('fake_s3')->exists($company->name.'/'.$cabin->name)) { Storage::disk('fake_s3')->makeDirectory($company->name.'/'.$cabin->name); $folder = Folder::create([ 'path' => $company->name.'/'.$cabin->name ]); $folder->parent_id = $company->folder_id; $folder->company_id = $company->id; $folder->save(); } } $cabin->save(); foreach ($cabinClass['products'] as $cabinProduct) { $product = isset($cabinProduct['id']) ? Product::find($cabinProduct['id']) : null; if (!$product && $cabinProduct['serial_number'] != '') { $check = Product::where([ ['serial_number', '=', $cabinProduct['serial_number']], ['cabin_class_id', '=', $cabin->id], ])->first(); // Check PN duplicato if (!$check || $check) { $product = Product::create(['serial_number' => $cabinProduct['serial_number']]); $product->cabin_class_id = $cabin->id; $product->active = 1; $product->save(); } } else { if ($cabinProduct['serial_number'] != '') { $product->serial_number = $cabinProduct['serial_number']; $product->save(); } } } } $notification = UserNotification::create(['cta_label' => 'View Company']); $notification->company_id = $company->id; $notification->message = 'An administrator modified your company.'; $notification->href = '/company'; $notification->save(); event(new UserNotificationEvent($company, $notification)); return response()->json(['success' => 'Company updated successfully.']); } public function create(Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required|unique:companies' ]); if ($validator->fails()) { throw new ValidationException($validator); } $company = Company::create([ 'name' => $request->name ]); Storage::disk('fake_s3')->makeDirectory($company->name); $path = $company->name; $companyFolder = Folder::create(['path' => $path]); $company->folder_id = $companyFolder->id; $companyFolder->company_id = $company->id; $company->save(); $cabinClasses = $request->cabin_classes; foreach ($cabinClasses as $cabinClass) { $cabin = CabinClass::create([ 'name' => $cabinClass['name'] ]); $cabin->company_id = $company->id; Storage::disk('fake_s3')->makeDirectory($company->name.'/'.$cabin->name); $folder = Folder::create([ 'path' => $company->name.'/'.$cabin->name ]); $folder->parent_id = $companyFolder->id; $folder->company_id = $company->id; $folder->save(); $cabin->save(); $products = $cabinClass['products']; foreach ($products as $product) { if ($product['serial_number'] != '') { $p = Product::create([ 'serial_number' => $product['serial_number'] ]); $p->active = 1; $p->cabin_class_id = $cabin->id; $p->save(); } } } return response()->json(['success' => 'Company created successfully', 'company' => $company]); } public function linkUser(Request $request) { $company = Company::find($request->company_id); $user = User::find($request->user_id); if (!$company || !$user) { return response()->json(['error' => 'Resource not found.'], 404); } $user->company_id = $company->id; $user->save(); return response()->json(['success' => 'User linked successfully.'], 200); } public function unlinkUser(Request $request) { $user = User::find($request->user_id); if (!$user) { return response()->json(['error' => 'User not found'], 404); } $user->company_id = null; $user->save(); return response()->json(['success' => 'User unlinked successfully.'], 200); } public function toggleActiveProduct(Request $request) { $product_id = $request->product_id; $active = $request->active; if ($product_id > 0) { $product = Product::find($product_id); if ($active == true) { $product->active = 1; }else{ $product->active = 0; } $product->save(); } return response()->json(['success' => 'Product Activation toggled successfully'], 200); } public function validateCompany(Request $request) { if (isset($request->company_id)) { $company = Company::where('id', $request->company_id)->with('cabinClasses')->with('cabinClasses.products')->with('users')->with('folder')->first(); $first_validation = 0; if ($company && $company->active == 0) { if (count($company->folder) == 0) { Storage::disk('fake_s3')->makeDirectory($company->name); $path = $company->name; $companyFolder = Folder::create(['path' => $path]); $company->folder_id = $companyFolder->id; $companyFolder->company_id = $company->id; if (count( $company->cabinClasses ) > 0) { foreach ($company->cabinClasses as $kk => $v_cabin) { $v_cabin->removable = true; Storage::disk('fake_s3')->makeDirectory($company->name.'/'.$v_cabin->name); $folder = Folder::create([ 'path' => $company->name.'/'.$v_cabin->name ]); if ($companyFolder) { $folder->parent_id = $companyFolder->id; } $folder->company_id = $company->id; $folder->save(); if (count($v_cabin->products) > 0) { foreach ($v_cabin->products as $k => $value) { $v_cabin->products[$k]->active = ($v_cabin->products[$k]->active == 1 ? true : false); } } } } $company->active = 1; //$company->save(); $first_validation = 1; $company->missing_folders = 0; $company->save(); } if ($company->active == 0) { $company->active = 1; $company->save(); } } // Caso in cui la Company esiste, è attiva, ma un utente ha richiesto una classe non presente prima if ($company && $company->active == 1 && $first_validation != 1) { if (count($company->cabinClasses) != count($company->folder) ) { $company->missing_folders = 0; $company->save(); $dirs = Storage::disk('fake_s3')->allDirectories($company->name); $check_real_dirs = []; foreach ($dirs as $key => $value) { $check_real_dirs[ $value ] = $value; } $folder_list = []; foreach ($company->folder as $k => $v_folder) { $name_expl = explode("/", $v_folder->path); $name = $name_expl[count($name_expl)-1]; $folder_list[ $name ] = $v_folder->path; } foreach ($company->cabinClasses as $key => $v_cabin) { // Se manca va creata if ( !array_key_exists($v_cabin->name, $folder_list) ) { $v_cabin->removable = true; Storage::disk('fake_s3')->makeDirectory($company->name.'/'.$v_cabin->name); $folder = Folder::create([ 'path' => $company->name.'/'.$v_cabin->name ]); if ($company->folder_id) { $folder->parent_id = $company->folder_id; } $folder->company_id = $company->id; $folder->save(); if (count($v_cabin->products) > 0) { foreach ($v_cabin->products as $k => $value) { $v_cabin->products[$k]->active = ($v_cabin->products[$k]->active == 1 ? true : false); } } }else{ unset($folder_list[ $v_cabin->name ]); unset($check_real_dirs[ $company->name.'/'.$v_cabin->name ]); } } } # var_dump($check_real_dirs);die(); foreach ($check_real_dirs as $k => $dir_to_delete) { if (strpos($dir_to_delete, "/") > 0) { Storage::disk('fake_s3')->deleteDirectory($dir_to_delete); $folder = Folder::where('path', $dir_to_delete)->first(); if ($folder) { $folder->delete(); } $company->missing_folders = 0; $company->save(); } } // if (count( $folder_list ) > 0 ) { // foreach ($folder_list as $k => $v_folder) { // // Local delete // // Subfolder // if (strpos($v_folder, "/") > 0) { // Storage::disk('fake_s3')->deleteDirectory($v_folder); // $folder = Folder::where('path', $v_folder)->first(); // if ($folder) { // $folder->delete(); // } // }else{ // var_dump($dirs); // var_dump($company->folder); // var_dump($folder_list); // die(); // } // } // } } if (!$company) { return response()->json(['error' => 'Company not found.'], 404); } return response()->json(['company' => $company], 200); } } public function allInactivePN(Request $request) { $only_inactive = 0; if (isset($request->only_inactive) && $request->only_inactive == 1) { $only_inactive = 1; $companies = Company::where('id', '>', 0)->with('cabinClasses')->with('folder')->with('cabinClasses.products', function($query) { return $query->where('active', '<', 1); })->get(); }else{ $companies = Company::where('id', '>', 0)->with('cabinClasses')->with('folder')->with('cabinClasses.products')->get(); } # $companies = Company::where('id', '>', 0)->with('cabinClasses', function($query) { # return $query->where('active', '<', 1)})->with('folder')->with('cabinClasses.products')->get(); $selected_companies_with_inactive_pn = []; foreach ($companies as $k => $v) { $cabin_folders = []; foreach ($v->folder as $kf => $vf) { if (isset( $path_expl[1] )) { $path_expl = explode("/", $vf['path']); $cabin_folders[ $path_expl[1] ] = $vf['id']; } } foreach ($v->cabinClasses as $kk => $v_cabin) { if ( count($v_cabin->products) ) { $selected_companies_with_inactive_pn['list'][$k] = $v; $cabin_name = $v_cabin['name']; foreach ($v_cabin->products as $kkk => $v_product) { # if ($v_product->active != 1 || $only_inactive = 0) { if ($selected_companies_with_inactive_pn['list'][$k]['cabinClasses'][$kk]['products'][$kkk]['active'] == 1) { $selected_companies_with_inactive_pn['list'][$k]['cabinClasses'][$kk]['products'][$kkk]['active'] = true; }else{ $selected_companies_with_inactive_pn['list'][$k]['cabinClasses'][$kk]['products'][$kkk]['active'] = false; } if (array_key_exists($cabin_name, $cabin_folders)) { $selected_companies_with_inactive_pn['list'][$k]['cabinClasses'][$kk]['folder_id'] = $cabin_folders[ $cabin_name ]; } # } } } } } $selected_companies_with_inactive_pn['count'] = count($selected_companies_with_inactive_pn); return response()->json($selected_companies_with_inactive_pn, 200); } function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") { // open raw memory as file so no temp files needed, you might run out of memory though $f = fopen('php://memory', 'w'); // loop over the input array foreach ($array as $line) { // generate csv lines from the inner arrays fputcsv($f, $line, $delimiter); } // reset the file pointer to the start of the file fseek($f, 0); // tell the browser it's going to be a csv file header('Content-Type: text/csv'); // tell the browser we want to save it instead of displaying it header('Content-Disposition: attachment; filename="'.$filename.'";'); // make php send the generated csv lines to the browser fpassthru($f); } public function exportInactivePN(Request $request) { $companies = Company::where('id', '>', 0)->with('cabinClasses')->with('folder')->with('cabinClasses.products', function($query) { return $query->where('active', '<', 1); })->get(); $out_obj = []; $out_obj[] = ['Company', 'Cabin Class', 'PN']; $out_txt = "<b>COMPANY, CABIN CLASS, PN</b><br>"; foreach ($companies as $k => $v) { $cabin_folders = []; foreach ($v->folder as $kf => $vf) { $path_expl = explode("/", $vf['path']); $cabin_folders[ $path_expl[1] ] = $vf['id']; } foreach ($v->cabinClasses as $kk => $v_cabin) { if ( count($v_cabin->products) ) { $cabin_name = $v_cabin['name']; foreach ($v_cabin->products as $kkk => $v_product) { $out_obj[] = [ $v->name, $cabin_name, $v_product->serial_number ]; $out_txt .= $v->name.', <i>'.$cabin_name.'</i>: <b>'.$v_product->serial_number."</b><br>"; } } } } // INACTIVE PNs $mail = EmailQueue::create([ 'label' => 'Inactive P/N (s)', 'type' => '3', 'info' => $out_txt, 'to' => "test.sito@external.aviointeriors.it" ]); $this->array_to_csv_download( $out_obj, "export.csv" ); die(); return response()->json($out_obj, 200); } public function exportCustomersAndFiles(Request $request) { $file_list = []; $file_list[] = [ 'Nome compagnia' => 'Nome compagnia', 'Nome file' => 'Nome file', 'Percorso file' => 'Percorso file', 'Email' => 'Email', 'Nome e cognome' => 'Nome e cognome' ]; // Prendo tutte le Compagnie attive $companies = Company::where('id', '>', 0)->with('cabinClasses')->with('folder')->with('cabinClasses.products', function($query) { return $query->where('active', '>=', 1); })->get(); foreach ($companies as $k => $v_company) { $company_folder_id = $v_company->folder_id; foreach ($v_company->folder as $kf => $v_folder) { // Prendo il path $current_folder_path = $v_folder->path; if ($current_folder_path != '' ) { // Cerco i file presenti nella tabella documents, e poi vedo se esistono davvero sul filesystem $documents = Document::where('path', 'LIKE', "%".$current_folder_path."%")->get(); # return response()->json($documents, 200); foreach ($documents as $kd => $v_document) { $current_document = $v_document->path; $current_document_name = $v_document->name; // Controllo su filesystem $file_check = Storage::disk($this->local_store)->exists($current_document); // Se esiste if ($file_check) { $file_list_item = [ 'Nome compagnia' => $v_company->name, 'Nome file' => '', 'Percorso file' => '', 'Email' => '', 'Nome e cognome' => '' ]; // Controllo se è associato a un prodotto if ($v_document->product_id != NULL) { $product = Product::find($v_document->product_id); // Controllo se il prodotto esiste ancora e se ha un utente associato if ($product && $product->user_id != NULL) { $user_info = User::find($product->user_id); // Se lo è prendo eventuali info del cliente che ha richiesto il PN if ($user_info) { $nome_completo = $user_info->first_name." ".$user_info->last_name; $email = $user_info->email; $file_list_item['Email'] = $email; $file_list_item['Nome e cognome'] = $nome_completo; } } } // Se no lo inserisco in lista senza queste info $file_list_item['Percorso file'] = $current_document; $file_list_item['Nome file'] = $current_document_name; } #return response()->json($file_check, 200); $file_list[] = $file_list_item; } } } } $this->array_to_csv_download( $file_list, "export_file_list_".date("Y-m-d").".csv" ); die(); return response()->json($file_list, 200); } protected function pathFromUrl($path) { $path = str_replace(config('app.url'), '', $path); $path = str_replace('storage/', '', $path); $path = trim($path, '/'); return $path; } } Admin/PasswordResetController.php 0000644 00000011465 15233463364 0013176 0 ustar 00 <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\ValidationException; use App\Models\PasswordReset; use Carbon\Carbon; use App\Models\User; #use Illuminate\Mail; use Illuminate\Support\Facades\Hash; use DB; use Illuminate\Support\Str; use Illuminate\Support\Facades\Mail; use App\Events\NotificationEvent; use App\Models\AdminNotification; use App\Events\AdminNotificationEvent; class PasswordResetController extends Controller { public function __construct() { $this->middleware('auth:admin', ['except' => ['create', 'submitForgetPasswordForm', 'submitResetPasswordForm', 'showResetPasswordForm']]); // // $this->middleware('auth:admin'); // $adminUser = auth()->guard('admin')->user(); // if (!$adminUser) // { // return response()->json(['error' => 'Unauthorized.'], 401); // } } public function showResetPasswordForm($token) { return view('auth.forgetPasswordLink', ['token' => $token]); } /** * * @return response() */ public function submitForgetPasswordForm(Request $request) { $validator = Validator::make($request->all(), [ 'email' => 'required|email|exists:users', ]); $token = Str::random(64); DB::table('password_resets')->insert([ 'email' => $request->email, 'token' => $token, 'created_at' => Carbon::now() ]); Mail::send('email.forgetPassword', ['token' => $token], function($message) use($request){ $message->to($request->email); $message->subject('AVIO Interiors - Reset Password'); }); $notification = AdminNotification::create(['cta_label' => 'view']); $user = User::where('email', $request->email)->first(); if($user){ $notification->instigator_id = $user->id; $notification->message = $user->first_name.' '.$user->last_name.' requests a password reset.'; $notification->href = 'users/'.$user->id; $notification->save(); $notification = $notification->toArray(); $notification['instigator'] = $user; event(new AdminNotificationEvent($notification)); } return response()->json(['status' => 'ok', 'info' => 'We have e-mailed your password reset link!'], 200); } /** * Write code on Method * * @return response() */ public function submitResetPasswordForm(Request $request) { $validator = Validator::make($request->all(), [ 'email' => 'required|email|exists:users', 'password' => [ 'required', 'string', 'min:6', 'confirmed', 'regex:/[A-Z]/', // Almeno una lettera maiuscola 'regex:/[0-9]/' // Almeno un numero ], 'password_confirmation' => 'required' ], [ 'password.regex' => 'Password must contain at least one uppercase letter and one number.' ]); if ($validator->fails()) { if ($request->expectsJson() || $request->ajax()) { return response()->json(['status' => 'error', 'errors' => $validator->errors()], 422); } else { // In case of a normal web request, show errors $token = $request->token; $errors = $validator->errors(); return view('auth.forgetPasswordLink', compact('token', 'errors')); } } $updatePassword = DB::table('password_resets') ->where([ 'email' => $request->email, 'token' => $request->token ]) ->first(); if(!$updatePassword){ return response()->json(['status' => 'error', 'message' => 'Invalid token!'], 400); } $user = User::where('email', $request->email) ->update(['password' => Hash::make($request->password)]); DB::table('password_resets')->where(['email'=> $request->email])->delete(); // Check if the request is an AJAX/API request or a normal web request if ($request->expectsJson() || $request->ajax()) { return response()->json(['status' => 'ok', 'info' => 'Password updated successfully!'], 200); } else { // Redirect the user to the /user/ page after password reset return response('Password updated successfully!', 302) ->header('Location', '/user/'); } } } Admin/ProductController.php 0000644 00000005133 15233463364 0012004 0 ustar 00 <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\ValidationException; use App\Models\User; use App\Models\Product; use App\Models\EmailQueue; class ProductController extends Controller { public function __construct() { // $this->middleware('auth:admin'); $adminUser = auth()->guard('admin')->user(); if (!$adminUser) { return response()->json(['error' => 'Unauthorized.'], 401); } } public function delete($id, Request $request) { $product = Product::find($id); if ($product) { if ($product->user_id != NULL) { $user = User::find($product->user_id); $mail = EmailQueue::create([ 'label' => 'PN / MCC rejected', 'type' => '4', 'user_id' => $user->id, 'info' => '', 'to' => $user->email ]); } $product->delete(); } return response()->json(['success' => 'Product deleted successfully']); } public function activatePN(Request $request) { $all_pn_to_activate = $request->pn_list; foreach ($all_pn_to_activate as $key => $company) { foreach ($company['cabin_classes'] as $k => $cabin) { foreach ($cabin['products'] as $kk => $product) { $product_obj = Product::find($product['id']); if ($product_obj) { if ($product['active'] != $product_obj->active) { if ($product['active'] == true) { $product_obj->active = 1; }else{ $product_obj->active = 0; } } } $product_obj->save(); } } } return response()->json(['info' => 'Products successfully activated'], 200); } public function countInactivePn(Request $request) { $all_inactive = Product::where('active', '<', 1)->get(); $pn_count = 0; foreach ($all_inactive as $key => $value) { $pn_count = $pn_count+1; } return response()->json(['company_count' => count($all_inactive), 'product_count' => $pn_count ], 200); } } Admin/UserController.php 0000644 00000047113 15233463364 0011306 0 ustar 00 <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\ValidationException; use App\Models\User; use App\Models\EmailQueue; use App\Models\Company; use App\Models\CabinClass; use App\Models\Product; use App\Models\Folder; use App\Events\NotificationEvent; use App\Models\AdminNotification; use App\Events\AdminNotificationEvent; use Illuminate\Support\Facades\Mail; use App\Http\Controllers\RatingController; use Carbon\Carbon; class UserController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { // $this->middleware('auth:admin', ['except' => ['renewExpiredUser']]); $adminUser = auth()->guard('admin')->user(); if (!$adminUser) { return response()->json(['error' => 'Unauthorized.'], 401); } } public function index(Request $req) { if (isset( $req->inactive ) && $req->inactive == 1) { $users = User::where('active', '!=', 1)->with('company:id,name')->with('company.cabinClasses')->get(); }else{ $users = User::with('company:id,name')->with('company.cabinClasses')->get(); } return response()->json($users); } public function inactiveUsers(Request $req) { $users = User::where('active', '!=', 1)->with('company:id,name')->with('company.cabinClasses')->get(); return response()->json($users); } // public function create(Request $req) { $validator = Validator::make($req->all(), [ 'first_name' => 'required', 'last_name' => 'required', 'company_name' => 'required', 'email' => 'required|unique:users|email', 'password' => [ 'required', 'min:6', 'confirmed', 'regex:/[A-Z]/', // At least one uppercase letter 'regex:/[0-9]/' // At least one number ] ], [ 'password.regex' => 'Password must contain at least one uppercase letter and one number.' ]); if ($validator->fails()) { //throw new ValidationException($validator); # var_dump($validator->errors()->first());die(); return response()->json(['error' => $validator->errors()->first()], 500); } $req->company_name = ucwords( strtolower( $req->company_name ) ); $company = Company::where('name', $req->company_name)->first(); $companyFolder = null; $cabinClasses = $req->cabin_classes; #var_dump($cabinClasses);die(); $user = User::create([ 'first_name' => $req->first_name, 'last_name' => $req->last_name, 'email' => $req->email, 'active' => 0, 'password' => Hash::make($req->password) ]); if (isset($req->req_from) && $req->req_from == 'registration') { // $notification = new AdminNotification([ // 'cta_label' => 'New User registered', // 'instigator_id' => $user->id, // 'message' => $user->first_name.' '.$user->last_name.' registered.', // 'href' => 'users/'.$user->id, // ]); // $notification->save(); $notification = AdminNotification::create([ 'cta_label' => 'New User registered', // 'instigator_id' => $user->id, // 'message' => $user->first_name.' '.$user->last_name.' registered.', // 'href' => 'users/'.$user->id ]); $notification->instigator_id = $user->id; $notification->message = $user->first_name.' '.$user->last_name.' registered.'; $notification->href = 'users/'.$user->id; $notification->save(); $notification = $notification->toArray(); $notification['instigator'] = $user; event(new AdminNotificationEvent($notification)); $mail = EmailQueue::create([ 'label' => 'New User registered', 'type' => '0', 'user_id' => $user->id, 'info' => $user->first_name.' '.$user->last_name.' registered.', 'to' => $user->email ]); // $emails = ['a.bellamio@mandarino.agency', 'f.quagliotto@mandarino.agency', 'a.zerbinati@mandarino.agency', $user->email]; // $emails = ['a.zerbinati@mandarino.agency', $user->email]; // Mail::send('email.userRegistration', [ // 'first_name' => $user->first_name, // 'last_name' => $user->last_name, // 'email' => $user->email, // 'company' => $req->company_name // ], function($message) use($req, $user, $emails){ // $message->to($emails); // $message->subject('AVIO Interiors - New user registration'); // }); } $existing_company = 0; if ($company) { $user->company_id = $company->id; $existing_company = 1; } else { $company = Company::create(['name' => $req->company_name]); # var_dump($company->id);die(); $user->company_id = $company->id; // Da spostare in fase di attivazione /* Storage::disk('fake_s3')->makeDirectory($company->name); $path = $company->name; $companyFolder = Folder::create(['path' => $path]); $company->folder_id = $companyFolder->id; $companyFolder->company_id = $company->id; */ $company->save(); if (isset($req->req_from) && $req->req_from == 'registration') { // $notification = new AdminNotification([ // 'cta_label' => 'New Company', // 'instigator_id' => $user->id, // 'message' => $user->first_name.' '.$user->last_name.' created a company '.$company->name.'.', // 'href' => 'companies/'.$company->id, // ]); // $notification->save(); $notification = AdminNotification::create([ 'cta_label' => 'New Company', // 'instigator_id' => $user->id, // 'message' => $user->first_name.' '.$user->last_name.' created a company '.$company->name.'.', // 'href' => 'companies/'.$company->id ]); $notification->instigator_id = $user->id; $notification->message = $user->first_name.' '.$user->last_name.' created a company '.$company->name.'.'; $notification->href = 'companies/'.$company->id; $notification->save(); $notification = $notification->toArray(); $notification['instigator'] = $user; // $emails = ['a.bellamio@mandarino.agency', 'f.quagliotto@mandarino.agency', 'a.zerbinati@mandarino.agency']; // $emails = ['a.zerbinati@mandarino.agency']; $mail = EmailQueue::create([ 'label' => 'New Company', 'type' => '1', 'user_id' => $user->id, 'info' => $user->first_name.' '.$user->last_name.' created a company '.$company->name.'.', 'to' => $user->email ]); // Mail::send('email.companyCreation', [ // 'first_name' => $user->first_name, // 'last_name' => $user->last_name, // 'email' => $user->email, // 'company' => $req->company_name // ], function($message) use($req, $user, $emails){ // $message->to($emails); // $message->subject('AVIO Interiors - New company creation after user registration'); // }); event(new AdminNotificationEvent($notification)); } } foreach($cabinClasses as $cabinClass) { if ($company->cabinClasses->count() <= 4 && array_key_exists('name', $cabinClass) ) { if($existing_company == 1){ $cabin = CabinClass::where([ ['name', $cabinClass['name'] ], ['company_id', $company->id] ] )->first(); // Nel caso non è ancora presente nella Company if (!$cabin) { $cabin = new CabinClass(['name' => $cabinClass['name'], 'company_id' => $company->id]); $company->cabinClasses()->save($cabin); } }else{ $cabin = new CabinClass(['name' => $cabinClass['name'], 'company_id' => $company->id]); $company->cabinClasses()->save($cabin); # $cabin = CabinClass::create(['name' => $cabinClass['name'], 'company_id' => $company->id]); } # $cabin->company_id = $company->id; // Da spostare in fase di attivazione /* Storage::disk('fake_s3')->makeDirectory($company->name.'/'.$cabin->name); $folder = Folder::create([ 'path' => $company->name.'/'.$cabin->name ]); if ($companyFolder) { $folder->parent_id = $companyFolder->id; } $folder->company_id = $company->id; $folder->save(); */ # $cabin->save(); foreach($cabinClass['products'] as $product) { $p = new Product([ 'serial_number' => $product['serial_number'], 'cabin_class_id' => $cabin->id, 'user_id' => $user->id, 'active' => 0, 'user_first_name' => $user->first_name, 'user_last_name' => $user->last_name, ]); # $p = Product::create(['serial_number' => $product['serial_number']]); # $p->cabin_class_id = $cabin->id; # $p->save(); $cabin->products()->save($p); } } } //$user = User::create($req->only(['name', 'email'])); if ($req->req_from == 'registration') { $user->save(); return response()->json(["status"=> 'ok',"user" => $user], 200); } $user->save(); return response()->json($user); } public function show($id, Request $request) { $user = User::where('id', $id)->with('company')->with('company.cabinClasses')->first(); if ($user && $user->company) { foreach($user->company->cabinClasses as $cabinClass) { $cabinClass->products = Product::where('cabin_class_id', $cabinClass->id)->get(); } }; if (!$user) { return response()->json(['error' => 'User not found'], 404); }; return response()->json($user); } public function validateCompany($company_id = null) { if ($company_id != null) { $company = Company::where('id', $company_id)->with('cabinClasses')->with('cabinClasses.products')->with('users')->with('folder')->first(); if ($company && $company->active == 0) { if (count($company->folder) == 0) { Storage::disk('fake_s3')->makeDirectory($company->name); $path = $company->name; $companyFolder = Folder::create(['path' => $path]); $company->folder_id = $companyFolder->id; $companyFolder->company_id = $company->id; if (count( $company->cabinClasses ) > 0) { foreach ($company->cabinClasses as $kk => $v_cabin) { $v_cabin->removable = true; Storage::disk('fake_s3')->makeDirectory($company->name.'/'.$v_cabin->name); $folder = Folder::create([ 'path' => $company->name.'/'.$v_cabin->name ]); if ($companyFolder) { $folder->parent_id = $companyFolder->id; } $folder->company_id = $company->id; $folder->save(); if (count($v_cabin->products) > 0) { foreach ($v_cabin->products as $k => $value) { $v_cabin->products[$k]->active = ($v_cabin->products[$k]->active == 1 ? true : false); } } } } $company->active = 1; $company->save(); } } // Caso in cui la Company esiste, è attiva, ma un utente ha richiesto una classe non presente prima if ($company && $company->active == 1) { //if (count($company->cabinClasses) != count($company->folder) ) { $company->missing_folders = 0; $folder_list = []; foreach ($company->folder as $k => $v_folder) { $name_expl = explode("/", $v_folder->path); $name = $name_expl[count($name_expl)-1]; $folder_list[ $name ] = $v_folder->path; } foreach ($company->cabinClasses as $key => $v_cabin) { $check_folder = Folder::where('path', $company->name.'/'.$v_cabin->name)->first(); if (!$check_folder) { // Se manca va creata if ( !array_key_exists($v_cabin->name, $folder_list) ) { $v_cabin->removable = true; Storage::disk('fake_s3')->makeDirectory($company->name.'/'.$v_cabin->name); $folder = Folder::create([ 'path' => $company->name.'/'.$v_cabin->name ]); if ($company->folder_id) { $folder->parent_id = $company->folder_id; } $folder->company_id = $company->id; $folder->save(); if (count($v_cabin->products) > 0) { foreach ($v_cabin->products as $k => $value) { $v_cabin->products[$k]->active = ($v_cabin->products[$k]->active == 1 ? true : false); } } } } } } if (!$company) { return response()->json(['error' => 'Company not found.'], 404); } return response()->json(['company' => $company], 200); } } public function edit($id, Request $request) { $validator = Validator::make($request->all(), [ 'first_name' => 'required', 'last_name' => 'required', 'email' => 'required|unique:users,email,'.$id.'|email', 'password' => 'min:6|confirmed' ]); if ($validator->fails()) { throw new ValidationException($validator); } $user = User::find($id); if (!$user) { return response()->json(['error' => 'User not found'], 404); } $user->first_name = $request->first_name; $user->last_name = $request->last_name; if ($user->active == 0 && $request->active == true) { $this->validateCompany($user->company_id); } $user->active = ($request->active == true ? 1 : 0); if ($request->password) { $user->password = Hash::make($request->password); } if ($request->selected_company) { $company = Company::where('name', $request->selected_company)->first(); $user->company_id = $company->id; } $user->save(); return response()->json(['success' => 'User updated']); } public function delete($id, Request $request) { $user = User::find($id); $user->delete(); return response()->json(['success' => 'User deleted successfully.'], 200); } public function fireNotification(Request $request) { return response()->json(['success' => 'Notification fired successfully.'], 200); } public function activateUser(Request $request) { $user_id = $request->user_id; $user = User::find($user_id); if ($user) { if ($user->active != 1) { $user->active = 1; if (isset($user->company_id) && $user->company_id > 0) { $this->validateCompany($user->company_id); } }else{ $user->active = 0; } } $user->save(); return response()->json(['info' => 'User successfully activated'], 200); } public function activateUsers(Request $request) { $all_user_to_activate = $request->users_list; foreach ($all_user_to_activate as $key => $value) { if ($value != null && is_bool( $value ) && $value == true) { $user_id = $key; $user = User::find($user_id); if ($user) { if ($user->active != 1) { $user->active = 1; if (isset($user->company_id) && $user->company_id > 0) { $this->validateCompany($user->company_id); } }else{ # $user->active = 0; } } $user->save(); } } return response()->json(['info' => 'Users successfully activated'], 200); } public function renewExpiredUser(Request $request) { $token = $request->token; $request->rating1 = $request->rating_1; $request->rating2 = $request->rating_2; $request->rating3 = $request->rating_3; $request->rating4 = $request->rating_4; if ($token != '') { $user = User::where('renewal_token', $token)->first(); if ($user) { $request->email = $user->email; $res = (new RatingController)->save($request); if (isset($res->original['status']) && $res->original['status'] == 'ok') { $user->active = 1; $user->expired = 0; $user->renewal_token = NULL; $user->renew_date = Carbon::now(); $user->save(); return response()->json(['status' => 'ok', 'info' => 'all done'], 200); }else{ return response()->json(['error' => 'Problem saving ratings'], 500); } }else{ return response()->json(['error' => 'No user found'], 404); } } } } Admin/MailQueueController.php 0000644 00000004742 15233463364 0012260 0 ustar 00 <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Carbon\Carbon; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\ValidationException; use App\Models\AdminNotification; use App\Models\EmailQueue; use App\Models\User; use DB; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Str; use Illuminate\Support\Facades\Mail; class MailQueueController extends Controller { public function __construct() { $this->middleware('auth:admin'); $adminUser = auth()->guard('admin')->user(); if (!$adminUser) { return response()->json(['error' => 'Unauthorized.'], 401); } } /** * Tipi di mail */ public function mail_type($type, $mode='') { $mail_type = []; if ($mode == 'id') { $mail_type['NEW_USER'] = 0; $mail_type['NEW_COMPANY'] = 1; $mail_type['ACCOUNT_EXPIRED_12'] = 2; $mail_type['INACTIVE_PN'] = 3; $mail_type['PN_REJECTED'] = 4; $mail_type['PN_MODIFIED'] = 5; }else{ $mail_type[0] = 'NEW_USER'; $mail_type[1] = 'NEW_COMPANY'; $mail_type[2] = 'ACCOUNT_EXPIRED_12'; $mail_type[3] = 'INACTIVE_PN'; $mail_type[4] = 'PN_REJECTED'; $mail_type[5] = 'PN_MODIFIED'; } if (array_key_exists($type, $mail_type)) { return $mail_type[$type]; }else{ return false; } } /** * Salva la mail nella queue */ public function insertMailToQueue(Request $request) { $mail_to_insert = [ "label" => $request->label, "type" => $this->mail_type($request->type), "status" => '', "info" => '', "mail_json" => $request->body, "to" => $request->to, "from" => $request->from, "cc" => $request->cc, "ccn" => $request->ccn, "send_at" => Carbon::now() ]; $mail = EmailQueue::create[ $mail_to_insert ]; } /** * Controlla le mail da mandare */ public function checkMAilToSend(Request $request) {} /** * Manda le mail in queue */ public function sendMailQueue(Request $request) {} /** * Manda una singola mail */ public function sendSingleMail($mail_obj) {} } Admin/AuthController.php 0000644 00000017224 15233463364 0011271 0 ustar 00 <?php namespace App\Http\Controllers\Admin; use Illuminate\Support\Facades\Auth; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Models\User; use App\Models\Admin; use App\Http\Controllers\Admin\UserController; use App\Http\Controllers\Admin\PasswordResetController; use Illuminate\Auth\Passwords\PasswordBrokerManager; use Illuminate\Support\Facades\Password; # use Laravel\Lumen\Routing\Controller; # use Illuminate\Http\Request; class AuthController extends Controller { /** * Create a new AuthController instance. * * @return void */ public function __construct() { $this->middleware('auth:admin', ['except' => ['login', 'register', 'ratings', 'generateResetToken']]); } /** * Get a JWT via given credentials. * * @return \Illuminate\Http\JsonResponse */ public function login(Request $request) { $credentials = $request->only(['email', 'password']); if (!$token = auth()->guard('admin')->attempt($credentials)) { return response()->json(['error' => 'Forbidden'], 403); } return $this->respondWithToken($token); } /** * Get the authenticated User. * * @return \Illuminate\Http\JsonResponse */ public function me() { return response()->json(auth()->guard('admin')->user()); } /** * Log the user out (Invalidate the token). * * @return \Illuminate\Http\JsonResponse */ public function logout() { auth()->logout(); return response()->json(['message' => 'Successfully logged out']); } /** * Refresh a token. * * @return \Illuminate\Http\JsonResponse */ public function refresh() { return $this->respondWithToken(auth()->refresh()); } /** * Get the token array structure. * * @param string $token * * @return \Illuminate\Http\JsonResponse */ protected function respondWithToken($token) { return response()->json([ 'access_token' => $token, 'token_type' => 'bearer', 'expires_in' => auth()->factory()->getTTL() * 360 ]); } public function register(Request $request) { $tipologie_selezionate = $request->tipologie_selezionate; $check_tipologie = []; if (count($tipologie_selezionate) > 0) { foreach ($tipologie_selezionate as $key => $value) { $check_tipologie[$value] = $value; } } $productsEconomy = []; $productsPremiumEconomy = []; $productsBusiness = []; $productsFirstClass = []; $cabinClasses = []; if (isset( $request->products_economy ) && array_key_exists('Economy', $check_tipologie)) { $productsEconomy = $request->products_economy; $cabinClasses['Economy']['name'] = 'Economy'; $cabinClasses['Economy']['products'] = []; foreach ($productsEconomy as $k => $v) { $cabinClasses['Economy']['products'][] = ['serial_number' => $v['label']]; } } if (isset( $request->products_premium_economy ) && array_key_exists('Premium Economy', $check_tipologie)) { $productsPremiumEconomy = $request->products_premium_economy; $cabinClasses['Premium Economy']['name'] = 'Premium Economy'; $cabinClasses['Premium Economy']['products'] = []; foreach ($productsPremiumEconomy as $k => $v) { $cabinClasses['Premium Economy']['products'][] = ['serial_number' => $v['label']]; } } if (isset( $request->products_business ) && array_key_exists('Business', $check_tipologie)) { $productsBusiness = $request->products_business; $cabinClasses['Business']['name'] = 'Business'; $cabinClasses['Business']['products'] = []; foreach ($productsBusiness as $k => $v) { $cabinClasses['Business']['products'][] = ['serial_number' => $v['label']]; } } if (isset( $request->products_first_class ) && array_key_exists('First Class', $check_tipologie)) { $productsFirstClass = $request->products_first_class; $cabinClasses['First class']['name'] = 'First class'; $cabinClasses['First class']['products'] = []; foreach ($productsFirstClass as $k => $v) { $cabinClasses['First class']['products'][] = ['serial_number' => $v['label']]; } } $request->cabin_classes = $cabinClasses; $request->req_from = 'registration'; $res = (new UserController)->create($request); return response()->json($res, 200); // // Controllo email // $email = $request->email; // $name = $request->name; // $surname = $request->surname; // // Controllo che non esista la company, nel caso che non esiste, posso anche creare la cartella se le info sono tutte corrette // $company_name = $request->company_name; // // In base alle tipologie selezionate, se le info generiche sono ok, vado a popolare la tabella products // $tipologie_selezionate = $request->tipologie_selezionate; // // Controllo password & controllo utente già esistente // $username = $request->username; // $password = $request->password; // $password_confirmation = $request->password_confirmation; // if ($password != $password_confirmation) { // return response()->json(['status' => false, 'info' => 'Le password non coincidono']); // } // return response()->json($request); } // 1. Send reset password email public function generateResetToken(Request $request) { # var_dump($request->email);die(); // Check email address is valid $this->validate($request, ['email' => 'required|email']); # var_dump(PasswordReset::create(['email' => 'andreazerbinati@gmail.com', 'token' => 'wedfnwefinefnwefnwoefnwoefn']));die(); // Send password reset to the user with this email address $response = $this->broker()->sendResetLink( $request->only('email') ); return $response == Password::RESET_LINK_SENT ? response()->json(true) : response()->json(false); } // 2. Reset Password public function resetPassword(Request $request) { // Check input is valid $rules = [ 'token' => 'required', 'username' => 'required|string', 'password' => 'required|confirmed|min:6', ]; $this->validate($request, $rules); // Reset the password $response = $this->broker()->reset( $this->credentials($request), function ($user, $password) { $user->password = app('hash')->make($password); $user->save(); } ); return $response == Password::PASSWORD_RESET ? response()->json(true) : response()->json(false); } /** * Get the password reset credentials from the request. * * @param \Illuminate\Http\Request $request * @return array */ protected function credentials(Request $request) { return $request->only('username', 'password', 'password_confirmation', 'token'); } /** * Get the broker to be used during password reset. * * @return \Illuminate\Contracts\Auth\PasswordBroker */ public function broker() { $passwordBrokerManager = new PasswordBrokerManager(app()); return $passwordBrokerManager->broker(); } } RatingsController.php 0000644 00000003576 15233463364 0010754 0 ustar 00 <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\ValidationException; use App\Models\Rating; class RatingsController extends Controller { public function __construct() { // // $this->middleware('auth:admin'); // $adminUser = auth()->guard('admin')->user(); //if (!$adminUser) //{ // return response()->json(['error' => 'Unauthorized.'], 401); //} } public function save(Request $request) { $user_id = $request->user_id; $company_id = $request->company_id; $rating_1 = $request->rating_1; $rating_2 = $request->rating_2; $rating_3 = $request->rating_3; $rating_4 = $request->rating_4; $all_rates = []; $all_rates[] = ['rate' => $rating_1, 'type' => 1, 'user_id' => $user_id, 'company_id' => $company_id]; $all_rates[] = ['rate' => $rating_2, 'type' => 2, 'user_id' => $user_id, 'company_id' => $company_id]; $all_rates[] = ['rate' => $rating_3, 'type' => 3, 'user_id' => $user_id, 'company_id' => $company_id]; $all_rates[] = ['rate' => $rating_4, 'type' => 4, 'user_id' => $user_id, 'company_id' => $company_id]; #var_dump($all_rates);die(); foreach ($all_rates as $k => $v) { $check = Rating::where([ 'user_id', $user_id, 'company_id', $company_id, 'type', $v['type'] ])->first(); if (!$check) { $rating = Rating::create([ 'rate' => $v['rate'], 'type' => $v['type'], 'user_id' => $user_id, 'company_id' => $company_id ]); var_dump($rating); die('ok'); $rating->save(); } } $type = $request->type; return response()->json($request); } } RatingController.php 0000644 00000023020 15233463364 0010553 0 ustar 00 <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\ValidationException; use App\Models\Rating; use App\Models\User; use App\Models\Company; class RatingController extends Controller { public function __construct() { // // $this->middleware('auth:admin'); // $adminUser = auth()->guard('admin')->user(); //if (!$adminUser) //{ // return response()->json(['error' => 'Unauthorized.'], 401); //} } public function save(Request $request) { # echo "<pre>"; # var_dump($request); # die; # $user_id = $request->user_id; # $company_id = $request['company_id']; $email = $request->email; $user = User::where('email', $email)->first(); if(!$user){ return response()->json(['error' => 'No user found'], 404); } $user_id = $user->id; $company_id = $user->company_id; #var_dump($company_id);die; $rating_1 = $request->rating_1; $rating_2 = $request->rating_2; $rating_3 = $request->rating_3; $rating_4 = $request->rating_4; $all_rates = []; $all_rates[] = ['rate' => $rating_1, 'type' => 1, 'user_id' => $user_id, 'company_id' => $company_id]; $all_rates[] = ['rate' => $rating_2, 'type' => 2, 'user_id' => $user_id, 'company_id' => $company_id]; $all_rates[] = ['rate' => $rating_3, 'type' => 3, 'user_id' => $user_id, 'company_id' => $company_id]; $all_rates[] = ['rate' => $rating_4, 'type' => 4, 'user_id' => $user_id, 'company_id' => $company_id]; foreach ($all_rates as $k => $v) { # $check = new Rating(); // $check = Rating::where([ // ['user_id', $user_id], // ['company_id', $company_id], // ['type', $v['type']] // ])->first(); // if ($check && $check->id > 0) { // $check->rate = $v['rate']; // $check->save(); // }else{ $rating = Rating::create([ 'rate' => $v['rate'], 'type' => $v['type'], 'user_id' => $user_id, 'company_id' => $company_id ]); $rating->save(); // } } return response()->json(['status' => 'ok', 'info' => 'all done'], 200); } public function listAll(Request $request) { $company_id = 0; if (isset($request->company_id)) { $company_id = $request->company_id; $all_ratings = Rating::where('company_id', $company_id)->get(); $ratings_by_users = []; # $ratings_by_users['list'] = []; # $ratings_by_users['user'] = null; $ratings_by_users['count'] = 0; $ratings_by_users['average'] = []; $ratings_by_users['average'][1]['sum'] = 0; $ratings_by_users['average'][1]['count'] = 0; $ratings_by_users['average'][2]['sum'] = 0; $ratings_by_users['average'][2]['count'] = 0; $ratings_by_users['average'][3]['sum'] = 0; $ratings_by_users['average'][3]['count'] = 0; $ratings_by_users['average'][4]['sum'] = 0; $ratings_by_users['average'][4]['count'] = 0; $regroup = []; foreach ($all_ratings as $k => $v) { $regroup[ $v['user_id'] ."_". $v['company_id'] ."_".$v['type'] ][ $v['created_at']->toDateTimeString() ] = $v; } foreach ($regroup as $kk => $vv) { foreach ($vv as $k => $v) { $user = User::find($v['user_id']); if($user) { # var_dump($v['type']); $user->only('first_name', 'last_name'); $ratings_by_users['list'][ $v['user_id'] ][ $k ]['user'] = $user; $ratings_by_users['list'][ $v['user_id'] ][ $k ]['ratings'][ $v['type'] ] = $v['rate']; $ratings_by_users['average'][ $v['type'] ]['sum'] += intval($v['rate']); $ratings_by_users['average'][ $v['type'] ]['count'] += 1; } } $ratings_by_users['count'] += 0.25; } # foreach ($ratings_by_users['list'] as $key => $value) { # $ratings_by_users['count'] += count($value); # } # var_dump($all_ratings);die(); return response()->json($ratings_by_users, 200); }else{ return response()->json(['error' => 'I need a Company Id'], 404); } } public function latestReview(Request $request) { $last_rate = Rating::where('id', '>', 0)->latest(); $ratings_by_users = []; $ratings_by_users['list'] = []; $ratings_by_users['user'] = null; $ratings_by_users['average'] = []; $ratings_by_users['average'][1]['sum'] = 0; $ratings_by_users['average'][1]['count'] = 0; $ratings_by_users['average'][2]['sum'] = 0; $ratings_by_users['average'][2]['count'] = 0; $ratings_by_users['average'][3]['sum'] = 0; $ratings_by_users['average'][3]['count'] = 0; $ratings_by_users['average'][4]['sum'] = 0; $ratings_by_users['average'][4]['count'] = 0; $user = User::find($last_rate['user_id']); if($user) { $user->only('first_name', 'last_name'); $ratings_by_users['list'][ $last_rate['user_id'] ]['user'] = $user; $ratings_by_users['list'][ $last_rate['user_id'] ]['ratings'][ $last_rate['type'] ] = $last_rate['rate']; $ratings_by_users['average'][ $last_rate['type'] ]['sum'] += intval($last_rate['rate']); $ratings_by_users['average'][ $last_rate['type'] ]['count'] += 1; } # var_dump($all_ratings);die(); return response()->json($ratings_by_users, 200); } function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") { // open raw memory as file so no temp files needed, you might run out of memory though $f = fopen('php://memory', 'w'); // loop over the input array foreach ($array as $line) { // generate csv lines from the inner arrays fputcsv($f, $line, $delimiter); } // reset the file pointer to the start of the file fseek($f, 0); // tell the browser it's going to be a csv file header('Content-Type: text/csv'); // tell the browser we want to save it instead of displaying it header('Content-Disposition: attachment; filename="'.$filename.'";'); // make php send the generated csv lines to the browser fpassthru($f); } public function export(Request $request) { $all = Rating::where('id', '>', 0)->get(); $export_obj = []; $export_obj_csv = []; // 'Sei soddisfatto del prodotto Aviointeriors?', // 'Sei soddisfatto del Lead Time?', // 'Sei soddisfatto del Customer Support?', // 'Sei soddisfatto del Technical Support?', $export_obj_csv[] = [ 'Comapany name', 'User', 'Are you satisfied with the Aviointeriors product?', 'Are you satisfied with the Lead Time?', 'Are you satisfied with Customer Support?', 'Are you satisfied with the Technical Support?', 'Data Recensione' ]; if ($all) { $regroup = []; foreach ($all as $k => $v) { $rate_date = $v['created_at']->toDateTimeString(); $regroup[ $v['user_id'] ]['rates'][$rate_date][ $v['type'] ] = $v['rate']; $regroup[ $v['user_id'] ]['info'][$rate_date] = $v; } foreach ($regroup as $k => $v) { # echo "<pre>"; # var_dump($v);die(); foreach ($v['info'] as $k_info_data => $v_info) { $user = User::find($v_info['user_id']); $company = Company::find($v_info['company_id']); $user_first_name = ''; $user_last_name = ''; $company_name = ''; if ($user) { $user_first_name = $user['first_name']; $user_last_name = $user['last_name']; } if ($company) { $company_name = $company['name']; } if ($user && $company) { # echo "<pre>"; # var_dump($vv);die; # $export_obj[ $company_name ][ $user_first_name.' '.$user_last_name ][ $v_info['type'] ] = $v_info['rate']; $export_obj_csv[] = [ $company_name, $user_first_name.' '.$user_last_name, $v['rates'][ $k_info_data ][1], $v['rates'][ $k_info_data ][2], $v['rates'][ $k_info_data ][3], $v['rates'][ $k_info_data ][4], $k_info_data ]; } } } } $this->array_to_csv_download( $export_obj_csv, "export.csv" ); die(); # return response()->json($export_obj, 200); } } AuthController.php 0000644 00000010104 15233463364 0010227 0 ustar 00 <?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Auth; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Models\User; use Illuminate\Auth\Passwords\PasswordBrokerManager; use Illuminate\Support\Facades\Password; class AuthController extends Controller { /** * Create a new AuthController instance. * * @return void */ public function __construct() { $this->middleware('auth:api', ['except' => ['login', 'ratings']]); } /** * Get a JWT via given credentials. * * @return \Illuminate\Http\JsonResponse */ public function login(Request $request) { $email = $request->email; $user = User::where('email', $email)->first(); if ($user && $user->active != 1) { return response()->json(['error' => 'Forbidden', 'info' => 'User is not active yet!'], 403); } $credentials = $request->only(['email', 'password']); if (! $token = auth()->guard('api')->attempt($credentials)) { return response()->json(['error' => 'Forbidden'], 403); } return $this->respondWithToken($token); } /** * Get the authenticated User. * * @return \Illuminate\Http\JsonResponse */ public function me() { return response()->json(User::where('id', auth()->guard('api')->user()->id)->with('company')->with('company.cabinClasses')->first()); } /** * Log the user out (Invalidate the token). * * @return \Illuminate\Http\JsonResponse */ public function logout() { auth()->logout(); return response()->json(['message' => 'Successfully logged out']); } /** * Refresh a token. * * @return \Illuminate\Http\JsonResponse */ public function refresh() { return $this->respondWithToken(auth()->refresh()); } /** * Get the token array structure. * * @param string $token * * @return \Illuminate\Http\JsonResponse */ protected function respondWithToken($token) { return response()->json([ 'access_token' => $token, 'token_type' => 'bearer', 'expires_in' => auth()->factory()->getTTL() * 60 ]); } // 1. Send reset password email public function generateResetToken(Request $request) { // Check email address is valid $this->validate($request, ['email' => 'required|email']); // Send password reset to the user with this email address $response = $this->broker()->sendResetLink( $request->only('email') ); return $response == Password::RESET_LINK_SENT ? response()->json(true) : response()->json(false); } // 2. Reset Password public function resetPassword(Request $request) { // Check input is valid $rules = [ 'token' => 'required', 'username' => 'required|string', 'password' => 'required|confirmed|min:6', ]; $this->validate($request, $rules); // Reset the password $response = $this->broker()->reset( $this->credentials($request), function ($user, $password) { $user->password = app('hash')->make($password); $user->save(); } ); return $response == Password::PASSWORD_RESET ? response()->json(true) : response()->json(false); } /** * Get the password reset credentials from the request. * * @param \Illuminate\Http\Request $request * @return array */ protected function credentials(Request $request) { return $request->only('username', 'password', 'password_confirmation', 'token'); } /** * Get the broker to be used during password reset. * * @return \Illuminate\Contracts\Auth\PasswordBroker */ public function broker() { $passwordBrokerManager = new PasswordBrokerManager(app()); return $passwordBrokerManager->broker(); } }
| ver. 1.4 |
Github
|
.
| PHP 8.2.5 | Генерация страницы: 0.01 |
proxy
|
phpinfo
|
Настройка