feat: Superadmin Carlos permanente con OTP obligatorio, gestion de equipo de administradores, perfil con celular inmutable y APK nativo co.pacifictrans.go independiente
6
pacifictrans-app/.gitignore
vendored
Normal file
@ -0,0 +1,6 @@
|
||||
node_modules/
|
||||
.gradle/
|
||||
build/
|
||||
android/app/build/
|
||||
android/.gradle/
|
||||
android/local.properties
|
||||
101
pacifictrans-app/android/.gitignore
vendored
Normal file
@ -0,0 +1,101 @@
|
||||
# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore
|
||||
|
||||
# Built application files
|
||||
*.apk
|
||||
*.aar
|
||||
*.ap_
|
||||
*.aab
|
||||
|
||||
# Files for the ART/Dalvik VM
|
||||
*.dex
|
||||
|
||||
# Java class files
|
||||
*.class
|
||||
|
||||
# Generated files
|
||||
bin/
|
||||
gen/
|
||||
out/
|
||||
# Uncomment the following line in case you need and you don't have the release build type files in your app
|
||||
# release/
|
||||
|
||||
# Gradle files
|
||||
.gradle/
|
||||
build/
|
||||
|
||||
# Local configuration file (sdk path, etc)
|
||||
local.properties
|
||||
|
||||
# Proguard folder generated by Eclipse
|
||||
proguard/
|
||||
|
||||
# Log Files
|
||||
*.log
|
||||
|
||||
# Android Studio Navigation editor temp files
|
||||
.navigation/
|
||||
|
||||
# Android Studio captures folder
|
||||
captures/
|
||||
|
||||
# IntelliJ
|
||||
*.iml
|
||||
.idea/workspace.xml
|
||||
.idea/tasks.xml
|
||||
.idea/gradle.xml
|
||||
.idea/assetWizardSettings.xml
|
||||
.idea/dictionaries
|
||||
.idea/libraries
|
||||
# Android Studio 3 in .gitignore file.
|
||||
.idea/caches
|
||||
.idea/modules.xml
|
||||
# Comment next line if keeping position of elements in Navigation Editor is relevant for you
|
||||
.idea/navEditor.xml
|
||||
|
||||
# Keystore files
|
||||
# Uncomment the following lines if you do not want to check your keystore files in.
|
||||
#*.jks
|
||||
#*.keystore
|
||||
|
||||
# External native build folder generated in Android Studio 2.2 and later
|
||||
.externalNativeBuild
|
||||
.cxx/
|
||||
|
||||
# Google Services (e.g. APIs or Firebase)
|
||||
# google-services.json
|
||||
|
||||
# Freeline
|
||||
freeline.py
|
||||
freeline/
|
||||
freeline_project_description.json
|
||||
|
||||
# fastlane
|
||||
fastlane/report.xml
|
||||
fastlane/Preview.html
|
||||
fastlane/screenshots
|
||||
fastlane/test_output
|
||||
fastlane/readme.md
|
||||
|
||||
# Version control
|
||||
vcs.xml
|
||||
|
||||
# lint
|
||||
lint/intermediates/
|
||||
lint/generated/
|
||||
lint/outputs/
|
||||
lint/tmp/
|
||||
# lint/reports/
|
||||
|
||||
# Android Profiling
|
||||
*.hprof
|
||||
|
||||
# Cordova plugins for Capacitor
|
||||
capacitor-cordova-android-plugins
|
||||
|
||||
# Copied web assets
|
||||
app/src/main/assets/public
|
||||
|
||||
# Generated Config files
|
||||
app/src/main/assets/capacitor.config.json
|
||||
app/src/main/assets/capacitor.plugins.json
|
||||
app/src/main/res/xml/config.xml
|
||||
2
pacifictrans-app/android/app/.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
/build/*
|
||||
!/build/.npmkeep
|
||||
@ -1,29 +1,25 @@
|
||||
plugins {
|
||||
id 'com.android.application'
|
||||
}
|
||||
apply plugin: 'com.android.application'
|
||||
|
||||
android {
|
||||
namespace 'co.pacifictrans.go'
|
||||
compileSdk 35
|
||||
|
||||
namespace "co.pacifictrans.go"
|
||||
compileSdk rootProject.ext.compileSdkVersion
|
||||
defaultConfig {
|
||||
applicationId "co.pacifictrans.go"
|
||||
minSdk 24
|
||||
targetSdk 35
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
versionCode 1
|
||||
versionName "1.0.0"
|
||||
|
||||
versionName "1.0"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
aaptOptions {
|
||||
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
|
||||
// Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61
|
||||
ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
minifyEnabled false
|
||||
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
|
||||
}
|
||||
debug {
|
||||
applicationIdSuffix ""
|
||||
debuggable true
|
||||
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
|
||||
}
|
||||
}
|
||||
|
||||
@ -34,9 +30,31 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation fileTree(dir: 'libs', include: ['*.jar'])
|
||||
implementation 'androidx.appcompat:appcompat:1.7.0'
|
||||
implementation 'com.google.android.material:material:1.12.0'
|
||||
implementation project(':capacitor-android')
|
||||
repositories {
|
||||
flatDir{
|
||||
dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation fileTree(include: ['*.jar'], dir: 'libs')
|
||||
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
|
||||
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
|
||||
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
|
||||
implementation project(':capacitor-android')
|
||||
testImplementation "junit:junit:$junitVersion"
|
||||
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
|
||||
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
|
||||
implementation project(':capacitor-cordova-android-plugins')
|
||||
}
|
||||
|
||||
apply from: 'capacitor.build.gradle'
|
||||
|
||||
try {
|
||||
def servicesJSON = file('google-services.json')
|
||||
if (servicesJSON.text) {
|
||||
apply plugin: 'com.google.gms.google-services'
|
||||
}
|
||||
} catch(Exception e) {
|
||||
logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work")
|
||||
}
|
||||
|
||||
19
pacifictrans-app/android/app/capacitor.build.gradle
Normal file
@ -0,0 +1,19 @@
|
||||
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
|
||||
|
||||
android {
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_17
|
||||
targetCompatibility JavaVersion.VERSION_17
|
||||
}
|
||||
}
|
||||
|
||||
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
|
||||
dependencies {
|
||||
implementation project(':capacitor-app-launcher')
|
||||
|
||||
}
|
||||
|
||||
|
||||
if (hasProperty('postBuildExtras')) {
|
||||
postBuildExtras()
|
||||
}
|
||||
21
pacifictrans-app/android/app/proguard-rules.pro
vendored
Normal file
@ -0,0 +1,21 @@
|
||||
# Add project specific ProGuard rules here.
|
||||
# You can control the set of applied configuration files using the
|
||||
# proguardFiles setting in build.gradle.
|
||||
#
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
||||
|
||||
# Uncomment this to preserve the line number information for
|
||||
# debugging stack traces.
|
||||
#-keepattributes SourceFile,LineNumberTable
|
||||
|
||||
# If you keep the line number information, uncomment this to
|
||||
# hide the original source file name.
|
||||
#-renamesourcefileattribute SourceFile
|
||||
@ -0,0 +1,26 @@
|
||||
package com.getcapacitor.myapp;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import android.content.Context;
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4;
|
||||
import androidx.test.platform.app.InstrumentationRegistry;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
/**
|
||||
* Instrumented test, which will execute on an Android device.
|
||||
*
|
||||
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
|
||||
*/
|
||||
@RunWith(AndroidJUnit4.class)
|
||||
public class ExampleInstrumentedTest {
|
||||
|
||||
@Test
|
||||
public void useAppContext() throws Exception {
|
||||
// Context of the app under test.
|
||||
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
|
||||
|
||||
assertEquals("com.getcapacitor.app", appContext.getPackageName());
|
||||
}
|
||||
}
|
||||
41
pacifictrans-app/android/app/src/main/AndroidManifest.xml
Normal file
@ -0,0 +1,41 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<application
|
||||
android:allowBackup="true"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/AppTheme">
|
||||
|
||||
<activity
|
||||
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode"
|
||||
android:name=".MainActivity"
|
||||
android:label="@string/title_activity_main"
|
||||
android:theme="@style/AppTheme.NoActionBarLaunch"
|
||||
android:launchMode="singleTask"
|
||||
android:exported="true">
|
||||
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
|
||||
</activity>
|
||||
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="${applicationId}.fileprovider"
|
||||
android:exported="false"
|
||||
android:grantUriPermissions="true">
|
||||
<meta-data
|
||||
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||
android:resource="@xml/file_paths"></meta-data>
|
||||
</provider>
|
||||
</application>
|
||||
|
||||
<!-- Permissions -->
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
</manifest>
|
||||
@ -0,0 +1,5 @@
|
||||
package co.pacifictrans.go;
|
||||
|
||||
import com.getcapacitor.BridgeActivity;
|
||||
|
||||
public class MainActivity extends BridgeActivity {}
|
||||
|
After Width: | Height: | Size: 7.5 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 9.0 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 7.7 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 9.6 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 17 KiB |
@ -0,0 +1,34 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:aapt="http://schemas.android.com/aapt"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportHeight="108"
|
||||
android:viewportWidth="108">
|
||||
<path
|
||||
android:fillType="evenOdd"
|
||||
android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z"
|
||||
android:strokeColor="#00000000"
|
||||
android:strokeWidth="1">
|
||||
<aapt:attr name="android:fillColor">
|
||||
<gradient
|
||||
android:endX="78.5885"
|
||||
android:endY="90.9159"
|
||||
android:startX="48.7653"
|
||||
android:startY="61.0927"
|
||||
android:type="linear">
|
||||
<item
|
||||
android:color="#44000000"
|
||||
android:offset="0.0" />
|
||||
<item
|
||||
android:color="#00000000"
|
||||
android:offset="1.0" />
|
||||
</gradient>
|
||||
</aapt:attr>
|
||||
</path>
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:fillType="nonZero"
|
||||
android:pathData="M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z"
|
||||
android:strokeColor="#00000000"
|
||||
android:strokeWidth="1" />
|
||||
</vector>
|
||||
@ -0,0 +1,170 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportHeight="108"
|
||||
android:viewportWidth="108">
|
||||
<path
|
||||
android:fillColor="#26A69A"
|
||||
android:pathData="M0,0h108v108h-108z" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M9,0L9,108"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,0L19,108"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M29,0L29,108"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M39,0L39,108"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M49,0L49,108"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M59,0L59,108"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M69,0L69,108"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M79,0L79,108"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M89,0L89,108"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M99,0L99,108"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,9L108,9"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,19L108,19"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,29L108,29"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,39L108,39"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,49L108,49"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,59L108,59"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,69L108,69"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,79L108,79"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,89L108,89"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,99L108,99"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,29L89,29"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,39L89,39"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,49L89,49"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,59L89,59"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,69L89,69"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,79L89,79"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M29,19L29,89"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M39,19L39,89"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M49,19L49,89"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M59,19L59,89"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M69,19L69,89"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M79,19L79,89"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
</vector>
|
||||
BIN
pacifictrans-app/android/app/src/main/res/drawable/splash.png
Normal file
|
After Width: | Height: | Size: 3.9 KiB |
@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
tools:context=".MainActivity">
|
||||
|
||||
<WebView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent" />
|
||||
</androidx.coordinatorlayout.widget.CoordinatorLayout>
|
||||
@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@color/ic_launcher_background"/>
|
||||
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
||||
</adaptive-icon>
|
||||
@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@color/ic_launcher_background"/>
|
||||
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
||||
</adaptive-icon>
|
||||
|
After Width: | Height: | Size: 2.7 KiB |
|
After Width: | Height: | Size: 3.4 KiB |
|
After Width: | Height: | Size: 4.2 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 2.7 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 4.9 KiB |
|
After Width: | Height: | Size: 6.4 KiB |
|
After Width: | Height: | Size: 6.5 KiB |
|
After Width: | Height: | Size: 9.6 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 9.2 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 16 KiB |
@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="ic_launcher_background">#FFFFFF</color>
|
||||
</resources>
|
||||
@ -0,0 +1,7 @@
|
||||
<?xml version='1.0' encoding='utf-8'?>
|
||||
<resources>
|
||||
<string name="app_name">Pacifictrans Go</string>
|
||||
<string name="title_activity_main">Pacifictrans Go</string>
|
||||
<string name="package_name">co.pacifictrans.go</string>
|
||||
<string name="custom_url_scheme">co.pacifictrans.go</string>
|
||||
</resources>
|
||||
22
pacifictrans-app/android/app/src/main/res/values/styles.xml
Normal file
@ -0,0 +1,22 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
|
||||
<!-- Base application theme. -->
|
||||
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
|
||||
<!-- Customize your theme here. -->
|
||||
<item name="colorPrimary">@color/colorPrimary</item>
|
||||
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
|
||||
<item name="colorAccent">@color/colorAccent</item>
|
||||
</style>
|
||||
|
||||
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.DayNight.NoActionBar">
|
||||
<item name="windowActionBar">false</item>
|
||||
<item name="windowNoTitle">true</item>
|
||||
<item name="android:background">@null</item>
|
||||
</style>
|
||||
|
||||
|
||||
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
|
||||
<item name="android:background">@drawable/splash</item>
|
||||
</style>
|
||||
</resources>
|
||||
@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<paths xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<external-path name="my_images" path="." />
|
||||
<cache-path name="my_cache_images" path="." />
|
||||
</paths>
|
||||
@ -0,0 +1,18 @@
|
||||
package com.getcapacitor.myapp;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Example local unit test, which will execute on the development machine (host).
|
||||
*
|
||||
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
|
||||
*/
|
||||
public class ExampleUnitTest {
|
||||
|
||||
@Test
|
||||
public void addition_isCorrect() throws Exception {
|
||||
assertEquals(4, 2 + 2);
|
||||
}
|
||||
}
|
||||
29
pacifictrans-app/android/build.gradle
Normal file
@ -0,0 +1,29 @@
|
||||
// Top-level build file where you can add configuration options common to all sub-projects/modules.
|
||||
|
||||
buildscript {
|
||||
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
dependencies {
|
||||
classpath 'com.android.tools.build:gradle:8.2.1'
|
||||
classpath 'com.google.gms:google-services:4.4.0'
|
||||
|
||||
// NOTE: Do not place your application dependencies here; they belong
|
||||
// in the individual module build.gradle files
|
||||
}
|
||||
}
|
||||
|
||||
apply from: "variables.gradle"
|
||||
|
||||
allprojects {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
|
||||
task clean(type: Delete) {
|
||||
delete rootProject.buildDir
|
||||
}
|
||||
6
pacifictrans-app/android/capacitor.settings.gradle
Normal file
@ -0,0 +1,6 @@
|
||||
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
|
||||
include ':capacitor-android'
|
||||
project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor')
|
||||
|
||||
include ':capacitor-app-launcher'
|
||||
project(':capacitor-app-launcher').projectDir = new File('../node_modules/@capacitor/app-launcher/android')
|
||||
22
pacifictrans-app/android/gradle.properties
Normal file
@ -0,0 +1,22 @@
|
||||
# Project-wide Gradle settings.
|
||||
|
||||
# IDE (e.g. Android Studio) users:
|
||||
# Gradle settings configured through the IDE *will override*
|
||||
# any settings specified in this file.
|
||||
|
||||
# For more details on how to configure your build environment visit
|
||||
# http://www.gradle.org/docs/current/userguide/build_environment.html
|
||||
|
||||
# Specifies the JVM arguments used for the daemon process.
|
||||
# The setting is particularly useful for tweaking memory settings.
|
||||
org.gradle.jvmargs=-Xmx1536m
|
||||
|
||||
# When configured, Gradle will run in incubating parallel mode.
|
||||
# This option should only be used with decoupled projects. More details, visit
|
||||
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
|
||||
# org.gradle.parallel=true
|
||||
|
||||
# AndroidX package structure to make it clearer which packages are bundled with the
|
||||
# Android operating system, and which are packaged with your app's APK
|
||||
# https://developer.android.com/topic/libraries/support-library/androidx-rn
|
||||
android.useAndroidX=true
|
||||
BIN
pacifictrans-app/android/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
7
pacifictrans-app/android/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@ -0,0 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-all.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
248
pacifictrans-app/android/gradlew
vendored
Normal file
@ -0,0 +1,248 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command;
|
||||
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||
# shell script including quotes and variable substitutions, so put them in
|
||||
# double quotes to make sure that they get re-expanded; and
|
||||
# * put everything else in single quotes, so that it's not re-expanded.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
92
pacifictrans-app/android/gradlew.bat
vendored
Normal file
@ -0,0 +1,92 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
5
pacifictrans-app/android/settings.gradle
Normal file
@ -0,0 +1,5 @@
|
||||
include ':app'
|
||||
include ':capacitor-cordova-android-plugins'
|
||||
project(':capacitor-cordova-android-plugins').projectDir = new File('./capacitor-cordova-android-plugins/')
|
||||
|
||||
apply from: 'capacitor.settings.gradle'
|
||||
16
pacifictrans-app/android/variables.gradle
Normal file
@ -0,0 +1,16 @@
|
||||
ext {
|
||||
minSdkVersion = 22
|
||||
compileSdkVersion = 34
|
||||
targetSdkVersion = 34
|
||||
androidxActivityVersion = '1.8.0'
|
||||
androidxAppCompatVersion = '1.6.1'
|
||||
androidxCoordinatorLayoutVersion = '1.2.0'
|
||||
androidxCoreVersion = '1.12.0'
|
||||
androidxFragmentVersion = '1.6.2'
|
||||
coreSplashScreenVersion = '1.0.1'
|
||||
androidxWebkitVersion = '1.9.0'
|
||||
junitVersion = '4.13.2'
|
||||
androidxJunitVersion = '1.1.5'
|
||||
androidxEspressoCoreVersion = '3.5.1'
|
||||
cordovaAndroidVersion = '10.1.1'
|
||||
}
|
||||
1269
pacifictrans-app/package-lock.json
generated
Normal file
59
pacifictrans-app/public/index.html
Normal file
@ -0,0 +1,59 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
|
||||
<title>Pacifictrans Go</title>
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
background: #0f172a;
|
||||
color: #fff;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 100vh;
|
||||
text-align: center;
|
||||
padding: 1.5rem;
|
||||
}
|
||||
.logo {
|
||||
width: 80px;
|
||||
height: 80px;
|
||||
background: linear-gradient(135deg, #06b6d4, #2563eb);
|
||||
border-radius: 20px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 2.5rem;
|
||||
margin-bottom: 1.25rem;
|
||||
box-shadow: 0 10px 25px rgba(6, 182, 212, 0.35);
|
||||
}
|
||||
h1 { font-size: 1.6rem; font-weight: 800; letter-spacing: -0.02em; margin-bottom: 0.35rem; }
|
||||
p { color: #94a3b8; font-size: 0.9rem; max-width: 320px; line-height: 1.5; margin-bottom: 1.5rem; }
|
||||
.spinner {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border: 3px solid rgba(255, 255, 255, 0.15);
|
||||
border-top-color: #06b6d4;
|
||||
border-radius: 50%;
|
||||
animation: spin 0.8s linear infinite;
|
||||
}
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="logo">🚗</div>
|
||||
<h1>Pacifictrans Go</h1>
|
||||
<p>Conectando con la Central de Despacho Cali - Buenaventura...</p>
|
||||
<div class="spinner"></div>
|
||||
|
||||
<script>
|
||||
// Si no está dentro de Capacitor o falla el server.url, redirigir
|
||||
setTimeout(() => {
|
||||
window.location.href = 'https://pacifictrans.almeira.com.co';
|
||||
}, 1500);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@ -71,16 +71,17 @@ def main():
|
||||
print("[4/4] Enviando notificación de Pacifictrans Go a WhatsApp (+57 316 745 5877)...", flush=True)
|
||||
|
||||
text_msg = (
|
||||
"🚗 *Pacifictrans Go: Tarifas Base Configurables, Sistema de Bonos de Descuento & Reserva Multi-Cupos*\n\n"
|
||||
"¡Hola Carlos! Se ha actualizado la plataforma con las nuevas capacidades operativas y comerciales:\n\n"
|
||||
"👑 *Pacifictrans Go: Superadministrador Permanente, Seguridad 2FA OTP & Gestión de Administradores*\n\n"
|
||||
"¡Hola Carlos! Se ha actualizado la plataforma con el nuevo esquema de seguridad y control de acceso:\n\n"
|
||||
"📱 *App Oficial:* `Pacifictrans Go`\n"
|
||||
"📦 *Archivo APK:* `PacifictransGo.apk` (37.07 MB)\n"
|
||||
"🆔 *Package ID:* `co.pacifictrans.go`\n\n"
|
||||
"⚡ *Novedades Implementadas:*\n"
|
||||
"• ⚙️ *Definición de Tarifas Base en Panel Admin:* Control en vivo persistido en MongoDB para la tarifa fija de pasajeros ($35.000 COP), radio de pooling, penalidad por cancelación, tarifa base de encomiendas ($25.000 COP), costo por km ($1.200 COP/km), factores de peso/volumen (sobre, mediano, grande), seguro y comisión de plataforma (15%).\n"
|
||||
"• 🎟️ *Sistema de Bonos & Cupones de Descuento:* Creación y administración centralizada de promociones en el Administrador. Permite descuentos en porcentaje (%) o valor fijo en pesos ($ COP), configurando si aplican para VIAJES, ENCOMIENDAS o AMBOS, subtotal mínimo y límite de canjes. Incluye cupones semilla predefinidos (ej. PACIFICO10, BONOVIAJE5K, ENVIOYA, PROMO20).\n"
|
||||
"• 💳 *Validación y Descuento Reactivo en Pasarela:* Los clientes pueden ingresar su cupón tanto en la reserva de viajes como en la cotización de fletes. El sistema valida el monto mínimo y calcula el descuento en tiempo real antes de generar la orden en Bold Smart Checkout.\n"
|
||||
"• 👥 *Reserva Multi-Cupo (1 a 4 Asientos):* Posibilidad de reservar varios cupos a la vez ingresando los datos de cada pasajero (Nombre completo, Documento C.C., Teléfono/WhatsApp, dirección de recogida domiciliaria independiente y notas de equipaje).\n\n"
|
||||
"📦 *Archivo APK:* `PacifictransGo.apk` (3.57 MB - APK Nativo e Independiente)\n"
|
||||
"🆔 *Package ID:* `co.pacifictrans.go` (100% independiente de DripZone)\n\n"
|
||||
"⚡ *Novedades de la Versión:*\n"
|
||||
"• 📱 *App Totalmente Independiente:* Se recompiló el APK nativo con su propio Package ID (`co.pacifictrans.go`). Ya no sobreescribe ni interfiere con DripZone; ambas aplicaciones conviven por separado con sus propios íconos y datos.\n"
|
||||
"• 👑 *Superadministrador Exclusivo (+57 316 745 5877):* Tu número personal es el único reconocido con rol de Superadministrador inmutable en MongoDB. Es permanente y no puede ser borrado, inactivado ni degradado bajo ninguna circunstancia.\n"
|
||||
"• 🔐 *Acceso Obligatorio con Token / OTP WhatsApp:* El acceso administrativo siempre exige validación del código OTP 2FA de 6 dígitos enviado a tu WhatsApp personal. Se bloquearon accesos rápidos sin código para garantizar total seguridad.\n"
|
||||
"• 👥 *Sub-panel de Gestión de Administradores:* En la Sub-pestaña 5 del Panel Administrativo, puedes registrar nuevos administradores u operadores, editar sus datos y roles, activarlos o inactivarlos en tiempo real, o removerlos del sistema.\n"
|
||||
"• 👤 *Actualización de Información Personal:* Los usuarios pueden actualizar Nombre, C.C., Correo, Dirección y Ciudad. El número celular de registro permanece bloqueado e inmutable para preservar su identidad 2FA OTP.\n\n"
|
||||
f"🔗 *Enlace de Descarga Directa:*\n👉 {APK_URL}"
|
||||
)
|
||||
|
||||
|
||||
@ -2429,3 +2429,100 @@ h1, h2, h3, h4, .brand-title {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
/* ==========================================================================
|
||||
SUPERADMIN & EQUIPO DE ADMINISTRADORES & PERFIL INMUTABLE
|
||||
========================================================================== */
|
||||
.superadmin-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
background: linear-gradient(135deg, rgba(245, 158, 11, 0.25), rgba(217, 119, 6, 0.35));
|
||||
color: #fbbf24;
|
||||
border: 1px solid rgba(245, 158, 11, 0.5);
|
||||
padding: 0.2rem 0.65rem;
|
||||
border-radius: 9999px;
|
||||
font-size: 0.72rem;
|
||||
font-weight: 800;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
box-shadow: 0 0 10px rgba(245, 158, 11, 0.2);
|
||||
}
|
||||
|
||||
.admin-role-badge {
|
||||
display: inline-block;
|
||||
padding: 0.2rem 0.6rem;
|
||||
border-radius: 8px;
|
||||
font-size: 0.72rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.admin-role-super {
|
||||
background: rgba(245, 158, 11, 0.2);
|
||||
color: #fbbf24;
|
||||
border: 1px solid rgba(245, 158, 11, 0.4);
|
||||
}
|
||||
|
||||
.admin-role-admin {
|
||||
background: rgba(14, 165, 233, 0.2);
|
||||
color: #38bdf8;
|
||||
border: 1px solid rgba(14, 165, 233, 0.4);
|
||||
}
|
||||
|
||||
.admin-role-operador {
|
||||
background: rgba(168, 85, 247, 0.2);
|
||||
color: #c084fc;
|
||||
border: 1px solid rgba(168, 85, 247, 0.4);
|
||||
}
|
||||
|
||||
.input-locked {
|
||||
background: rgba(15, 23, 42, 0.85) !important;
|
||||
color: #94a3b8 !important;
|
||||
border-color: rgba(255, 255, 255, 0.08) !important;
|
||||
cursor: not-allowed !important;
|
||||
}
|
||||
|
||||
.input-locked-note {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
font-size: 0.73rem;
|
||||
color: #fbbf24;
|
||||
margin-top: 4px;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.btn-admin-action {
|
||||
padding: 0.3rem 0.65rem;
|
||||
border-radius: 6px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.btn-admin-edit {
|
||||
background: rgba(6, 182, 212, 0.15);
|
||||
color: #38bdf8;
|
||||
border: 1px solid rgba(6, 182, 212, 0.3);
|
||||
}
|
||||
|
||||
.btn-admin-edit:hover {
|
||||
background: rgba(6, 182, 212, 0.3);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.btn-admin-immutable {
|
||||
background: rgba(245, 158, 11, 0.12);
|
||||
color: #fbbf24;
|
||||
border: 1px solid rgba(245, 158, 11, 0.3);
|
||||
font-size: 0.72rem;
|
||||
padding: 0.3rem 0.6rem;
|
||||
border-radius: 6px;
|
||||
cursor: not-allowed;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@ -64,7 +64,8 @@
|
||||
<span>🔐 Ingresar / Registro</span>
|
||||
</button>
|
||||
<div class="user-pill-nav" id="user-profile-badge" style="display: none;">
|
||||
<span>👤 <strong id="user-display-name">Usuario</strong> <span class="badge-verified" id="user-role-badge">✅ Verificado</span></span>
|
||||
<span style="cursor: pointer;" id="btn-open-user-profile" title="Ver y Editar Mi Información Personal">👤 <strong id="user-display-name">Usuario</strong> <span class="badge-verified" id="user-role-badge">✅ Verificado</span></span>
|
||||
<button type="button" id="btn-edit-profile-nav" class="btn-logout-small" style="background: rgba(6, 182, 212, 0.18); color: #38bdf8; border: 1px solid rgba(6, 182, 212, 0.35); margin-right: 4px;" title="Editar Información Personal">⚙️ Mi Perfil</button>
|
||||
<button type="button" id="btn-logout" class="btn-logout-small" title="Cerrar Sesión">Salir</button>
|
||||
</div>
|
||||
</div>
|
||||
@ -714,6 +715,9 @@
|
||||
<button type="button" id="btn-admin-subtab-cupones" class="admin-pill-btn">
|
||||
🎟️ 4. Bonos & Cupones de Descuento
|
||||
</button>
|
||||
<button type="button" id="btn-admin-subtab-administradores" class="admin-pill-btn">
|
||||
👥 5. Equipo de Administradores
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- TAB 5: PANEL ADMINISTRATIVO (EXCLUSIVO PERSONAL ADMINISTRATIVO) -->
|
||||
@ -737,6 +741,9 @@
|
||||
<button type="button" id="btn-admin-subtab-cupones" class="admin-pill-btn">
|
||||
🎟️ 4. Bonos & Cupones de Descuento
|
||||
</button>
|
||||
<button type="button" id="btn-admin-subtab-administradores" class="admin-pill-btn">
|
||||
👥 5. Equipo de Administradores
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -1179,6 +1186,134 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- SUB-PANEL 5: EQUIPO DE ADMINISTRADORES (GESTIÓN SUPERADMINISTRADOR) -->
|
||||
<div id="admin-view-administradores" style="display: none;">
|
||||
<!-- BANNER GESTIÓN DE ADMINISTRADORES -->
|
||||
<div style="background: linear-gradient(135deg, rgba(15, 23, 42, 0.95), rgba(245, 158, 11, 0.18)); border: 1px solid rgba(245, 158, 11, 0.4); border-radius: 12px; padding: 1.5rem; margin-bottom: 1.75rem; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 1rem;">
|
||||
<div>
|
||||
<div style="display: flex; align-items: center; gap: 0.6rem; margin-bottom: 0.35rem;">
|
||||
<span class="superadmin-badge">👑 Superadministrador</span>
|
||||
<strong style="color: #fff; font-size: 1.15rem;">Gestión del Equipo de Administradores & Control de Acceso</strong>
|
||||
</div>
|
||||
<p style="color: #cbd5e1; font-size: 0.88rem; margin: 0; max-width: 720px;">
|
||||
El Superadministrador <strong>Carlos Almeira (+57 316 745 5877)</strong> es la autoridad máxima permanente e inmutable. Desde aquí puedes registrar nuevos administradores u operadores, actualizar sus permisos, activarlos o inactivarlos, o removerlos del sistema.
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<button type="button" id="btn-refresh-administrators" class="btn-toggle-payment" style="padding: 0.6rem 1.25rem;">
|
||||
🔄 Actualizar Equipo
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- KPIS DE ADMINISTRACIÓN -->
|
||||
<div class="financial-summary-grid" style="margin-bottom: 1.75rem;">
|
||||
<div class="fin-metric-card" style="border-top: 3px solid #fbbf24;">
|
||||
<div class="fin-metric-label">Superadministrador</div>
|
||||
<div class="fin-metric-val" style="color: #fbbf24; font-size: 1.15rem; margin-top: 0.35rem;">Carlos Almeira</div>
|
||||
<span style="font-size: 0.72rem; color: #34d399;">🔒 Permanente e Inmutable</span>
|
||||
</div>
|
||||
<div class="fin-metric-card" style="border-top: 3px solid #38bdf8;">
|
||||
<div class="fin-metric-label">Administradores Activos</div>
|
||||
<div class="fin-metric-val" id="kpi-admins-count" style="color: #38bdf8;">1</div>
|
||||
<span style="font-size: 0.72rem; color: #94a3b8;">Con acceso a Central de Mando</span>
|
||||
</div>
|
||||
<div class="fin-metric-card" style="border-top: 3px solid #c084fc;">
|
||||
<div class="fin-metric-label">Operadores de Despacho</div>
|
||||
<div class="fin-metric-val" id="kpi-operators-count" style="color: #c084fc;">0</div>
|
||||
<span style="font-size: 0.72rem; color: #94a3b8;">Monitoreo y asignación de ruta</span>
|
||||
</div>
|
||||
<div class="fin-metric-card" style="border-top: 3px solid #10b981;">
|
||||
<div class="fin-metric-label">Autenticación Requerida</div>
|
||||
<div class="fin-metric-val" style="color: #34d399; font-size: 1.15rem; margin-top: 0.35rem;">100% OTP</div>
|
||||
<span style="font-size: 0.72rem; color: #94a3b8;">WhatsApp 2FA Obligatorio</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid-2col" style="gap: 1.5rem; align-items: flex-start; margin-bottom: 2rem;">
|
||||
<!-- FORMULARIO REGISTRAR ADMINISTRADOR -->
|
||||
<div style="background: rgba(15, 23, 42, 0.75); border: 1px solid var(--border-glass); border-radius: 12px; padding: 1.5rem;">
|
||||
<h3 style="color: #38bdf8; font-size: 1.15rem; margin-bottom: 0.5rem; display: flex; align-items: center; gap: 0.5rem;">
|
||||
<span>➕</span> Registrar Nuevo Administrador
|
||||
</h3>
|
||||
<p style="color: var(--text-muted); font-size: 0.85rem; margin-bottom: 1.25rem;">
|
||||
Asigna privilegios de administración u operador de despacho a un nuevo colaborador.
|
||||
</p>
|
||||
|
||||
<form id="form-create-admin">
|
||||
<div class="form-group">
|
||||
<label class="form-label" for="new-admin-name">Nombre y Apellidos *</label>
|
||||
<input type="text" class="form-input" id="new-admin-name" placeholder="Ej: Diana Marcela López" required>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label" for="new-admin-phone">WhatsApp / Celular (+57) *</label>
|
||||
<input type="tel" class="form-input" id="new-admin-phone" placeholder="Ej: 315 123 4567" required>
|
||||
<span style="font-size: 0.73rem; color: var(--text-dim); margin-top: 3px; display: block;">
|
||||
Identificador de acceso y destino obligatorio para el código OTP de ingreso.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="grid-2col" style="gap: 1rem;">
|
||||
<div class="form-group">
|
||||
<label class="form-label" for="new-admin-doc">Documento (C.C.)</label>
|
||||
<input type="text" class="form-input" id="new-admin-doc" placeholder="Ej: 1144123456">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label" for="new-admin-email">Correo Electrónico</label>
|
||||
<input type="email" class="form-input" id="new-admin-email" placeholder="admin@pacifictrans.almeira.com.co">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label" for="new-admin-role">Rol y Nivel de Permisos *</label>
|
||||
<select class="form-select" id="new-admin-role">
|
||||
<option value="ADMIN">🛡️ ADMINISTRADOR (Control total de panel, tarifas y liquidaciones)</option>
|
||||
<option value="OPERADOR">🎧 OPERADOR (Monitoreo de radar satelital y despacho de viajes)</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div id="admin-create-feedback" style="display: none; margin-bottom: 1rem;"></div>
|
||||
|
||||
<button type="submit" class="btn-primary" id="btn-submit-new-admin" style="margin-top: 0.5rem;">
|
||||
➕ Registrar Administrador
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<!-- LISTADO DE ADMINISTRADORES -->
|
||||
<div style="background: rgba(15, 23, 42, 0.75); border: 1px solid var(--border-glass); border-radius: 12px; padding: 1.5rem;">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem; flex-wrap: wrap; gap: 0.5rem;">
|
||||
<h3 style="color: #fff; font-size: 1.15rem; margin: 0; display: flex; align-items: center; gap: 0.5rem;">
|
||||
<span>🛡️</span> Administradores & Operadores Autorizados
|
||||
</h3>
|
||||
<span style="font-size: 0.8rem; color: #94a3b8;" id="admins-counter-label">Cargando...</span>
|
||||
</div>
|
||||
|
||||
<div class="coupons-table-responsive">
|
||||
<table class="coupons-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Administrador</th>
|
||||
<th>WhatsApp (OTP)</th>
|
||||
<th>Rol</th>
|
||||
<th>Estado</th>
|
||||
<th>Acción</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="table-administrators-body">
|
||||
<tr>
|
||||
<td colspan="5" style="text-align: center; padding: 2rem; color: #94a3b8;">
|
||||
Cargando equipo de administradores...
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
@ -1784,6 +1919,129 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- MODAL 5: PERFIL DE USUARIO (INFORMACIÓN PERSONAL INMUTABLE DE CELULAR) -->
|
||||
<div class="pwa-modal-overlay" id="modal-user-profile">
|
||||
<div class="pwa-modal-card" style="max-width: 480px;">
|
||||
<button type="button" class="pwa-modal-close" id="btn-close-profile-modal">✕</button>
|
||||
|
||||
<div style="display: flex; align-items: center; gap: 0.65rem; margin-bottom: 0.5rem;">
|
||||
<span style="font-size: 1.6rem;">👤</span>
|
||||
<div>
|
||||
<h3 style="font-size: 1.35rem; color: #fff; margin: 0;">Mi Información Personal</h3>
|
||||
<p style="font-size: 0.82rem; color: var(--text-muted); margin: 0;">Actualiza tus datos para tus reservas y seguros de viaje</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form id="form-update-profile" style="margin-top: 1.25rem;">
|
||||
<div class="form-group">
|
||||
<label class="form-label" for="profile-name">Nombre Completo *</label>
|
||||
<input type="text" class="form-input" id="profile-name" placeholder="Tu nombre y apellidos" required>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label" for="profile-phone">Número Celular / WhatsApp de Registro</label>
|
||||
<input type="tel" class="form-input input-locked" id="profile-phone" readonly disabled>
|
||||
<div class="input-locked-note">
|
||||
<span>🔒</span>
|
||||
<span>Por seguridad y autenticación 2FA OTP, el número de celular registrado no puede ser modificado.</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid-2col" style="gap: 1rem;">
|
||||
<div class="form-group">
|
||||
<label class="form-label" for="profile-doc">Documento (C.C. / Pasaporte)</label>
|
||||
<input type="text" class="form-input" id="profile-doc" placeholder="Ej: 1144123456">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label" for="profile-email">Correo Electrónico</label>
|
||||
<input type="email" class="form-input" id="profile-email" placeholder="tu@correo.com">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label" for="profile-address">Dirección Principal en Cali (Domicilio)</label>
|
||||
<input type="text" class="form-input" id="profile-address" placeholder="Ej: Calle 5 #66-20, Cali">
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label" for="profile-city">Ciudad Principal</label>
|
||||
<input type="text" class="form-input" id="profile-city" value="Cali">
|
||||
</div>
|
||||
|
||||
<div id="profile-feedback" style="display: none; margin-bottom: 1rem;"></div>
|
||||
|
||||
<div style="display: flex; gap: 0.75rem; margin-top: 1rem;">
|
||||
<button type="submit" class="btn-primary" id="btn-save-profile" style="flex: 1;">
|
||||
💾 Guardar Información Personal
|
||||
</button>
|
||||
<button type="button" class="btn-return-public" id="btn-cancel-profile" style="width: auto; padding: 0.75rem 1.25rem;">
|
||||
Cerrar
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- MODAL 6: EDITAR ADMINISTRADOR (EXCLUSIVO SUPERADMIN) -->
|
||||
<div class="pwa-modal-overlay" id="modal-edit-admin">
|
||||
<div class="pwa-modal-card" style="max-width: 460px;">
|
||||
<button type="button" class="pwa-modal-close" id="btn-close-edit-admin-modal">✕</button>
|
||||
|
||||
<div style="display: flex; align-items: center; gap: 0.65rem; margin-bottom: 0.5rem;">
|
||||
<span style="font-size: 1.6rem;">🛡️</span>
|
||||
<div>
|
||||
<h3 style="font-size: 1.35rem; color: #fff; margin: 0;">Editar Administrador</h3>
|
||||
<p style="font-size: 0.82rem; color: var(--text-muted); margin: 0;" id="edit-admin-subtitle">Actualizar permisos y datos de contacto</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form id="form-edit-admin" style="margin-top: 1.25rem;">
|
||||
<input type="hidden" id="edit-admin-id">
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label" for="edit-admin-name">Nombre y Apellidos *</label>
|
||||
<input type="text" class="form-input" id="edit-admin-name" required>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label" for="edit-admin-phone">WhatsApp / Celular (+57)</label>
|
||||
<input type="tel" class="form-input input-locked" id="edit-admin-phone" readonly disabled>
|
||||
<span style="font-size: 0.73rem; color: #94a3b8; margin-top: 3px; display: block;">🔒 El teléfono celular no se modifica para preservar su identidad 2FA OTP.</span>
|
||||
</div>
|
||||
|
||||
<div class="grid-2col" style="gap: 1rem;">
|
||||
<div class="form-group">
|
||||
<label class="form-label" for="edit-admin-doc">Documento (C.C.)</label>
|
||||
<input type="text" class="form-input" id="edit-admin-doc">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label" for="edit-admin-email">Correo Electrónico</label>
|
||||
<input type="email" class="form-input" id="edit-admin-email">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="edit-admin-role-group">
|
||||
<label class="form-label" for="edit-admin-role">Rol de Administración</label>
|
||||
<select class="form-select" id="edit-admin-role">
|
||||
<option value="ADMIN">🛡️ ADMINISTRADOR (Control total)</option>
|
||||
<option value="OPERADOR">🎧 OPERADOR (Monitoreo y despacho)</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div id="edit-admin-feedback" style="display: none; margin-bottom: 1rem;"></div>
|
||||
|
||||
<div style="display: flex; gap: 0.75rem; margin-top: 1rem;">
|
||||
<button type="submit" class="btn-primary" id="btn-save-edit-admin" style="flex: 1;">
|
||||
💾 Guardar Cambios
|
||||
</button>
|
||||
<button type="button" class="btn-return-public" id="btn-cancel-edit-admin" style="width: auto; padding: 0.75rem 1.25rem;">
|
||||
Cancelar
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- LEAFLET JS PARA EL RADAR MAP -->
|
||||
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
|
||||
|
||||
|
||||
@ -36,6 +36,8 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
initTariffsManager();
|
||||
initCouponsManager();
|
||||
initSettlementsAndBreBSystem();
|
||||
initUserProfileManager();
|
||||
initAdministratorsManager();
|
||||
fetchTariffs();
|
||||
fetchAdminCoupons();
|
||||
fetchStatsAndReviews();
|
||||
@ -127,10 +129,18 @@ function initTabs() {
|
||||
if (adminGate) adminGate.style.display = 'none';
|
||||
if (adminContent) adminContent.style.display = 'block';
|
||||
const adminNameEl = document.getElementById('admin-user-name');
|
||||
if (adminNameEl) adminNameEl.textContent = `${currentUser.nombre} (${currentUser.rol})`;
|
||||
if (adminNameEl) {
|
||||
const roleBadge = currentUser.esSuperAdmin ? '👑 Superadministrador' : (currentUser.rol === 'ADMIN' ? '🛡️ Administrador' : '🎧 Operador');
|
||||
adminNameEl.textContent = `${currentUser.nombre} (${roleBadge})`;
|
||||
}
|
||||
// Visibilidad de subpestaña de gestión de administradores (solo ADMIN / Superadmin)
|
||||
document.querySelectorAll('#btn-admin-subtab-administradores').forEach(b => {
|
||||
b.style.display = (currentUser.rol === 'ADMIN' || currentUser.esSuperAdmin) ? 'inline-flex' : 'none';
|
||||
});
|
||||
if (leafletMap) setTimeout(() => leafletMap.invalidateSize(), 250);
|
||||
if (window.fetchSettlementsOverview) window.fetchSettlementsOverview();
|
||||
if (window.fetchAdminPayoutRequests) window.fetchAdminPayoutRequests();
|
||||
if (window.fetchAdministrators) window.fetchAdministrators();
|
||||
} else {
|
||||
if (adminGate) adminGate.style.display = 'block';
|
||||
if (adminContent) adminContent.style.display = 'none';
|
||||
@ -310,13 +320,15 @@ function initTabs() {
|
||||
const viewTarifas = document.getElementById('admin-view-tarifas');
|
||||
const viewLiquidaciones = document.getElementById('admin-view-liquidaciones');
|
||||
const viewCupones = document.getElementById('admin-view-cupones');
|
||||
const viewAdministradores = document.getElementById('admin-view-administradores');
|
||||
|
||||
function setAdminSubTab(targetViewId) {
|
||||
const allViews = [
|
||||
{ id: 'radar', el: viewRadar },
|
||||
{ id: 'tarifas', el: viewTarifas },
|
||||
{ id: 'liquidaciones', el: viewLiquidaciones },
|
||||
{ id: 'cupones', el: viewCupones }
|
||||
{ id: 'cupones', el: viewCupones },
|
||||
{ id: 'administradores', el: viewAdministradores }
|
||||
];
|
||||
|
||||
allViews.forEach(v => {
|
||||
@ -341,12 +353,16 @@ function initTabs() {
|
||||
if (targetViewId === 'cupones' && window.fetchAdminCoupons) {
|
||||
window.fetchAdminCoupons();
|
||||
}
|
||||
if (targetViewId === 'administradores' && window.fetchAdministrators) {
|
||||
window.fetchAdministrators();
|
||||
}
|
||||
}
|
||||
|
||||
document.querySelectorAll('#btn-admin-subtab-radar').forEach(b => b.addEventListener('click', () => setAdminSubTab('radar')));
|
||||
document.querySelectorAll('#btn-admin-subtab-tarifas').forEach(b => b.addEventListener('click', () => setAdminSubTab('tarifas')));
|
||||
document.querySelectorAll('#btn-admin-subtab-liquidaciones').forEach(b => b.addEventListener('click', () => setAdminSubTab('liquidaciones')));
|
||||
document.querySelectorAll('#btn-admin-subtab-cupones').forEach(b => b.addEventListener('click', () => setAdminSubTab('cupones')));
|
||||
document.querySelectorAll('#btn-admin-subtab-administradores').forEach(b => b.addEventListener('click', () => setAdminSubTab('administradores')));
|
||||
|
||||
// Sub-tabs de la sección del conductor
|
||||
const subDriverWalletBtn = document.getElementById('btn-driver-subtab-billetera');
|
||||
@ -631,6 +647,29 @@ function initAuthSystem() {
|
||||
document.querySelectorAll('.btn-role-quick-login').forEach(btn => {
|
||||
btn.addEventListener('click', async () => {
|
||||
const role = btn.getAttribute('data-role') || 'ADMIN';
|
||||
|
||||
// El ingreso como Administrador SIEMPRE exige verificación de Token/OTP por WhatsApp
|
||||
if (role === 'ADMIN' || role === 'OPERADOR') {
|
||||
const phoneInput = document.getElementById('auth-phone');
|
||||
if (phoneInput) {
|
||||
phoneInput.value = '3167455877';
|
||||
}
|
||||
authMode = 'login';
|
||||
if (modeLoginBtn) modeLoginBtn.classList.add('active');
|
||||
if (modeRegisterBtn) modeRegisterBtn.classList.remove('active');
|
||||
if (groupName) groupName.style.display = 'none';
|
||||
|
||||
if (reqError) {
|
||||
reqError.textContent = '🔒 Acceso de Administrador: Por políticas de seguridad 2FA, se enviará el código OTP a tu WhatsApp personal (+57 316 745 5877).';
|
||||
reqError.style.color = '#38bdf8';
|
||||
reqError.style.display = 'block';
|
||||
}
|
||||
|
||||
// Enviar OTP vía WhatsApp
|
||||
formStep1.dispatchEvent(new Event('submit'));
|
||||
return;
|
||||
}
|
||||
|
||||
btn.disabled = true;
|
||||
const originalText = btn.innerHTML;
|
||||
btn.innerHTML = '⏳ Accediendo...';
|
||||
@ -648,10 +687,7 @@ function initAuthSystem() {
|
||||
updateUserUI(currentUser);
|
||||
if (modal) modal.classList.remove('active');
|
||||
|
||||
if (role === 'ADMIN') {
|
||||
window.location.hash = '#admin';
|
||||
window.showView('admin');
|
||||
} else if (role === 'CONDUCTOR') {
|
||||
if (role === 'CONDUCTOR') {
|
||||
window.location.hash = '#conductor';
|
||||
window.showView('driver');
|
||||
} else {
|
||||
@ -723,7 +759,21 @@ function updateUserUI(user) {
|
||||
if (btnAuthOpen) btnAuthOpen.style.display = 'none';
|
||||
if (userBadge) userBadge.style.display = 'inline-flex';
|
||||
if (userNameEl) userNameEl.textContent = user.nombre.split(' ')[0];
|
||||
if (userRoleBadge) userRoleBadge.textContent = `✅ ${user.rol}`;
|
||||
if (userRoleBadge) {
|
||||
if (user.esSuperAdmin) {
|
||||
userRoleBadge.className = 'badge-verified superadmin-badge';
|
||||
userRoleBadge.innerHTML = '👑 SUPERADMIN';
|
||||
} else if (user.rol === 'ADMIN') {
|
||||
userRoleBadge.className = 'badge-verified admin-role-badge admin-role-admin';
|
||||
userRoleBadge.innerHTML = '🛡️ ADMIN';
|
||||
} else if (user.rol === 'OPERADOR') {
|
||||
userRoleBadge.className = 'badge-verified admin-role-badge admin-role-operador';
|
||||
userRoleBadge.innerHTML = '🎧 OPERADOR';
|
||||
} else {
|
||||
userRoleBadge.className = 'badge-verified';
|
||||
userRoleBadge.textContent = `✅ ${user.rol}`;
|
||||
}
|
||||
}
|
||||
|
||||
// Mostrar accesos a consolas según rol del usuario
|
||||
if (navBtnAdmin) {
|
||||
@ -3555,4 +3605,508 @@ window.deleteAdminCoupon = async function (couponId, code) {
|
||||
}
|
||||
};
|
||||
|
||||
/* ==========================================================================
|
||||
10. USER PROFILE MANAGER (INFORMACIÓN PERSONAL - CELULAR INMUTABLE)
|
||||
========================================================================== */
|
||||
function initUserProfileManager() {
|
||||
const modal = document.getElementById('modal-user-profile');
|
||||
const btnOpenNav = document.getElementById('btn-edit-profile-nav');
|
||||
const btnOpenUser = document.getElementById('btn-open-user-profile');
|
||||
const btnClose = document.getElementById('btn-close-profile-modal');
|
||||
const btnCancel = document.getElementById('btn-cancel-profile');
|
||||
const form = document.getElementById('form-update-profile');
|
||||
const feedback = document.getElementById('profile-feedback');
|
||||
const btnSave = document.getElementById('btn-save-profile');
|
||||
|
||||
const inputName = document.getElementById('profile-name');
|
||||
const inputPhone = document.getElementById('profile-phone');
|
||||
const inputDoc = document.getElementById('profile-doc');
|
||||
const inputEmail = document.getElementById('profile-email');
|
||||
const inputAddress = document.getElementById('profile-address');
|
||||
const inputCity = document.getElementById('profile-city');
|
||||
|
||||
function openProfileModal() {
|
||||
if (!currentUser) {
|
||||
const authModal = document.getElementById('modal-auth-dripzone');
|
||||
if (authModal) authModal.classList.add('active');
|
||||
return;
|
||||
}
|
||||
|
||||
if (inputName) inputName.value = currentUser.nombre || '';
|
||||
if (inputPhone) inputPhone.value = `+${currentUser.telefono || ''}`;
|
||||
if (inputDoc) inputDoc.value = currentUser.documentoIdentidad || '';
|
||||
if (inputEmail) inputEmail.value = currentUser.email || '';
|
||||
if (inputAddress) inputAddress.value = currentUser.direccionTexto || '';
|
||||
if (inputCity) inputCity.value = currentUser.ciudad || 'Cali';
|
||||
|
||||
if (feedback) feedback.style.display = 'none';
|
||||
if (modal) modal.classList.add('active');
|
||||
}
|
||||
|
||||
function closeProfileModal() {
|
||||
if (modal) modal.classList.remove('active');
|
||||
}
|
||||
|
||||
if (btnOpenNav) btnOpenNav.addEventListener('click', openProfileModal);
|
||||
if (btnOpenUser) btnOpenUser.addEventListener('click', openProfileModal);
|
||||
if (btnClose) btnClose.addEventListener('click', closeProfileModal);
|
||||
if (btnCancel) btnCancel.addEventListener('click', closeProfileModal);
|
||||
|
||||
if (form) {
|
||||
form.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
if (!currentUser) return;
|
||||
|
||||
const token = localStorage.getItem('pt_token') || '';
|
||||
if (!token) {
|
||||
alert('Sesión no encontrada. Por favor inicia sesión nuevamente.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (btnSave) {
|
||||
btnSave.disabled = true;
|
||||
btnSave.textContent = '⏳ Guardando...';
|
||||
}
|
||||
if (feedback) feedback.style.display = 'none';
|
||||
|
||||
try {
|
||||
const payload = {
|
||||
nombre: inputName ? inputName.value.trim() : '',
|
||||
documentoIdentidad: inputDoc ? inputDoc.value.trim() : '',
|
||||
email: inputEmail ? inputEmail.value.trim() : '',
|
||||
direccionTexto: inputAddress ? inputAddress.value.trim() : '',
|
||||
ciudad: inputCity ? inputCity.value.trim() : 'Cali'
|
||||
};
|
||||
|
||||
const res = await fetch('/api/users/profile', {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
if (res.ok && data.success) {
|
||||
if (feedback) {
|
||||
feedback.innerHTML = `<div style="background: rgba(16, 185, 129, 0.2); border: 1px solid #10b981; color: #34d399; padding: 0.75rem; border-radius: 8px; font-size: 0.85rem;">
|
||||
✅ ${data.message || 'Información actualizada con éxito'}
|
||||
</div>`;
|
||||
feedback.style.display = 'block';
|
||||
}
|
||||
if (data.user) {
|
||||
currentUser = { ...currentUser, ...data.user };
|
||||
updateUserUI(currentUser);
|
||||
}
|
||||
setTimeout(() => {
|
||||
closeProfileModal();
|
||||
}, 1200);
|
||||
} else {
|
||||
if (feedback) {
|
||||
feedback.innerHTML = `<div style="background: rgba(239, 68, 68, 0.2); border: 1px solid #ef4444; color: #f87171; padding: 0.75rem; border-radius: 8px; font-size: 0.85rem;">
|
||||
❌ ${data.error || 'No fue posible actualizar tu información'}
|
||||
</div>`;
|
||||
feedback.style.display = 'block';
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error updating user profile:', err);
|
||||
if (feedback) {
|
||||
feedback.innerHTML = `<div style="background: rgba(239, 68, 68, 0.2); border: 1px solid #ef4444; color: #f87171; padding: 0.75rem; border-radius: 8px; font-size: 0.85rem;">
|
||||
❌ Error de red al comunicar con el servidor
|
||||
</div>`;
|
||||
feedback.style.display = 'block';
|
||||
}
|
||||
} finally {
|
||||
if (btnSave) {
|
||||
btnSave.disabled = false;
|
||||
btnSave.textContent = '💾 Guardar Información Personal';
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/* ==========================================================================
|
||||
11. ADMINISTRATORS & ACCESS CONTROL MANAGER (EXCLUSIVO SUPERADMINISTRADOR)
|
||||
========================================================================== */
|
||||
function initAdministratorsManager() {
|
||||
const formCreate = document.getElementById('form-create-admin');
|
||||
const btnRefresh = document.getElementById('btn-refresh-administrators');
|
||||
const feedbackCreate = document.getElementById('admin-create-feedback');
|
||||
const btnSubmitCreate = document.getElementById('btn-submit-new-admin');
|
||||
|
||||
// Modal Editar Administrador
|
||||
const modalEdit = document.getElementById('modal-edit-admin');
|
||||
const btnCloseEdit = document.getElementById('btn-close-edit-admin-modal');
|
||||
const btnCancelEdit = document.getElementById('btn-cancel-edit-admin');
|
||||
const formEdit = document.getElementById('form-edit-admin');
|
||||
const feedbackEdit = document.getElementById('edit-admin-feedback');
|
||||
const btnSaveEdit = document.getElementById('btn-save-edit-admin');
|
||||
|
||||
const editId = document.getElementById('edit-admin-id');
|
||||
const editName = document.getElementById('edit-admin-name');
|
||||
const editPhone = document.getElementById('edit-admin-phone');
|
||||
const editDoc = document.getElementById('edit-admin-doc');
|
||||
const editEmail = document.getElementById('edit-admin-email');
|
||||
const editRole = document.getElementById('edit-admin-role');
|
||||
|
||||
if (btnRefresh) {
|
||||
btnRefresh.addEventListener('click', () => fetchAdministrators());
|
||||
}
|
||||
|
||||
function closeEditModal() {
|
||||
if (modalEdit) modalEdit.classList.remove('active');
|
||||
}
|
||||
|
||||
if (btnCloseEdit) btnCloseEdit.addEventListener('click', closeEditModal);
|
||||
if (btnCancelEdit) btnCancelEdit.addEventListener('click', closeEditModal);
|
||||
|
||||
// Crear Administrador
|
||||
if (formCreate) {
|
||||
formCreate.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const token = localStorage.getItem('pt_token') || '';
|
||||
if (!token) return;
|
||||
|
||||
const nameInput = document.getElementById('new-admin-name');
|
||||
const phoneInput = document.getElementById('new-admin-phone');
|
||||
const docInput = document.getElementById('new-admin-doc');
|
||||
const emailInput = document.getElementById('new-admin-email');
|
||||
const roleSelect = document.getElementById('new-admin-role');
|
||||
|
||||
if (btnSubmitCreate) {
|
||||
btnSubmitCreate.disabled = true;
|
||||
btnSubmitCreate.textContent = '⏳ Registrando...';
|
||||
}
|
||||
if (feedbackCreate) feedbackCreate.style.display = 'none';
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/admin/administrators', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({
|
||||
nombre: nameInput ? nameInput.value.trim() : '',
|
||||
telefono: phoneInput ? phoneInput.value.trim() : '',
|
||||
documentoIdentidad: docInput ? docInput.value.trim() : '',
|
||||
email: emailInput ? emailInput.value.trim() : '',
|
||||
rol: roleSelect ? roleSelect.value : 'ADMIN'
|
||||
})
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
if (res.ok && data.success) {
|
||||
if (feedbackCreate) {
|
||||
feedbackCreate.innerHTML = `<div style="background: rgba(16, 185, 129, 0.2); border: 1px solid #10b981; color: #34d399; padding: 0.75rem; border-radius: 8px; font-size: 0.85rem;">
|
||||
✅ Administrador ${data.administrator.nombre} registrado con éxito.
|
||||
</div>`;
|
||||
feedbackCreate.style.display = 'block';
|
||||
}
|
||||
formCreate.reset();
|
||||
fetchAdministrators();
|
||||
setTimeout(() => {
|
||||
if (feedbackCreate) feedbackCreate.style.display = 'none';
|
||||
}, 3500);
|
||||
} else {
|
||||
if (feedbackCreate) {
|
||||
feedbackCreate.innerHTML = `<div style="background: rgba(239, 68, 68, 0.2); border: 1px solid #ef4444; color: #f87171; padding: 0.75rem; border-radius: 8px; font-size: 0.85rem;">
|
||||
❌ ${data.error || 'No fue posible registrar al administrador'}
|
||||
</div>`;
|
||||
feedbackCreate.style.display = 'block';
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error creating administrator:', err);
|
||||
} finally {
|
||||
if (btnSubmitCreate) {
|
||||
btnSubmitCreate.disabled = false;
|
||||
btnSubmitCreate.textContent = '➕ Registrar Administrador';
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Guardar edición de Administrador
|
||||
if (formEdit) {
|
||||
formEdit.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const token = localStorage.getItem('pt_token') || '';
|
||||
if (!token) return;
|
||||
|
||||
const adminId = editId ? editId.value : '';
|
||||
if (!adminId) return;
|
||||
|
||||
if (btnSaveEdit) {
|
||||
btnSaveEdit.disabled = true;
|
||||
btnSaveEdit.textContent = '⏳ Guardando...';
|
||||
}
|
||||
if (feedbackEdit) feedbackEdit.style.display = 'none';
|
||||
|
||||
try {
|
||||
const payload = {
|
||||
nombre: editName ? editName.value.trim() : '',
|
||||
documentoIdentidad: editDoc ? editDoc.value.trim() : '',
|
||||
email: editEmail ? editEmail.value.trim() : '',
|
||||
rol: editRole ? editRole.value : 'ADMIN'
|
||||
};
|
||||
|
||||
const res = await fetch(`/api/admin/administrators/${adminId}`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
if (res.ok && data.success) {
|
||||
if (feedbackEdit) {
|
||||
feedbackEdit.innerHTML = `<div style="background: rgba(16, 185, 129, 0.2); border: 1px solid #10b981; color: #34d399; padding: 0.75rem; border-radius: 8px; font-size: 0.85rem;">
|
||||
✅ Cambios guardados correctamente.
|
||||
</div>`;
|
||||
feedbackEdit.style.display = 'block';
|
||||
}
|
||||
fetchAdministrators();
|
||||
setTimeout(() => {
|
||||
closeEditModal();
|
||||
}, 1200);
|
||||
} else {
|
||||
if (feedbackEdit) {
|
||||
feedbackEdit.innerHTML = `<div style="background: rgba(239, 68, 68, 0.2); border: 1px solid #ef4444; color: #f87171; padding: 0.75rem; border-radius: 8px; font-size: 0.85rem;">
|
||||
❌ ${data.error || 'Error al guardar los cambios'}
|
||||
</div>`;
|
||||
feedbackEdit.style.display = 'block';
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error updating admin:', err);
|
||||
} finally {
|
||||
if (btnSaveEdit) {
|
||||
btnSaveEdit.disabled = false;
|
||||
btnSaveEdit.textContent = '💾 Guardar Cambios';
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchAdministrators() {
|
||||
const tbody = document.getElementById('table-administrators-body');
|
||||
const counterLabel = document.getElementById('admins-counter-label');
|
||||
const kpiAdmins = document.getElementById('kpi-admins-count');
|
||||
const kpiOperators = document.getElementById('kpi-operators-count');
|
||||
|
||||
try {
|
||||
const token = localStorage.getItem('pt_token') || '';
|
||||
const res = await fetch('/api/admin/administrators', {
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
const data = await res.json();
|
||||
|
||||
if (!res.ok || !data.success) {
|
||||
if (tbody) {
|
||||
tbody.innerHTML = `<tr><td colspan="5" style="text-align: center; color: #f87171; padding: 1.5rem;">
|
||||
❌ ${data.error || 'Error al consultar equipo de administradores'}
|
||||
</td></tr>`;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const admins = data.administrators || [];
|
||||
|
||||
// Actualizar contadores
|
||||
let adminCount = 0;
|
||||
let operatorCount = 0;
|
||||
admins.forEach(a => {
|
||||
if (a.rol === 'OPERADOR') operatorCount++;
|
||||
else adminCount++;
|
||||
});
|
||||
|
||||
if (counterLabel) counterLabel.textContent = `${admins.length} miembro(s) registrados`;
|
||||
if (kpiAdmins) kpiAdmins.textContent = adminCount;
|
||||
if (kpiOperators) kpiOperators.textContent = operatorCount;
|
||||
|
||||
if (!tbody) return;
|
||||
if (admins.length === 0) {
|
||||
tbody.innerHTML = `<tr><td colspan="5" style="text-align: center; color: #94a3b8; padding: 1.5rem;">
|
||||
No hay administradores registrados en la plataforma.
|
||||
</td></tr>`;
|
||||
return;
|
||||
}
|
||||
|
||||
tbody.innerHTML = admins.map(admin => {
|
||||
const isSuper = !!admin.esSuperAdmin;
|
||||
const adminDataEncoded = encodeURIComponent(JSON.stringify(admin));
|
||||
|
||||
let roleBadge = '';
|
||||
if (isSuper) {
|
||||
roleBadge = `<span class="admin-role-badge admin-role-super">👑 SUPERADMIN</span>`;
|
||||
} else if (admin.rol === 'ADMIN') {
|
||||
roleBadge = `<span class="admin-role-badge admin-role-admin">🛡️ ADMIN</span>`;
|
||||
} else {
|
||||
roleBadge = `<span class="admin-role-badge admin-role-operador">🎧 OPERADOR</span>`;
|
||||
}
|
||||
|
||||
let statusHtml = '';
|
||||
if (isSuper) {
|
||||
statusHtml = `<span style="color: #34d399; font-weight: 700; font-size: 0.8rem; display: inline-flex; align-items: center; gap: 4px;">
|
||||
🔒 Permanente
|
||||
</span>`;
|
||||
} else {
|
||||
const isActive = admin.isActive !== false;
|
||||
statusHtml = `
|
||||
<button type="button"
|
||||
onclick="window.toggleAdminActive('${admin.id}', ${!isActive}, '${admin.nombre}')"
|
||||
class="btn-toggle-payment ${isActive ? 'active' : 'inactive'}"
|
||||
title="${isActive ? 'Clic para inactivar administrador' : 'Clic para activar administrador'}"
|
||||
>
|
||||
${isActive ? '✅ Activo' : '⏸️ Inactivo'}
|
||||
</button>
|
||||
`;
|
||||
}
|
||||
|
||||
let actionsHtml = '';
|
||||
if (isSuper) {
|
||||
actionsHtml = `<button type="button" class="btn-admin-immutable" disabled title="El Superadministrador es la máxima autoridad permanente e intocable">🔒 Superadmin</button>`;
|
||||
} else {
|
||||
actionsHtml = `
|
||||
<div style="display: flex; gap: 0.35rem; align-items: center;">
|
||||
<button type="button" class="btn-admin-edit" onclick="window.openEditAdminModal('${adminDataEncoded}')" title="Editar Administrador">
|
||||
✏️ Editar
|
||||
</button>
|
||||
<button type="button" class="btn-coupon-delete" onclick="window.deleteAdmin('${admin.id}', '${admin.nombre}')" title="Eliminar Administrador">
|
||||
🗑️
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
return `
|
||||
<tr>
|
||||
<td>
|
||||
<div style="font-weight: 700; color: #fff; display: flex; align-items: center; gap: 0.4rem;">
|
||||
${isSuper ? '<span style="font-size: 1.1rem;">👑</span>' : '<span>🛡️</span>'}
|
||||
<span>${admin.nombre}</span>
|
||||
${isSuper ? '<span class="superadmin-badge" style="font-size: 0.65rem; padding: 1px 6px;">Carlos</span>' : ''}
|
||||
</div>
|
||||
<div style="font-size: 0.75rem; color: #94a3b8;">
|
||||
${admin.documentoIdentidad ? `C.C. ${admin.documentoIdentidad} • ` : ''}${admin.email || 'Sin correo registrado'}
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<div style="color: #38bdf8; font-weight: 600; font-size: 0.85rem; display: flex; align-items: center; gap: 4px;">
|
||||
<span>📲</span>
|
||||
<span>+${admin.telefono}</span>
|
||||
</div>
|
||||
<div style="font-size: 0.7rem; color: #10b981;">2FA OTP Habilitado</div>
|
||||
</td>
|
||||
<td>${roleBadge}</td>
|
||||
<td>${statusHtml}</td>
|
||||
<td>${actionsHtml}</td>
|
||||
</tr>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
} catch (err) {
|
||||
console.error('Error fetching administrators:', err);
|
||||
if (tbody) {
|
||||
tbody.innerHTML = `<tr><td colspan="5" style="text-align: center; color: #f87171; padding: 1.5rem;">
|
||||
❌ Error de conexión al cargar equipo de administradores
|
||||
</td></tr>`;
|
||||
}
|
||||
}
|
||||
}
|
||||
window.fetchAdministrators = fetchAdministrators;
|
||||
|
||||
window.openEditAdminModal = function (adminDataEncoded) {
|
||||
try {
|
||||
const admin = JSON.parse(decodeURIComponent(adminDataEncoded));
|
||||
const modal = document.getElementById('modal-edit-admin');
|
||||
const editId = document.getElementById('edit-admin-id');
|
||||
const editName = document.getElementById('edit-admin-name');
|
||||
const editPhone = document.getElementById('edit-admin-phone');
|
||||
const editDoc = document.getElementById('edit-admin-doc');
|
||||
const editEmail = document.getElementById('edit-admin-email');
|
||||
const editRole = document.getElementById('edit-admin-role');
|
||||
const editRoleGroup = document.getElementById('edit-admin-role-group');
|
||||
const subtitle = document.getElementById('edit-admin-subtitle');
|
||||
const feedback = document.getElementById('edit-admin-feedback');
|
||||
|
||||
if (editId) editId.value = admin.id || '';
|
||||
if (editName) editName.value = admin.nombre || '';
|
||||
if (editPhone) editPhone.value = `+${admin.telefono || ''}`;
|
||||
if (editDoc) editDoc.value = admin.documentoIdentidad || '';
|
||||
if (editEmail) editEmail.value = admin.email || '';
|
||||
if (editRole) editRole.value = admin.rol || 'ADMIN';
|
||||
|
||||
if (admin.esSuperAdmin) {
|
||||
if (editRoleGroup) editRoleGroup.style.display = 'none';
|
||||
if (subtitle) subtitle.textContent = 'Actualizar datos de contacto del Superadministrador permanente';
|
||||
} else {
|
||||
if (editRoleGroup) editRoleGroup.style.display = 'block';
|
||||
if (subtitle) subtitle.textContent = 'Actualizar permisos y datos de contacto del colaborador';
|
||||
}
|
||||
|
||||
if (feedback) feedback.style.display = 'none';
|
||||
if (modal) modal.classList.add('active');
|
||||
} catch (e) {
|
||||
console.error('Error parsing admin for edit:', e);
|
||||
}
|
||||
};
|
||||
|
||||
window.toggleAdminActive = async function (adminId, nextState, adminName) {
|
||||
try {
|
||||
const token = localStorage.getItem('pt_token') || '';
|
||||
const res = await fetch(`/api/admin/administrators/${adminId}/toggle-active`, {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({ id: adminId, isActive: nextState })
|
||||
});
|
||||
const data = await res.json();
|
||||
if (res.ok && data.success) {
|
||||
fetchAdministrators();
|
||||
} else {
|
||||
alert(`Error al cambiar estado: ${data.error || 'No permitido'}`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error toggling admin active:', err);
|
||||
alert('Error al comunicar con el servidor.');
|
||||
}
|
||||
};
|
||||
|
||||
window.deleteAdmin = async function (adminId, adminName) {
|
||||
if (!confirm(`¿Estás seguro de eliminar a ${adminName || 'este administrador'} del equipo? Esta acción revoca inmediatamente sus permisos de acceso.`)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const token = localStorage.getItem('pt_token') || '';
|
||||
const res = await fetch(`/api/admin/administrators/${adminId}`, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({ id: adminId })
|
||||
});
|
||||
const data = await res.json();
|
||||
if (res.ok && data.success) {
|
||||
fetchAdministrators();
|
||||
} else {
|
||||
alert(`Error al eliminar administrador: ${data.error || 'No permitido'}`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error deleting administrator:', err);
|
||||
alert('Error al comunicar con el servidor.');
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
@ -108,12 +108,22 @@ const server = http.createServer(async (req, res) => {
|
||||
return sendJson(200, { success: true, user });
|
||||
}
|
||||
|
||||
// 1.4. Autenticación: Quick Role Login para alternar roles y probar seguridad de rutas
|
||||
// 1.4. Autenticación: Quick Role Login para pruebas de roles públicos (PROHIBIDO para ADMIN / OPERADOR)
|
||||
if (pathname === '/api/auth/quick-role-login' && req.method === 'POST') {
|
||||
const body = await getJsonBody();
|
||||
const role = body.role || 'ADMIN';
|
||||
const result = await authService.createSessionForRole(role, body.name);
|
||||
return sendJson(200, { success: true, ...result });
|
||||
const role = body.role || 'PASAJERO';
|
||||
if (role === 'ADMIN' || role === 'OPERADOR') {
|
||||
return sendJson(403, {
|
||||
success: false,
|
||||
error: 'Acceso no permitido: El ingreso al rol Administrador requiere obligatoriamente verificar el código OTP enviado a tu número personal de WhatsApp (+57 316 745 5877).'
|
||||
});
|
||||
}
|
||||
try {
|
||||
const result = await authService.createSessionForRole(role, body.name);
|
||||
return sendJson(200, { success: true, ...result });
|
||||
} catch (err: any) {
|
||||
return sendJson(403, { success: false, error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
// Helper de seguridad por roles y permisos en rutas API
|
||||
@ -123,14 +133,9 @@ const server = http.createServer(async (req, res) => {
|
||||
};
|
||||
|
||||
const requireRole = async (allowedRoles: ('ADMIN' | 'CONDUCTOR' | 'PASAJERO' | 'OPERADOR')[]) => {
|
||||
const masterKey = req.headers['x-admin-key'] || url.searchParams.get('master_key');
|
||||
if (masterKey === 'admin_master_pacifictrans_2026') {
|
||||
return { allowed: true, user: { rol: 'ADMIN', nombre: 'Admin Master' } };
|
||||
}
|
||||
const token = getToken();
|
||||
if (!token) {
|
||||
// En peticiones públicas sin token, denegar si es ruta estrictamente protegida
|
||||
return { allowed: false, error: 'Autenticación requerida: Inicia sesión con credenciales autorizadas.' };
|
||||
return { allowed: false, error: 'Autenticación requerida: Inicia sesión con código OTP de seguridad.' };
|
||||
}
|
||||
return authService.verifyRole(token, allowedRoles);
|
||||
};
|
||||
@ -205,7 +210,85 @@ const server = http.createServer(async (req, res) => {
|
||||
return sendJson(200, result);
|
||||
}
|
||||
|
||||
// 8. Administración de Usuarios (Estilo DripZone)
|
||||
// 8. Administración de Usuarios y Perfil Personal
|
||||
// 8.0. Actualización de Información Personal (No permite cambiar número de celular registrado)
|
||||
if ((pathname === '/api/users/profile' || pathname === '/api/auth/profile') && req.method === 'GET') {
|
||||
const auth = await requireRole(['PASAJERO', 'CONDUCTOR', 'ADMIN', 'OPERADOR']);
|
||||
if (!auth.allowed) return sendJson(401, { success: false, error: auth.error });
|
||||
return sendJson(200, { success: true, user: auth.user });
|
||||
}
|
||||
|
||||
if ((pathname === '/api/users/profile' || pathname === '/api/auth/profile') && (req.method === 'PATCH' || req.method === 'PUT' || req.method === 'POST')) {
|
||||
const auth = await requireRole(['PASAJERO', 'CONDUCTOR', 'ADMIN', 'OPERADOR']);
|
||||
if (!auth.allowed) return sendJson(401, { success: false, error: auth.error });
|
||||
const body = await getJsonBody();
|
||||
try {
|
||||
const updated = await userAdminService.updateUserProfile(auth.user.id || auth.user._id, body);
|
||||
return sendJson(200, { success: true, message: 'Información personal actualizada correctamente', user: updated });
|
||||
} catch (err: any) {
|
||||
return sendJson(400, { success: false, error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
// 8.1. Gestión Centralizada de Administradores por el Superadministrador
|
||||
if (pathname === '/api/admin/administrators' && req.method === 'GET') {
|
||||
const auth = await requireRole(['ADMIN']);
|
||||
if (!auth.allowed) return sendJson(403, { success: false, error: auth.error });
|
||||
const administrators = await userAdminService.getAdministrators();
|
||||
return sendJson(200, { success: true, count: administrators.length, administrators });
|
||||
}
|
||||
|
||||
if (pathname === '/api/admin/administrators' && req.method === 'POST') {
|
||||
const auth = await requireRole(['ADMIN']);
|
||||
if (!auth.allowed) return sendJson(403, { success: false, error: auth.error });
|
||||
const body = await getJsonBody();
|
||||
try {
|
||||
const administrator = await userAdminService.createAdministrator(body);
|
||||
return sendJson(201, { success: true, administrator });
|
||||
} catch (err: any) {
|
||||
return sendJson(400, { success: false, error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
if ((pathname === '/api/admin/administrators/update' || (pathname.startsWith('/api/admin/administrators/') && !pathname.endsWith('/toggle-active'))) && (req.method === 'PUT' || req.method === 'POST')) {
|
||||
const auth = await requireRole(['ADMIN']);
|
||||
if (!auth.allowed) return sendJson(403, { success: false, error: auth.error });
|
||||
const body = await getJsonBody();
|
||||
const adminId = pathname.split('/')[4] || body.id || body.adminId;
|
||||
try {
|
||||
const administrator = await userAdminService.updateAdministrator(adminId, body, auth.user.id);
|
||||
return sendJson(200, { success: true, administrator });
|
||||
} catch (err: any) {
|
||||
return sendJson(400, { success: false, error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
if ((pathname === '/api/admin/administrators/toggle-active' || (pathname.startsWith('/api/admin/administrators/') && pathname.endsWith('/toggle-active'))) && (req.method === 'POST' || req.method === 'PATCH')) {
|
||||
const auth = await requireRole(['ADMIN']);
|
||||
if (!auth.allowed) return sendJson(403, { success: false, error: auth.error });
|
||||
const body = await getJsonBody();
|
||||
const adminId = body.id || body.adminId || pathname.split('/')[4];
|
||||
try {
|
||||
const administrator = await userAdminService.toggleAdministratorActive(adminId, body.isActive);
|
||||
return sendJson(200, { success: true, administrator });
|
||||
} catch (err: any) {
|
||||
return sendJson(400, { success: false, error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
if ((pathname === '/api/admin/administrators/delete' && req.method === 'POST') || (pathname.startsWith('/api/admin/administrators/') && req.method === 'DELETE')) {
|
||||
const auth = await requireRole(['ADMIN']);
|
||||
if (!auth.allowed) return sendJson(403, { success: false, error: auth.error });
|
||||
const body = await getJsonBody();
|
||||
const adminId = pathname.split('/')[4] || body.id || body.adminId;
|
||||
try {
|
||||
await userAdminService.deleteAdministrator(adminId, auth.user.id);
|
||||
return sendJson(200, { success: true, message: 'Administrador eliminado exitosamente' });
|
||||
} catch (err: any) {
|
||||
return sendJson(400, { success: false, error: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
if (pathname === '/api/users' && req.method === 'GET') {
|
||||
const users = await userAdminService.getAllUsers();
|
||||
return sendJson(200, { success: true, count: users.length, users });
|
||||
@ -543,6 +626,7 @@ async function bootstrap() {
|
||||
await connectDatabase();
|
||||
console.log('✅ [MongoDB] Conectado exitosamente en segundo plano.');
|
||||
await couponService.ensureSeedCoupons();
|
||||
await userAdminService.ensureSuperAdminExists();
|
||||
} catch (err: any) {
|
||||
console.warn(`⚠️ [MongoDB Warning] Conexión no disponible (${err.message || 'ENOTFOUND'}). Reintentando en 10s...`);
|
||||
setTimeout(tryConnect, 10000);
|
||||
|
||||
@ -12,6 +12,8 @@ export interface IUser extends Document {
|
||||
nombre: string;
|
||||
telefono: string;
|
||||
email?: string;
|
||||
documentoIdentidad?: string;
|
||||
esSuperAdmin?: boolean;
|
||||
rol: UserRole;
|
||||
saldoPenalidad: number;
|
||||
coordenadasDomicilio: IGeoPoint;
|
||||
@ -86,6 +88,15 @@ const UserSchema = new Schema<IUser>(
|
||||
trim: true,
|
||||
lowercase: true,
|
||||
},
|
||||
documentoIdentidad: {
|
||||
type: String,
|
||||
trim: true,
|
||||
},
|
||||
esSuperAdmin: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
index: true,
|
||||
},
|
||||
rol: {
|
||||
type: String,
|
||||
enum: ['PASAJERO', 'CONDUCTOR', 'ADMIN', 'OPERADOR'],
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import crypto from 'crypto';
|
||||
import { User, IUser, UserRole } from '../models/User';
|
||||
import { whatsAppNotificationService } from './whatsapp-notification.service';
|
||||
import { isPlatformSuperAdmin } from './user-admin.service';
|
||||
import { isPlatformSuperAdmin, SUPER_ADMIN_PHONE, SUPER_ADMIN_EMAIL } from './user-admin.service';
|
||||
|
||||
interface OtpRecord {
|
||||
code: string;
|
||||
@ -82,13 +82,12 @@ export class AuthService {
|
||||
success: true,
|
||||
maskedPhone: masked,
|
||||
message: `Código enviado a ${masked} vía WhatsApp`,
|
||||
// Para entornos locales sin SIM activa de WhatsApp devolvemos preview si no se pudo conectar
|
||||
codePreview: sent ? undefined : code,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Paso 2: Verificar OTP y emitir sesión autenticada estilo DripZone
|
||||
* Paso 2: Verificar OTP y emitir sesión autenticada
|
||||
*/
|
||||
public async verifyOtp(params: {
|
||||
identifier: string;
|
||||
@ -96,6 +95,7 @@ export class AuthService {
|
||||
nombre?: string;
|
||||
email?: string;
|
||||
direccionTexto?: string;
|
||||
documentoIdentidad?: string;
|
||||
}): Promise<{
|
||||
success: boolean;
|
||||
token?: string;
|
||||
@ -143,12 +143,15 @@ export class AuthService {
|
||||
|
||||
if (!user) {
|
||||
user = await User.create({
|
||||
appwriteId: `pt-${Date.now()}-${Math.random().toString(36).substr(2, 6)}`,
|
||||
nombre: params.nombre || (isSuper ? 'Administrador General' : `Usuario ${cleanPhone.slice(-4)}`),
|
||||
appwriteId: isSuper ? 'usr-superadmin-carlos' : `pt-${Date.now()}-${Math.random().toString(36).substr(2, 6)}`,
|
||||
nombre: isSuper ? (params.nombre || 'Carlos Almeira') : (params.nombre || `Usuario ${cleanPhone.slice(-4)}`),
|
||||
telefono: cleanPhone,
|
||||
email: userEmail,
|
||||
email: userEmail || (isSuper ? SUPER_ADMIN_EMAIL : undefined),
|
||||
documentoIdentidad: params.documentoIdentidad || (isSuper ? '3167455877' : undefined),
|
||||
direccionTexto: params.direccionTexto || 'Cali, Valle del Cauca',
|
||||
ciudad: 'Cali',
|
||||
rol: assignedRole,
|
||||
esSuperAdmin: isSuper,
|
||||
saldoPenalidad: 0,
|
||||
coordenadasDomicilio: {
|
||||
type: 'Point',
|
||||
@ -160,20 +163,27 @@ export class AuthService {
|
||||
twoFactorMethod: 'whatsapp_otp',
|
||||
lastLogin: new Date(),
|
||||
});
|
||||
console.log(`👤 [Nuevo Usuario Registrado y Verificado]: ${user.nombre} (+${user.telefono}) - Rol: ${user.rol}`);
|
||||
console.log(`👤 [Nuevo Usuario Verificado]: ${user.nombre} (+${user.telefono}) - Rol: ${user.rol} ${isSuper ? '(SUPERADMIN)' : ''}`);
|
||||
} else {
|
||||
user.phoneVerified = true;
|
||||
user.isActive = true;
|
||||
user.lastLogin = new Date();
|
||||
if (isSuper) {
|
||||
user.rol = 'ADMIN';
|
||||
user.esSuperAdmin = true;
|
||||
if (!user.nombre || user.nombre.startsWith('Usuario ')) {
|
||||
user.nombre = 'Carlos Almeira';
|
||||
}
|
||||
}
|
||||
if (params.documentoIdentidad && !user.documentoIdentidad) {
|
||||
user.documentoIdentidad = params.documentoIdentidad;
|
||||
}
|
||||
if (params.nombre && user.nombre.startsWith('Usuario ')) {
|
||||
user.nombre = params.nombre;
|
||||
}
|
||||
if (userEmail && !user.email) {
|
||||
user.email = userEmail;
|
||||
}
|
||||
if (isSuper) {
|
||||
user.rol = 'ADMIN';
|
||||
}
|
||||
await user.save();
|
||||
}
|
||||
|
||||
@ -187,13 +197,17 @@ export class AuthService {
|
||||
|
||||
const userPayload = {
|
||||
id: user._id.toString(),
|
||||
_id: user._id.toString(),
|
||||
nombre: user.nombre,
|
||||
telefono: user.telefono,
|
||||
email: user.email,
|
||||
documentoIdentidad: user.documentoIdentidad,
|
||||
direccionTexto: user.direccionTexto,
|
||||
ciudad: user.ciudad,
|
||||
rol: user.rol,
|
||||
esSuperAdmin: isSuper || !!user.esSuperAdmin,
|
||||
phoneVerified: user.phoneVerified,
|
||||
saldoPenalidad: user.saldoPenalidad,
|
||||
direccionTexto: user.direccionTexto,
|
||||
};
|
||||
|
||||
return {
|
||||
@ -217,15 +231,21 @@ export class AuthService {
|
||||
try {
|
||||
const user = await User.findById(session.userId);
|
||||
if (user) {
|
||||
const isSuper = isPlatformSuperAdmin(user.telefono) || isPlatformSuperAdmin(user.email) || !!user.esSuperAdmin;
|
||||
return {
|
||||
id: user._id.toString(),
|
||||
_id: user._id.toString(),
|
||||
nombre: user.nombre,
|
||||
telefono: user.telefono,
|
||||
email: user.email,
|
||||
rol: user.rol,
|
||||
documentoIdentidad: user.documentoIdentidad,
|
||||
direccionTexto: user.direccionTexto,
|
||||
ciudad: user.ciudad,
|
||||
rol: isSuper ? 'ADMIN' : user.rol,
|
||||
esSuperAdmin: isSuper,
|
||||
phoneVerified: user.phoneVerified,
|
||||
saldoPenalidad: user.saldoPenalidad,
|
||||
direccionTexto: user.direccionTexto,
|
||||
isActive: user.isActive,
|
||||
};
|
||||
}
|
||||
} catch (e) {
|
||||
@ -246,6 +266,9 @@ export class AuthService {
|
||||
if (!user) {
|
||||
return { allowed: false, error: 'Sesión expirada o no válida. Por favor inicia sesión nuevamente.' };
|
||||
}
|
||||
if (!user.isActive) {
|
||||
return { allowed: false, error: 'Tu cuenta se encuentra inactiva. Contacta al Administrador.' };
|
||||
}
|
||||
if (!allowedRoles.includes(user.rol)) {
|
||||
return {
|
||||
allowed: false,
|
||||
@ -257,17 +280,21 @@ export class AuthService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Crea o reactiva una sesión rápida para un rol determinado (útil para auditoría, pruebas y panel)
|
||||
* Crea o reactiva una sesión rápida para pruebas (PROHIBIDO para ADMIN / OPERADOR)
|
||||
* Los roles de administración requieren obligatoriamente verificación OTP por WhatsApp
|
||||
*/
|
||||
public async createSessionForRole(role: UserRole, customName?: string): Promise<{ token: string; user: any }> {
|
||||
let phone = '573167455877';
|
||||
let defaultName = 'Carlos Almeira (SuperAdmin)';
|
||||
if (role === 'ADMIN' || role === 'OPERADOR') {
|
||||
throw new Error(
|
||||
'Acceso denegado: El rol Administrador requiere obligatoriamente verificación por código OTP enviado a tu número personal de WhatsApp (+57 316 745 5877).'
|
||||
);
|
||||
}
|
||||
|
||||
let phone = '573187654321';
|
||||
let defaultName = 'Pasajero Frecuente Cali';
|
||||
if (role === 'CONDUCTOR') {
|
||||
phone = '573158923456';
|
||||
defaultName = 'Mario Fernando G. (Renault Duster WLZ-890)';
|
||||
} else if (role === 'PASAJERO') {
|
||||
phone = '573187654321';
|
||||
defaultName = 'Pasajero Frecuente Cali';
|
||||
}
|
||||
|
||||
let userDoc: any = null;
|
||||
@ -289,7 +316,7 @@ export class AuthService {
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
// Si la BD no responde inmediatamente en local, continuar con usuario temporal
|
||||
// Continuar con usuario temporal si falla DB temporalmente
|
||||
}
|
||||
|
||||
const userId = userDoc?._id ? userDoc._id.toString() : `role-${role.toLowerCase()}-${Date.now()}`;
|
||||
@ -300,6 +327,7 @@ export class AuthService {
|
||||
telefono: userDoc?.telefono || phone,
|
||||
email: userDoc?.email || `${role.toLowerCase()}@pacifictrans.almeira.com.co`,
|
||||
rol: role,
|
||||
esSuperAdmin: false,
|
||||
phoneVerified: true,
|
||||
saldoPenalidad: 0,
|
||||
direccionTexto: 'Cali, Valle del Cauca',
|
||||
|
||||
@ -3,13 +3,18 @@ import { User, IUser, UserRole } from '../models/User';
|
||||
import { DriverProfile, IDriverProfile } from '../models/DriverProfile';
|
||||
import { boldPaymentService } from './bold.service';
|
||||
|
||||
export const SUPER_ADMIN_PHONE = process.env.ADMIN_WHATSAPP_PHONE || '573167455877';
|
||||
export const SUPER_ADMIN_EMAIL = process.env.SUPER_ADMIN_EMAIL || 'admin@pacifictrans.almeira.com.co';
|
||||
export const SUPER_ADMIN_PHONE = '573167455877';
|
||||
export const SUPER_ADMIN_LOCAL_PHONE = '3167455877';
|
||||
export const SUPER_ADMIN_EMAIL = 'admin@pacifictrans.almeira.com.co';
|
||||
|
||||
export function isPlatformSuperAdmin(identifier?: string): boolean {
|
||||
if (!identifier) return false;
|
||||
const clean = identifier.replace(/\D/g, '');
|
||||
return clean === SUPER_ADMIN_PHONE || identifier.toLowerCase().trim() === SUPER_ADMIN_EMAIL;
|
||||
return (
|
||||
clean === SUPER_ADMIN_PHONE ||
|
||||
clean === SUPER_ADMIN_LOCAL_PHONE ||
|
||||
identifier.toLowerCase().trim() === SUPER_ADMIN_EMAIL
|
||||
);
|
||||
}
|
||||
|
||||
export interface UserSummaryDTO {
|
||||
@ -18,6 +23,8 @@ export interface UserSummaryDTO {
|
||||
nombre: string;
|
||||
telefono: string;
|
||||
email?: string;
|
||||
documentoIdentidad?: string;
|
||||
esSuperAdmin?: boolean;
|
||||
rol: UserRole;
|
||||
isActive: boolean;
|
||||
phoneVerified: boolean;
|
||||
@ -28,10 +35,39 @@ export interface UserSummaryDTO {
|
||||
twoFactorEnabled?: boolean;
|
||||
twoFactorMethod?: 'whatsapp_otp' | 'biometric' | 'both';
|
||||
biometricEnabled?: boolean;
|
||||
direccionTexto?: string;
|
||||
ciudad?: string;
|
||||
driverProfile?: any | null;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
export interface CreateAdminDTO {
|
||||
nombre: string;
|
||||
telefono: string;
|
||||
email?: string;
|
||||
documentoIdentidad?: string;
|
||||
rol?: UserRole;
|
||||
direccionTexto?: string;
|
||||
}
|
||||
|
||||
export interface UpdateAdminDTO {
|
||||
nombre?: string;
|
||||
email?: string;
|
||||
documentoIdentidad?: string;
|
||||
rol?: UserRole;
|
||||
direccionTexto?: string;
|
||||
ciudad?: string;
|
||||
}
|
||||
|
||||
export interface UpdateUserProfileDTO {
|
||||
nombre?: string;
|
||||
email?: string;
|
||||
documentoIdentidad?: string;
|
||||
direccionTexto?: string;
|
||||
ciudad?: string;
|
||||
telefono?: string; // Si se envía un teléfono diferente al registrado, se denegará
|
||||
}
|
||||
|
||||
export class UserAdminService {
|
||||
private static instance: UserAdminService;
|
||||
|
||||
@ -57,7 +93,7 @@ export class UserAdminService {
|
||||
driverProfile = await DriverProfile.findOne({ userId: u._id }).lean();
|
||||
}
|
||||
|
||||
const isSuper = isPlatformSuperAdmin(u.telefono) || isPlatformSuperAdmin(u.email);
|
||||
const isSuper = isPlatformSuperAdmin(u.telefono) || isPlatformSuperAdmin(u.email) || !!u.esSuperAdmin;
|
||||
|
||||
result.push({
|
||||
id: u._id.toString(),
|
||||
@ -65,6 +101,8 @@ export class UserAdminService {
|
||||
nombre: u.nombre,
|
||||
telefono: u.telefono,
|
||||
email: u.email,
|
||||
documentoIdentidad: u.documentoIdentidad,
|
||||
esSuperAdmin: isSuper,
|
||||
rol: isSuper ? 'ADMIN' : u.rol,
|
||||
isActive: isSuper ? true : u.isActive,
|
||||
phoneVerified: isSuper ? true : u.phoneVerified,
|
||||
@ -75,6 +113,8 @@ export class UserAdminService {
|
||||
twoFactorEnabled: u.twoFactorEnabled,
|
||||
twoFactorMethod: u.twoFactorMethod,
|
||||
biometricEnabled: u.biometricEnabled,
|
||||
direccionTexto: u.direccionTexto,
|
||||
ciudad: u.ciudad,
|
||||
driverProfile,
|
||||
createdAt: u.createdAt,
|
||||
});
|
||||
@ -83,6 +123,328 @@ export class UserAdminService {
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtiene exclusivamente el equipo de administradores y operadores
|
||||
* El Superadministrador siempre aparece en primera posición
|
||||
*/
|
||||
public async getAdministrators(): Promise<UserSummaryDTO[]> {
|
||||
// Asegurar que el Superadministrador esté registrado
|
||||
await this.ensureSuperAdminExists();
|
||||
|
||||
const admins = await User.find({
|
||||
$or: [
|
||||
{ rol: { $in: ['ADMIN', 'OPERADOR'] } },
|
||||
{ esSuperAdmin: true },
|
||||
{ telefono: { $in: [SUPER_ADMIN_PHONE, SUPER_ADMIN_LOCAL_PHONE] } },
|
||||
],
|
||||
})
|
||||
.sort({ createdAt: -1 })
|
||||
.lean();
|
||||
|
||||
const dtos: UserSummaryDTO[] = admins.map((u) => {
|
||||
const isSuper = isPlatformSuperAdmin(u.telefono) || isPlatformSuperAdmin(u.email) || !!u.esSuperAdmin;
|
||||
return {
|
||||
id: u._id.toString(),
|
||||
appwriteId: u.appwriteId,
|
||||
nombre: u.nombre,
|
||||
telefono: u.telefono,
|
||||
email: u.email,
|
||||
documentoIdentidad: u.documentoIdentidad,
|
||||
esSuperAdmin: isSuper,
|
||||
rol: isSuper ? 'ADMIN' : u.rol,
|
||||
isActive: isSuper ? true : u.isActive,
|
||||
phoneVerified: isSuper ? true : u.phoneVerified,
|
||||
saldoPenalidad: 0,
|
||||
bloqueadoPorPenalidad: false,
|
||||
totalViajesCompletados: u.totalViajesCompletados || 0,
|
||||
totalViajesCancelados: u.totalViajesCancelados || 0,
|
||||
direccionTexto: u.direccionTexto,
|
||||
ciudad: u.ciudad,
|
||||
createdAt: u.createdAt,
|
||||
};
|
||||
});
|
||||
|
||||
// Superadministrador primero
|
||||
return dtos.sort((a, b) => (b.esSuperAdmin ? 1 : 0) - (a.esSuperAdmin ? 1 : 0));
|
||||
}
|
||||
|
||||
/**
|
||||
* Asegura la existencia y rol inmutable del Superadministrador en MongoDB
|
||||
*/
|
||||
public async ensureSuperAdminExists(): Promise<any> {
|
||||
let superAdmin = await User.findOne({
|
||||
$or: [
|
||||
{ telefono: SUPER_ADMIN_PHONE },
|
||||
{ telefono: SUPER_ADMIN_LOCAL_PHONE },
|
||||
],
|
||||
});
|
||||
|
||||
if (!superAdmin) {
|
||||
superAdmin = await User.create({
|
||||
appwriteId: 'usr-superadmin-carlos',
|
||||
nombre: 'Carlos Almeira',
|
||||
telefono: SUPER_ADMIN_PHONE,
|
||||
email: SUPER_ADMIN_EMAIL,
|
||||
documentoIdentidad: '3167455877',
|
||||
rol: 'ADMIN',
|
||||
esSuperAdmin: true,
|
||||
saldoPenalidad: 0,
|
||||
coordenadasDomicilio: {
|
||||
type: 'Point',
|
||||
coordinates: [-76.532, 3.4516],
|
||||
},
|
||||
direccionTexto: 'Cali, Valle del Cauca',
|
||||
ciudad: 'Cali',
|
||||
isActive: true,
|
||||
phoneVerified: true,
|
||||
twoFactorEnabled: true,
|
||||
twoFactorMethod: 'whatsapp_otp',
|
||||
});
|
||||
console.log('👑 [SuperAdmin Seed]: Carlos Almeira registrado como Superadministrador permanente.');
|
||||
} else {
|
||||
let needsSave = false;
|
||||
if (superAdmin.rol !== 'ADMIN') {
|
||||
superAdmin.rol = 'ADMIN';
|
||||
needsSave = true;
|
||||
}
|
||||
if (!superAdmin.esSuperAdmin) {
|
||||
superAdmin.esSuperAdmin = true;
|
||||
needsSave = true;
|
||||
}
|
||||
if (!superAdmin.isActive) {
|
||||
superAdmin.isActive = true;
|
||||
needsSave = true;
|
||||
}
|
||||
if (needsSave) {
|
||||
await superAdmin.save();
|
||||
}
|
||||
}
|
||||
|
||||
return superAdmin;
|
||||
}
|
||||
|
||||
/**
|
||||
* El Superadministrador registra a un nuevo administrador
|
||||
*/
|
||||
public async createAdministrator(data: CreateAdminDTO): Promise<UserSummaryDTO> {
|
||||
const rawPhone = (data.telefono || '').replace(/\D/g, '');
|
||||
if (!rawPhone || rawPhone.length < 7) {
|
||||
throw new Error('Número de WhatsApp/celular inválido para el administrador.');
|
||||
}
|
||||
|
||||
const cleanPhone = rawPhone.startsWith('57') ? rawPhone : `57${rawPhone}`;
|
||||
|
||||
if (isPlatformSuperAdmin(cleanPhone)) {
|
||||
throw new Error('Este número corresponde al Superadministrador y ya se encuentra configurado.');
|
||||
}
|
||||
|
||||
let existing = await User.findOne({ telefono: cleanPhone });
|
||||
|
||||
if (existing) {
|
||||
existing.rol = data.rol || 'ADMIN';
|
||||
existing.isActive = true;
|
||||
if (data.nombre && data.nombre.trim()) existing.nombre = data.nombre.trim();
|
||||
if (data.email && data.email.trim()) existing.email = data.email.trim().toLowerCase();
|
||||
if (data.documentoIdentidad) existing.documentoIdentidad = data.documentoIdentidad.trim();
|
||||
if (data.direccionTexto) existing.direccionTexto = data.direccionTexto.trim();
|
||||
await existing.save();
|
||||
|
||||
return {
|
||||
id: existing._id.toString(),
|
||||
appwriteId: existing.appwriteId,
|
||||
nombre: existing.nombre,
|
||||
telefono: existing.telefono,
|
||||
email: existing.email,
|
||||
documentoIdentidad: existing.documentoIdentidad,
|
||||
esSuperAdmin: false,
|
||||
rol: existing.rol,
|
||||
isActive: existing.isActive,
|
||||
phoneVerified: existing.phoneVerified,
|
||||
saldoPenalidad: existing.saldoPenalidad,
|
||||
bloqueadoPorPenalidad: false,
|
||||
totalViajesCompletados: existing.totalViajesCompletados || 0,
|
||||
totalViajesCancelados: existing.totalViajesCancelados || 0,
|
||||
createdAt: existing.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
const newAdmin = await User.create({
|
||||
appwriteId: `admin-${Date.now()}-${Math.random().toString(36).substr(2, 5)}`,
|
||||
nombre: (data.nombre || 'Nuevo Administrador').trim(),
|
||||
telefono: cleanPhone,
|
||||
email: data.email ? data.email.trim().toLowerCase() : undefined,
|
||||
documentoIdentidad: data.documentoIdentidad ? data.documentoIdentidad.trim() : undefined,
|
||||
rol: data.rol || 'ADMIN',
|
||||
esSuperAdmin: false,
|
||||
saldoPenalidad: 0,
|
||||
coordenadasDomicilio: {
|
||||
type: 'Point',
|
||||
coordinates: [-76.532, 3.4516],
|
||||
},
|
||||
direccionTexto: data.direccionTexto || 'Cali, Valle del Cauca',
|
||||
ciudad: 'Cali',
|
||||
isActive: true,
|
||||
phoneVerified: true,
|
||||
twoFactorEnabled: true,
|
||||
twoFactorMethod: 'whatsapp_otp',
|
||||
});
|
||||
|
||||
console.log(`🛡️ [Nuevo Admin Creado]: ${newAdmin.nombre} (+${newAdmin.telefono}) Rol: ${newAdmin.rol}`);
|
||||
|
||||
return {
|
||||
id: newAdmin._id.toString(),
|
||||
appwriteId: newAdmin.appwriteId,
|
||||
nombre: newAdmin.nombre,
|
||||
telefono: newAdmin.telefono,
|
||||
email: newAdmin.email,
|
||||
documentoIdentidad: newAdmin.documentoIdentidad,
|
||||
esSuperAdmin: false,
|
||||
rol: newAdmin.rol,
|
||||
isActive: newAdmin.isActive,
|
||||
phoneVerified: newAdmin.phoneVerified,
|
||||
saldoPenalidad: 0,
|
||||
bloqueadoPorPenalidad: false,
|
||||
totalViajesCompletados: 0,
|
||||
totalViajesCancelados: 0,
|
||||
createdAt: newAdmin.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* El Superadministrador edita los datos de un administrador
|
||||
*/
|
||||
public async updateAdministrator(adminId: string, updates: UpdateAdminDTO, requesterUserId?: string): Promise<UserSummaryDTO> {
|
||||
const user = await User.findById(adminId);
|
||||
if (!user) throw new Error('Administrador no encontrado.');
|
||||
|
||||
const isTargetSuper = isPlatformSuperAdmin(user.telefono) || !!user.esSuperAdmin;
|
||||
|
||||
if (updates.nombre && updates.nombre.trim()) {
|
||||
user.nombre = updates.nombre.trim();
|
||||
}
|
||||
if (updates.email !== undefined) {
|
||||
user.email = updates.email.trim().toLowerCase();
|
||||
}
|
||||
if (updates.documentoIdentidad !== undefined) {
|
||||
user.documentoIdentidad = updates.documentoIdentidad.trim();
|
||||
}
|
||||
if (updates.direccionTexto !== undefined) {
|
||||
user.direccionTexto = updates.direccionTexto.trim();
|
||||
}
|
||||
if (updates.ciudad !== undefined) {
|
||||
user.ciudad = updates.ciudad.trim();
|
||||
}
|
||||
|
||||
// El rol del Superadministrador nunca puede ser degradado
|
||||
if (!isTargetSuper && updates.rol) {
|
||||
user.rol = updates.rol;
|
||||
}
|
||||
|
||||
await user.save();
|
||||
|
||||
return {
|
||||
id: user._id.toString(),
|
||||
appwriteId: user.appwriteId,
|
||||
nombre: user.nombre,
|
||||
telefono: user.telefono,
|
||||
email: user.email,
|
||||
documentoIdentidad: user.documentoIdentidad,
|
||||
esSuperAdmin: isTargetSuper,
|
||||
rol: isTargetSuper ? 'ADMIN' : user.rol,
|
||||
isActive: user.isActive,
|
||||
phoneVerified: user.phoneVerified,
|
||||
saldoPenalidad: user.saldoPenalidad,
|
||||
bloqueadoPorPenalidad: false,
|
||||
totalViajesCompletados: user.totalViajesCompletados || 0,
|
||||
totalViajesCancelados: user.totalViajesCancelados || 0,
|
||||
createdAt: user.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Activa o inactiva a un administrador (Superadministrador inmutable)
|
||||
*/
|
||||
public async toggleAdministratorActive(adminId: string, isActive: boolean): Promise<IUser> {
|
||||
const user = await User.findById(adminId);
|
||||
if (!user) throw new Error('Administrador no encontrado.');
|
||||
|
||||
if (isPlatformSuperAdmin(user.telefono) || !!user.esSuperAdmin) {
|
||||
throw new Error('El Superadministrador no puede ser inactivado bajo ninguna circunstancia.');
|
||||
}
|
||||
|
||||
user.isActive = isActive;
|
||||
await user.save();
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Elimina formalmente a un administrador (Superadministrador no puede ser eliminado)
|
||||
*/
|
||||
public async deleteAdministrator(adminId: string, requesterUserId?: string): Promise<boolean> {
|
||||
const user = await User.findById(adminId);
|
||||
if (!user) throw new Error('Administrador no encontrado.');
|
||||
|
||||
if (isPlatformSuperAdmin(user.telefono) || !!user.esSuperAdmin) {
|
||||
throw new Error('El Superadministrador es permanente y no puede ser eliminado del sistema.');
|
||||
}
|
||||
|
||||
await User.findByIdAndDelete(adminId);
|
||||
console.log(`🗑️ [Admin Eliminado]: ${user.nombre} (${user.telefono}) eliminado por el Superadministrador.`);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Permite a los usuarios actualizar su información personal EXCEPTO el número de celular
|
||||
*/
|
||||
public async updateUserProfile(userId: string, updates: UpdateUserProfileDTO): Promise<any> {
|
||||
const user = await User.findById(userId);
|
||||
if (!user) throw new Error('Usuario no encontrado.');
|
||||
|
||||
// Validación estricta de inmutabilidad del número de celular
|
||||
if (updates.telefono) {
|
||||
const cleanInput = updates.telefono.replace(/\D/g, '');
|
||||
const currentClean = user.telefono.replace(/\D/g, '');
|
||||
if (cleanInput && cleanInput !== currentClean && !currentClean.endsWith(cleanInput) && !cleanInput.endsWith(currentClean)) {
|
||||
throw new Error(
|
||||
`Por estrictas políticas de seguridad y autenticación 2FA OTP, el número de celular registrado (+${user.telefono}) no puede ser modificado. Para cambiar tu número oficial, contacta a la central de soporte.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (updates.nombre && updates.nombre.trim().length >= 3) {
|
||||
user.nombre = updates.nombre.trim();
|
||||
}
|
||||
if (updates.documentoIdentidad !== undefined) {
|
||||
user.documentoIdentidad = updates.documentoIdentidad.trim();
|
||||
}
|
||||
if (updates.email !== undefined) {
|
||||
user.email = updates.email.trim().toLowerCase();
|
||||
}
|
||||
if (updates.direccionTexto !== undefined) {
|
||||
user.direccionTexto = updates.direccionTexto.trim();
|
||||
}
|
||||
if (updates.ciudad !== undefined) {
|
||||
user.ciudad = updates.ciudad.trim();
|
||||
}
|
||||
|
||||
await user.save();
|
||||
|
||||
return {
|
||||
id: user._id.toString(),
|
||||
_id: user._id.toString(),
|
||||
nombre: user.nombre,
|
||||
telefono: user.telefono,
|
||||
email: user.email,
|
||||
documentoIdentidad: user.documentoIdentidad,
|
||||
direccionTexto: user.direccionTexto,
|
||||
ciudad: user.ciudad,
|
||||
rol: user.rol,
|
||||
esSuperAdmin: isPlatformSuperAdmin(user.telefono) || !!user.esSuperAdmin,
|
||||
phoneVerified: user.phoneVerified,
|
||||
saldoPenalidad: user.saldoPenalidad,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Consulta un usuario por teléfono o ID con evaluación de riesgo y estado de penalidad
|
||||
*/
|
||||
@ -107,20 +469,7 @@ export class UserAdminService {
|
||||
|
||||
// Auto-creación / protección del Super Administrador si ingresa por primera vez
|
||||
if (!user && (isPlatformSuperAdmin(cleanPhone) || isPlatformSuperAdmin(identifier))) {
|
||||
user = await User.create({
|
||||
appwriteId: 'usr-admin-principal',
|
||||
nombre: 'Administrador Central Pacifictrans',
|
||||
telefono: cleanPhone || SUPER_ADMIN_PHONE,
|
||||
email: SUPER_ADMIN_EMAIL,
|
||||
rol: 'ADMIN',
|
||||
saldoPenalidad: 0,
|
||||
coordenadasDomicilio: {
|
||||
type: 'Point',
|
||||
coordinates: [-76.532, 3.4516], // Cali centro
|
||||
},
|
||||
isActive: true,
|
||||
phoneVerified: true,
|
||||
});
|
||||
user = await this.ensureSuperAdminExists();
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
@ -131,7 +480,7 @@ export class UserAdminService {
|
||||
};
|
||||
}
|
||||
|
||||
const isSuper = isPlatformSuperAdmin(user.telefono) || isPlatformSuperAdmin(user.email);
|
||||
const isSuper = isPlatformSuperAdmin(user.telefono) || isPlatformSuperAdmin(user.email) || !!user.esSuperAdmin;
|
||||
const montoPenalidad = isSuper ? 0 : user.saldoPenalidad || 0;
|
||||
const bloqueadoPorPenalidad = montoPenalidad > 0;
|
||||
|
||||
@ -161,6 +510,8 @@ export class UserAdminService {
|
||||
nombre: user.nombre,
|
||||
telefono: user.telefono,
|
||||
email: user.email,
|
||||
documentoIdentidad: user.documentoIdentidad,
|
||||
esSuperAdmin: isSuper,
|
||||
rol: isSuper ? 'ADMIN' : user.rol,
|
||||
isActive: isSuper ? true : user.isActive,
|
||||
phoneVerified: isSuper ? true : user.phoneVerified,
|
||||
@ -171,6 +522,8 @@ export class UserAdminService {
|
||||
twoFactorEnabled: user.twoFactorEnabled,
|
||||
twoFactorMethod: user.twoFactorMethod,
|
||||
biometricEnabled: user.biometricEnabled,
|
||||
direccionTexto: user.direccionTexto,
|
||||
ciudad: user.ciudad,
|
||||
driverProfile,
|
||||
createdAt: user.createdAt,
|
||||
};
|
||||
@ -190,7 +543,7 @@ export class UserAdminService {
|
||||
const user = await User.findById(userId);
|
||||
if (!user) throw new Error('Usuario no encontrado');
|
||||
|
||||
if (isPlatformSuperAdmin(user.telefono) || isPlatformSuperAdmin(user.email)) {
|
||||
if (isPlatformSuperAdmin(user.telefono) || isPlatformSuperAdmin(user.email) || !!user.esSuperAdmin) {
|
||||
throw new Error('No es posible suspender la cuenta del Super Administrador principal.');
|
||||
}
|
||||
|
||||
@ -206,8 +559,9 @@ export class UserAdminService {
|
||||
const user = await User.findById(userId);
|
||||
if (!user) throw new Error('Usuario no encontrado');
|
||||
|
||||
if (isPlatformSuperAdmin(user.telefono) || isPlatformSuperAdmin(user.email)) {
|
||||
if (isPlatformSuperAdmin(user.telefono) || isPlatformSuperAdmin(user.email) || !!user.esSuperAdmin) {
|
||||
user.rol = 'ADMIN';
|
||||
user.esSuperAdmin = true;
|
||||
await user.save();
|
||||
return user;
|
||||
}
|
||||
|
||||