Skip to content

Commit

Permalink
v1.1.21
Browse files Browse the repository at this point in the history
  • Loading branch information
andiwijaya-dev committed Jul 10, 2021
1 parent 7673544 commit c5ab8d4
Show file tree
Hide file tree
Showing 31 changed files with 852 additions and 89 deletions.
10 changes: 7 additions & 3 deletions src/AppCoreServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
use Andiwijaya\AppCore\Console\Commands\Ping;
use Andiwijaya\AppCore\Console\Commands\ScheduledTaskRun;
use Andiwijaya\AppCore\Console\Commands\TestEmail;
use Andiwijaya\AppCore\Exceptions\Handler;
use Andiwijaya\AppCore\Responses\HTMLResponse;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Routing\ResponseFactory;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Log;
Expand All @@ -29,6 +31,11 @@ public function register()
Ping::class,
ScheduledTaskRun::class
]);

$this->app->singleton(
ExceptionHandler::class,
Handler::class
);
}

/**
Expand All @@ -44,10 +51,7 @@ public function boot(){
$this->publishes(
[
__DIR__.'/database/default/' => database_path(),
__DIR__.'/assets/' => public_path(),
__DIR__.'/views/default/' => resource_path('views'),
__DIR__.'/lang/' => resource_path('lang'),
__DIR__.'/Exceptions/' => app_path('Exceptions'),
__DIR__.'/websocket/' => base_path(),
]
);
Expand Down
4 changes: 1 addition & 3 deletions src/Console/Commands/ScheduledTaskRun.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,7 @@ public function handle()
if($delay > 0) sleep($delay);

if($id > 0){
$task = ScheduledTask::findOrFail($id);
//Log::error("Run task:{$task->id}, description:{$task->description}");
$task->run();
($task = ScheduledTask::find($id)) ? $task->run() : Log::info("schedule-task:run {$id} task not found");
}
else{
if(!file_exists(storage_path('logs/scheduled-task-run.lock'))){
Expand Down
53 changes: 44 additions & 9 deletions src/Exceptions/Handler.php
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
<?php

namespace App\Exceptions;
namespace Andiwijaya\AppCore\Exceptions;

use Andiwijaya\AppCore\Models\ScheduledTask;
use Andiwijaya\AppCore\Models\SysLog;
use Andiwijaya\AppCore\Notifications\SlackNotification;
use App\Notifications\LogToSlackNotification;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Exceptions\PostTooLargeException;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Session;

Expand Down Expand Up @@ -39,20 +43,54 @@ class Handler extends ExceptionHandler
*/
public function report(Exception $exception)
{
$message = substr($exception->getMessage(), 0, 255);
$traces = $exception->getTraceAsString();

SysLog::create([
'type'=>SysLog::TYPE_ERROR,
'message'=>substr($exception->getMessage(), 0, 255),
'message'=>$message,
'data'=>[
'console'=>app()->runningInConsole(),
'session_id'=>Session::getId(),
'method'=>Request::method(),
'url'=>Request::fullUrl(),
'data'=>Request::input(null),
'traces'=>$exception->getTrace()
'traces'=>$traces,
'session'=>Session::get(null),
'user_agent'=>$_SERVER['HTTP_USER_AGENT'] ?? '',
'remote_ip'=>$_SERVER['REMOTE_ADDR'] ?? '',
'cookies'=>$_COOKIE ?? '',
]
]);

//parent::report($exception);
if(strlen(env('LOG_SLACK_WEBHOOK_URL')) > 0){
try{
ScheduledTask::runOnce(function() use($message, $traces){
try{
Notification::route('slack', env('LOG_SLACK_WEBHOOK_URL'))
->notify(new SlackNotification($message, 'error', $traces));
}
catch(\Exception $ex){
SysLog::create([
'type'=>SysLog::TYPE_ERROR,
'message'=>$ex->getMessage(),
'data'=>[
'traces'=>$ex->getTraceAsString(),
]
]);
}
});
}
catch(\Exception $ex){
SysLog::create([
'type'=>SysLog::TYPE_ERROR,
'message'=>$ex->getMessage(),
'data'=>[
'traces'=>$ex->getTraceAsString(),
]
]);
}
}
}

