Skip to content

Commit

Permalink
Dashboard Ranks,Module Settings, Timezone fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
root committed Sep 13, 2024
1 parent a78a366 commit cf1ed81
Show file tree
Hide file tree
Showing 13 changed files with 150 additions and 87 deletions.
55 changes: 31 additions & 24 deletions app/Helpers/ModuleHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,38 +7,45 @@
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;

class ModuleHelper
{
public static function useConnection($moduleName, $serverId = null): void
{
if(empty($serverId) && empty(Session::get($moduleName.'_server'))){
$setting = ModuleServerSetting::where('module_name', $moduleName)->where('active', 1)->first();
Session::put($moduleName.'_server', $setting->id);
} else {
if(!empty($serverId)){
$serverId = Crypt::decrypt($serverId);
Session::put($moduleName.'_server',$serverId);
try {
if (empty($serverId) && empty(Session::get($moduleName . '_server'))) {
$setting = ModuleServerSetting::where('module_name', $moduleName)->where('active', 1)->first();
Session::put($moduleName . '_server', $setting->id);
} else {
if (!empty($serverId)) {
$serverId = Crypt::decrypt($serverId);
Session::put($moduleName . '_server', $serverId);
}
$setting = ModuleServerSetting::where('module_name', $moduleName)
->where('active', 1)
->where('id', Session::get($moduleName . '_server'))
->first();
}
$setting = ModuleServerSetting::where('module_name', $moduleName)
->where('active', 1)
->where('id', Session::get($moduleName.'_server'))
->first();
Config::set('database.connections.mysqlranks', [
'driver' => 'mysql',
'host' => $setting->db_host,
'database' => $setting->db_name,
'username' => $setting->db_user,
'password' => $setting->db_pass,
'port' => $setting->port,
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
]);
} catch (\Exception $e) {
Log::error('module.error ' . $e->getMessage());
echo '<div style="color: red; font-weight: bold;">Module DB settings not found. To fix this, go to .env file search RANKS, disable the ranks module, then go to Settings tab > Modules and add new DB settings, and re-enable the module.</div>';
die();
}
Config::set('database.connections.mysqlranks', [
'driver' => 'mysql',
'host' => $setting->db_host,
'database' => $setting->db_name,
'username' => $setting->db_user,
'password' => $setting->db_pass,
'port' => $setting->port,
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
]);

DB::setDefaultConnection('mysqlranks');
}
Expand Down
13 changes: 9 additions & 4 deletions app/Http/Controllers/DashboardController.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use App\Helpers\PermissionsHelper;
use App\Models\K4Ranks\Ranks;
use App\Models\K4Ranks\ZenithPlayerStorage;
use App\Models\ModuleServerSetting;
use App\Models\SaAdmin;
use App\Models\SaBan;
use App\Models\SaMute;
Expand All @@ -24,7 +25,7 @@ public function check() {
return view('requirement');
}

public function home()
public function home(Request $request)
{
$updates = [];
$activeBans = null;
Expand All @@ -43,9 +44,14 @@ public function home()
$updates = $this->checkUpdates();
}
$topPlayersData = [];
$servers = [];
if(env('RANKS') == 'Enabled') {
$serverId = $request->query('server_id');
ModuleHelper::useConnection('Ranks', $serverId);
$servers = ModuleServerSetting::all();
$topPlayersData = $this->getTop5Players();
}

return view('admin.dashboard',
compact(
'totalBans',
Expand All @@ -57,7 +63,8 @@ public function home()
'activeBans',
'activeMutes',
'totalActiveBans',
'totalActiveMutes'
'totalActiveMutes',
'servers'
)
);
}
Expand Down Expand Up @@ -105,8 +112,6 @@ private function checkUpdates()

public function getTop5Players()
{
ModuleHelper::useConnection('Ranks');

// Get the flag to determine whether to use old or new logic
$useOldLogic = env('K4LegacySupport', 'no') == 'yes' ? true : false;

Expand Down
4 changes: 3 additions & 1 deletion app/Http/Controllers/K4Ranks/RanksController.php
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,9 @@ public function viewProfile(Request $request, $steam_id, $server_id) {
// Check if the image exists, if not, use a default image
$weapon->image_url = File::exists(public_path($imagePath))
? asset($imagePath)
: asset('images/weapons/weapon_elite.png');
: (stripos($weapon->weapon, 'knife') !== false
? asset('images/weapons/weapon_knife_css.png')
: asset('images/weapons/weapon_elite.png'));

return $weapon;
});
Expand Down
3 changes: 2 additions & 1 deletion app/Http/Controllers/ModuleServerSettingsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

use App\Models\ModuleServerSetting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class ModuleServerSettingsController extends Controller
{
Expand Down Expand Up @@ -67,8 +68,8 @@ public function update(Request $request, $id)
public function destroy($id)
{
$setting = ModuleServerSetting::findOrFail($id);
Session::forget('Ranks_server');
$setting->delete();

return redirect()->route('module-server-settings.index')->with('success', 'Server settings deleted successfully.');
}
}
7 changes: 7 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 5 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@
"vite": "^3.0.0"
},
"dependencies": {
"bootstrap": "^5.2.1",
"sass": "^1.55.0",
"@types/datatables.net": "^1.10.28",
"@types/jquery": "^3.5.29",
"datatables.net-responsive": "^3.0.2",
"bootstrap": "^5.2.1",
"datatables.net-dt": "^2.0.2",
"datatables.net-fixedcolumns": "^5.0.0"
"datatables.net-fixedcolumns": "^5.0.0",
"datatables.net-responsive": "^3.0.2",
"dayjs": "^1.11.13",
"sass": "^1.55.0"
}
}
3 changes: 2 additions & 1 deletion resources/js/bans/bans.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ function loadBans() {
} else if (progress === 100) {
progressBarClass = 'bg-success';
}
progress = isNaN(progress) ? 100 : progress;
return `
<div class="progress">
<div class="progress-bar progress-bar-striped progress-bar-animated custom-progress ${progressBarClass}"
Expand Down Expand Up @@ -120,4 +121,4 @@ $(document).on('click', '.unban-btn', function () {
});
}
});
});
});
1 change: 0 additions & 1 deletion resources/js/dashboard/recent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ function constructTableRows(data: any[]): string {
else if (item.duration === 0) {
progressBarClass = 'bg-danger';
}

progress = isNaN(progress) ? 100 : progress;
html += `
<tr>
Expand Down
1 change: 1 addition & 0 deletions resources/js/mutes/mutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ function loadMutes() {
else if (progress == 100) {
progressBarClass = 'bg-success';
}
progress = isNaN(progress) ? 100 : progress;
return `
<div class="progress">
<div class="progress-bar progress-bar-striped progress-bar-animated custom-progress ${progressBarClass}"
Expand Down
102 changes: 52 additions & 50 deletions resources/js/utility/utility.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
import duration from 'dayjs/plugin/duration';
import relativeTime from 'dayjs/plugin/relativeTime';

dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.extend(duration);
dayjs.extend(relativeTime);


export function appendTableData(data: string, elemtId: string) {
const tableBody = document.getElementById(elemtId);
if (tableBody) {
Expand All @@ -6,60 +18,50 @@ export function appendTableData(data: string, elemtId: string) {
}

export function formatDuration(created: string): string {
const createdUTCDate = new Date(created + 'Z');
const currentUTCDate = new Date();

const timeDifference = currentUTCDate.getTime() - createdUTCDate.getTime();
const secondsDifference = Math.floor(timeDifference / 1000);

// Define time intervals in seconds
const intervals = {
year: 31536000,
month: 2592000,
week: 604800,
day: 86400,
hour: 3600,
minute: 60,
};

// Iterate through intervals to find the appropriate time format
for (const [interval, seconds] of Object.entries(intervals)) {
const intervalCount = Math.floor(secondsDifference / seconds);
if (intervalCount >= 1) {
return `${intervalCount} ${interval}${intervalCount > 1 ? 's' : ''} ago`;
}
}

return 'Just now';
const createdDate = dayjs.tz(created, timeZone);

const currentDate = dayjs().tz(timeZone);
// Calculate the difference between currentDate and createdDate in human-readable form
const timeDifference = currentDate.diff(createdDate);

return createdDate.from(currentDate);
}

export function calculateProgress(created: string, ends: string): number {
const createdDate = new Date(created);
const endsDate = new Date(ends);
const currentDate = new Date();

// Convert current date time to UTC
const currentUTCDate = new Date(
Date.UTC(
currentDate.getUTCFullYear(),
currentDate.getUTCMonth(),
currentDate.getUTCDate(),
currentDate.getUTCHours(),
currentDate.getUTCMinutes(),
currentDate.getUTCSeconds(),
currentDate.getUTCMilliseconds()
)
);

const totalTime = endsDate.getTime() - createdDate.getTime();
const elapsedTime = currentUTCDate.getTime() - createdDate.getTime();

let progress = (elapsedTime / totalTime) * 100;

// Ensure progress doesn't exceed 100% or go below 0%
progress = Math.min(100, Math.max(0, progress));

return progress;
try {

const format = 'YYYY-MM-DD HH:mm:ss';

const createdDate = dayjs.tz(created, format, timeZone);
const endsDate = dayjs.tz(ends, format, timeZone);
const currentDate = dayjs().tz(timeZone);

// Validate the date strings to make sure they are valid
if (!createdDate.isValid() || !endsDate.isValid()) {
return "NA";
}

// Calculate total time between creation and end
const totalTime = endsDate.diff(createdDate); // Difference in milliseconds

// Prevent division by zero or invalid total time
if (totalTime <= 0) {
return "NA";
}

// Calculate elapsed time from creation to current date
const elapsedTime = currentDate.diff(createdDate);

// Calculate progress as a percentage
let progress = (elapsedTime / totalTime) * 100;

// Ensure progress is a valid number and doesn't exceed 100% or go below 0%
progress = Math.min(100, Math.max(0, isNaN(progress) ? "NA" : progress));
return Number(progress.toFixed(2));
} catch (e) {
return "NA";
}
}

export function showLoader(loaderId = 'loader') {
Expand Down
15 changes: 15 additions & 0 deletions resources/scss/dark/assets/main.scss
Original file line number Diff line number Diff line change
Expand Up @@ -5012,3 +5012,18 @@ body.layout-dark #sidebar ul.menu-categories li.menu ul.submenu>li a:before {
.dashboard-rank .rank-profile {
margin-top: -14px;
}

.rank-servers.dashboard #serverSelect {
width: 315px;
margin: 6px;
height: 48px;
margin-top: 4px;
}

.rank-servers.dashboard label {
font-size: 15px;
line-height: 35px;
color: #888ea8;
letter-spacing: 0px;
display: inline-block;
}
19 changes: 19 additions & 0 deletions resources/views/admin/dashboard.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,18 @@
<strong>{{ __('dashboard.topPlayers') }} <span class="badge badge-info">5 {{ __('dashboard.of') }} {{$topPlayersData['totalPlayers']}} {{ __('dashboard.players') }}</span></strong>
</h5>
</div>
<div class="rank-servers dashboard">
<select class="form-select" id="serverSelect">
@foreach ($servers as $server)
<option
{{$server->id == Session::get('Ranks_server') ? 'selected': ''}} value="{{ Crypt::encrypt($server->id) }}">
{{ $server->name }}
</option>
@endforeach
</select>
<label for="serverSelect"
class="serverSelectLabel form-label">{{ __('admins.selectServers') }}</label>
</div>
<table class="table-responsive table align-middle mb-0 table-borderless">
<thead class="bg-light">
<tr>
Expand Down Expand Up @@ -281,6 +293,13 @@ function showModal(){
const recentMutesUrl = '{!! env('VITE_SITE_DIR') !!}/mutes';
const playerActionUrl = '{!! env('VITE_SITE_DIR') !!}/players/action';
const ranksListUrl = '{!! env('VITE_SITE_DIR') !!}/list/ranks';
window.addEventListener("load", (event) => {
$('#serverSelect').change(function () {
const serverId = $(this).val();
window.location.href = '{{ url()->current() }}' + '?server_id=' + serverId;
});
});
</script>
<!-- END CUSTOM SCRIPTS FILE -->
</x-base-layout>
Loading

0 comments on commit cf1ed81

Please sign in to comment.