/**
Expand All @@ -67,7 +105,7 @@ public function render($request, Exception $exception)
if($request->ajax()){

if ($exception instanceof TokenMismatchException)
return response()->json([ 'script'=>"$.alert('Maaf, form ini tidak dapat dikirim. Silakan perbarui halaman ini dan lakukan pengisian ulang.')" ]);
return htmlresponse()->redirect($request->fullUrl());

else if($exception->getMessage() == 'Login required')
return response()->json([ 'script'=>"window.location = '/login';" ]);
Expand Down Expand Up @@ -100,13 +138,10 @@ public function render($request, Exception $exception)
}

}

}
else{

if ($exception instanceof TokenMismatchException)
return redirect($request->fullUrl())->with('warning', 'Maaf, form ini tidak dapat dikirim. Silakan perbarui halaman ini dan lakukan pengisian ulang.');

return redirect($request->fullUrl())->with('warning', 'Session expired, please reload the page.');
}

return parent::render($request, $exception);
Expand Down
8 changes: 8 additions & 0 deletions src/Exceptions/UserException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace Andiwijaya\AppCore\Exceptions;

class UserException extends \Exception{


}
3 changes: 2 additions & 1 deletion src/Http/Controllers/ChatAdminController.php
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,8 @@ public function checkOnline(Request $request){

public function store(Request $request){

$method = action2method($request->get('action', 'send-message'));
$action = isset(($actions = explode('|', $request->get('action', 'send-message')))[0]) ? $actions[0] : '';
$method = action2method($action);
if(method_exists($this, $method))
return call_user_func_array([ $this, $method ], func_get_args());
}
Expand Down
151 changes: 151 additions & 0 deletions src/Http/Controllers/ImportDialogController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
<?php

namespace Andiwijaya\AppCore\Http\Controllers;

use Andiwijaya\AppCore\Imports\GenericImport;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\View;
use Maatwebsite\Excel\Facades\Excel;

class ImportDialogController extends ActionableController
{
protected $columns = [];
protected $view;

public function view(Request $request)
{
return htmlresponse()
->modal(
'import-dialog',
view('andiwijaya::sections.import-dialog-1')->render(),
[
'width'=>540
]
);
}

public function analyse(Request $request)
{
if(!$request->hasFile('file')) exc('File belum diupload');

$params = Session::get('import', [
'filename'=>'',
'files'=>[],
'columns'=>[]
]);

if(is_zip($request->file('file')->getMimeType())) {

$zip = new \ZipArchive();
$zip->open($request->file('file')->getRealPath());
$dir = storage_path('app/uploads/' . md5_file($request->file('file')->getRealPath()));
$zip->extractTo($dir);

$files = array_merge(
rglob("{$dir}/*.xlsx"),
rglob("{$dir}/*.xls"),
rglob("{$dir}/*.csv")
);
if(!isset($files[0])) exc("File xlsx, xls atau csv tidak ditemukan didalam file zip.");
$params['filename'] = $files[0];

$all_files = rglob("{$dir}/*.*");
$files = [];
foreach($all_files as $file){
if(in_array(explode('.', basename($file))[1] ?? '', [ 'xlsx', 'xls', 'csv', 'zip' ])) continue;
$files[basename($file)] = $file;
}
$params['files'] = $files;
}
else{

if(!in_array($request->file('file')->getClientOriginalExtension(), [ 'csv', 'xls', 'xlsx' ]))
exc('File tidak didukung, masukkan file csv, xls, xlsx atau zip');

$filename = md5_file($request->file('file')->getRealPath()) . '.' . $request->file('file')->getClientOriginalExtension();
$request->file('file')->storeAs('uploads', $filename);
$params['filename'] = storage_path('app/uploads/' . $filename);
}

if($request->file('file')->getClientOriginalExtension() == 'csv'){
$sheets = array_map('str_getcsv', file($params['filename']));
$rows = [ $sheets ];
}
else{
$rows = Excel::toArray(new GenericImport, $params['filename']);
}
$params['columns'] = array_filter($rows[0][0] ?? []);

Session::put('import', $params);

View::share([
'columns'=>$this->columns,
'data_columns'=>$params['columns']
]);

return htmlresponse()
->html('#import-dialog', view('andiwijaya::sections.import-dialog-2')->render())
->script("ui('#import-dialog').modal_resize()");
}

public function import(Request $request, $data){}

public function proceed(Request $request)
{
$params = Session::get('import', []);

if(strpos($params['filename'], '.csv') !== false)
$rows = csv_to_array($params['filename']);
else
$rows = Excel::toArray(new GenericImport, $params['filename']);
if(!isset($rows[0][0])) exc('Unexpected data value.');

$columnIdx = [];
foreach($params['columns'] as $idx=>$column){
$columnIdx[$column] = $idx;
}

$data = [];
foreach($rows as $sheet){

foreach($sheet as $idx=>$row){
if($idx == 0) continue;

$obj = [];

foreach($this->columns as $column){
$mapped_to = $request->input($column['name']);
$mapped_to_idx = $columnIdx[$mapped_to] ?? -1;

$optional = $column['optional'] ?? 0;
$value = $row[$mapped_to_idx] ?? null;

if(!$optional && !$value) exc("Data tidak ditemukan untuk kolom " . $column['name']);

if($mapped_to_idx >= 0)
$obj[$column['name']] = $value;
}

$data[] = $obj;
}
}

$request->merge([
'columns'=>$params['columns'],
'filename'=>$params['filename'],
'files'=>$params['files'] ?? [],
]);

$result = $this->import($request, $data);

$response = htmlresponse()
->html('#import-dialog', view('andiwijaya::sections.import-dialog-3', $result)->render())
->script("ui('#import-dialog').modal_resize()");

if(isset($result['script']))
$response->script($result['script']);

return $response;
}
}
Loading

0 comments on commit c5ab8d4

Please sign in to comment.